Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

feat: v0.6.1 — citations, cascading updates, expanded mesh (#79)

Rohit Ghumare005b8c80873d
diff --git a/src/functions/cascade.ts b/src/functions/cascade.ts
new file mode 100644
index 00000000..08d3864e
--- /dev/null
+++ b/src/functions/cascade.ts
@@ -0,0 +1,80 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type { Memory, GraphNode, GraphEdge } from "../types.js";
+
+export function registerCascadeFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::cascade-update" },
+ async (data: { supersededMemoryId: string }) => {
+ if (!data.supersededMemoryId || typeof data.supersededMemoryId !== "string") {
+ return { success: false, error: "supersededMemoryId is required" };
+ }
+
+ const superseded = await kv.get<Memory>(KV.memories, data.supersededMemoryId);
+ if (!superseded) {
+ return { success: false, error: "superseded memory not found" };
+ }
+
+ let flaggedNodes = 0;
+ let flaggedEdges = 0;
+ let flaggedMemories = 0;
+
+ const obsIds = new Set(superseded.sourceObservationIds || []);
+
+ if (obsIds.size > 0) {
+ const now = new Date().toISOString();
+ const nodes = await kv.list<GraphNode>(KV.graphNodes);
+ for (const node of nodes) {
+ if (node.stale) continue;
+ const overlap = (node.sourceObservationIds ?? []).some((id) => obsIds.has(id));
+ if (overlap) {
+ node.stale = true;
+ node.updatedAt = now;
+ await kv.set(KV.graphNodes, node.id, node);
+ flaggedNodes++;
+ }
+ }
+
+ const edges = await kv.list<GraphEdge>(KV.graphEdges);
+ for (const edge of edges) {
+ if (edge.stale) continue;
+ const overlap = (edge.sourceObservationIds ?? []).some((id) => obsIds.has(id));
+ if (overlap) {
+ edge.stale = true;
+ await kv.set(KV.graphEdges, edge.id, edge);
+ flaggedEdges++;
+ }
+ }
+ }
+
+ const supersededConcepts = new Set(
+ (superseded.concepts ?? []).map((c) => c.toLowerCase()),
+ );
+ if (supersededConcepts.size >= 2) {
+ const allMemories = await kv.list<Memory>(KV.memories);
+ for (const mem of allMemories) {
+ if (mem.id === data.supersededMemoryId) continue;
+ if (!mem.isLatest) continue;
+
+ const sharedCount = (mem.concepts ?? []).filter((c) =>
+ supersededConcepts.has(c.toLowerCase()),
+ ).length;
+ if (sharedCount >= 2) {
+ flaggedMemories++;
+ }
+ }
+ }
+
+ return {
+ success: true,
+ flagged: {
+ nodes: flaggedNodes,
+ edges: flaggedEdges,
+ siblingMemories: flaggedMemories,
+ },
+ total: flaggedNodes + flaggedEdges + flaggedMemories,
+ };
+ },
+ );
+}
diff --git a/src/functions/compress.ts b/src/functions/compress.ts
index 8efa989f..74f32387 100644
--- a/src/functions/compress.ts
+++ b/src/functions/compress.ts
@@ -129,6 +129,7 @@ export function registerCompressFunction(
sessionId: data.sessionId,
timestamp: data.raw.timestamp,
...parsed,
+ confidence: qualityScore / 100,
};
await kv.set(
diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts
index 4b70f50a..72f9ed0f 100644
--- a/src/functions/consolidate.ts
+++ b/src/functions/consolidate.ts
@@ -158,6 +158,7 @@ export function registerConsolidateFunction(
);
const now = new Date().toISOString();
+ const obsIds = [...new Set(top.map((o) => o.id))];
if (existingMatch) {
existingMatch.isLatest = false;
await kv.set(KV.memories, existingMatch.id, existingMatch);
@@ -173,6 +174,7 @@ export function registerConsolidateFunction(
existingMatch.id,
...(existingMatch.supersedes || []),
],
+ sourceObservationIds: obsIds,
isLatest: true,
};
await kv.set(KV.memories, evolved.id, evolved);
@@ -184,6 +186,7 @@ export function registerConsolidateFunction(
createdAt: now,
updatedAt: now,
...parsed,
+ sourceObservationIds: obsIds,
version: 1,
isLatest: true,
};
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 2c32763f..8a69284b 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -162,7 +162,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
const strategy = data.strategy || "merge";
const importData = data.exportData;
- const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0"]);
+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1"]);
if (!supportedVersions.has(importData.version)) {
return {
success: false,
diff --git a/src/functions/graph-retrieval.ts b/src/functions/graph-retrieval.ts
index bc82c5e4..245d2efb 100644
--- a/src/functions/graph-retrieval.ts
+++ b/src/functions/graph-retrieval.ts
@@ -46,8 +46,8 @@ export class GraphRetrieval {
maxDepth = 2,
maxResults = 20,
): Promise<GraphRetrievalResult[]> {
- const allNodes = await this.kv.list<GraphNode>(KV.graphNodes);
- const allEdges = await this.kv.list<GraphEdge>(KV.graphEdges);
+ const allNodes = (await this.kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
+ const allEdges = (await this.kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
const matchingNodes = allNodes.filter((n) => {
const nameLower = n.name.toLowerCase();
@@ -119,8 +119,8 @@ export class GraphRetrieval {
maxDepth = 1,
maxResults = 10,
): Promise<GraphRetrievalResult[]> {
- const allNodes = await this.kv.list<GraphNode>(KV.graphNodes);
- const allEdges = await this.kv.list<GraphEdge>(KV.graphEdges);
+ const allNodes = (await this.kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
+ const allEdges = (await this.kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
const linkedNodes = allNodes.filter((n) =>
n.sourceObservationIds.some((id) => obsIds.includes(id)),
@@ -163,8 +163,8 @@ export class GraphRetrieval {
currentState: GraphEdge[];
history: GraphEdge[];
}> {
- const allNodes = await this.kv.list<GraphNode>(KV.graphNodes);
- const allEdges = await this.kv.list<GraphEdge>(KV.graphEdges);
+ const allNodes = (await this.kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
+ const allEdges = (await this.kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
const entity = allNodes.find(
(n) => n.name.toLowerCase() === entityName.toLowerCase(),
diff --git a/src/functions/graph.ts b/src/functions/graph.ts
index 919d208f..afb7d201 100644
--- a/src/functions/graph.ts
+++ b/src/functions/graph.ts
@@ -181,8 +181,8 @@ export function registerGraphFunction(
maxDepth?: number;
query?: string;
}): Promise<GraphQueryResult> => {
- const allNodes = await kv.list<GraphNode>(KV.graphNodes);
- const allEdges = await kv.list<GraphEdge>(KV.graphEdges);
+ const allNodes = (await kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
+ const allEdges = (await kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
const maxDepth = Math.min(data.maxDepth || 3, 5);
if (data.query) {
diff --git a/src/functions/mesh.ts b/src/functions/mesh.ts
index a14dd06e..63351765 100644
--- a/src/functions/mesh.ts
+++ b/src/functions/mesh.ts
@@ -2,7 +2,16 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
-import type { MeshPeer, Memory, Action } from "../types.js";
+import type {
+ MeshPeer,
+ Memory,
+ Action,
+ SemanticMemory,
+ ProceduralMemory,
+ MemoryRelation,
+ GraphNode,
+ GraphEdge,
+} from "../types.js";
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
@@ -44,6 +53,88 @@ async function isAllowedUrl(urlStr: string): Promise<boolean> {
}
}
+const DEFAULT_SHARED_SCOPES = [
+ "memories",
+ "actions",
+ "semantic",
+ "procedural",
+ "relations",
+ "graph:nodes",
+ "graph:edges",
+];
+
+interface MeshSyncPayload {
+ memories?: Memory[];
+ actions?: Action[];
+ semantic?: SemanticMemory[];
+ procedural?: ProceduralMemory[];
+ relations?: MemoryRelation[];
+ graphNodes?: GraphNode[];
+ graphEdges?: GraphEdge[];
+}
+
+async function lwwMergeList<T extends { id: string }>(
+ kv: StateKV,
+ scope: string,
+ items: T[] | undefined,
+ lockPrefix: string,
+ tsField: "updatedAt" | "createdAt",
+): Promise<number> {
+ if (!items || !Array.isArray(items)) return 0;
+ let count = 0;
+ for (const item of items) {
+ if (!item.id || typeof item.id !== "string") continue;
+ const ts = (item as Record<string, unknown>)[tsField];
+ if (typeof ts !== "string" || Number.isNaN(new Date(ts).getTime())) continue;
+ const wrote = await withKeyedLock(`${lockPrefix}:${item.id}`, async () => {
+ const existing = await kv.get<T>(scope, item.id);
+ if (!existing) {
+ await kv.set(scope, item.id, item);
+ return true;
+ }
+ const existingTs = (existing as Record<string, unknown>)[tsField] as string;
+ if (new Date(ts) > new Date(existingTs)) {
+ await kv.set(scope, item.id, item);
+ return true;
+ }
+ return false;
+ });
+ if (wrote) count++;
+ }
+ return count;
+}
+
+function graphNodeTs(node: GraphNode): string {
+ return node.updatedAt || node.createdAt;
+}
+
+async function lwwMergeGraphNodes(
+ kv: StateKV,
+ items: GraphNode[] | undefined,
+): Promise<number> {
+ if (!items || !Array.isArray(items)) return 0;
+ let count = 0;
+ for (const item of items) {
+ if (!item.id || typeof item.id !== "string") continue;
+ const ts = graphNodeTs(item);
+ if (!ts || Number.isNaN(new Date(ts).getTime())) continue;
+ const wrote = await withKeyedLock(`mem:gnode:${item.id}`, async () => {
+ const existing = await kv.get<GraphNode>(KV.graphNodes, item.id);
+ if (!existing) {
+ await kv.set(KV.graphNodes, item.id, item);
+ return true;
+ }
+ if (new Date(ts) > new Date(graphNodeTs(existing))) {
+ await kv.set(KV.graphNodes, item.id, item);
+ return true;
+ }
+ return false;
+ });
+ if (wrote) count++;
+ }
+ return count;
+}
+
export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction(
{ id: "mem::mesh-register" },
@@ -51,6 +142,7 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
url: string;
name: string;
sharedScopes?: string[];
+ syncFilter?: { project?: string };
}) => {
if (!data.url || !data.name) {
return { success: false, error: "url and name are required" };
@@ -71,7 +163,8 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
url: data.url,
name: data.name,
status: "disconnected",
- sharedScopes: data.sharedScopes || ["memories", "actions"],
+ sharedScopes: data.sharedScopes || DEFAULT_SHARED_SCOPES,
+ syncFilter: data.syncFilter,
};
await kv.set(KV.mesh, peer.id, peer);
@@ -133,7 +226,7 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
}
if (direction === "push" || direction === "both") {
- const pushData = await collectSyncData(kv, scopes, peer.lastSyncAt);
+ const pushData = await collectSyncData(kv, scopes, peer.lastSyncAt, peer.syncFilter);
try {
const response = await fetch(`${peer.url}/agentmemory/mesh/receive`, {
method: "POST",
@@ -192,50 +285,28 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction(
{ id: "mem::mesh-receive" },
- async (data: { memories?: Memory[]; actions?: Action[] }) => {
+ async (data: MeshSyncPayload) => {
let accepted = 0;
- if (data.memories && Array.isArray(data.memories)) {
- for (const mem of data.memories) {
- if (!mem.id || typeof mem.id !== "string" || !mem.updatedAt) continue;
- if (Number.isNaN(new Date(mem.updatedAt).getTime())) continue;
- const wrote = await withKeyedLock(`mem:memory:${mem.id}`, async () => {
- const existing = await kv.get<Memory>(KV.memories, mem.id);
+ accepted += await lwwMergeList(kv, KV.memories, data.memories, "mem:memory", "updatedAt");
+ accepted += await lwwMergeList(kv, KV.actions, data.actions, "mem:action", "updatedAt");
+ accepted += await lwwMergeList(kv, KV.semantic, data.semantic, "mem:semantic", "updatedAt");
+ accepted += await lwwMergeList(kv, KV.procedural, data.procedural, "mem:procedural", "updatedAt");
+ if (data.relations && Array.isArray(data.relations)) {
+ for (const rel of data.relations) {
+ if (!rel.sourceId || !rel.targetId || !rel.type) continue;
+ const relKey = `${rel.sourceId}:${rel.targetId}:${rel.type}`;
+ await withKeyedLock(`mem:relation:${relKey}`, async () => {
+ const existing = await kv.get<MemoryRelation>(KV.relations, relKey);
if (!existing) {
- await kv.set(KV.memories, mem.id, mem);
- return true;
- } else if (
- new Date(mem.updatedAt) > new Date(existing.updatedAt)
- ) {
- await kv.set(KV.memories, mem.id, mem);
- return true;
+ await kv.set(KV.relations, relKey, rel);
+ accepted++;
}
- return false;
});
- if (wrote) accepted++;
- }
- }
-
- if (data.actions && Array.isArray(data.actions)) {
- for (const action of data.actions) {
- if (!action.id || typeof action.id !== "string" || !action.updatedAt) continue;
- if (Number.isNaN(new Date(action.updatedAt).getTime())) continue;
- const wrote = await withKeyedLock(`mem:action:${action.id}`, async () => {
- const existing = await kv.get<Action>(KV.actions, action.id);
- if (!existing) {
- await kv.set(KV.actions, action.id, action);
- return true;
- } else if (
- new Date(action.updatedAt) > new Date(existing.updatedAt)
- ) {
- await kv.set(KV.actions, action.id, action);
- return true;
- }
- return false;
- });
- if (wrote) accepted++;
}
}
+ accepted += await lwwMergeGraphNodes(kv, data.graphNodes);
+ accepted += await lwwMergeList(kv, KV.graphEdges, data.graphEdges, "mem:gedge", "createdAt");
return { success: true, accepted };
},
@@ -253,63 +324,98 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
);
}
+function deltaFilter<T>(
+ items: T[],
+ sinceTime: number,
+ tsField: "updatedAt" | "createdAt",
+): T[] {
+ return items.filter(
+ (item) => new Date((item as Record<string, unknown>)[tsField] as string).getTime() > sinceTime,
+ );
+}
+
async function collectSyncData(
kv: StateKV,
scopes: string[],
since?: string,
-): Promise<{ memories?: Memory[]; actions?: Action[] }> {
- const result: { memories?: Memory[]; actions?: Action[] } = {};
+ syncFilter?: { project?: string },
+): Promise<MeshSyncPayload> {
+ const result: MeshSyncPayload = {};
const parsed = since ? new Date(since).getTime() : 0;
const sinceTime = Number.isNaN(parsed) ? 0 : parsed;
if (scopes.includes("memories")) {
- const allMemories = await kv.list<Memory>(KV.memories);
- result.memories = allMemories.filter(
- (m) => new Date(m.updatedAt).getTime() > sinceTime,
- );
+ const all = await kv.list<Memory>(KV.memories);
+ result.memories = deltaFilter(all, sinceTime, "updatedAt");
}
if (scopes.includes("actions")) {
- const allActions = await kv.list<Action>(KV.actions);
- result.actions = allActions.filter(
- (a) => new Date(a.updatedAt).getTime() > sinceTime,
+ let all = await kv.list<Action>(KV.actions);
+ if (syncFilter?.project) {
+ all = all.filter((a) => a.project === syncFilter.project);
+ }
+ result.actions = deltaFilter(all, sinceTime, "updatedAt");
+ }
+
+ const projectScoped = !!syncFilter?.project;
+
+ if (scopes.includes("semantic") && !projectScoped) {
+ const all = await kv.list<SemanticMemory>(KV.semantic);
+ result.semantic = deltaFilter(all, sinceTime, "updatedAt");
+ }
+
+ if (scopes.includes("procedural") && !projectScoped) {
+ const all = await kv.list<ProceduralMemory>(KV.procedural);
+ result.procedural = deltaFilter(all, sinceTime, "updatedAt");
+ }
+
+ if (scopes.includes("relations") && !projectScoped) {
+ const all = await kv.list<MemoryRelation>(KV.relations);
+ result.relations = deltaFilter(all, sinceTime, "createdAt");
+ }
+
+ if (scopes.includes("graph:nodes") && !projectScoped) {
+ const all = await kv.list<GraphNode>(KV.graphNodes);
+ result.graphNodes = all.filter(
+ (n) => new Date(graphNodeTs(n)).getTime() > sinceTime,
);
}
+ if (scopes.includes("graph:edges") && !projectScoped) {
+ const all = await kv.list<GraphEdge>(KV.graphEdges);
+ result.graphEdges = deltaFilter(all, sinceTime, "createdAt");
+ }
+
return result;
}
async function applySyncData(
kv: StateKV,
- data: { memories?: Memory[]; actions?: Action[] },
+ data: MeshSyncPayload,
scopes: string[],
): Promise<number> {
let applied = 0;
- if (scopes.includes("memories") && data.memories) {
- for (const mem of data.memories) {
- if (!mem.id || typeof mem.id !== "string" || !mem.updatedAt) continue;
- if (Number.isNaN(new Date(mem.updatedAt).getTime())) continue;
- const wrote = await withKeyedLock(`mem:memory:${mem.id}`, async () => {
- const existing = await kv.get<Memory>(KV.memories, mem.id);
- if (!existing || new Date(mem.updatedAt) > new Date(existing.updatedAt)) {
- await kv.set(KV.memories, mem.id, mem);
- return true;
- }
- return false;
- });
- if (wrote) applied++;
- }
+ if (scopes.includes("memories")) {
+ applied += await lwwMergeList(kv, KV.memories, data.memories, "mem:memory", "updatedAt");
}
-
- if (scopes.includes("actions") && data.actions) {
- for (const action of data.actions) {
- if (!action.id || typeof action.id !== "string" || !action.updatedAt) continue;
- if (Number.isNaN(new Date(action.updatedAt).getTime())) continue;
- const wrote = await withKeyedLock(`mem:action:${action.id}`, async () => {
- const existing = await kv.get<Action>(KV.actions, action.id);
- if (!existing || new Date(action.updatedAt) > new Date(existing.updatedAt)) {
- await kv.set(KV.actions, action.id, action);
+ if (scopes.includes("actions")) {
+ applied += await lwwMergeList(kv, KV.actions, data.actions, "mem:action", "updatedAt");
+ }
+ if (scopes.includes("semantic")) {
+ applied += await lwwMergeList(kv, KV.semantic, data.semantic, "mem:semantic", "updatedAt");
+ }
+ if (scopes.includes("procedural")) {
+ applied += await lwwMergeList(kv, KV.procedural, data.procedural, "mem:procedural", "updatedAt");
+ }
+ if (scopes.includes("relations") && data.relations) {
+ for (const rel of data.relations) {
+ if (!rel.sourceId || !rel.targetId || !rel.type) continue;
+ const relKey = `${rel.sourceId}:${rel.targetId}:${rel.type}`;
+ const wrote = await withKeyedLock(`mem:relation:${relKey}`, async () => {
+ const existing = await kv.get<MemoryRelation>(KV.relations, relKey);
+ if (!existing) {
+ await kv.set(KV.relations, relKey, rel);
return true;
}
return false;
@@ -317,6 +423,12 @@ async function applySyncData(
if (wrote) applied++;
}
}
+ if (scopes.includes("graph:nodes")) {
+ applied += await lwwMergeGraphNodes(kv, data.graphNodes);
+ }
+ if (scopes.includes("graph:edges")) {
+ applied += await lwwMergeList(kv, KV.graphEdges, data.graphEdges, "mem:gedge", "createdAt");
+ }
return applied;
}
diff --git a/src/functions/remember.ts b/src/functions/remember.ts
index e5f08986..dced14e1 100644
--- a/src/functions/remember.ts
+++ b/src/functions/remember.ts
@@ -14,6 +14,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
concepts?: string[];
files?: string[];
ttlDays?: number;
+ sourceObservationIds?: string[];
}) => {
const ctx = getContext();
if (
@@ -29,6 +30,9 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
if (data.concepts && !Array.isArray(data.concepts)) {
return { success: false, error: "concepts must be an array" };
}
+ if (data.sourceObservationIds && !Array.isArray(data.sourceObservationIds)) {
+ return { success: false, error: "sourceObservationIds must be an array" };
+ }
const validTypes = new Set([
"pattern",
"preference",
@@ -77,6 +81,9 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
version: supersededId ? supersededVersion + 1 : 1,
parentId: supersededId,
supersedes: supersededId ? [supersededId] : [],
+ sourceObservationIds: (data.sourceObservationIds || []).filter(
+ (id): id is string => typeof id === "string" && id.length > 0,
+ ),
isLatest: true,
};
@@ -90,6 +97,12 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
}
await kv.set(KV.memories, memory.id, memory);
+ if (supersededId) {
+ sdk.triggerVoid("mem::cascade-update", {
+ supersededMemoryId: supersededId,
+ });
+ }
+
ctx.logger.info("Memory saved", {
memId: memory.id,
type: memory.type,
diff --git a/src/functions/verify.ts b/src/functions/verify.ts
new file mode 100644
index 00000000..74753b15
--- /dev/null
+++ b/src/functions/verify.ts
@@ -0,0 +1,117 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type {
+ Memory,
+ CompressedObservation,
+ Session,
+} from "../types.js";
+
+export function registerVerifyFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::verify" },
+ async (data: { id: string }) => {
+ if (!data.id || typeof data.id !== "string") {
+ return { success: false, error: "id is required" };
+ }
+
+ const memory = await kv.get<Memory>(KV.memories, data.id);
+ if (memory) {
+ const observationIds = memory.sourceObservationIds || [];
+ const observations: Array<{
+ observation: CompressedObservation;
+ session?: Session;
+ }> = [];
+
+ for (const obsId of observationIds) {
+ const obs = await findObservation(kv, obsId, memory.sessionIds);
+ if (obs) {
+ const session = await kv.get<Session>(KV.sessions, obs.sessionId);
+ observations.push({ observation: obs, session: session || undefined });
+ }
+ }
+
+ return {
+ success: true,
+ type: "memory",
+ memory: {
+ id: memory.id,
+ title: memory.title,
+ type: memory.type,
+ version: memory.version,
+ strength: memory.strength,
+ isLatest: memory.isLatest,
+ createdAt: memory.createdAt,
+ updatedAt: memory.updatedAt,
+ supersedes: memory.supersedes,
+ parentId: memory.parentId,
+ },
+ citations: observations.map((o) => ({
+ observationId: o.observation.id,
+ title: o.observation.title,
+ type: o.observation.type,
+ confidence: o.observation.confidence,
+ timestamp: o.observation.timestamp,
+ sessionId: o.observation.sessionId,
+ sessionProject: o.session?.project,
+ sessionStatus: o.session?.status,
+ })),
+ citationCount: observations.length,
+ };
+ }
+
+ const obs = await findObservation(kv, data.id);
+ if (obs) {
+ const session = await kv.get<Session>(KV.sessions, obs.sessionId);
+ return {
+ success: true,
+ type: "observation",
+ observation: {
+ id: obs.id,
+ title: obs.title,
+ type: obs.type,
+ confidence: obs.confidence,
+ importance: obs.importance,
+ timestamp: obs.timestamp,
+ sessionId: obs.sessionId,
+ },
+ session: session
+ ? {
+ id: session.id,
+ project: session.project,
+ status: session.status,
+ startedAt: session.startedAt,
+ }
+ : null,
+ citationCount: 0,
+ citations: [],
+ };
+ }
+
+ return { success: false, error: "not found" };
+ },
+ );
+}
+
+async function findObservation(
+ kv: StateKV,
+ obsId: string,
+ hintSessionIds?: string[],
+): Promise<CompressedObservation | null> {
+ if (hintSessionIds) {
+ for (const sid of hintSessionIds) {
+ const obs = await kv.get<CompressedObservation>(KV.observations(sid), obsId);
+ if (obs) return obs;
+ }
+ }
+ const sessions = await kv.list<Session>(KV.sessions);
+ for (const session of sessions) {
+ if (hintSessionIds?.includes(session.id)) continue;
+ const obs = await kv.get<CompressedObservation>(
+ KV.observations(session.id),
+ obsId,
+ );
+ if (obs) return obs;
+ }
+ return null;
+}
diff --git a/src/index.ts b/src/index.ts
index f8c47f30..353791c6 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -62,6 +62,8 @@ import { registerSketchesFunction } from "./functions/sketches.js";
import { registerCrystallizeFunction } from "./functions/crystallize.js";
import { registerDiagnosticsFunction } from "./functions/diagnostics.js";
import { registerFacetsFunction } from "./functions/facets.js";
+import { registerVerifyFunction } from "./functions/verify.js";
+import { registerCascadeFunction } from "./functions/cascade.js";
import { registerSlidingWindowFunction } from "./functions/sliding-window.js";
import { registerQueryExpansionFunction } from "./functions/query-expansion.js";
import { registerTemporalGraphFunctions } from "./functions/temporal-graph.js";
@@ -189,6 +191,8 @@ async function main() {
registerCrystallizeFunction(sdk, kv, provider);
registerDiagnosticsFunction(sdk, kv);
registerFacetsFunction(sdk, kv);
+ registerVerifyFunction(sdk, kv);
+ registerCascadeFunction(sdk, kv);
registerSlidingWindowFunction(sdk, kv, provider);
registerQueryExpansionFunction(sdk, provider);
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index db6516a6..c6b5141b 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -915,6 +915,14 @@ export function registerMcpEndpoints(
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fqResult, null, 2) }] } };
}
+ case "memory_verify": {
+ if (!args.id || typeof args.id !== "string") {
+ return { status_code: 400, body: { error: "id is required" } };
+ }
+ const verifyResult = await sdk.trigger("mem::verify", { id: args.id });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(verifyResult, null, 2) }] } };
+ }
+
default:
return {
status_code: 400,
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index 9732ab53..64227797 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -666,6 +666,24 @@ export const V051_TOOLS: McpToolDef[] = [
},
];
+export const V061_TOOLS: McpToolDef[] = [
+ {
+ name: "memory_verify",
+ description:
+ "Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description: "Memory ID or observation ID to verify",
+ },
+ },
+ required: ["id"],
+ },
+ },
+];
+
export function getAllTools(): McpToolDef[] {
- return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS];
+ return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS, ...V061_TOOLS];
}
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 2526a8f9..4f7568eb 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1478,20 +1478,34 @@ export function registerApiTriggers(
return { status_code: 400, body: { error: "Invalid 'since' date format" } };
}
}
- const memories = await kv.list<import("../types.js").Memory>(KV.memories);
- const actions = await kv.list<import("../types.js").Action>(KV.actions);
+ const project = req.query_params?.["project"] as string | undefined;
const sinceTime = since ? new Date(since).getTime() : 0;
- return {
- status_code: 200,
- body: {
- memories: memories.filter(
- (m) => new Date(m.updatedAt).getTime() > sinceTime,
- ),
- actions: actions.filter(
- (a) => new Date(a.updatedAt).getTime() > sinceTime,
- ),
- },
+ const df = <T>(items: T[], field: "updatedAt" | "createdAt") =>
+ items.filter((i) => new Date((i as Record<string, unknown>)[field] as string).getTime() > sinceTime);
+ const memories = await kv.list<import("../types.js").Memory>(KV.memories);
+ let actions = await kv.list<import("../types.js").Action>(KV.actions);
+ if (project) {
+ actions = actions.filter((a) => a.project === project);
+ }
+ const body: Record<string, unknown> = {
+ memories: df(memories, "updatedAt"),
+ actions: df(actions, "updatedAt"),
};
+ if (!project) {
+ const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic);
+ const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural);
+ const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations);
+ const graphNodes = await kv.list<import("../types.js").GraphNode>(KV.graphNodes);
+ const graphEdges = await kv.list<import("../types.js").GraphEdge>(KV.graphEdges);
+ body.semantic = df(semantic, "updatedAt");
+ body.procedural = df(procedural, "updatedAt");
+ body.relations = df(relations, "createdAt");
+ body.graphNodes = graphNodes.filter(
+ (n) => new Date(n.updatedAt || n.createdAt).getTime() > sinceTime,
+ );
+ body.graphEdges = df(graphEdges, "createdAt");
+ }
+ return { status_code: 200, body };
},
);
sdk.registerTrigger({
@@ -1802,4 +1816,26 @@ export function registerApiTriggers(
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::verify" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.id || typeof body.id !== "string") return { status_code: 400, body: { error: "id is required" } };
+ const result = await sdk.trigger("mem::verify", { id: body.id });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::cascade-update" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") {
+ return { status_code: 400, body: { error: "supersededMemoryId is required" } };
+ }
+ const result = await sdk.trigger("mem::cascade-update", { supersededMemoryId: body.supersededMemoryId });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } });
}
diff --git a/src/types.ts b/src/types.ts
index 4bea1906..bfa8d979 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -35,6 +35,7 @@ export interface CompressedObservation {
concepts: string[];
files: string[];
importance: number;
+ confidence?: number;
}
export type ObservationType =
@@ -68,6 +69,7 @@ export interface Memory {
parentId?: string;
supersedes?: string[];
relatedIds?: string[];
+ sourceObservationIds?: string[];
isLatest: boolean;
forgetAfter?: string;
}
@@ -247,7 +249,7 @@ export interface ExportPagination {
}
export interface ExportData {
- version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0";
+ version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1";
exportedAt: string;
sessions: Session[];
observations: Record<string, CompressedObservation[]>;
@@ -317,6 +319,7 @@ export interface GraphNode {
createdAt: string;
updatedAt?: string;
aliases?: string[];
+ stale?: boolean;
}
export type GraphEdgeType =
@@ -352,6 +355,7 @@ export interface GraphEdge {
version?: number;
supersededBy?: string;
isLatest?: boolean;
+ stale?: boolean;
}
export interface EdgeContext {
@@ -660,6 +664,7 @@ export interface MeshPeer {
lastSyncAt?: string;
status: "connected" | "disconnected" | "syncing" | "error";
sharedScopes: string[];
+ syncFilter?: { project?: string };
}
diff --git a/src/version.ts b/src/version.ts
index bed5cb39..b910864b 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1 @@
-export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" = "0.6.0";
+export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" = "0.6.1";
diff --git a/test/cascade.test.ts b/test/cascade.test.ts
new file mode 100644
index 00000000..38ec7090
--- /dev/null
+++ b/test/cascade.test.ts
@@ -0,0 +1,277 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerCascadeFunction } from "../src/functions/cascade.js";
+import type { Memory, GraphNode, GraphEdge } from "../src/types.js";
+import { mockKV, mockSdk } from "./helpers/mocks.js";
+
+describe("Cascade Update Function", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ vi.clearAllMocks();
+ registerCascadeFunction(sdk as never, kv as never);
+ });
+
+ it("returns error when supersededMemoryId is missing", async () => {
+ const result = (await sdk.trigger("mem::cascade-update", {})) as {
+ success: boolean;
+ error: string;
+ };
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("supersededMemoryId is required");
+ });
+
+ it("returns error for non-existent memory", async () => {
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_missing",
+ })) as { success: boolean; error: string };
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("superseded memory not found");
+ });
+
+ it("flags graph nodes referencing superseded observation IDs", async () => {
+ const memory: Memory = {
+ id: "mem_old",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "Old fact",
+ content: "Old content",
+ concepts: ["react"],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: false,
+ sourceObservationIds: ["obs_a", "obs_b"],
+ };
+ await kv.set("mem:memories", "mem_old", memory);
+
+ const node: GraphNode = {
+ id: "node_1",
+ type: "concept",
+ name: "react",
+ properties: {},
+ sourceObservationIds: ["obs_a"],
+ createdAt: "2026-03-01T00:00:00Z",
+ };
+ await kv.set("mem:graph:nodes", "node_1", node);
+
+ const unrelatedNode: GraphNode = {
+ id: "node_2",
+ type: "file",
+ name: "index.ts",
+ properties: {},
+ sourceObservationIds: ["obs_c"],
+ createdAt: "2026-03-01T00:00:00Z",
+ };
+ await kv.set("mem:graph:nodes", "node_2", unrelatedNode);
+
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_old",
+ })) as { success: boolean; flagged: { nodes: number; edges: number } };
+
+ expect(result.success).toBe(true);
+ expect(result.flagged.nodes).toBe(1);
+
+ const updated = await kv.get<GraphNode>("mem:graph:nodes", "node_1");
+ expect(updated!.stale).toBe(true);
+
+ const unchanged = await kv.get<GraphNode>("mem:graph:nodes", "node_2");
+ expect(unchanged!.stale).toBeUndefined();
+ });
+
+ it("flags graph edges referencing superseded observation IDs", async () => {
+ const memory: Memory = {
+ id: "mem_old2",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "pattern",
+ title: "Old pattern",
+ content: "Old pattern content",
+ concepts: ["testing"],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: false,
+ sourceObservationIds: ["obs_x"],
+ };
+ await kv.set("mem:memories", "mem_old2", memory);
+
+ const edge: GraphEdge = {
+ id: "edge_1",
+ type: "uses",
+ sourceNodeId: "node_a",
+ targetNodeId: "node_b",
+ weight: 1,
+ sourceObservationIds: ["obs_x", "obs_y"],
+ createdAt: "2026-03-01T00:00:00Z",
+ };
+ await kv.set("mem:graph:edges", "edge_1", edge);
+
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_old2",
+ })) as { success: boolean; flagged: { edges: number } };
+
+ expect(result.success).toBe(true);
+ expect(result.flagged.edges).toBe(1);
+
+ const updated = await kv.get<GraphEdge>("mem:graph:edges", "edge_1");
+ expect(updated!.stale).toBe(true);
+ });
+
+ it("counts sibling memories sharing 2+ concepts", async () => {
+ const superseded: Memory = {
+ id: "mem_superseded",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "architecture",
+ title: "React architecture",
+ content: "Old arch",
+ concepts: ["react", "frontend", "typescript"],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: false,
+ };
+ await kv.set("mem:memories", "mem_superseded", superseded);
+
+ const sibling: Memory = {
+ id: "mem_sibling",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "pattern",
+ title: "React patterns",
+ content: "Sibling memory sharing concepts",
+ concepts: ["react", "typescript"],
+ files: [],
+ sessionIds: [],
+ strength: 6,
+ version: 1,
+ isLatest: true,
+ };
+ await kv.set("mem:memories", "mem_sibling", sibling);
+
+ const unrelated: Memory = {
+ id: "mem_unrelated",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "Python setup",
+ content: "Unrelated memory",
+ concepts: ["python", "backend"],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ };
+ await kv.set("mem:memories", "mem_unrelated", unrelated);
+
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_superseded",
+ })) as { success: boolean; flagged: { siblingMemories: number }; total: number };
+
+ expect(result.success).toBe(true);
+ expect(result.flagged.siblingMemories).toBe(1);
+ expect(result.total).toBeGreaterThanOrEqual(1);
+ });
+
+ it("skips already stale nodes", async () => {
+ const memory: Memory = {
+ id: "mem_skip",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "Skip test",
+ content: "Content",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: false,
+ sourceObservationIds: ["obs_s"],
+ };
+ await kv.set("mem:memories", "mem_skip", memory);
+
+ const node: GraphNode = {
+ id: "node_stale",
+ type: "concept",
+ name: "already stale",
+ properties: {},
+ sourceObservationIds: ["obs_s"],
+ createdAt: "2026-03-01T00:00:00Z",
+ stale: true,
+ };
+ await kv.set("mem:graph:nodes", "node_stale", node);
+
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_skip",
+ })) as { success: boolean; flagged: { nodes: number } };
+
+ expect(result.success).toBe(true);
+ expect(result.flagged.nodes).toBe(0);
+ });
+
+ it("does not flag siblings when fewer than 2 shared concepts", async () => {
+ const memory: Memory = {
+ id: "mem_one_concept",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "One concept",
+ content: "Content",
+ concepts: ["react"],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: false,
+ };
+ await kv.set("mem:memories", "mem_one_concept", memory);
+
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_one_concept",
+ })) as { success: boolean; flagged: { siblingMemories: number } };
+
+ expect(result.success).toBe(true);
+ expect(result.flagged.siblingMemories).toBe(0);
+ });
+
+ it("returns zero counts when no sourceObservationIds and < 2 concepts", async () => {
+ const memory: Memory = {
+ id: "mem_empty",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "Empty refs",
+ content: "No references",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: false,
+ };
+ await kv.set("mem:memories", "mem_empty", memory);
+
+ const result = (await sdk.trigger("mem::cascade-update", {
+ supersededMemoryId: "mem_empty",
+ })) as { success: boolean; total: number };
+
+ expect(result.success).toBe(true);
+ expect(result.total).toBe(0);
+ });
+});
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index fa52102b..11043ae2 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -118,7 +118,7 @@ describe("Export/Import Functions", () => {
it("export produces valid ExportData structure", async () => {
const result = (await sdk.trigger("mem::export", {})) as ExportData;
- expect(result.version).toBe("0.6.0");
+ expect(result.version).toBe("0.6.1");
expect(result.exportedAt).toBeDefined();
expect(result.sessions.length).toBe(1);
expect(result.sessions[0].id).toBe("ses_1");
diff --git a/test/helpers/mocks.ts b/test/helpers/mocks.ts
new file mode 100644
index 00000000..8b5f48cf
--- /dev/null
+++ b/test/helpers/mocks.ts
@@ -0,0 +1,40 @@
+import { vi } from "vitest";
+
+type Handler = (data: unknown) => Promise<unknown>;
+
+export function mockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ get: async <T>(scope: string, key: string): Promise<T | null> => {
+ return (store.get(scope)?.get(key) as T) ?? null;
+ },
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ delete: async (scope: string, key: string): Promise<void> => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const entries = store.get(scope);
+ return entries ? (Array.from(entries.values()) as T[]) : [];
+ },
+ };
+}
+
+export function mockSdk() {
+ const functions = new Map<string, Handler>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Handler) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: vi.fn(),
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ triggerVoid: vi.fn(),
+ };
+}
diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts
index 6afb0f1e..d5a2223e 100644
--- a/test/mcp-standalone.test.ts
+++ b/test/mcp-standalone.test.ts
@@ -22,9 +22,10 @@ import { InMemoryKV } from "../src/mcp/in-memory-kv.js";
import { writeFileSync } from "node:fs";
describe("Tools Registry", () => {
- it("getAllTools returns 37 tools", () => {
+ it("getAllTools returns 38 tools including memory_verify", () => {
const tools = getAllTools();
- expect(tools.length).toBe(37);
+ expect(tools.length).toBe(38);
+ expect(tools.some((t) => t.name === "memory_verify")).toBe(true);
});
it("CORE_TOOLS has 10 items", () => {
diff --git a/test/mesh.test.ts b/test/mesh.test.ts
index 89dd48ee..2f65697b 100644
--- a/test/mesh.test.ts
+++ b/test/mesh.test.ts
@@ -7,7 +7,16 @@ vi.mock("iii-sdk", () => ({
}));
import { registerMeshFunction } from "../src/functions/mesh.js";
-import type { MeshPeer, Memory, Action } from "../src/types.js";
+import type {
+ MeshPeer,
+ Memory,
+ Action,
+ SemanticMemory,
+ ProceduralMemory,
+ MemoryRelation,
+ GraphNode,
+ GraphEdge,
+} from "../src/types.js";
function mockKV() {
const store = new Map<string, Map<string, unknown>>();
@@ -75,14 +84,33 @@ describe("Mesh Functions", () => {
expect(peers.length).toBe(1);
});
- it("uses default sharedScopes when not provided", async () => {
+ it("uses expanded default sharedScopes when not provided", async () => {
const result = (await sdk.trigger("mem::mesh-register", {
url: "https://peer2.example.com",
name: "peer-2",
})) as { success: boolean; peer: MeshPeer };
expect(result.success).toBe(true);
- expect(result.peer.sharedScopes).toEqual(["memories", "actions"]);
+ expect(result.peer.sharedScopes).toEqual([
+ "memories",
+ "actions",
+ "semantic",
+ "procedural",
+ "relations",
+ "graph:nodes",
+ "graph:edges",
+ ]);
+ });
+
+ it("stores syncFilter when provided", async () => {
+ const result = (await sdk.trigger("mem::mesh-register", {
+ url: "https://peer3.example.com",
+ name: "peer-3",
+ syncFilter: { project: "/my/project" },
+ })) as { success: boolean; peer: MeshPeer };
+
+ expect(result.success).toBe(true);
+ expect(result.peer.syncFilter).toEqual({ project: "/my/project" });
});
it("returns error when url is missing", async () => {
@@ -483,4 +511,190 @@ describe("Mesh Functions", () => {
expect(result.success).toBe(true);
});
});
+
+ describe("mesh-receive expanded scopes", () => {
+ it("accepts semantic memories", async () => {
+ const sem: SemanticMemory = {
+ id: "sem_1",
+ fact: "React uses JSX",
+ confidence: 0.9,
+ sourceSessionIds: ["ses_1"],
+ sourceMemoryIds: ["mem_1"],
+ accessCount: 1,
+ lastAccessedAt: "2026-03-01T00:00:00Z",
+ strength: 7,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ semantic: [sem],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+ const stored = await kv.get<SemanticMemory>("mem:semantic", "sem_1");
+ expect(stored).toBeDefined();
+ expect(stored!.fact).toBe("React uses JSX");
+ });
+
+ it("accepts procedural memories", async () => {
+ const proc: ProceduralMemory = {
+ id: "proc_1",
+ name: "Deploy to prod",
+ steps: ["build", "test", "deploy"],
+ triggerCondition: "on merge to main",
+ frequency: 5,
+ sourceSessionIds: ["ses_1"],
+ strength: 8,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ procedural: [proc],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+ const stored = await kv.get<ProceduralMemory>("mem:procedural", "proc_1");
+ expect(stored!.name).toBe("Deploy to prod");
+ });
+
+ it("accepts graph nodes", async () => {
+ const node: GraphNode = {
+ id: "gn_1",
+ type: "concept",
+ name: "typescript",
+ properties: {},
+ sourceObservationIds: ["obs_1"],
+ createdAt: "2026-03-01T00:00:00Z",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ graphNodes: [node],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+ const stored = await kv.get<GraphNode>("mem:graph:nodes", "gn_1");
+ expect(stored!.name).toBe("typescript");
+ });
+
+ it("accepts graph edges", async () => {
+ const edge: GraphEdge = {
+ id: "ge_1",
+ type: "uses",
+ sourceNodeId: "gn_1",
+ targetNodeId: "gn_2",
+ weight: 1,
+ sourceObservationIds: ["obs_1"],
+ createdAt: "2026-03-01T00:00:00Z",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ graphEdges: [edge],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+ const stored = await kv.get<GraphEdge>("mem:graph:edges", "ge_1");
+ expect(stored!.type).toBe("uses");
+ });
+
+ it("accepts relations", async () => {
+ const rel: MemoryRelation = {
+ type: "supersedes",
+ sourceId: "mem_2",
+ targetId: "mem_1",
+ createdAt: "2026-03-01T00:00:00Z",
+ confidence: 0.95,
+ };
+ const relWithId = { ...rel, id: "rel_1" } as MemoryRelation & { id: string };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ relations: [relWithId],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+ });
+
+ it("accepts all scope types in one call", async () => {
+ const mem: Memory = {
+ id: "mem_all",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "All scopes test",
+ content: "Content",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ };
+ const sem: SemanticMemory = {
+ id: "sem_all",
+ fact: "Test",
+ confidence: 0.5,
+ sourceSessionIds: [],
+ sourceMemoryIds: [],
+ accessCount: 0,
+ lastAccessedAt: "2026-03-01T00:00:00Z",
+ strength: 5,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ };
+ const node: GraphNode = {
+ id: "gn_all",
+ type: "file",
+ name: "test.ts",
+ properties: {},
+ sourceObservationIds: [],
+ createdAt: "2026-03-01T00:00:00Z",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [mem],
+ semantic: [sem],
+ graphNodes: [node],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(3);
+ });
+
+ it("applies LWW for semantic memories", async () => {
+ const older: SemanticMemory = {
+ id: "sem_lww",
+ fact: "Old fact",
+ confidence: 0.5,
+ sourceSessionIds: [],
+ sourceMemoryIds: [],
+ accessCount: 1,
+ lastAccessedAt: "2026-03-01T00:00:00Z",
+ strength: 5,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ };
+ await kv.set("mem:semantic", "sem_lww", older);
+
+ const newer: SemanticMemory = {
+ ...older,
+ fact: "New fact",
+ updatedAt: "2026-03-02T00:00:00Z",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ semantic: [newer],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+ const stored = await kv.get<SemanticMemory>("mem:semantic", "sem_lww");
+ expect(stored!.fact).toBe("New fact");
+ });
+ });
});
diff --git a/test/verify.test.ts b/test/verify.test.ts
new file mode 100644
index 00000000..36581e50
--- /dev/null
+++ b/test/verify.test.ts
@@ -0,0 +1,209 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerVerifyFunction } from "../src/functions/verify.js";
+import type { Memory, CompressedObservation, Session } from "../src/types.js";
+import { mockKV, mockSdk } from "./helpers/mocks.js";
+
+describe("Verify Function", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ vi.clearAllMocks();
+ registerVerifyFunction(sdk as never, kv as never);
+ });
+
+ it("returns error when id is missing", async () => {
+ const result = (await sdk.trigger("mem::verify", {})) as {
+ success: boolean;
+ error: string;
+ };
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("id is required");
+ });
+
+ it("returns not found for unknown id", async () => {
+ const result = (await sdk.trigger("mem::verify", {
+ id: "unknown_123",
+ })) as { success: boolean; error: string };
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("not found");
+ });
+
+ it("verifies a memory with citation chain", async () => {
+ const session: Session = {
+ id: "ses_1",
+ project: "/test/project",
+ cwd: "/test",
+ startedAt: "2026-03-01T00:00:00Z",
+ status: "completed",
+ observationCount: 2,
+ };
+ await kv.set("mem:sessions", "ses_1", session);
+
+ const obs: CompressedObservation = {
+ id: "obs_1",
+ sessionId: "ses_1",
+ timestamp: "2026-03-01T00:01:00Z",
+ type: "decision",
+ title: "Chose React over Vue",
+ facts: ["React chosen for ecosystem"],
+ narrative: "Team decided on React",
+ concepts: ["react", "frontend"],
+ files: ["src/App.tsx"],
+ importance: 8,
+ confidence: 0.85,
+ };
+ await kv.set("mem:obs:ses_1", "obs_1", obs);
+
+ const memory: Memory = {
+ id: "mem_1",
+ createdAt: "2026-03-01T00:02:00Z",
+ updatedAt: "2026-03-01T00:02:00Z",
+ type: "architecture",
+ title: "Using React for frontend",
+ content: "The team uses React for the frontend framework",
+ concepts: ["react", "frontend"],
+ files: ["src/App.tsx"],
+ sessionIds: ["ses_1"],
+ strength: 8,
+ version: 1,
+ isLatest: true,
+ sourceObservationIds: ["obs_1"],
+ };
+ await kv.set("mem:memories", "mem_1", memory);
+
+ const result = (await sdk.trigger("mem::verify", { id: "mem_1" })) as {
+ success: boolean;
+ type: string;
+ citations: Array<{
+ observationId: string;
+ confidence: number;
+ sessionProject: string;
+ }>;
+ citationCount: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.type).toBe("memory");
+ expect(result.citationCount).toBe(1);
+ expect(result.citations[0].observationId).toBe("obs_1");
+ expect(result.citations[0].confidence).toBe(0.85);
+ expect(result.citations[0].sessionProject).toBe("/test/project");
+ });
+
+ it("verifies a memory with no source observations", async () => {
+ const memory: Memory = {
+ id: "mem_2",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "API uses REST",
+ content: "The API follows REST conventions",
+ concepts: ["api", "rest"],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ };
+ await kv.set("mem:memories", "mem_2", memory);
+
+ const result = (await sdk.trigger("mem::verify", { id: "mem_2" })) as {
+ success: boolean;
+ type: string;
+ citationCount: number;
+ citations: unknown[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.type).toBe("memory");
+ expect(result.citationCount).toBe(0);
+ expect(result.citations).toEqual([]);
+ });
+
+ it("verifies an observation directly", async () => {
+ const session: Session = {
+ id: "ses_2",
+ project: "/my/project",
+ cwd: "/my",
+ startedAt: "2026-03-01T00:00:00Z",
+ status: "active",
+ observationCount: 1,
+ };
+ await kv.set("mem:sessions", "ses_2", session);
+
+ const obs: CompressedObservation = {
+ id: "obs_direct",
+ sessionId: "ses_2",
+ timestamp: "2026-03-01T00:01:00Z",
+ type: "file_write",
+ title: "Created index.ts",
+ facts: ["Created file"],
+ narrative: "Agent created the index file",
+ concepts: ["typescript"],
+ files: ["index.ts"],
+ importance: 6,
+ confidence: 0.72,
+ };
+ await kv.set("mem:obs:ses_2", "obs_direct", obs);
+
+ const result = (await sdk.trigger("mem::verify", {
+ id: "obs_direct",
+ })) as {
+ success: boolean;
+ type: string;
+ observation: { id: string; confidence: number };
+ session: { project: string };
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.type).toBe("observation");
+ expect(result.observation.id).toBe("obs_direct");
+ expect(result.observation.confidence).toBe(0.72);
+ expect(result.session.project).toBe("/my/project");
+ });
+
+ it("returns memory info with supersede chain", async () => {
+ const memory: Memory = {
+ id: "mem_v2",
+ createdAt: "2026-03-02T00:00:00Z",
+ updatedAt: "2026-03-02T00:00:00Z",
+ type: "pattern",
+ title: "Updated pattern",
+ content: "Updated pattern content",
+ concepts: ["testing"],
+ files: [],
+ sessionIds: [],
+ strength: 9,
+ version: 2,
+ parentId: "mem_v1",
+ supersedes: ["mem_v1"],
+ isLatest: true,
+ };
+ await kv.set("mem:memories", "mem_v2", memory);
+
+ const result = (await sdk.trigger("mem::verify", { id: "mem_v2" })) as {
+ success: boolean;
+ memory: {
+ id: string;
+ version: number;
+ parentId: string;
+ supersedes: string[];
+ };
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.memory.version).toBe(2);
+ expect(result.memory.parentId).toBe("mem_v1");
+ expect(result.memory.supersedes).toEqual(["mem_v1"]);
+ });
+});