Skip to content

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

feat: v0.5.0 orchestration layer — 14 modules, 518 tests (#74)

Rohit Ghumare1ca0ec0414b6
diff --git a/README.md b/README.md
index f4e1a972..920bc429 100644
--- a/README.md
+++ b/README.md
@@ -96,7 +96,7 @@ These agents support hooks natively. agentmemory captures tool usage automatical
### MCP support (any MCP-compatible agent)
-Any agent that connects to MCP servers can use agentmemory's 18 tools, 6 resources, and 3 prompts. The agent actively queries and saves memory through MCP calls.
+Any agent that connects to MCP servers can use agentmemory's 37 tools, 6 resources, and 3 prompts. The agent actively queries and saves memory through MCP calls.
| Agent | How to connect |
|---|---|
@@ -108,7 +108,7 @@ Any agent that connects to MCP servers can use agentmemory's 18 tools, 6 resourc
### REST API (any agent, any language)
-Agents without hooks or MCP can integrate via 49 REST endpoints directly. This works with any agent, language, or framework.
+Agents without hooks or MCP can integrate via 93 REST endpoints directly. This works with any agent, language, or framework.
```bash
POST /agentmemory/observe # Capture what the agent did
@@ -125,8 +125,8 @@ GET /agentmemory/profile # Get project intelligence
|---|---|
| Claude Code user | Plugin install (hooks + MCP + skills) |
| Building a custom agent with Claude SDK | AgentSDKProvider (zero config) |
-| Using Cursor, Windsurf, or any MCP client | MCP server (18 tools + 6 resources + 3 prompts) |
-| Building your own agent framework | REST API (49 endpoints) |
+| Using Cursor, Windsurf, or any MCP client | MCP server (37 tools + 6 resources + 3 prompts) |
+| Building your own agent framework | REST API (93 endpoints) |
| Sharing memory across multiple agents | All agents point to the same iii-engine instance |
## Quick Start
@@ -163,7 +163,7 @@ open http://localhost:3113
{
"status": "healthy",
"service": "agentmemory",
- "version": "0.4.0",
+ "version": "0.5.0",
"health": {
"memory": { "heapUsed": 42000000, "heapTotal": 67000000 },
"cpu": { "percent": 2.1 },
@@ -377,7 +377,7 @@ Collects every 30 seconds: heap usage, CPU percentage (delta sampling), event lo
## MCP Server
-### Tools (18)
+### Tools (37)
| Tool | Description |
|------|-------------|
@@ -399,6 +399,25 @@ Collects every 30 seconds: heap usage, CPU percentage (delta sampling), event lo
| `memory_audit` | View the audit trail of memory operations |
| `memory_governance_delete` | Delete specific memories with audit trail |
| `memory_snapshot_create` | Create a git-versioned snapshot of memory state |
+| `memory_action_create` | Create actionable work items with typed dependencies |
+| `memory_action_update` | Update action status, priority, or details |
+| `memory_frontier` | Get unblocked actions ranked by priority and urgency |
+| `memory_next` | Get the single most important next action |
+| `memory_lease` | Acquire, release, or renew exclusive action leases |
+| `memory_routine_run` | Instantiate a frozen workflow routine into action chains |
+| `memory_signal_send` | Send threaded messages between agents |
+| `memory_signal_read` | Read messages for an agent with read receipts |
+| `memory_checkpoint` | Create or resolve external condition gates (CI, approval, deploy) |
+| `memory_mesh_sync` | Sync memories and actions with peer instances |
+| `memory_sentinel_create` | Create event-driven condition watchers |
+| `memory_sentinel_trigger` | Externally fire a sentinel to unblock gated actions |
+| `memory_sketch_create` | Create ephemeral action graphs for exploratory work |
+| `memory_sketch_promote` | Promote sketch actions to permanent actions |
+| `memory_crystallize` | LLM-powered compaction of completed action chains |
+| `memory_diagnose` | Health checks across all subsystems |
+| `memory_heal` | Auto-fix stuck, orphaned, and inconsistent state |
+| `memory_facet_tag` | Attach structured dimension:value tags to targets |
+| `memory_facet_query` | Query targets by facet tags with AND/OR logic |
### Resources (6)
@@ -527,28 +546,28 @@ ANTHROPIC_API_KEY=sk-ant-...
# TOKEN_BUDGET=2000
# MAX_OBS_PER_SESSION=500
-# Claude Code Memory Bridge (v0.4.0)
+# Claude Code Memory Bridge (v0.5.0)
# CLAUDE_MEMORY_BRIDGE=false
# CLAUDE_MEMORY_LINE_BUDGET=200
-# Standalone MCP Server (v0.4.0)
+# Standalone MCP Server (v0.5.0)
# STANDALONE_MCP=false
# STANDALONE_PERSIST_PATH=~/.agentmemory/standalone.json
-# Knowledge Graph (v0.4.0)
+# Knowledge Graph (v0.5.0)
# GRAPH_EXTRACTION_ENABLED=false
# GRAPH_EXTRACTION_BATCH_SIZE=10
-# Consolidation Pipeline (v0.4.0)
+# Consolidation Pipeline (v0.5.0)
# CONSOLIDATION_ENABLED=false
# CONSOLIDATION_DECAY_DAYS=30
-# Team Memory (v0.4.0)
+# Team Memory (v0.5.0)
# TEAM_ID=
# USER_ID=
# TEAM_MODE=private
-# Git Snapshots (v0.4.0)
+# Git Snapshots (v0.5.0)
# SNAPSHOT_ENABLED=false
# SNAPSHOT_INTERVAL=3600
# SNAPSHOT_DIR=~/.agentmemory/snapshots
@@ -556,7 +575,7 @@ ANTHROPIC_API_KEY=sk-ant-...
## API
-49 endpoints on port `3111` (43 core + 6 MCP protocol). Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set.
+93 endpoints on port `3111` (87 core + 6 MCP protocol). Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set. The table below shows a representative subset; see `src/api.ts` for the full endpoint list.
| Method | Path | Description |
|--------|------|-------------|
@@ -619,7 +638,7 @@ ANTHROPIC_API_KEY=sk-ant-...
/plugin install agentmemory
```
-Restart Claude Code. All 12 hooks, 4 skills, and 18 MCP tools are registered automatically.
+Restart Claude Code. All 12 hooks, 4 skills, and 37 MCP tools are registered automatically.
### Plugin Commands
@@ -643,9 +662,9 @@ agentmemory is built on iii-engine's three primitives:
| Prometheus / Grafana | iii OTEL + built-in health monitor |
| Redis (circuit breaker) | In-process circuit breaker + fallback chain |
-**87 source files. ~11,300 LOC. 216 tests. 232KB bundled (218KB main + 14KB standalone).**
+**101 source files. ~15,000 LOC. 518 tests. 365KB bundled.**
-### Functions (33)
+### Functions (50)
| Function | Purpose |
|----------|---------|
@@ -670,7 +689,7 @@ agentmemory is built on iii-engine's three primitives:
| `mem::profile` | Aggregate project profile |
| `mem::auto-forget` | TTL expiry + contradiction detection |
| `mem::enrich` | Unified enrichment (file context + observations + bug memories) |
-| `mem::export` / `mem::import` | Full JSON round-trip (v0.3.0 + v0.4.0 formats) |
+| `mem::export` / `mem::import` | Full JSON round-trip (v0.3.0 + v0.4.0 + v0.5.0 formats) |
| `mem::claude-bridge-read` | Read Claude Code native MEMORY.md |
| `mem::claude-bridge-sync` | Sync top memories back to MEMORY.md |
| `mem::graph-extract` | LLM-powered entity extraction from observations |
@@ -685,8 +704,22 @@ agentmemory is built on iii-engine's three primitives:
| `mem::snapshot-create` | Git commit memory state |
| `mem::snapshot-list` | List all snapshots |
| `mem::snapshot-restore` | Restore memory from snapshot commit |
-
-### Data Model (21 KV scopes)
+| `mem::action-create` / `action-update` | Dependency-aware work items with typed edges |
+| `mem::frontier` / `mem::next` | Priority-ranked unblocked action queue |
+| `mem::lease-acquire` / `release` / `renew` | TTL-based atomic agent claims |
+| `mem::routine-create` / `run` / `status` | Frozen workflow templates instantiated into action chains |
+| `mem::signal-send` / `read` / `threads` | Threaded inter-agent messaging with read receipts |
+| `mem::checkpoint-create` / `resolve` | External condition gates (CI, approval, deploy) |
+| `mem::flow-compress` | LLM-powered summarization of completed action chains |
+| `mem::mesh-register` / `sync` / `receive` | P2P sync between agentmemory instances |
+| `mem::detect-worktree` / `branch-sessions` | Git worktree detection for shared memory |
+| `mem::sentinel-create` / `trigger` / `check` | Event-driven condition watchers (webhook, timer, threshold, pattern, approval) |
+| `mem::sketch-create` / `add` / `promote` / `discard` | Ephemeral action graphs for exploratory work with auto-expiry |
+| `mem::crystallize` / `auto-crystallize` | LLM-powered compaction of completed action chains into crystal digests |
+| `mem::diagnose` / `heal` | Self-diagnosis across 8 categories with auto-fix for stuck/orphaned/stale state |
+| `mem::facet-tag` / `query` / `stats` | Multi-dimensional tagging with AND/OR queries on actions, memories, observations |
+
+### Data Model (33 KV scopes)
| Scope | Stores |
|-------|--------|
@@ -711,13 +744,25 @@ agentmemory is built on iii-engine's three primitives:
| `mem:team:{id}:users:{uid}` | Per-user team state |
| `mem:team:{id}:profile` | Aggregated team profile |
| `mem:audit` | Audit trail for all operations |
+| `mem:actions` | Dependency-aware work items |
+| `mem:action-edges` | Typed edges (requires, unlocks, gated_by, etc.) |
+| `mem:leases` | TTL-based agent work claims |
+| `mem:routines` | Frozen workflow templates |
+| `mem:routine-runs` | Instantiated routine execution tracking |
+| `mem:signals` | Inter-agent messages with threading |
+| `mem:checkpoints` | External condition gates |
+| `mem:mesh` | Registered P2P sync peers |
+| `mem:sentinels` | Event-driven condition watchers |
+| `mem:sketches` | Ephemeral action graphs |
+| `mem:crystals` | Compacted action chain digests |
+| `mem:facets` | Multi-dimensional tags |
## Development
```bash
npm run dev # Hot reload
-npm run build # Production build (208KB)
-npm test # Unit tests (216 tests, ~1s)
+npm run build # Production build (365KB)
+npm test # Unit tests (518 tests, ~1s)
npm run test:integration # API tests (requires running services)
```
diff --git a/package.json b/package.json
index 25ccaa45..f4f2bd95 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "agentmemory",
- "version": "0.4.0",
+ "version": "0.5.0",
"description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives",
"type": "module",
"main": "dist/index.mjs",
diff --git a/src/functions/actions.ts b/src/functions/actions.ts
new file mode 100644
index 00000000..54a6f3b7
--- /dev/null
+++ b/src/functions/actions.ts
@@ -0,0 +1,288 @@
+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 { Action, ActionEdge } from "../types.js";
+
+export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::action-create" },
+ async (data: {
+ title: string;
+ description?: string;
+ priority?: number;
+ createdBy?: string;
+ project?: string;
+ tags?: string[];
+ parentId?: string;
+ sourceObservationIds?: string[];
+ sourceMemoryIds?: string[];
+ edges?: Array<{ type: string; targetActionId: string }>;
+ }) => {
+ if (!data.title || typeof data.title !== "string") {
+ return { success: false, error: "title is required" };
+ }
+
+ return withKeyedLock("mem:actions", async () => {
+ const now = new Date().toISOString();
+ const action: Action = {
+ id: generateId("act"),
+ title: data.title.trim(),
+ description: (data.description || "").trim(),
+ status: "pending",
+ priority: Math.max(1, Math.min(10, data.priority || 5)),
+ createdAt: now,
+ updatedAt: now,
+ createdBy: data.createdBy || "unknown",
+ project: data.project,
+ tags: data.tags || [],
+ sourceObservationIds: data.sourceObservationIds || [],
+ sourceMemoryIds: data.sourceMemoryIds || [],
+ parentId: data.parentId,
+ };
+
+ if (data.parentId) {
+ const parent = await kv.get<Action>(KV.actions, data.parentId);
+ if (!parent) {
+ return { success: false, error: "parent action not found" };
+ }
+ }
+
+ const validEdgeTypes = [
+ "requires",
+ "unlocks",
+ "spawned_by",
+ "gated_by",
+ "conflicts_with",
+ ];
+ const pendingEdges: ActionEdge[] = [];
+ let hasRequires = false;
+ if (data.edges && Array.isArray(data.edges)) {
+ for (const e of data.edges) {
+ if (!validEdgeTypes.includes(e.type)) {
+ return { success: false, error: `invalid edge type: ${e.type}` };
+ }
+ const targetAction = await kv.get<Action>(KV.actions, e.targetActionId);
+ if (!targetAction) {
+ return { success: false, error: `target action not found: ${e.targetActionId}` };
+ }
+ if (e.type === "requires") hasRequires = true;
+ pendingEdges.push({
+ id: generateId("ae"),
+ type: e.type as ActionEdge["type"],
+ sourceActionId: action.id,
+ targetActionId: e.targetActionId,
+ createdAt: now,
+ });
+ }
+ }
+
+ if (hasRequires) {
+ action.status = "blocked";
+ }
+
+ await kv.set(KV.actions, action.id, action);
+
+ for (const edge of pendingEdges) {
+ await kv.set(KV.actionEdges, edge.id, edge);
+ }
+
+ return { success: true, action, edges: pendingEdges };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::action-update" },
+ async (data: {
+ actionId: string;
+ status?: Action["status"];
+ title?: string;
+ description?: string;
+ priority?: number;
+ assignedTo?: string;
+ result?: string;
+ tags?: string[];
+ }) => {
+ if (!data.actionId) {
+ return { success: false, error: "actionId is required" };
+ }
+
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
+ const action = await kv.get<Action>(KV.actions, data.actionId);
+ if (!action) {
+ return { success: false, error: "action not found" };
+ }
+
+ if (data.status !== undefined) action.status = data.status;
+ if (data.title !== undefined) action.title = data.title.trim();
+ if (data.description !== undefined)
+ action.description = data.description.trim();
+ if (data.priority !== undefined)
+ action.priority = Math.max(1, Math.min(10, data.priority));
+ if (data.assignedTo !== undefined) action.assignedTo = data.assignedTo;
+ if (data.result !== undefined) action.result = data.result;
+ if (data.tags !== undefined) action.tags = data.tags;
+ action.updatedAt = new Date().toISOString();
+
+ await kv.set(KV.actions, action.id, action);
+
+ if (data.status === "done") {
+ await propagateCompletion(kv, action.id);
+ }
+
+ return { success: true, action };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::action-edge-create" },
+ async (data: {
+ sourceActionId: string;
+ targetActionId: string;
+ type: string;
+ metadata?: Record<string, unknown>;
+ }) => {
+ if (!data.sourceActionId || !data.targetActionId || !data.type) {
+ return {
+ success: false,
+ error: "sourceActionId, targetActionId, and type are required",
+ };
+ }
+
+ const validTypes = [
+ "requires",
+ "unlocks",
+ "spawned_by",
+ "gated_by",
+ "conflicts_with",
+ ];
+ if (!validTypes.includes(data.type)) {
+ return {
+ success: false,
+ error: `type must be one of: ${validTypes.join(", ")}`,
+ };
+ }
+
+ const sourceAction = await kv.get<Action>(KV.actions, data.sourceActionId);
+ if (!sourceAction) {
+ return { success: false, error: "source action not found" };
+ }
+ const targetAction = await kv.get<Action>(KV.actions, data.targetActionId);
+ if (!targetAction) {
+ return { success: false, error: "target action not found" };
+ }
+
+ const edge: ActionEdge = {
+ id: generateId("ae"),
+ type: data.type as ActionEdge["type"],
+ sourceActionId: data.sourceActionId,
+ targetActionId: data.targetActionId,
+ createdAt: new Date().toISOString(),
+ metadata: data.metadata,
+ };
+
+ await kv.set(KV.actionEdges, edge.id, edge);
+ return { success: true, edge };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::action-list" },
+ async (data: {
+ status?: string;
+ project?: string;
+ parentId?: string;
+ tags?: string[];
+ limit?: number;
+ }) => {
+ let actions = await kv.list<Action>(KV.actions);
+
+ if (data.status) {
+ actions = actions.filter((a) => a.status === data.status);
+ }
+ if (data.project) {
+ actions = actions.filter((a) => a.project === data.project);
+ }
+ if (data.parentId) {
+ actions = actions.filter((a) => a.parentId === data.parentId);
+ }
+ if (data.tags && data.tags.length > 0) {
+ actions = actions.filter((a) =>
+ data.tags!.some((t) => a.tags.includes(t)),
+ );
+ }
+
+ actions.sort(
+ (a, b) =>
+ new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
+ );
+
+ const limit = data.limit || 50;
+ return { success: true, actions: actions.slice(0, limit) };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::action-get" },
+ async (data: { actionId: string }) => {
+ if (!data.actionId) {
+ return { success: false, error: "actionId is required" };
+ }
+ const action = await kv.get<Action>(KV.actions, data.actionId);
+ if (!action) {
+ return { success: false, error: "action not found" };
+ }
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const edges = allEdges.filter(
+ (e) =>
+ e.sourceActionId === data.actionId ||
+ e.targetActionId === data.actionId,
+ );
+
+ const children = (await kv.list<Action>(KV.actions)).filter(
+ (a) => a.parentId === data.actionId,
+ );
+
+ return { success: true, action, edges, children };
+ },
+ );
+}
+
+async function propagateCompletion(
+ kv: StateKV,
+ completedActionId: string,
+): Promise<void> {
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const unlockEdges = allEdges.filter(
+ (e) =>
+ e.targetActionId === completedActionId &&
+ (e.type === "requires" || e.type === "unlocks"),
+ );
+
+ const allActions = await kv.list<Action>(KV.actions);
+ const actionMap = new Map(allActions.map((a) => [a.id, a]));
+
+ for (const edge of unlockEdges) {
+ const candidateId = edge.sourceActionId;
+ await withKeyedLock(`mem:action:${candidateId}`, async () => {
+ const action = await kv.get<Action>(KV.actions, candidateId);
+ if (action && action.status === "blocked") {
+ const deps = allEdges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "requires",
+ );
+ const allDone = deps.every((d) => {
+ const target = actionMap.get(d.targetActionId);
+ return target && target.status === "done";
+ });
+ if (allDone) {
+ action.status = "pending";
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ }
+ }
+ });
+ }
+}
diff --git a/src/functions/branch-aware.ts b/src/functions/branch-aware.ts
new file mode 100644
index 00000000..35e86f26
--- /dev/null
+++ b/src/functions/branch-aware.ts
@@ -0,0 +1,169 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type { Session } from "../types.js";
+import { execFile } from "node:child_process";
+import { resolve } from "node:path";
+
+function execAsync(
+ cmd: string,
+ args: string[],
+ cwd: string,
+): Promise<string> {
+ return new Promise((resolve, reject) => {
+ execFile(cmd, args, { cwd, timeout: 5000 }, (err, stdout) => {
+ if (err) reject(err);
+ else resolve(stdout.trim());
+ });
+ });
+}
+
+export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::detect-worktree" },
+ async (data: { cwd: string }) => {
+ if (!data.cwd) {
+ return { success: false, error: "cwd is required" };
+ }
+
+ try {
+ const gitDir = await execAsync(
+ "git",
+ ["rev-parse", "--git-dir"],
+ data.cwd,
+ );
+ const commonDir = await execAsync(
+ "git",
+ ["rev-parse", "--git-common-dir"],
+ data.cwd,
+ );
+ const branch = await execAsync(
+ "git",
+ ["rev-parse", "--abbrev-ref", "HEAD"],
+ data.cwd,
+ ).catch(() => "detached");
+
+ const topLevel = await execAsync(
+ "git",
+ ["rev-parse", "--show-toplevel"],
+ data.cwd,
+ );
+
+ const isWorktree = resolve(data.cwd, gitDir) !== resolve(data.cwd, commonDir);
+ const mainRepoRoot = isWorktree
+ ? resolve(data.cwd, commonDir, "..")
+ : topLevel;
+
+ return {
+ success: true,
+ isWorktree,
+ branch,
+ topLevel,
+ mainRepoRoot,
+ gitDir: resolve(data.cwd, gitDir),
+ commonDir: resolve(data.cwd, commonDir),
+ };
+ } catch {
+ return {
+ success: true,
+ isWorktree: false,
+ branch: null,
+ topLevel: data.cwd,
+ mainRepoRoot: data.cwd,
+ gitDir: null,
+ commonDir: null,
+ };
+ }
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::list-worktrees" },
+ async (data: { cwd: string }) => {
+ if (!data.cwd) {
+ return { success: false, error: "cwd is required" };
+ }
+
+ try {
+ const output = await execAsync(
+ "git",
+ ["worktree", "list", "--porcelain"],
+ data.cwd,
+ );
+
+ const worktrees: Array<{
+ path: string;
+ head: string;
+ branch: string;
+ bare: boolean;
+ }> = [];
+
+ const blocks = output.split("\n\n").filter(Boolean);
+ for (const block of blocks) {
+ const lines = block.split("\n");
+ const wt: { path: string; head: string; branch: string; bare: boolean } = {
+ path: "",
+ head: "",
+ branch: "",
+ bare: false,
+ };
+ for (const line of lines) {
+ if (line.startsWith("worktree ")) wt.path = line.slice(9);
+ else if (line.startsWith("HEAD ")) wt.head = line.slice(5);
+ else if (line.startsWith("branch "))
+ wt.branch = line.slice(7).replace("refs/heads/", "");
+ else if (line === "bare") wt.bare = true;
+ }
+ if (wt.path) worktrees.push(wt);
+ }
+
+ return { success: true, worktrees };
+ } catch {
+ return { success: true, worktrees: [] };
+ }
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::branch-sessions" },
+ async (data: { cwd: string; branch?: string }) => {
+ if (!data.cwd) {
+ return { success: false, error: "cwd is required" };
+ }
+
+ const worktreeInfo = await sdk.trigger<
+ { cwd: string },
+ {
+ success: boolean;
+ isWorktree: boolean;
+ mainRepoRoot: string;
+ branch: string | null;
+ }
+ >("mem::detect-worktree", { cwd: data.cwd });
+
+ const projectRoot = worktreeInfo.mainRepoRoot || data.cwd;
+ const branch = data.branch || worktreeInfo.branch;
+
+ const sessions = await kv.list<Session>(KV.sessions);
+
+ const matching = sessions.filter((s) => {
+ if (s.project === projectRoot || s.cwd === projectRoot) return true;
+ if (s.cwd.startsWith(projectRoot + "/")) return true;
+ return false;
+ });
+
+ matching.sort(
+ (a, b) =>
+ new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),
+ );
+
+ return {
+ success: true,
+ sessions: matching,
+ projectRoot,
+ branch,
+ isWorktree: worktreeInfo.isWorktree,
+ };
+ },
+ );
+}
diff --git a/src/functions/checkpoints.ts b/src/functions/checkpoints.ts
new file mode 100644
index 00000000..1d3759c5
--- /dev/null
+++ b/src/functions/checkpoints.ts
@@ -0,0 +1,209 @@
+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 { Action, ActionEdge, Checkpoint } from "../types.js";
+
+export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::checkpoint-create" },
+ async (data: {
+ name: string;
+ description?: string;
+ type?: Checkpoint["type"];
+ linkedActionIds?: string[];
+ expiresInMs?: number;
+ }) => {
+ if (!data.name) {
+ return { success: false, error: "name is required" };
+ }
+
+ const validTypes: Checkpoint["type"][] = ["ci", "approval", "deploy", "external", "timer"];
+ if (data.type && !validTypes.includes(data.type)) {
+ return { success: false, error: `invalid checkpoint type: ${data.type}. Must be one of: ${validTypes.join(", ")}` };
+ }
+
+ const now = new Date();
+ const checkpoint: Checkpoint = {
+ id: generateId("ckpt"),
+ name: data.name.trim(),
+ description: (data.description || "").trim(),
+ status: "pending",
+ type: data.type || "external",
+ createdAt: now.toISOString(),
+ linkedActionIds: data.linkedActionIds || [],
+ expiresAt: data.expiresInMs
+ ? new Date(now.getTime() + data.expiresInMs).toISOString()
+ : undefined,
+ };
+
+ if (data.linkedActionIds && data.linkedActionIds.length > 0) {
+ for (const actionId of data.linkedActionIds) {
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (!action) {
+ return { success: false, error: `linked action not found: ${actionId}` };
+ }
+ }
+ }
+
+ await kv.set(KV.checkpoints, checkpoint.id, checkpoint);
+
+ if (data.linkedActionIds && data.linkedActionIds.length > 0) {
+ for (const actionId of data.linkedActionIds) {
+ const edge: ActionEdge = {
+ id: generateId("ae"),
+ type: "gated_by",
+ sourceActionId: actionId,
+ targetActionId: checkpoint.id,
+ createdAt: now.toISOString(),
+ };
+ await kv.set(KV.actionEdges, edge.id, edge);
+
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (action && action.status === "pending") {
+ action.status = "blocked";
+ action.updatedAt = now.toISOString();
+ await kv.set(KV.actions, action.id, action);
+ }
+ }
+ }
+
+ return { success: true, checkpoint };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::checkpoint-resolve" },
+ async (data: {
+ checkpointId: string;
+ status: "passed" | "failed";
+ resolvedBy?: string;
+ result?: unknown;
+ }) => {
+ if (!data.checkpointId || !data.status) {
+ return {
+ success: false,
+ error: "checkpointId and status are required",
+ };
+ }
+
+ return withKeyedLock(
+ `mem:checkpoint:${data.checkpointId}`,
+ async () => {
+ const checkpoint = await kv.get<Checkpoint>(
+ KV.checkpoints,
+ data.checkpointId,
+ );
+ if (!checkpoint) {
+ return { success: false, error: "checkpoint not found" };
+ }
+ if (checkpoint.status !== "pending") {
+ return {
+ success: false,
+ error: `checkpoint already ${checkpoint.status}`,
+ };
+ }
+
+ checkpoint.status = data.status;
+ checkpoint.resolvedAt = new Date().toISOString();
+ checkpoint.resolvedBy = data.resolvedBy;
+ checkpoint.result = data.result;
+
+ await kv.set(KV.checkpoints, checkpoint.id, checkpoint);
+
+ let unblockedCount = 0;
+ if (data.status === "passed" && checkpoint.linkedActionIds.length > 0) {
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const allCheckpoints = await kv.list<Checkpoint>(KV.checkpoints);
+ const cpMap = new Map(allCheckpoints.map((c) => [c.id, c]));
+
+ for (const actionId of checkpoint.linkedActionIds) {
+ await withKeyedLock(`mem:action:${actionId}`, async () => {
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (action && action.status === "blocked") {
+ const gates = allEdges.filter(
+ (e) => e.sourceActionId === actionId && e.type === "gated_by",
+ );
+ const allGatesPassed = gates.every((g) => {
+ const cp = cpMap.get(g.targetActionId);
+ return cp && cp.status === "passed";
+ });
+ const requires = allEdges.filter(
+ (e) => e.sourceActionId === actionId && e.type === "requires",
+ );
+ const allActions = await kv.list<Action>(KV.actions);
+ const actionMap = new Map(allActions.map((a) => [a.id, a]));
+ const allRequiresMet = requires.every((r) => {
+ const dep = actionMap.get(r.targetActionId);
+ return dep && dep.status === "done";
+ });
+ if (allGatesPassed && allRequiresMet) {
+ action.status = "pending";
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ unblockedCount++;
+ }
+ }
+ });
+ }
+ }
+
+ return { success: true, checkpoint, unblockedCount };
+ },
+ );
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::checkpoint-list" },
+ async (data: { status?: string; type?: string }) => {
+ let checkpoints = await kv.list<Checkpoint>(KV.checkpoints);
+
+ if (data.status) {
+ checkpoints = checkpoints.filter((c) => c.status === data.status);
+ }
+ if (data.type) {
+ checkpoints = checkpoints.filter((c) => c.type === data.type);
+ }
+
+ checkpoints.sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ );
+
+ return { success: true, checkpoints };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::checkpoint-expire" },
+ async () => {
+ const checkpoints = await kv.list<Checkpoint>(KV.checkpoints);
+ const now = Date.now();
+ let expired = 0;
+
+ for (const cp of checkpoints) {
+ if (
+ cp.status === "pending" &&
+ cp.expiresAt &&
+ new Date(cp.expiresAt).getTime() <= now
+ ) {
+ const didExpire = await withKeyedLock(
+ `mem:checkpoint:${cp.id}`,
+ async () => {
+ const fresh = await kv.get<Checkpoint>(KV.checkpoints, cp.id);
+ if (!fresh || fresh.status !== "pending") return false;
+ fresh.status = "expired";
+ fresh.resolvedAt = new Date().toISOString();
+ await kv.set(KV.checkpoints, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didExpire) expired++;
+ }
+ }
+
+ return { success: true, expired };
+ },
+ );
+}
diff --git a/src/functions/crystallize.ts b/src/functions/crystallize.ts
new file mode 100644
index 00000000..b0bea552
--- /dev/null
+++ b/src/functions/crystallize.ts
@@ -0,0 +1,279 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV, generateId } from "../state/schema.js";
+import type { Action, ActionEdge, Crystal, MemoryProvider } from "../types.js";
+
+interface CrystalDigest {
+ narrative: string;
+ keyOutcomes: string[];
+ filesAffected: string[];
+ lessons: string[];
+}
+
+const CRYSTALLIZE_SYSTEM = `You are summarizing a completed chain of agent actions into a compact digest.
+Extract: (1) what was accomplished in 1-2 sentences, (2) key decisions as bullet points,
+(3) files affected, (4) any lessons or patterns worth remembering.
+Return as JSON: { "narrative": "...", "keyOutcomes": ["..."], "filesAffected": ["..."], "lessons": ["..."] }`;
+
+export function registerCrystallizeFunction(
+ sdk: ISdk,
+ kv: StateKV,
+ provider: MemoryProvider,
+): void {
+ sdk.registerFunction(
+ { id: "mem::crystallize" },
+ async (data: {
+ actionIds: string[];
+ sessionId?: string;
+ project?: string;
+ }) => {
+ if (!data.actionIds || data.actionIds.length === 0) {
+ return { success: false, error: "actionIds is required" };
+ }
+
+ const actions: Action[] = [];
+ for (const id of data.actionIds) {
+ const action = await kv.get<Action>(KV.actions, id);
+ if (!action) {
+ return { success: false, error: `action not found: ${id}` };
+ }
+ if (action.status !== "done" && action.status !== "cancelled") {
+ return {
+ success: false,
+ error: `action ${id} has status "${action.status}", expected "done" or "cancelled"`,
+ };
+ }
+ actions.push(action);
+ }
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const idSet = new Set(data.actionIds);
+ const relevantEdges = allEdges.filter(
+ (e) => idSet.has(e.sourceActionId) || idSet.has(e.targetActionId),
+ );
+
+ const prompt = buildChainText(actions, relevantEdges);
+
+ try {
+ const response = await provider.summarize(CRYSTALLIZE_SYSTEM, prompt);
+ const digest = parseDigest(response);
+
+ const crystal: Crystal = {
+ id: generateId("crys"),
+ narrative: digest.narrative,
+ keyOutcomes: digest.keyOutcomes,
+ filesAffected: digest.filesAffected,
+ lessons: digest.lessons,
+ sourceActionIds: data.actionIds,
+ sessionId: data.sessionId,
+ project: data.project,
+ createdAt: new Date().toISOString(),
+ };
+
+ await kv.set(KV.crystals, crystal.id, crystal);
+
+ for (const action of actions) {
+ const updated = { ...action, crystallizedInto: crystal.id };
+ await kv.set(KV.actions, action.id, updated);
+ }
+
+ return { success: true, crystal };
+ } catch (err) {
+ return {
+ success: false,
+ error: `crystallization failed: ${String(err)}`,
+ };
+ }
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::crystal-list" },
+ async (data: {
+ project?: string;
+ sessionId?: string;
+ limit?: number;
+ }) => {
+ const limit = data.limit ?? 20;
+ let crystals = await kv.list<Crystal>(KV.crystals);
+
+ if (data.project) {
+ crystals = crystals.filter((c) => c.project === data.project);
+ }
+ if (data.sessionId) {
+ crystals = crystals.filter((c) => c.sessionId === data.sessionId);
+ }
+
+ crystals.sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ );
+
+ return { success: true, crystals: crystals.slice(0, limit) };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::crystal-get" },
+ async (data: { crystalId: string }) => {
+ if (!data.crystalId) {
+ return { success: false, error: "crystalId is required" };
+ }
+
+ const crystal = await kv.get<Crystal>(KV.crystals, data.crystalId);
+ if (!crystal) {
+ return { success: false, error: "crystal not found" };
+ }
+
+ return { success: true, crystal };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::auto-crystallize" },
+ async (data: {
+ olderThanDays?: number;
+ project?: string;
+ dryRun?: boolean;
+ }) => {
+ const olderThanDays = data.olderThanDays ?? 7;
+ const dryRun = data.dryRun ?? false;
+ const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
+
+ let allActions = await kv.list<CrystallizableAction>(KV.actions);
+
+ allActions = allActions.filter(
+ (a) =>
+ a.status === "done" &&
+ !a.crystallizedInto &&
+ new Date(a.createdAt).getTime() < cutoff,
+ );
+
+ if (data.project) {
+ allActions = allActions.filter((a) => a.project === data.project);
+ }
+
+ if (allActions.length === 0) {
+ return { success: true, groupCount: 0, crystalIds: [] };
+ }
+
+ const groups = new Map<string, Action[]>();
+ for (const action of allActions) {
+ const key = action.parentId ?? action.project ?? "_ungrouped";
+ const group = groups.get(key);
+ if (group) {
+ group.push(action);
+ } else {
+ groups.set(key, [action]);
+ }
+ }
+
+ if (dryRun) {
+ const groupSummaries = Array.from(groups.entries()).map(
+ ([key, actions]) => ({
+ groupKey: key,
+ actionCount: actions.length,
+ actionIds: actions.map((a) => a.id),
+ }),
+ );
+ return {
+ success: true,
+ dryRun: true,
+ groupCount: groups.size,
+ groups: groupSummaries,
+ crystalIds: [],
+ };
+ }
+
+ const crystalIds: string[] = [];
+ for (const [, groupActions] of groups) {
+ const actionIds = groupActions.map((a) => a.id);
+ const project = groupActions[0].project;
+
+ try {
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds,
+ project,
+ })) as { success: boolean; crystal?: Crystal };
+
+ if (result.success && result.crystal) {
+ crystalIds.push(result.crystal.id);
+ }
+ } catch {
+ continue;
+ }
+ }
+
+ return {
+ success: true,
+ groupCount: groups.size,
+ crystalIds,
+ };
+ },
+ );
+}
+
+function buildChainText(actions: Action[], edges: ActionEdge[]): string {
+ const lines: string[] = ["## Completed Action Chain\n"];
+
+ const sorted = [...actions].sort(
+ (a, b) =>
+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
+ );
+
+ for (const action of sorted) {
+ lines.push(`### ${action.title}`);
+ if (action.description) lines.push(action.description);
+ if (action.result) lines.push(`Result: ${action.result}`);
+ lines.push(
+ `Tags: ${(action.tags ?? []).join(", ")}`,
+ );
+ lines.push("");
+ }
+
+ if (edges.length > 0) {
+ lines.push("## Dependencies");
+ for (const edge of edges) {
+ lines.push(
+ `- ${edge.sourceActionId} --${edge.type}--> ${edge.targetActionId}`,
+ );
+ }
+ }
+
+ return lines.join("\n");
+}
+
+function parseDigest(response: string): CrystalDigest {
+ try {
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
+ if (!jsonMatch) {
+ return {
+ narrative: response,
+ keyOutcomes: [],
+ filesAffected: [],
+ lessons: [],
+ };
+ }
+ const parsed = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
+ return {
+ narrative:
+ typeof parsed.narrative === "string" ? parsed.narrative : response,
+ keyOutcomes: Array.isArray(parsed.keyOutcomes)
+ ? (parsed.keyOutcomes as string[])
+ : [],
+ filesAffected: Array.isArray(parsed.filesAffected)
+ ? (parsed.filesAffected as string[])
+ : [],
+ lessons: Array.isArray(parsed.lessons)
+ ? (parsed.lessons as string[])
+ : [],
+ };
+ } catch {
+ return {
+ narrative: response,
+ keyOutcomes: [],
+ filesAffected: [],
+ lessons: [],
+ };
+ }
+}
diff --git a/src/functions/diagnostics.ts b/src/functions/diagnostics.ts
new file mode 100644
index 00000000..9d298bc7
--- /dev/null
+++ b/src/functions/diagnostics.ts
@@ -0,0 +1,785 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import { withKeyedLock } from "../state/keyed-mutex.js";
+import type {
+ Action,
+ ActionEdge,
+ DiagnosticCheck,
+ Lease,
+ Checkpoint,
+ Signal,
+ Sentinel,
+ Sketch,
+ MeshPeer,
+ Session,
+ Memory,
+} from "../types.js";
+
+const ALL_CATEGORIES = [
+ "actions",
+ "leases",
+ "sentinels",
+ "sketches",
+ "signals",
+ "sessions",
+ "memories",
+ "mesh",
+];
+
+const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
+const ONE_HOUR_MS = 60 * 60 * 1000;
+
+export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::diagnose" },
+ async (data: { categories?: string[] }) => {
+ const categories = data.categories && data.categories.length > 0
+ ? data.categories.filter((c) => ALL_CATEGORIES.includes(c))
+ : ALL_CATEGORIES;
+
+ const checks: DiagnosticCheck[] = [];
+ const now = Date.now();
+
+ if (categories.includes("actions")) {
+ const actions = await kv.list<Action>(KV.actions);
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const leases = await kv.list<Lease>(KV.leases);
+ const actionMap = new Map(actions.map((a) => [a.id, a]));
+
+ for (const action of actions) {
+ if (action.status === "active") {
+ const hasActiveLease = leases.some(
+ (l) =>
+ l.actionId === action.id &&
+ l.status === "active" &&
+ new Date(l.expiresAt).getTime() > now,
+ );
+ if (!hasActiveLease) {
+ checks.push({
+ name: `active-no-lease:${action.id}`,
+ category: "actions",
+ status: "warn",
+ message: `Action "${action.title}" is active but has no active lease`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (action.status === "blocked") {
+ const deps = allEdges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "requires",
+ );
+ if (deps.length > 0) {
+ const allDone = deps.every((d) => {
+ const target = actionMap.get(d.targetActionId);
+ return target && target.status === "done";
+ });
+ if (allDone) {
+ checks.push({
+ name: `blocked-deps-done:${action.id}`,
+ category: "actions",
+ status: "fail",
+ message: `Action "${action.title}" is blocked but all dependencies are done`,
+ fixable: true,
+ });
+ }
+ }
+ }
+
+ if (action.status === "pending") {
+ const deps = allEdges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "requires",
+ );
+ if (deps.length > 0) {
+ const hasUnsatisfied = deps.some((d) => {
+ const target = actionMap.get(d.targetActionId);
+ return !target || target.status !== "done";
+ });
+ if (hasUnsatisfied) {
+ checks.push({
+ name: `pending-unsatisfied-deps:${action.id}`,
+ category: "actions",
+ status: "fail",
+ message: `Action "${action.title}" is pending but has unsatisfied dependencies`,
+ fixable: true,
+ });
+ }
+ }
+ }
+ }
+
+ if (
+ !checks.some((c) => c.category === "actions" && c.status !== "pass")
+ ) {
+ checks.push({
+ name: "actions-ok",
+ category: "actions",
+ status: "pass",
+ message: `All ${actions.length} actions are consistent`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("leases")) {
+ const leases = await kv.list<Lease>(KV.leases);
+ const actions = await kv.list<Action>(KV.actions);
+ const actionIds = new Set(actions.map((a) => a.id));
+ let leaseIssues = 0;
+
+ for (const lease of leases) {
+ if (
+ lease.status === "active" &&
+ new Date(lease.expiresAt).getTime() <= now
+ ) {
+ checks.push({
+ name: `expired-lease:${lease.id}`,
+ category: "leases",
+ status: "fail",
+ message: `Lease ${lease.id} for action ${lease.actionId} expired at ${lease.expiresAt}`,
+ fixable: true,
+ });
+ leaseIssues++;
+ }
+
+ if (!actionIds.has(lease.actionId)) {
+ checks.push({
+ name: `orphaned-lease:${lease.id}`,
+ category: "leases",
+ status: "fail",
+ message: `Lease ${lease.id} references non-existent action ${lease.actionId}`,
+ fixable: true,
+ });
+ leaseIssues++;
+ }
+ }
+
+ if (leaseIssues === 0) {
+ checks.push({
+ name: "leases-ok",
+ category: "leases",
+ status: "pass",
+ message: `All ${leases.length} leases are healthy`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("sentinels")) {
+ const sentinels = await kv.list<Sentinel>(KV.sentinels);
+ const actions = await kv.list<Action>(KV.actions);
+ const actionIds = new Set(actions.map((a) => a.id));
+ let sentinelIssues = 0;
+
+ for (const sentinel of sentinels) {
+ if (
+ sentinel.status === "watching" &&
+ sentinel.expiresAt &&
+ new Date(sentinel.expiresAt).getTime() <= now
+ ) {
+ checks.push({
+ name: `expired-sentinel:${sentinel.id}`,
+ category: "sentinels",
+ status: "fail",
+ message: `Sentinel "${sentinel.name}" expired at ${sentinel.expiresAt}`,
+ fixable: true,
+ });
+ sentinelIssues++;
+ }
+
+ for (const actionId of sentinel.linkedActionIds) {
+ if (!actionIds.has(actionId)) {
+ checks.push({
+ name: `sentinel-missing-action:${sentinel.id}:${actionId}`,
+ category: "sentinels",
+ status: "warn",
+ message: `Sentinel "${sentinel.name}" references non-existent action ${actionId}`,
+ fixable: false,
+ });
+ sentinelIssues++;
+ }
+ }
+ }
+
+ if (sentinelIssues === 0) {
+ checks.push({
+ name: "sentinels-ok",
+ category: "sentinels",
+ status: "pass",
+ message: `All ${sentinels.length} sentinels are healthy`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("sketches")) {
+ const sketches = await kv.list<Sketch>(KV.sketches);
+ let sketchIssues = 0;
+
+ for (const sketch of sketches) {
+ if (
+ sketch.status === "active" &&
+ new Date(sketch.expiresAt).getTime() <= now
+ ) {
+ checks.push({
+ name: `expired-sketch:${sketch.id}`,
+ category: "sketches",
+ status: "fail",
+ message: `Sketch "${sketch.title}" expired at ${sketch.expiresAt}`,
+ fixable: true,
+ });
+ sketchIssues++;
+ }
+ }
+
+ if (sketchIssues === 0) {
+ checks.push({
+ name: "sketches-ok",
+ category: "sketches",
+ status: "pass",
+ message: `All ${sketches.length} sketches are healthy`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("signals")) {
+ const signals = await kv.list<Signal>(KV.signals);
+ let signalIssues = 0;
+
+ for (const signal of signals) {
+ if (
+ signal.expiresAt &&
+ new Date(signal.expiresAt).getTime() <= now
+ ) {
+ checks.push({
+ name: `expired-signal:${signal.id}`,
+ category: "signals",
+ status: "fail",
+ message: `Signal from "${signal.from}" expired at ${signal.expiresAt}`,
+ fixable: true,
+ });
+ signalIssues++;
+ }
+ }
+
+ if (signalIssues === 0) {
+ checks.push({
+ name: "signals-ok",
+ category: "signals",
+ status: "pass",
+ message: `All ${signals.length} signals are healthy`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("sessions")) {
+ const sessions = await kv.list<Session>(KV.sessions);
+ let sessionIssues = 0;
+
+ for (const session of sessions) {
+ if (
+ session.status === "active" &&
+ now - new Date(session.startedAt).getTime() > TWENTY_FOUR_HOURS_MS
+ ) {
+ checks.push({
+ name: `abandoned-session:${session.id}`,
+ category: "sessions",
+ status: "warn",
+ message: `Session ${session.id} has been active for over 24 hours`,
+ fixable: false,
+ });
+ sessionIssues++;
+ }
+ }
+
+ if (sessionIssues === 0) {
+ checks.push({
+ name: "sessions-ok",
+ category: "sessions",
+ status: "pass",
+ message: `All ${sessions.length} sessions are healthy`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("memories")) {
+ const memories = await kv.list<Memory>(KV.memories);
+ const memoryIds = new Set(memories.map((m) => m.id));
+ const supersededBy = new Map<string, string>();
+ let memoryIssues = 0;
+
+ for (const memory of memories) {
+ if (memory.supersedes && memory.supersedes.length > 0) {
+ for (const sid of memory.supersedes) {
+ if (!memoryIds.has(sid)) {
+ checks.push({
+ name: `memory-missing-supersedes:${memory.id}:${sid}`,
+ category: "memories",
+ status: "warn",
+ message: `Memory "${memory.title}" supersedes non-existent memory ${sid}`,
+ fixable: false,
+ });
+ memoryIssues++;
+ }
+ supersededBy.set(sid, memory.id);
+ }
+ }
+ }
+
+ for (const memory of memories) {
+ if (memory.isLatest && supersededBy.has(memory.id)) {
+ checks.push({
+ name: `memory-stale-latest:${memory.id}`,
+ category: "memories",
+ status: "fail",
+ message: `Memory "${memory.title}" has isLatest=true but is superseded by ${supersededBy.get(memory.id)}`,
+ fixable: true,
+ });
+ memoryIssues++;
+ }
+ }
+
+ if (memoryIssues === 0) {
+ checks.push({
+ name: "memories-ok",
+ category: "memories",
+ status: "pass",
+ message: `All ${memories.length} memories are consistent`,
+ fixable: false,
+ });
+ }
+ }
+
+ if (categories.includes("mesh")) {
+ const peers = await kv.list<MeshPeer>(KV.mesh);
+ let meshIssues = 0;
+
+ for (const peer of peers) {
+ if (
+ peer.lastSyncAt &&
+ now - new Date(peer.lastSyncAt).getTime() > ONE_HOUR_MS
+ ) {
+ checks.push({
+ name: `stale-peer:${peer.id}`,
+ category: "mesh",
+ status: "warn",
+ message: `Peer "${peer.name}" last synced over 1 hour ago`,
+ fixable: false,
+ });
+ meshIssues++;
+ }
+
+ if (peer.status === "error") {
+ checks.push({
+ name: `error-peer:${peer.id}`,
+ category: "mesh",
+ status: "warn",
+ message: `Peer "${peer.name}" is in error state`,
+ fixable: false,
+ });
+ meshIssues++;
+ }
+ }
+
+ if (meshIssues === 0) {
+ checks.push({
+ name: "mesh-ok",
+ category: "mesh",
+ status: "pass",
+ message: `All ${peers.length} mesh peers are healthy`,
+ fixable: false,
+ });
+ }
+ }
+
+ const summary = {
+ pass: checks.filter((c) => c.status === "pass").length,
+ warn: checks.filter((c) => c.status === "warn").length,
+ fail: checks.filter((c) => c.status === "fail").length,
+ fixable: checks.filter((c) => c.fixable).length,
+ };
+
+ return { success: true, checks, summary };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::heal" },
+ async (data: { categories?: string[]; dryRun?: boolean }) => {
+ const dryRun = data.dryRun ?? false;
+ const categories = data.categories && data.categories.length > 0
+ ? data.categories.filter((c) => ALL_CATEGORIES.includes(c))
+ : ALL_CATEGORIES;
+
+ let fixed = 0;
+ let skipped = 0;
+ const details: string[] = [];
+ const now = Date.now();
+
+ if (categories.includes("actions")) {
+ const actions = await kv.list<Action>(KV.actions);
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const actionMap = new Map(actions.map((a) => [a.id, a]));
+
+ for (const action of actions) {
+ if (action.status === "blocked") {
+ const deps = allEdges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "requires",
+ );
+ if (deps.length > 0) {
+ const allDone = deps.every((d) => {
+ const target = actionMap.get(d.targetActionId);
+ return target && target.status === "done";
+ });
+ if (allDone) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would unblock action "${action.title}" (${action.id})`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:action:${action.id}`,
+ async () => {
+ const fresh = await kv.get<Action>(KV.actions, action.id);
+ if (!fresh || fresh.status !== "blocked") return false;
+ const freshEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const freshDeps = freshEdges.filter(
+ (e) =>
+ e.sourceActionId === fresh.id && e.type === "requires",
+ );
+ const freshActions = await kv.list<Action>(KV.actions);
+ const freshMap = new Map(
+ freshActions.map((a) => [a.id, a]),
+ );
+ const stillAllDone = freshDeps.every((d) => {
+ const target = freshMap.get(d.targetActionId);
+ return target && target.status === "done";
+ });
+ if (!stillAllDone) return false;
+ fresh.status = "pending";
+ fresh.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Unblocked action "${action.title}" (${action.id})`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ }
+ }
+ }
+
+ if (action.status === "pending") {
+ const deps = allEdges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "requires",
+ );
+ if (deps.length > 0) {
+ const hasUnsatisfied = deps.some((d) => {
+ const target = actionMap.get(d.targetActionId);
+ return !target || target.status !== "done";
+ });
+ if (hasUnsatisfied) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would block action "${action.title}" (${action.id})`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:action:${action.id}`,
+ async () => {
+ const fresh = await kv.get<Action>(KV.actions, action.id);
+ if (!fresh || fresh.status !== "pending") return false;
+ const freshEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const freshDeps = freshEdges.filter(
+ (e) =>
+ e.sourceActionId === fresh.id && e.type === "requires",
+ );
+ const freshActions = await kv.list<Action>(KV.actions);
+ const freshMap = new Map(
+ freshActions.map((a) => [a.id, a]),
+ );
+ const stillUnsatisfied = freshDeps.some((d) => {
+ const target = freshMap.get(d.targetActionId);
+ return !target || target.status !== "done";
+ });
+ if (!stillUnsatisfied) return false;
+ fresh.status = "blocked";
+ fresh.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Blocked action "${action.title}" (${action.id})`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (categories.includes("leases")) {
+ const leases = await kv.list<Lease>(KV.leases);
+ const actions = await kv.list<Action>(KV.actions);
+ const actionIds = new Set(actions.map((a) => a.id));
+
+ for (const lease of leases) {
+ if (
+ lease.status === "active" &&
+ new Date(lease.expiresAt).getTime() <= now
+ ) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would expire lease ${lease.id} for action ${lease.actionId}`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:lease:${lease.actionId}`,
+ async () => {
+ const fresh = await kv.get<Lease>(KV.leases, lease.id);
+ if (
+ !fresh ||
+ fresh.status !== "active" ||
+ new Date(fresh.expiresAt).getTime() > Date.now()
+ ) {
+ return false;
+ }
+ fresh.status = "expired";
+ await kv.set(KV.leases, fresh.id, fresh);
+
+ const action = await kv.get<Action>(KV.actions, fresh.actionId);
+ if (
+ action &&
+ action.status === "active" &&
+ action.assignedTo === fresh.agentId
+ ) {
+ action.status = "pending";
+ action.assignedTo = undefined;
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ }
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Expired lease ${lease.id} for action ${lease.actionId}`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ continue;
+ }
+
+ if (!actionIds.has(lease.actionId)) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would delete orphaned lease ${lease.id}`,
+ );
+ fixed++;
+ continue;
+ }
+ await kv.delete(KV.leases, lease.id);
+ details.push(`Deleted orphaned lease ${lease.id}`);
+ fixed++;
+ }
+ }
+ }
+
+ if (categories.includes("sentinels")) {
+ const sentinels = await kv.list<Sentinel>(KV.sentinels);
+
+ for (const sentinel of sentinels) {
+ if (
+ sentinel.status === "watching" &&
+ sentinel.expiresAt &&
+ new Date(sentinel.expiresAt).getTime() <= now
+ ) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would expire sentinel "${sentinel.name}" (${sentinel.id})`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:sentinel:${sentinel.id}`,
+ async () => {
+ const fresh = await kv.get<Sentinel>(
+ KV.sentinels,
+ sentinel.id,
+ );
+ if (!fresh || fresh.status !== "watching") return false;
+ if (
+ !fresh.expiresAt ||
+ new Date(fresh.expiresAt).getTime() > Date.now()
+ ) {
+ return false;
+ }
+ fresh.status = "expired";
+ await kv.set(KV.sentinels, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Expired sentinel "${sentinel.name}" (${sentinel.id})`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ }
+ }
+ }
+
+ if (categories.includes("sketches")) {
+ const sketches = await kv.list<Sketch>(KV.sketches);
+
+ for (const sketch of sketches) {
+ if (
+ sketch.status === "active" &&
+ new Date(sketch.expiresAt).getTime() <= now
+ ) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would discard expired sketch "${sketch.title}" (${sketch.id})`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:sketch:${sketch.id}`,
+ async () => {
+ const fresh = await kv.get<Sketch>(KV.sketches, sketch.id);
+ if (
+ !fresh ||
+ fresh.status !== "active" ||
+ new Date(fresh.expiresAt).getTime() > Date.now()
+ ) {
+ return false;
+ }
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const actionIdSet = new Set(fresh.actionIds);
+ for (const edge of allEdges) {
+ if (
+ actionIdSet.has(edge.sourceActionId) ||
+ actionIdSet.has(edge.targetActionId)
+ ) {
+ await kv.delete(KV.actionEdges, edge.id);
+ }
+ }
+ for (const actionId of fresh.actionIds) {
+ await kv.delete(KV.actions, actionId);
+ }
+
+ fresh.status = "discarded";
+ fresh.discardedAt = new Date().toISOString();
+ await kv.set(KV.sketches, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Discarded expired sketch "${sketch.title}" (${sketch.id})`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ }
+ }
+ }
+
+ if (categories.includes("signals")) {
+ const signals = await kv.list<Signal>(KV.signals);
+
+ for (const signal of signals) {
+ if (
+ signal.expiresAt &&
+ new Date(signal.expiresAt).getTime() <= now
+ ) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would delete expired signal ${signal.id}`,
+ );
+ fixed++;
+ continue;
+ }
+ await kv.delete(KV.signals, signal.id);
+ details.push(`Deleted expired signal ${signal.id}`);
+ fixed++;
+ }
+ }
+ }
+
+ if (categories.includes("memories")) {
+ const memories = await kv.list<Memory>(KV.memories);
+ const supersededBy = new Map<string, string>();
+
+ for (const memory of memories) {
+ if (memory.supersedes && memory.supersedes.length > 0) {
+ for (const sid of memory.supersedes) {
+ supersededBy.set(sid, memory.id);
+ }
+ }
+ }
+
+ for (const memory of memories) {
+ if (memory.isLatest && supersededBy.has(memory.id)) {
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would set isLatest=false on memory "${memory.title}" (${memory.id})`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:memory:${memory.id}`,
+ async () => {
+ const fresh = await kv.get<Memory>(KV.memories, memory.id);
+ if (!fresh || !fresh.isLatest) return false;
+ fresh.isLatest = false;
+ fresh.updatedAt = new Date().toISOString();
+ await kv.set(KV.memories, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Set isLatest=false on memory "${memory.title}" (${memory.id})`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ }
+ }
+ }
+
+ return { success: true, fixed, skipped, details };
+ },
+ );
+}
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 05b98ec6..2fd86f97 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -11,6 +11,15 @@ import type {
GraphEdge,
SemanticMemory,
ProceduralMemory,
+ Action,
+ ActionEdge,
+ Routine,
+ Signal,
+ Checkpoint,
+ Sentinel,
+ Sketch,
+ Crystal,
+ Facet,
} from "../types.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
@@ -58,6 +67,16 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
.list<ProceduralMemory>(KV.procedural)
.catch(() => []);
+ const actions = await kv.list<Action>(KV.actions).catch(() => []);
+ const actionEdges = await kv.list<ActionEdge>(KV.actionEdges).catch(() => []);
+ const sentinels = await kv.list<Sentinel>(KV.sentinels).catch(() => []);
+ const sketches = await kv.list<Sketch>(KV.sketches).catch(() => []);
+ const crystals = await kv.list<Crystal>(KV.crystals).catch(() => []);
+ const facets = await kv.list<Facet>(KV.facets).catch(() => []);
+ const routines = await kv.list<Routine>(KV.routines).catch(() => []);
+ const signals = await kv.list<Signal>(KV.signals).catch(() => []);
+ const checkpoints = await kv.list<Checkpoint>(KV.checkpoints).catch(() => []);
+
const exportData: ExportData = {
version: VERSION,
exportedAt: new Date().toISOString(),
@@ -72,6 +91,15 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
semanticMemories.length > 0 ? semanticMemories : undefined,
proceduralMemories:
proceduralMemories.length > 0 ? proceduralMemories : undefined,
+ actions: actions.length > 0 ? actions : undefined,
+ actionEdges: actionEdges.length > 0 ? actionEdges : undefined,
+ sentinels: sentinels.length > 0 ? sentinels : undefined,
+ sketches: sketches.length > 0 ? sketches : undefined,
+ crystals: crystals.length > 0 ? crystals : undefined,
+ facets: facets.length > 0 ? facets : undefined,
+ routines: routines.length > 0 ? routines : undefined,
+ signals: signals.length > 0 ? signals : undefined,
+ checkpoints: checkpoints.length > 0 ? checkpoints : undefined,
};
const totalObs = Object.values(observations).reduce(
@@ -102,7 +130,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"]);
+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0"]);
if (!supportedVersions.has(importData.version)) {
return {
success: false,
@@ -207,6 +235,33 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
for (const s of existingSummaries) {
await kv.delete(KV.summaries, s.sessionId);
}
+ for (const a of await kv.list<Action>(KV.actions).catch(() => [])) {
+ await kv.delete(KV.actions, a.id);
+ }
+ for (const e of await kv.list<ActionEdge>(KV.actionEdges).catch(() => [])) {
+ await kv.delete(KV.actionEdges, e.id);
+ }
+ for (const r of await kv.list<Routine>(KV.routines).catch(() => [])) {
+ await kv.delete(KV.routines, r.id);
+ }
+ for (const s of await kv.list<Signal>(KV.signals).catch(() => [])) {
+ await kv.delete(KV.signals, s.id);
+ }
+ for (const c of await kv.list<Checkpoint>(KV.checkpoints).catch(() => [])) {
+ await kv.delete(KV.checkpoints, c.id);
+ }
+ for (const s of await kv.list<Sentinel>(KV.sentinels).catch(() => [])) {
+ await kv.delete(KV.sentinels, s.id);
+ }
+ for (const s of await kv.list<Sketch>(KV.sketches).catch(() => [])) {
+ await kv.delete(KV.sketches, s.id);
+ }
+ for (const c of await kv.list<Crystal>(KV.crystals).catch(() => [])) {
+ await kv.delete(KV.crystals, c.id);
+ }
+ for (const f of await kv.list<Facet>(KV.facets).catch(() => [])) {
+ await kv.delete(KV.facets, f.id);
+ }
}
for (const session of importData.sessions) {
@@ -269,25 +324,123 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
if (importData.graphNodes) {
for (const node of importData.graphNodes) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.graphNodes, node.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
await kv.set(KV.graphNodes, node.id, node);
}
}
if (importData.graphEdges) {
for (const edge of importData.graphEdges) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.graphEdges, edge.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
await kv.set(KV.graphEdges, edge.id, edge);
}
}
if (importData.semanticMemories) {
for (const sem of importData.semanticMemories) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.semantic, sem.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
await kv.set(KV.semantic, sem.id, sem);
}
}
if (importData.proceduralMemories) {
for (const proc of importData.proceduralMemories) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.procedural, proc.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
await kv.set(KV.procedural, proc.id, proc);
}
}
+ if (importData.actions) {
+ for (const action of importData.actions) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.actions, action.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.actions, action.id, action);
+ }
+ }
+ if (importData.actionEdges) {
+ for (const edge of importData.actionEdges) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.actionEdges, edge.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.actionEdges, edge.id, edge);
+ }
+ }
+ if (importData.routines) {
+ for (const routine of importData.routines) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.routines, routine.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.routines, routine.id, routine);
+ }
+ }
+ if (importData.signals) {
+ for (const signal of importData.signals) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.signals, signal.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.signals, signal.id, signal);
+ }
+ }
+ if (importData.checkpoints) {
+ for (const checkpoint of importData.checkpoints) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.checkpoints, checkpoint.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.checkpoints, checkpoint.id, checkpoint);
+ }
+ }
+ if (importData.sentinels) {
+ for (const sentinel of importData.sentinels) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.sentinels, sentinel.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+ }
+ }
+ if (importData.sketches) {
+ for (const sketch of importData.sketches) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.sketches, sketch.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.sketches, sketch.id, sketch);
+ }
+ }
+ if (importData.crystals) {
+ for (const crystal of importData.crystals) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.crystals, crystal.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.crystals, crystal.id, crystal);
+ }
+ }
+ if (importData.facets) {
+ for (const facet of importData.facets) {
+ if (strategy === "skip") {
+ const existing = await kv.get(KV.facets, facet.id).catch(() => null);
+ if (existing) { stats.skipped++; continue; }
+ }
+ await kv.set(KV.facets, facet.id, facet);
+ }
+ }
+
ctx.logger.info("Import complete", { strategy, ...stats });
return { success: true, strategy, ...stats };
},
diff --git a/src/functions/facets.ts b/src/functions/facets.ts
new file mode 100644
index 00000000..88f27446
--- /dev/null
+++ b/src/functions/facets.ts
@@ -0,0 +1,248 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV, generateId } from "../state/schema.js";
+import type { Facet } from "../types.js";
+
+export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::facet-tag" },
+ async (data: {
+ targetId: string;
+ targetType: string;
+ dimension: string;
+ value: string;
+ }) => {
+ if (!data.targetId || typeof data.targetId !== "string") {
+ return { success: false, error: "targetId is required" };
+ }
+
+ const validTypes = ["action", "memory", "observation"];
+ if (!validTypes.includes(data.targetType)) {
+ return {
+ success: false,
+ error: `targetType must be one of: ${validTypes.join(", ")}`,
+ };
+ }
+
+ if (
+ !data.dimension ||
+ typeof data.dimension !== "string" ||
+ data.dimension.trim() === ""
+ ) {
+ return { success: false, error: "dimension is required" };
+ }
+
+ if (
+ !data.value ||
+ typeof data.value !== "string" ||
+ data.value.trim() === ""
+ ) {
+ return { success: false, error: "value is required" };
+ }
+
+ const dimension = data.dimension.trim();
+ const value = data.value.trim();
+
+ const existing = await kv.list<Facet>(KV.facets);
+ const duplicate = existing.find(
+ (f) =>
+ f.targetId === data.targetId &&
+ f.dimension === dimension &&
+ f.value === value,
+ );
+ if (duplicate) {
+ return { success: true, facet: duplicate, skipped: true };
+ }
+
+ const facet: Facet = {
+ id: generateId("fct"),
+ targetId: data.targetId,
+ targetType: data.targetType as Facet["targetType"],
+ dimension,
+ value,
+ createdAt: new Date().toISOString(),
+ };
+
+ await kv.set(KV.facets, facet.id, facet);
+ return { success: true, facet };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::facet-untag" },
+ async (data: {
+ targetId: string;
+ dimension: string;
+ value?: string;
+ }) => {
+ if (!data.targetId) {
+ return { success: false, error: "targetId is required" };
+ }
+ if (!data.dimension) {
+ return { success: false, error: "dimension is required" };
+ }
+
+ const all = await kv.list<Facet>(KV.facets);
+ const matches = all.filter((f) => {
+ if (f.targetId !== data.targetId || f.dimension !== data.dimension) {
+ return false;
+ }
+ if (data.value !== undefined) {
+ return f.value === data.value;
+ }
+ return true;
+ });
+
+ for (const f of matches) {
+ await kv.delete(KV.facets, f.id);
+ }
+
+ return { success: true, removed: matches.length };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::facet-query" },
+ async (data: {
+ matchAll?: string[];
+ matchAny?: string[];
+ targetType?: string;
+ limit?: number;
+ }) => {
+ if (
+ (!data.matchAll || data.matchAll.length === 0) &&
+ (!data.matchAny || data.matchAny.length === 0)
+ ) {
+ return {
+ success: false,
+ error: "at least one of matchAll or matchAny is required",
+ };
+ }
+
+ const all = await kv.list<Facet>(KV.facets);
+ const filtered = data.targetType
+ ? all.filter((f) => f.targetType === data.targetType)
+ : all;
+
+ const targetFacetMap = new Map<string, { targetType: string; facetKeys: Set<string> }>();
+ for (const f of filtered) {
+ const key = `${f.dimension}:${f.value}`;
+ let entry = targetFacetMap.get(f.targetId);
+ if (!entry) {
+ entry = { targetType: f.targetType, facetKeys: new Set() };
+ targetFacetMap.set(f.targetId, entry);
+ }
+ entry.facetKeys.add(key);
+ }
+
+ const results: Array<{ targetId: string; targetType: string; matchedFacets: string[] }> = [];
+
+ for (const [targetId, entry] of targetFacetMap) {
+ const matched: string[] = [];
+
+ if (data.matchAll && data.matchAll.length > 0) {
+ const allPresent = data.matchAll.every((k) => entry.facetKeys.has(k));
+ if (!allPresent) continue;
+ for (const k of data.matchAll) {
+ if (!matched.includes(k)) matched.push(k);
+ }
+ }
+
+ if (data.matchAny && data.matchAny.length > 0) {
+ const anyPresent = data.matchAny.filter((k) => entry.facetKeys.has(k));
+ if (anyPresent.length === 0) continue;
+ for (const k of anyPresent) {
+ if (!matched.includes(k)) matched.push(k);
+ }
+ }
+
+ results.push({
+ targetId,
+ targetType: entry.targetType,
+ matchedFacets: matched,
+ });
+ }
+
+ const limit = data.limit || 50;
+ return { success: true, results: results.slice(0, limit) };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::facet-get" },
+ async (data: { targetId: string }) => {
+ if (!data.targetId) {
+ return { success: false, error: "targetId is required" };
+ }
+
+ const all = await kv.list<Facet>(KV.facets);
+ const targetFacets = all.filter((f) => f.targetId === data.targetId);
+
+ const dimMap = new Map<string, string[]>();
+ for (const f of targetFacets) {
+ let values = dimMap.get(f.dimension);
+ if (!values) {
+ values = [];
+ dimMap.set(f.dimension, values);
+ }
+ values.push(f.value);
+ }
+
+ const dimensions = Array.from(dimMap.entries()).map(([dimension, values]) => ({
+ dimension,
+ values,
+ }));
+
+ return { success: true, dimensions };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::facet-stats" },
+ async (data: { targetType?: string }) => {
+ const all = await kv.list<Facet>(KV.facets);
+ const filtered = data.targetType
+ ? all.filter((f) => f.targetType === data.targetType)
+ : all;
+
+ const dimMap = new Map<string, Map<string, number>>();
+ for (const f of filtered) {
+ let valueMap = dimMap.get(f.dimension);
+ if (!valueMap) {
+ valueMap = new Map();
+ dimMap.set(f.dimension, valueMap);
+ }
+ valueMap.set(f.value, (valueMap.get(f.value) || 0) + 1);
+ }
+
+ const dimensions = Array.from(dimMap.entries()).map(([dimension, valueMap]) => ({
+ dimension,
+ values: Array.from(valueMap.entries()).map(([value, count]) => ({
+ value,
+ count,
+ })),
+ }));
+
+ return { success: true, dimensions, totalFacets: filtered.length };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::facet-dimensions" },
+ async () => {
+ const all = await kv.list<Facet>(KV.facets);
+
+ const counts = new Map<string, number>();
+ for (const f of all) {
+ counts.set(f.dimension, (counts.get(f.dimension) || 0) + 1);
+ }
+
+ const dimensions = Array.from(counts.entries()).map(([dimension, count]) => ({
+ dimension,
+ count,
+ }));
+
+ return { success: true, dimensions };
+ },
+ );
+}
diff --git a/src/functions/flow-compress.ts b/src/functions/flow-compress.ts
new file mode 100644
index 00000000..78adfd1a
--- /dev/null
+++ b/src/functions/flow-compress.ts
@@ -0,0 +1,214 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV, generateId } from "../state/schema.js";
+import type { Action, ActionEdge, RoutineRun, MemoryProvider } from "../types.js";
+
+const FLOW_COMPRESS_SYSTEM = `You are a workflow summarizer. Given a completed action chain, produce a concise summary capturing:
+1. The overall goal and outcome
+2. Key steps taken and their results
+3. Any notable decisions or discoveries
+4. Lessons learned
+
+Output as XML:
+<summary>
+<goal>What was the workflow trying to achieve</goal>
+<outcome>What happened</outcome>
+<steps>Numbered list of key steps</steps>
+<discoveries>Any new insights or discoveries</discoveries>
+<lesson>What to remember for next time</lesson>
+</summary>`;
+
+export function registerFlowCompressFunction(
+ sdk: ISdk,
+ kv: StateKV,
+ provider: MemoryProvider,
+): void {
+ sdk.registerFunction(
+ { id: "mem::flow-compress" },
+ async (data: { runId?: string; actionIds?: string[]; project?: string }) => {
+ let actionsToCompress: Action[] = [];
+
+ if (data.runId) {
+ const run = await kv.get<RoutineRun>(KV.routineRuns, data.runId);
+ if (!run) {
+ return { success: false, error: "run not found" };
+ }
+ for (const id of run.actionIds) {
+ const action = await kv.get<Action>(KV.actions, id);
+ if (action) actionsToCompress.push(action);
+ }
+ } else if (data.actionIds && data.actionIds.length > 0) {
+ for (const id of data.actionIds) {
+ const action = await kv.get<Action>(KV.actions, id);
+ if (action) actionsToCompress.push(action);
+ }
+ } else if (data.project) {
+ const allActions = await kv.list<Action>(KV.actions);
+ actionsToCompress = allActions.filter(
+ (a) => a.project === data.project && a.status === "done",
+ );
+ } else {
+ return {
+ success: false,
+ error: "runId, actionIds, or project is required",
+ };
+ }
+
+ const doneActions = actionsToCompress.filter(
+ (a) => a.status === "done",
+ );
+ if (doneActions.length === 0) {
+ return {
+ success: true,
+ message: "No completed actions to compress",
+ compressed: 0,
+ };
+ }
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const relevantIds = new Set(doneActions.map((a) => a.id));
+ const relevantEdges = allEdges.filter(
+ (e) =>
+ relevantIds.has(e.sourceActionId) ||
+ relevantIds.has(e.targetActionId),
+ );
+
+ const prompt = buildFlowPrompt(doneActions, relevantEdges);
+
+ try {
+ const response = await provider.summarize(
+ FLOW_COMPRESS_SYSTEM,
+ prompt,
+ );
+ const summary = parseFlowSummary(response);
+
+ const memory = {
+ id: generateId("mem"),
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ type: "workflow" as const,
+ title: summary.goal || `Workflow: ${doneActions.length} actions`,
+ content: formatSummary(summary),
+ concepts: extractConcepts(doneActions),
+ files: extractFiles(doneActions),
+ sessionIds: [],
+ strength: 1.0,
+ version: 1,
+ isLatest: true,
+ metadata: {
+ flowCompressed: true,
+ actionCount: doneActions.length,
+ actionIds: doneActions.map((a) => a.id),
+ },
+ };
+
+ await kv.set(KV.memories, memory.id, memory);
+
+ return {
+ success: true,
+ compressed: doneActions.length,
+ memoryId: memory.id,
+ summary,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ error: `compression failed: ${String(err)}`,
+ compressed: 0,
+ };
+ }
+ },
+ );
+}
+
+function buildFlowPrompt(
+ actions: Action[],
+ edges: ActionEdge[],
+): string {
+ const lines: string[] = ["## Completed Action Chain\n"];
+
+ const sorted = [...actions].sort(
+ (a, b) =>
+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
+ );
+
+ for (const action of sorted) {
+ lines.push(`### ${action.title}`);
+ if (action.description) lines.push(action.description);
+ if (action.result) lines.push(`Result: ${action.result}`);
+ lines.push(`Priority: ${action.priority}, Tags: ${(action.tags ?? []).join(", ")}`);
+ lines.push("");
+ }
+
+ if (edges.length > 0) {
+ lines.push("## Dependencies");
+ for (const edge of edges) {
+ lines.push(`- ${edge.sourceActionId} --${edge.type}--> ${edge.targetActionId}`);
+ }
+ }
+
+ return lines.join("\n");
+}
+
+function parseFlowSummary(response: string): {
+ goal: string;
+ outcome: string;
+ steps: string;
+ discoveries: string;
+ lesson: string;
+} {
+ const extract = (tag: string): string => {
+ const match = response.match(
+ new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),
+ );
+ return match ? match[1].trim() : "";
+ };
+ return {
+ goal: extract("goal"),
+ outcome: extract("outcome"),
+ steps: extract("steps"),
+ discoveries: extract("discoveries"),
+ lesson: extract("lesson"),
+ };
+}
+
+function formatSummary(s: {
+ goal: string;
+ outcome: string;
+ steps: string;
+ discoveries: string;
+ lesson: string;
+}): string {
+ const parts: string[] = [];
+ if (s.goal) parts.push(`Goal: ${s.goal}`);
+ if (s.outcome) parts.push(`Outcome: ${s.outcome}`);
+ if (s.steps) parts.push(`Steps: ${s.steps}`);
+ if (s.discoveries) parts.push(`Discoveries: ${s.discoveries}`);
+ if (s.lesson) parts.push(`Lesson: ${s.lesson}`);
+ return parts.join("\n\n");
+}
+
+function extractConcepts(actions: Action[]): string[] {
+ const concepts = new Set<string>();
+ for (const a of actions) {
+ for (const tag of a.tags ?? []) {
+ if (!tag.startsWith("routine:")) concepts.add(tag);
+ }
+ }
+ return Array.from(concepts);
+}
+
+function extractFiles(actions: Action[]): string[] {
+ const files = new Set<string>();
+ for (const a of actions) {
+ if (a.metadata && typeof a.metadata === "object") {
+ const meta = a.metadata as Record<string, unknown>;
+ if (Array.isArray(meta.files)) {
+ for (const f of meta.files) {
+ if (typeof f === "string") files.add(f);
+ }
+ }
+ }
+ }
+ return Array.from(files);
+}
diff --git a/src/functions/frontier.ts b/src/functions/frontier.ts
new file mode 100644
index 00000000..2040be6d
--- /dev/null
+++ b/src/functions/frontier.ts
@@ -0,0 +1,196 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type { Action, ActionEdge, Checkpoint, Lease } from "../types.js";
+
+export interface FrontierItem {
+ action: Action;
+ score: number;
+ blockers: string[];
+ leased: boolean;
+}
+
+export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::frontier" },
+ async (data: {
+ project?: string;
+ agentId?: string;
+ limit?: number;
+ includeLeasedByOthers?: boolean;
+ }) => {
+ const actions = await kv.list<Action>(KV.actions);
+ const edges = await kv.list<ActionEdge>(KV.actionEdges);
+ const leases = await kv.list<Lease>(KV.leases);
+ const checkpoints = await kv.list<Checkpoint>(KV.checkpoints);
+ const now = Date.now();
+
+ const activeLeaseMap = new Map<string, Lease>();
+ for (const lease of leases) {
+ if (
+ lease.status === "active" &&
+ new Date(lease.expiresAt).getTime() > now
+ ) {
+ activeLeaseMap.set(lease.actionId, lease);
+ }
+ }
+
+ const checkpointMap = new Map<string, Checkpoint>();
+ for (const cp of checkpoints) {
+ checkpointMap.set(cp.id, cp);
+ }
+
+ const actionMap = new Map<string, Action>();
+ for (const a of actions) actionMap.set(a.id, a);
+
+ const frontier: FrontierItem[] = [];
+
+ for (const action of actions) {
+ if (action.status === "done" || action.status === "cancelled") continue;
+ if (data.project && action.project !== data.project) continue;
+
+ const blockers: string[] = [];
+ const inEdges = edges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "requires",
+ );
+
+ for (const edge of inEdges) {
+ const dep = actionMap.get(edge.targetActionId);
+ if (dep && dep.status !== "done") {
+ blockers.push(`requires:${dep.id}:${dep.title}`);
+ }
+ }
+
+ const gateEdges = edges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "gated_by",
+ );
+ for (const edge of gateEdges) {
+ const cp = checkpointMap.get(edge.targetActionId);
+ if (cp && cp.status !== "passed") {
+ blockers.push(`checkpoint:${cp.id}:${cp.name}`);
+ }
+ }
+
+ const conflictEdges = edges.filter(
+ (e) =>
+ (e.sourceActionId === action.id ||
+ e.targetActionId === action.id) &&
+ e.type === "conflicts_with",
+ );
+ for (const edge of conflictEdges) {
+ const otherId =
+ edge.sourceActionId === action.id
+ ? edge.targetActionId
+ : edge.sourceActionId;
+ const other = actionMap.get(otherId);
+ if (other && other.status === "active") {
+ blockers.push(`conflict:${other.id}:${other.title}`);
+ }
+ }
+
+ if (blockers.length > 0) continue;
+
+ const lease = activeLeaseMap.get(action.id);
+ const leasedByOther =
+ lease && data.agentId && lease.agentId !== data.agentId;
+ if (leasedByOther && !data.includeLeasedByOthers) continue;
+
+ const score = computeScore(action, edges, now);
+
+ frontier.push({
+ action,
+ score,
+ blockers: [],
+ leased: !!lease,
+ });
+ }
+
+ frontier.sort((a, b) => b.score - a.score);
+ const limit = data.limit || 20;
+
+ return {
+ success: true,
+ frontier: frontier.slice(0, limit),
+ totalActions: actions.length,
+ totalUnblocked: frontier.length,
+ };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::next" },
+ async (data: { project?: string; agentId?: string }) => {
+ const result = await sdk.trigger<
+ { project?: string; agentId?: string; limit?: number },
+ {
+ success: boolean;
+ frontier: FrontierItem[];
+ totalActions: number;
+ totalUnblocked: number;
+ }
+ >("mem::frontier", {
+ project: data.project,
+ agentId: data.agentId,
+ limit: 1,
+ });
+
+ if (!result.success) {
+ return {
+ success: false,
+ suggestion: null,
+ message: "Failed to compute frontier",
+ totalActions: 0,
+ };
+ }
+ if (result.frontier.length === 0) {
+ return {
+ success: true,
+ suggestion: null,
+ message: "No actionable work found",
+ totalActions: result.totalActions || 0,
+ };
+ }
+
+ const top = result.frontier[0];
+ return {
+ success: true,
+ suggestion: {
+ actionId: top.action.id,
+ title: top.action.title,
+ description: top.action.description,
+ priority: top.action.priority,
+ score: top.score,
+ tags: top.action.tags,
+ },
+ message: `Suggested: ${top.action.title} (priority ${top.action.priority}, score ${top.score.toFixed(2)})`,
+ totalActions: result.totalActions,
+ totalUnblocked: result.totalUnblocked,
+ };
+ },
+ );
+}
+
+function computeScore(
+ action: Action,
+ edges: ActionEdge[],
+ now: number,
+): number {
+ let score = action.priority * 10;
+
+ const ageHours =
+ (now - new Date(action.createdAt).getTime()) / (1000 * 60 * 60);
+ score += Math.min(ageHours * 0.5, 20);
+
+ const unlockCount = edges.filter(
+ (e) => e.sourceActionId === action.id && e.type === "unlocks",
+ ).length;
+ score += unlockCount * 5;
+
+ if (edges.some((e) => e.sourceActionId === action.id && e.type === "spawned_by")) {
+ score += 3;
+ }
+
+ if (action.status === "active") score += 15;
+
+ return Math.round(score * 100) / 100;
+}
diff --git a/src/functions/leases.ts b/src/functions/leases.ts
new file mode 100644
index 00000000..748361f5
--- /dev/null
+++ b/src/functions/leases.ts
@@ -0,0 +1,204 @@
+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 { Action, Lease } from "../types.js";
+
+const DEFAULT_LEASE_TTL_MS = 10 * 60 * 1000;
+const MAX_LEASE_TTL_MS = 60 * 60 * 1000;
+
+export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::lease-acquire" },
+ async (data: { actionId: string; agentId: string; ttlMs?: number }) => {
+ if (!data.actionId || !data.agentId) {
+ return { success: false, error: "actionId and agentId are required" };
+ }
+
+ const rawTtl = typeof data.ttlMs === "number" && Number.isFinite(data.ttlMs) && data.ttlMs > 0
+ ? data.ttlMs
+ : DEFAULT_LEASE_TTL_MS;
+ const ttl = Math.min(rawTtl, MAX_LEASE_TTL_MS);
+
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
+ const action = await kv.get<Action>(KV.actions, data.actionId);
+ if (!action) {
+ return { success: false, error: "action not found" };
+ }
+ if (action.status === "done" || action.status === "cancelled") {
+ return { success: false, error: "action already completed" };
+ }
+ if (action.status === "blocked") {
+ return { success: false, error: "action is blocked" };
+ }
+
+ const existingLeases = await kv.list<Lease>(KV.leases);
+ const activeLease = existingLeases.find(
+ (l) =>
+ l.actionId === data.actionId &&
+ l.status === "active" &&
+ new Date(l.expiresAt).getTime() > Date.now(),
+ );
+
+ if (activeLease) {
+ if (activeLease.agentId === data.agentId) {
+ return {
+ success: true,
+ lease: activeLease,
+ renewed: false,
+ message: "Already holding this lease",
+ };
+ }
+ return {
+ success: false,
+ error: "action already leased",
+ heldBy: activeLease.agentId,
+ expiresAt: activeLease.expiresAt,
+ };
+ }
+
+ const now = new Date();
+ const lease: Lease = {
+ id: generateId("lse"),
+ actionId: data.actionId,
+ agentId: data.agentId,
+ acquiredAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + ttl).toISOString(),
+ status: "active",
+ };
+
+ await kv.set(KV.leases, lease.id, lease);
+
+ action.status = "active";
+ action.assignedTo = data.agentId;
+ action.updatedAt = now.toISOString();
+ await kv.set(KV.actions, action.id, action);
+
+ return { success: true, lease, renewed: false };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lease-release" },
+ async (data: { actionId: string; agentId: string; result?: string }) => {
+ if (!data.actionId || !data.agentId) {
+ return { success: false, error: "actionId and agentId are required" };
+ }
+
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
+ const leases = await kv.list<Lease>(KV.leases);
+ const activeLease = leases.find(
+ (l) =>
+ l.actionId === data.actionId &&
+ l.agentId === data.agentId &&
+ l.status === "active" &&
+ new Date(l.expiresAt).getTime() > Date.now(),
+ );
+
+ if (!activeLease) {
+ return { success: false, error: "no active lease found for this agent" };
+ }
+
+ activeLease.status = "released";
+ await kv.set(KV.leases, activeLease.id, activeLease);
+
+ const action = await kv.get<Action>(KV.actions, data.actionId);
+ if (action && action.status === "active" && action.assignedTo === data.agentId) {
+ if (data.result) {
+ action.status = "done";
+ action.result = data.result;
+ } else {
+ action.status = "pending";
+ }
+ action.assignedTo = undefined;
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ }
+
+ return { success: true, released: true };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lease-renew" },
+ async (data: { actionId: string; agentId: string; ttlMs?: number }) => {
+ if (!data.actionId || !data.agentId) {
+ return { success: false, error: "actionId and agentId are required" };
+ }
+
+ const rawTtl = typeof data.ttlMs === "number" && Number.isFinite(data.ttlMs) && data.ttlMs > 0
+ ? data.ttlMs
+ : DEFAULT_LEASE_TTL_MS;
+ const ttl = Math.min(rawTtl, MAX_LEASE_TTL_MS);
+
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
+ const leases = await kv.list<Lease>(KV.leases);
+ const activeLease = leases.find(
+ (l) =>
+ l.actionId === data.actionId &&
+ l.agentId === data.agentId &&
+ l.status === "active" &&
+ new Date(l.expiresAt).getTime() > Date.now(),
+ );
+
+ if (!activeLease) {
+ return { success: false, error: "no active (non-expired) lease to renew" };
+ }
+
+ const now = new Date();
+ const base = Math.max(now.getTime(), new Date(activeLease.expiresAt).getTime());
+ activeLease.expiresAt = new Date(base + ttl).toISOString();
+ activeLease.renewedAt = now.toISOString();
+ await kv.set(KV.leases, activeLease.id, activeLease);
+
+ return { success: true, lease: activeLease };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::lease-cleanup" },
+ async () => {
+ const leases = await kv.list<Lease>(KV.leases);
+ const now = Date.now();
+ let expired = 0;
+
+ for (const lease of leases) {
+ if (
+ lease.status === "active" &&
+ new Date(lease.expiresAt).getTime() <= now
+ ) {
+ const didExpire = await withKeyedLock(
+ `mem:action:${lease.actionId}`,
+ async () => {
+ const currentLease = await kv.get<Lease>(KV.leases, lease.id);
+ if (
+ !currentLease ||
+ currentLease.status !== "active" ||
+ new Date(currentLease.expiresAt).getTime() > Date.now()
+ ) {
+ return false;
+ }
+ currentLease.status = "expired";
+ await kv.set(KV.leases, currentLease.id, currentLease);
+
+ const action = await kv.get<Action>(KV.actions, currentLease.actionId);
+ if (action && action.status === "active" && action.assignedTo === currentLease.agentId) {
+ action.status = "pending";
+ action.assignedTo = undefined;
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ }
+ return true;
+ },
+ );
+ if (didExpire) expired++;
+ }
+ }
+
+ return { success: true, expired };
+ },
+ );
+}
diff --git a/src/functions/mesh.ts b/src/functions/mesh.ts
new file mode 100644
index 00000000..a877ab46
--- /dev/null
+++ b/src/functions/mesh.ts
@@ -0,0 +1,309 @@
+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";
+
+function isAllowedUrl(urlStr: string): boolean {
+ try {
+ const parsed = new URL(urlStr);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
+ const host = parsed.hostname.toLowerCase();
+ if (
+ host === "localhost" ||
+ host === "127.0.0.1" ||
+ host === "::1" ||
+ host === "0.0.0.0" ||
+ host.startsWith("10.") ||
+ host.startsWith("192.168.") ||
+ host === "169.254.169.254" ||
+ /^172\.(1[6-9]|2\d|3[01])\./.test(host) ||
+ host.startsWith("fe80:") ||
+ host.startsWith("fc00:") ||
+ host.startsWith("fd") ||
+ host.startsWith("::ffff:")
+ ) {
+ return false;
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::mesh-register" },
+ async (data: {
+ url: string;
+ name: string;
+ sharedScopes?: string[];
+ }) => {
+ if (!data.url || !data.name) {
+ return { success: false, error: "url and name are required" };
+ }
+
+ if (!isAllowedUrl(data.url)) {
+ return { success: false, error: "URL blocked: private/local address not allowed" };
+ }
+
+ const existing = await kv.list<MeshPeer>(KV.mesh);
+ const duplicate = existing.find((p) => p.url === data.url);
+ if (duplicate) {
+ return { success: false, error: "peer already registered", peerId: duplicate.id };
+ }
+
+ const peer: MeshPeer = {
+ id: generateId("peer"),
+ url: data.url,
+ name: data.name,
+ status: "disconnected",
+ sharedScopes: data.sharedScopes || ["memories", "actions"],
+ };
+
+ await kv.set(KV.mesh, peer.id, peer);
+ return { success: true, peer };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::mesh-list" },
+ async () => {
+ const peers = await kv.list<MeshPeer>(KV.mesh);
+ return { success: true, peers };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::mesh-sync" },
+ async (data: { peerId?: string; scopes?: string[]; direction?: "push" | "pull" | "both" }) => {
+ const direction = data.direction || "both";
+ let peers: MeshPeer[];
+
+ if (data.peerId) {
+ const peer = await kv.get<MeshPeer>(KV.mesh, data.peerId);
+ if (!peer) return { success: false, error: "peer not found" };
+ peers = [peer];
+ } else {
+ peers = await kv.list<MeshPeer>(KV.mesh);
+ }
+
+ const results: Array<{
+ peerId: string;
+ peerName: string;
+ pushed: number;
+ pulled: number;
+ errors: string[];
+ }> = [];
+
+ for (const peer of peers) {
+ const result = {
+ peerId: peer.id,
+ peerName: peer.name,
+ pushed: 0,
+ pulled: 0,
+ errors: [] as string[],
+ };
+
+ peer.status = "syncing";
+ await kv.set(KV.mesh, peer.id, peer);
+
+ const scopes = data.scopes || peer.sharedScopes;
+
+ try {
+ if (!isAllowedUrl(peer.url)) {
+ result.errors.push("peer URL blocked: private/local address not allowed");
+ peer.status = "error";
+ await kv.set(KV.mesh, peer.id, peer);
+ results.push(result);
+ continue;
+ }
+
+ if (direction === "push" || direction === "both") {
+ const pushData = await collectSyncData(kv, scopes, peer.lastSyncAt);
+ try {
+ const response = await fetch(`${peer.url}/agentmemory/mesh/receive`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(pushData),
+ signal: AbortSignal.timeout(30000),
+ redirect: "error",
+ });
+ if (response.ok) {
+ const body = (await response.json()) as { accepted: number };
+ result.pushed = body.accepted || 0;
+ } else {
+ result.errors.push(`push failed: HTTP ${response.status}`);
+ }
+ } catch (err) {
+ result.errors.push(`push failed: ${String(err)}`);
+ }
+ }
+
+ if (direction === "pull" || direction === "both") {
+ try {
+ const response = await fetch(
+ `${peer.url}/agentmemory/mesh/export?since=${peer.lastSyncAt || ""}`,
+ { signal: AbortSignal.timeout(30000), redirect: "error" },
+ );
+ if (response.ok) {
+ const pullData = (await response.json()) as {
+ memories?: Memory[];
+ actions?: Action[];
+ };
+ result.pulled = await applySyncData(kv, pullData, scopes);
+ } else {
+ result.errors.push(`pull failed: HTTP ${response.status}`);
+ }
+ } catch (err) {
+ result.errors.push(`pull failed: ${String(err)}`);
+ }
+ }
+
+ peer.status = result.errors.length > 0 ? "error" : "connected";
+ if (result.errors.length === 0) {
+ peer.lastSyncAt = new Date().toISOString();
+ }
+ } catch (err) {
+ peer.status = "disconnected";
+ result.errors.push(String(err));
+ }
+
+ await kv.set(KV.mesh, peer.id, peer);
+ results.push(result);
+ }
+
+ return { success: true, results };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::mesh-receive" },
+ async (data: { memories?: Memory[]; actions?: Action[] }) => {
+ 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);
+ 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;
+ }
+ 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++;
+ }
+ }
+
+ return { success: true, accepted };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::mesh-remove" },
+ async (data: { peerId: string }) => {
+ if (!data.peerId) {
+ return { success: false, error: "peerId is required" };
+ }
+ await kv.delete(KV.mesh, data.peerId);
+ return { success: true };
+ },
+ );
+}
+
+async function collectSyncData(
+ kv: StateKV,
+ scopes: string[],
+ since?: string,
+): Promise<{ memories?: Memory[]; actions?: Action[] }> {
+ const result: { memories?: Memory[]; actions?: Action[] } = {};
+ 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,
+ );
+ }
+
+ if (scopes.includes("actions")) {
+ const allActions = await kv.list<Action>(KV.actions);
+ result.actions = allActions.filter(
+ (a) => new Date(a.updatedAt).getTime() > sinceTime,
+ );
+ }
+
+ return result;
+}
+
+async function applySyncData(
+ kv: StateKV,
+ data: { memories?: Memory[]; actions?: Action[] },
+ 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("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);
+ return true;
+ }
+ return false;
+ });
+ if (wrote) applied++;
+ }
+ }
+
+ return applied;
+}
diff --git a/src/functions/routines.ts b/src/functions/routines.ts
new file mode 100644
index 00000000..e84f33c3
--- /dev/null
+++ b/src/functions/routines.ts
@@ -0,0 +1,289 @@
+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 { Action, Routine, RoutineStep, RoutineRun } from "../types.js";
+
+export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::routine-create" },
+ async (data: {
+ name: string;
+ description?: string;
+ steps: RoutineStep[];
+ tags?: string[];
+ frozen?: boolean;
+ sourceProceduralIds?: string[];
+ }) => {
+ if (!data.name || !Array.isArray(data.steps) || data.steps.length === 0) {
+ return { success: false, error: "name and steps are required" };
+ }
+
+ for (let i = 0; i < data.steps.length; i++) {
+ if (!data.steps[i].title?.trim()) {
+ return { success: false, error: `step ${i} must have a title` };
+ }
+ }
+
+ const orders = data.steps.map((s, i) => s.order ?? i);
+ const uniqueOrders = new Set(orders);
+ if (uniqueOrders.size !== orders.length) {
+ return { success: false, error: "duplicate step orders" };
+ }
+ for (const step of data.steps) {
+ if (step.dependsOn) {
+ for (const dep of step.dependsOn) {
+ if (!uniqueOrders.has(dep)) {
+ return { success: false, error: `step ${step.order ?? data.steps.indexOf(step)} depends on unknown order ${dep}` };
+ }
+ }
+ }
+ }
+
+ const now = new Date().toISOString();
+ const routine: Routine = {
+ id: generateId("rtn"),
+ name: data.name.trim(),
+ description: (data.description || "").trim(),
+ steps: data.steps.map((s, i) => ({
+ order: s.order ?? i,
+ title: s.title,
+ description: s.description || "",
+ actionTemplate: s.actionTemplate || {},
+ dependsOn: s.dependsOn || [],
+ })),
+ createdAt: now,
+ updatedAt: now,
+ frozen: data.frozen ?? true,
+ tags: data.tags || [],
+ sourceProceduralIds: data.sourceProceduralIds || [],
+ };
+
+ await kv.set(KV.routines, routine.id, routine);
+ return { success: true, routine };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::routine-list" },
+ async (data: { frozen?: boolean; tags?: string[] }) => {
+ let routines = await kv.list<Routine>(KV.routines);
+ if (data.frozen !== undefined) {
+ routines = routines.filter((r) => r.frozen === data.frozen);
+ }
+ if (data.tags && data.tags.length > 0) {
+ routines = routines.filter((r) =>
+ data.tags!.some((t) => r.tags.includes(t)),
+ );
+ }
+ routines.sort(
+ (a, b) =>
+ new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
+ );
+ return { success: true, routines };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::routine-run" },
+ async (data: {
+ routineId: string;
+ initiatedBy?: string;
+ project?: string;
+ overrides?: Record<number, Partial<Action>>;
+ }) => {
+ if (!data.routineId) {
+ return { success: false, error: "routineId is required" };
+ }
+
+ return withKeyedLock(`mem:routine:${data.routineId}`, async () => {
+ const routine = await kv.get<Routine>(KV.routines, data.routineId);
+ if (!routine) {
+ return { success: false, error: "routine not found" };
+ }
+
+ const now = new Date().toISOString();
+ const stepOrderToActionId = new Map<number, string>();
+ const actionIds: string[] = [];
+ const stepStatus: Record<number, "pending" | "active" | "done" | "failed"> = {};
+
+ for (const step of routine.steps) {
+ const template = step.actionTemplate || {};
+ const override = data.overrides?.[step.order] || {};
+
+ const hasDeps = (step.dependsOn || []).length > 0;
+ const action: Action = {
+ id: generateId("act"),
+ title: override.title || template.title || step.title,
+ description:
+ override.description ||
+ template.description ||
+ step.description,
+ status: hasDeps ? "blocked" : "pending",
+ priority:
+ override.priority ?? template.priority ?? 5,
+ createdAt: now,
+ updatedAt: now,
+ createdBy: data.initiatedBy || "routine",
+ project: data.project || template.project,
+ tags: [
+ ...(template.tags || []),
+ ...(override.tags || []),
+ `routine:${routine.id}`,
+ ],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ metadata: { routineId: routine.id, stepOrder: step.order },
+ };
+
+ await kv.set(KV.actions, action.id, action);
+ stepOrderToActionId.set(step.order, action.id);
+ actionIds.push(action.id);
+ stepStatus[step.order] = "pending";
+ }
+
+ for (const step of routine.steps) {
+ const actionId = stepOrderToActionId.get(step.order);
+ if (!actionId) continue;
+
+ for (const depOrder of step.dependsOn) {
+ const depActionId = stepOrderToActionId.get(depOrder);
+ if (!depActionId) continue;
+ const edge = {
+ id: generateId("ae"),
+ type: "requires" as const,
+ sourceActionId: actionId,
+ targetActionId: depActionId,
+ createdAt: now,
+ };
+ await kv.set(KV.actionEdges, edge.id, edge);
+ }
+ }
+
+ const run: RoutineRun = {
+ id: generateId("run"),
+ routineId: routine.id,
+ status: "running",
+ startedAt: now,
+ actionIds,
+ stepStatus,
+ initiatedBy: data.initiatedBy || "unknown",
+ };
+
+ await kv.set(KV.routineRuns, run.id, run);
+
+ return {
+ success: true,
+ run,
+ actionsCreated: actionIds.length,
+ };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::routine-status" },
+ async (data: { runId: string }) => {
+ if (!data.runId) {
+ return { success: false, error: "runId is required" };
+ }
+
+ const run = await kv.get<RoutineRun>(KV.routineRuns, data.runId);
+ if (!run) {
+ return { success: false, error: "run not found" };
+ }
+
+ const actionStates: Array<{
+ actionId: string;
+ status: string;
+ title: string;
+ }> = [];
+ let allDone = true;
+ let anyFailed = false;
+
+ let statusChanged = false;
+ for (const actionId of run.actionIds) {
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (action) {
+ actionStates.push({
+ actionId: action.id,
+ status: action.status,
+ title: action.title,
+ });
+ if (action.status !== "done") allDone = false;
+ if (action.status === "cancelled") anyFailed = true;
+
+ const stepOrder = (action.metadata as { stepOrder?: number })?.stepOrder;
+ if (stepOrder !== undefined && stepOrder in run.stepStatus) {
+ let mapped: "pending" | "active" | "done" | "failed";
+ if (action.status === "cancelled") {
+ mapped = "failed";
+ } else if (action.status === "blocked") {
+ mapped = "pending";
+ } else {
+ mapped = action.status as "pending" | "active" | "done";
+ }
+ if (run.stepStatus[stepOrder] !== mapped) {
+ run.stepStatus[stepOrder] = mapped;
+ statusChanged = true;
+ }
+ }
+ } else {
+ actionStates.push({
+ actionId,
+ status: "cancelled",
+ title: "(missing)",
+ });
+ allDone = false;
+ anyFailed = true;
+ }
+ }
+
+ if (allDone && run.status === "running") {
+ run.status = "completed";
+ run.completedAt = new Date().toISOString();
+ statusChanged = true;
+ } else if (anyFailed && run.status === "running") {
+ run.status = "failed";
+ statusChanged = true;
+ }
+
+ if (statusChanged) {
+ await kv.set(KV.routineRuns, run.id, run);
+ }
+
+ return {
+ success: true,
+ run,
+ actions: actionStates,
+ progress: {
+ total: run.actionIds.length,
+ done: actionStates.filter((a) => a.status === "done").length,
+ active: actionStates.filter((a) => a.status === "active").length,
+ pending: actionStates.filter((a) => a.status === "pending").length,
+ blocked: actionStates.filter((a) => a.status === "blocked").length,
+ cancelled: actionStates.filter((a) => a.status === "cancelled").length,
+ },
+ };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::routine-freeze" },
+ async (data: { routineId: string }) => {
+ if (!data.routineId) {
+ return { success: false, error: "routineId is required" };
+ }
+ return withKeyedLock(`mem:routine:${data.routineId}`, async () => {
+ const routine = await kv.get<Routine>(KV.routines, data.routineId);
+ if (!routine) {
+ return { success: false, error: "routine not found" };
+ }
+ routine.frozen = true;
+ routine.updatedAt = new Date().toISOString();
+ await kv.set(KV.routines, routine.id, routine);
+ return { success: true, routine };
+ });
+ },
+ );
+}
diff --git a/src/functions/sentinels.ts b/src/functions/sentinels.ts
new file mode 100644
index 00000000..f16c8147
--- /dev/null
+++ b/src/functions/sentinels.ts
@@ -0,0 +1,417 @@
+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 { Action, ActionEdge, Checkpoint, CompressedObservation, FunctionMetrics, Sentinel, Session } from "../types.js";
+
+const VALID_TYPES: Sentinel["type"][] = [
+ "webhook",
+ "timer",
+ "threshold",
+ "pattern",
+ "approval",
+ "custom",
+];
+
+export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::sentinel-create" },
+ async (data: {
+ name: string;
+ type: Sentinel["type"];
+ config?: Record<string, unknown>;
+ linkedActionIds?: string[];
+ expiresInMs?: number;
+ }) => {
+ if (!data.name || typeof data.name !== "string") {
+ return { success: false, error: "name is required" };
+ }
+ if (!data.type || !VALID_TYPES.includes(data.type)) {
+ return {
+ success: false,
+ error: `type must be one of: ${VALID_TYPES.join(", ")}`,
+ };
+ }
+
+ if (data.type === "threshold") {
+ const cfg = data.config as
+ | { metric?: string; operator?: string; value?: number }
+ | undefined;
+ if (
+ !cfg ||
+ !cfg.metric ||
+ !["gt", "lt", "eq"].includes(cfg.operator || "") ||
+ typeof cfg.value !== "number"
+ ) {
+ return {
+ success: false,
+ error:
+ "threshold config requires metric, operator (gt|lt|eq), and numeric value",
+ };
+ }
+ }
+
+ if (data.type === "pattern") {
+ const cfg = data.config as { pattern?: string } | undefined;
+ if (!cfg || !cfg.pattern || typeof cfg.pattern !== "string") {
+ return {
+ success: false,
+ error: "pattern config requires a pattern string",
+ };
+ }
+ }
+
+ if (data.type === "webhook") {
+ const cfg = data.config as { path?: string } | undefined;
+ if (!cfg || !cfg.path || typeof cfg.path !== "string") {
+ return {
+ success: false,
+ error: "webhook config requires a path string",
+ };
+ }
+ }
+
+ if (data.type === "timer") {
+ const cfg = data.config as { durationMs?: number } | undefined;
+ if (!cfg || typeof cfg.durationMs !== "number" || cfg.durationMs <= 0) {
+ return {
+ success: false,
+ error: "timer config requires a positive durationMs",
+ };
+ }
+ }
+
+ if (data.linkedActionIds && data.linkedActionIds.length > 0) {
+ for (const actionId of data.linkedActionIds) {
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (!action) {
+ return {
+ success: false,
+ error: `linked action not found: ${actionId}`,
+ };
+ }
+ }
+ }
+
+ const now = new Date();
+ const sentinel: Sentinel = {
+ id: generateId("snl"),
+ name: data.name.trim(),
+ type: data.type,
+ status: "watching",
+ config: data.config || {},
+ createdAt: now.toISOString(),
+ linkedActionIds: data.linkedActionIds || [],
+ expiresAt: data.expiresInMs
+ ? new Date(now.getTime() + data.expiresInMs).toISOString()
+ : undefined,
+ };
+
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+
+ if (data.linkedActionIds && data.linkedActionIds.length > 0) {
+ for (const actionId of data.linkedActionIds) {
+ const edge: ActionEdge = {
+ id: generateId("ae"),
+ type: "gated_by",
+ sourceActionId: actionId,
+ targetActionId: sentinel.id,
+ createdAt: now.toISOString(),
+ };
+ await kv.set(KV.actionEdges, edge.id, edge);
+ }
+ }
+
+ if (data.type === "timer") {
+ const durationMs = (data.config as { durationMs: number }).durationMs;
+ setTimeout(async () => {
+ await withKeyedLock(`mem:sentinel:${sentinel.id}`, async () => {
+ const fresh = await kv.get<Sentinel>(KV.sentinels, sentinel.id);
+ if (!fresh || fresh.status !== "watching") return;
+ fresh.status = "triggered";
+ fresh.triggeredAt = new Date().toISOString();
+ fresh.result = { reason: "timer_elapsed", durationMs };
+ await kv.set(KV.sentinels, fresh.id, fresh);
+ await unblockLinkedActions(kv, fresh);
+ });
+ }, durationMs);
+ }
+
+ return { success: true, sentinel };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sentinel-trigger" },
+ async (data: { sentinelId: string; result?: unknown }) => {
+ if (!data.sentinelId) {
+ return { success: false, error: "sentinelId is required" };
+ }
+
+ return withKeyedLock(
+ `mem:sentinel:${data.sentinelId}`,
+ async () => {
+ const sentinel = await kv.get<Sentinel>(
+ KV.sentinels,
+ data.sentinelId,
+ );
+ if (!sentinel) {
+ return { success: false, error: "sentinel not found" };
+ }
+ if (sentinel.status !== "watching") {
+ return {
+ success: false,
+ error: `sentinel already ${sentinel.status}`,
+ };
+ }
+
+ sentinel.status = "triggered";
+ sentinel.triggeredAt = new Date().toISOString();
+ sentinel.result = data.result;
+
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+
+ let unblockedCount = 0;
+ if (sentinel.linkedActionIds.length > 0) {
+ unblockedCount = await unblockLinkedActions(kv, sentinel);
+ }
+
+ return { success: true, sentinel, unblockedCount };
+ },
+ );
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sentinel-check" },
+ async () => {
+ const sentinels = await kv.list<Sentinel>(KV.sentinels);
+ const active = sentinels.filter((s) => s.status === "watching");
+ const triggered: string[] = [];
+
+ for (const sentinel of active) {
+ if (sentinel.type === "threshold") {
+ const cfg = sentinel.config as {
+ metric: string;
+ operator: "gt" | "lt" | "eq";
+ value: number;
+ };
+ const metrics = await kv.get<FunctionMetrics>(
+ KV.metrics,
+ cfg.metric,
+ );
+ if (!metrics) continue;
+
+ const current = metrics.totalCalls;
+ let matched = false;
+ if (cfg.operator === "gt") matched = current > cfg.value;
+ else if (cfg.operator === "lt") matched = current < cfg.value;
+ else if (cfg.operator === "eq") matched = current === cfg.value;
+
+ if (matched) {
+ await withKeyedLock(
+ `mem:sentinel:${sentinel.id}`,
+ async () => {
+ const fresh = await kv.get<Sentinel>(
+ KV.sentinels,
+ sentinel.id,
+ );
+ if (!fresh || fresh.status !== "watching") return;
+ fresh.status = "triggered";
+ fresh.triggeredAt = new Date().toISOString();
+ fresh.result = {
+ reason: "threshold_crossed",
+ metric: cfg.metric,
+ currentValue: current,
+ threshold: cfg.value,
+ operator: cfg.operator,
+ };
+ await kv.set(KV.sentinels, fresh.id, fresh);
+ await unblockLinkedActions(kv, fresh);
+ },
+ );
+ triggered.push(sentinel.id);
+ }
+ }
+
+ if (sentinel.type === "pattern") {
+ const cfg = sentinel.config as { pattern: string };
+ const regex = new RegExp(cfg.pattern, "i");
+ const sessions = await kv.list<Session>(KV.sessions);
+ let matchedObs: CompressedObservation | null = null;
+
+ for (const session of sessions) {
+ const observations = await kv.list<CompressedObservation>(
+ KV.observations(session.id),
+ );
+ const recent = observations
+ .filter(
+ (o) =>
+ new Date(o.timestamp).getTime() >=
+ new Date(sentinel.createdAt).getTime(),
+ )
+ .find((o) => regex.test(o.title));
+ if (recent) {
+ matchedObs = recent;
+ break;
+ }
+ }
+
+ if (matchedObs) {
+ await withKeyedLock(
+ `mem:sentinel:${sentinel.id}`,
+ async () => {
+ const fresh = await kv.get<Sentinel>(
+ KV.sentinels,
+ sentinel.id,
+ );
+ if (!fresh || fresh.status !== "watching") return;
+ fresh.status = "triggered";
+ fresh.triggeredAt = new Date().toISOString();
+ fresh.result = {
+ reason: "pattern_matched",
+ pattern: cfg.pattern,
+ matchedObservationId: matchedObs!.id,
+ matchedTitle: matchedObs!.title,
+ };
+ await kv.set(KV.sentinels, fresh.id, fresh);
+ await unblockLinkedActions(kv, fresh);
+ },
+ );
+ triggered.push(sentinel.id);
+ }
+ }
+ }
+
+ return { success: true, triggered, checkedCount: active.length };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sentinel-cancel" },
+ async (data: { sentinelId: string }) => {
+ if (!data.sentinelId) {
+ return { success: false, error: "sentinelId is required" };
+ }
+
+ return withKeyedLock(
+ `mem:sentinel:${data.sentinelId}`,
+ async () => {
+ const sentinel = await kv.get<Sentinel>(
+ KV.sentinels,
+ data.sentinelId,
+ );
+ if (!sentinel) {
+ return { success: false, error: "sentinel not found" };
+ }
+ if (sentinel.status !== "watching") {
+ return {
+ success: false,
+ error: `cannot cancel sentinel with status ${sentinel.status}`,
+ };
+ }
+
+ sentinel.status = "cancelled";
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+
+ return { success: true, sentinel };
+ },
+ );
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sentinel-list" },
+ async (data: { status?: string; type?: string }) => {
+ let sentinels = await kv.list<Sentinel>(KV.sentinels);
+
+ if (data.status) {
+ sentinels = sentinels.filter((s) => s.status === data.status);
+ }
+ if (data.type) {
+ sentinels = sentinels.filter((s) => s.type === data.type);
+ }
+
+ sentinels.sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ );
+
+ return { success: true, sentinels };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sentinel-expire" },
+ async () => {
+ const sentinels = await kv.list<Sentinel>(KV.sentinels);
+ const now = Date.now();
+ let expired = 0;
+
+ for (const sentinel of sentinels) {
+ if (
+ sentinel.status === "watching" &&
+ sentinel.expiresAt &&
+ new Date(sentinel.expiresAt).getTime() <= now
+ ) {
+ const didExpire = await withKeyedLock(
+ `mem:sentinel:${sentinel.id}`,
+ async () => {
+ const fresh = await kv.get<Sentinel>(
+ KV.sentinels,
+ sentinel.id,
+ );
+ if (!fresh || fresh.status !== "watching") return false;
+ fresh.status = "expired";
+ fresh.triggeredAt = new Date().toISOString();
+ await kv.set(KV.sentinels, fresh.id, fresh);
+ return true;
+ },
+ );
+ if (didExpire) expired++;
+ }
+ }
+
+ return { success: true, expired };
+ },
+ );
+}
+
+async function unblockLinkedActions(
+ kv: StateKV,
+ sentinel: Sentinel,
+): Promise<number> {
+ if (sentinel.linkedActionIds.length === 0) return 0;
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ const allSentinels = await kv.list<Sentinel>(KV.sentinels);
+ const allCheckpoints = await kv.list<Checkpoint>(KV.checkpoints);
+ const gateMap = new Map<string, { status: string }>();
+ for (const s of allSentinels) gateMap.set(s.id, { status: s.status === "triggered" ? "passed" : s.status });
+ for (const c of allCheckpoints) gateMap.set(c.id, { status: c.status });
+
+ let unblockedCount = 0;
+
+ for (const actionId of sentinel.linkedActionIds) {
+ await withKeyedLock(`mem:action:${actionId}`, async () => {
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (action && action.status === "blocked") {
+ const gates = allEdges.filter(
+ (e) => e.sourceActionId === actionId && e.type === "gated_by",
+ );
+ const allPassed = gates.every((g) => {
+ const gate = gateMap.get(g.targetActionId);
+ return gate && gate.status === "passed";
+ });
+ if (allPassed) {
+ action.status = "pending";
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ unblockedCount++;
+ }
+ }
+ });
+ }
+
+ return unblockedCount;
+}
diff --git a/src/functions/signals.ts b/src/functions/signals.ts
new file mode 100644
index 00000000..4a3b15b5
--- /dev/null
+++ b/src/functions/signals.ts
@@ -0,0 +1,186 @@
+import type { ISdk } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV, generateId } from "../state/schema.js";
+import type { Signal } from "../types.js";
+
+export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::signal-send" },
+ async (data: {
+ from: string;
+ to?: string;
+ content: string;
+ type?: Signal["type"];
+ threadId?: string;
+ replyTo?: string;
+ metadata?: Record<string, unknown>;
+ expiresInMs?: number;
+ }) => {
+ if (!data.from?.trim() || !data.content?.trim()) {
+ return { success: false, error: "from and non-empty content are required" };
+ }
+
+ const now = new Date();
+ let threadId = data.threadId;
+
+ if (data.replyTo && !threadId) {
+ const parent = await kv.get<Signal>(KV.signals, data.replyTo);
+ if (parent) {
+ threadId = parent.threadId || parent.id;
+ }
+ }
+
+ const signal: Signal = {
+ id: generateId("sig"),
+ from: data.from,
+ to: data.to,
+ content: data.content.trim(),
+ type: data.type || "info",
+ threadId: threadId || generateId("thr"),
+ replyTo: data.replyTo,
+ metadata: data.metadata,
+ createdAt: now.toISOString(),
+ expiresAt: data.expiresInMs
+ ? new Date(now.getTime() + data.expiresInMs).toISOString()
+ : undefined,
+ };
+
+ await kv.set(KV.signals, signal.id, signal);
+
+ return { success: true, signal };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::signal-read" },
+ async (data: {
+ agentId: string;
+ unreadOnly?: boolean;
+ threadId?: string;
+ type?: string;
+ limit?: number;
+ }) => {
+ if (!data.agentId) {
+ return { success: false, error: "agentId is required" };
+ }
+
+ let signals = await kv.list<Signal>(KV.signals);
+ const now = Date.now();
+
+ signals = signals.filter((s) => {
+ if (s.expiresAt && new Date(s.expiresAt).getTime() <= now) return false;
+ if (s.to && s.to !== data.agentId && s.from !== data.agentId)
+ return false;
+ if (!s.to && s.from !== data.agentId) return true;
+ return true;
+ });
+
+ if (data.unreadOnly) {
+ signals = signals.filter((s) => !s.readAt && s.to === data.agentId);
+ }
+ if (data.threadId) {
+ signals = signals.filter((s) => s.threadId === data.threadId);
+ }
+ if (data.type) {
+ signals = signals.filter((s) => s.type === data.type);
+ }
+
+ signals.sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ );
+
+ const limit = data.limit || 50;
+ const results = signals.slice(0, limit);
+
+ for (const sig of results) {
+ if (!sig.readAt && sig.to === data.agentId) {
+ sig.readAt = new Date().toISOString();
+ await kv.set(KV.signals, sig.id, sig);
+ }
+ }
+
+ return { success: true, signals: results };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::signal-threads" },
+ async (data: { agentId: string; limit?: number }) => {
+ if (!data.agentId) {
+ return { success: false, error: "agentId is required" };
+ }
+
+ const signals = await kv.list<Signal>(KV.signals);
+ const now = Date.now();
+
+ const relevant = signals.filter((s) => {
+ if (s.expiresAt && new Date(s.expiresAt).getTime() <= now) return false;
+ return (
+ s.from === data.agentId ||
+ s.to === data.agentId ||
+ !s.to
+ );
+ });
+
+ const threadMap = new Map<
+ string,
+ { threadId: string; messages: number; lastMessage: string; participants: Set<string> }
+ >();
+
+ for (const sig of relevant) {
+ const tid = sig.threadId || sig.id;
+ const existing = threadMap.get(tid);
+ if (existing) {
+ existing.messages++;
+ existing.participants.add(sig.from);
+ if (sig.to) existing.participants.add(sig.to);
+ if (new Date(sig.createdAt) > new Date(existing.lastMessage)) {
+ existing.lastMessage = sig.createdAt;
+ }
+ } else {
+ const participants = new Set<string>([sig.from]);
+ if (sig.to) participants.add(sig.to);
+ threadMap.set(tid, {
+ threadId: tid,
+ messages: 1,
+ lastMessage: sig.createdAt,
+ participants,
+ });
+ }
+ }
+
+ const threads = Array.from(threadMap.values())
+ .map((t) => ({
+ ...t,
+ participants: Array.from(t.participants),
+ }))
+ .sort(
+ (a, b) =>
+ new Date(b.lastMessage).getTime() -
+ new Date(a.lastMessage).getTime(),
+ )
+ .slice(0, data.limit || 20);
+
+ return { success: true, threads };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::signal-cleanup" },
+ async () => {
+ const signals = await kv.list<Signal>(KV.signals);
+ const now = Date.now();
+ let removed = 0;
+
+ for (const sig of signals) {
+ if (sig.expiresAt && new Date(sig.expiresAt).getTime() <= now) {
+ await kv.delete(KV.signals, sig.id);
+ removed++;
+ }
+ }
+
+ return { success: true, removed };
+ },
+ );
+}
diff --git a/src/functions/sketches.ts b/src/functions/sketches.ts
new file mode 100644
index 00000000..d8b675ed
--- /dev/null
+++ b/src/functions/sketches.ts
@@ -0,0 +1,274 @@
+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 { Action, ActionEdge, Sketch } from "../types.js";
+
+export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ { id: "mem::sketch-create" },
+ async (data: {
+ title: string;
+ description?: string;
+ expiresInMs?: number;
+ project?: string;
+ }) => {
+ if (!data.title || typeof data.title !== "string") {
+ return { success: false, error: "title is required" };
+ }
+
+ const now = new Date();
+ const expiresInMs = data.expiresInMs || 3600000;
+ const sketch: Sketch = {
+ id: generateId("sk"),
+ title: data.title.trim(),
+ description: (data.description || "").trim(),
+ status: "active",
+ actionIds: [],
+ project: data.project,
+ createdAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + expiresInMs).toISOString(),
+ };
+
+ await kv.set(KV.sketches, sketch.id, sketch);
+ return { success: true, sketch };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sketch-add" },
+ async (data: {
+ sketchId: string;
+ title: string;
+ description?: string;
+ priority?: number;
+ dependsOn?: string[];
+ }) => {
+ if (!data.sketchId) {
+ return { success: false, error: "sketchId is required" };
+ }
+ if (!data.title || typeof data.title !== "string") {
+ return { success: false, error: "title is required" };
+ }
+
+ return withKeyedLock(`mem:sketch:${data.sketchId}`, async () => {
+ const sketch = await kv.get<Sketch>(KV.sketches, data.sketchId);
+ if (!sketch) {
+ return { success: false, error: "sketch not found" };
+ }
+ if (sketch.status !== "active") {
+ return { success: false, error: "sketch is not active" };
+ }
+
+ const now = new Date().toISOString();
+ const action: Action = {
+ id: generateId("act"),
+ title: data.title.trim(),
+ description: (data.description || "").trim(),
+ status: "pending",
+ priority: Math.max(1, Math.min(10, data.priority || 5)),
+ createdAt: now,
+ updatedAt: now,
+ createdBy: "sketch",
+ project: sketch.project,
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ sketchId: data.sketchId,
+ };
+
+ if (data.dependsOn && data.dependsOn.length > 0) {
+ const sketchActionSet = new Set(sketch.actionIds);
+ for (const depId of data.dependsOn) {
+ if (!sketchActionSet.has(depId)) {
+ return {
+ success: false,
+ error: `dependency ${depId} not found in this sketch`,
+ };
+ }
+ }
+ }
+
+ await kv.set(KV.actions, action.id, action);
+
+ const createdEdges: ActionEdge[] = [];
+ if (data.dependsOn && data.dependsOn.length > 0) {
+ for (const depId of data.dependsOn) {
+ const edge: ActionEdge = {
+ id: generateId("ae"),
+ type: "requires",
+ sourceActionId: action.id,
+ targetActionId: depId,
+ createdAt: now,
+ };
+ await kv.set(KV.actionEdges, edge.id, edge);
+ createdEdges.push(edge);
+ }
+ }
+
+ sketch.actionIds.push(action.id);
+ await kv.set(KV.sketches, sketch.id, sketch);
+
+ return { success: true, action, edges: createdEdges };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sketch-promote" },
+ async (data: { sketchId: string; project?: string }) => {
+ if (!data.sketchId) {
+ return { success: false, error: "sketchId is required" };
+ }
+
+ return withKeyedLock(`mem:sketch:${data.sketchId}`, async () => {
+ const sketch = await kv.get<Sketch>(KV.sketches, data.sketchId);
+ if (!sketch) {
+ return { success: false, error: "sketch not found" };
+ }
+ if (sketch.status !== "active") {
+ return { success: false, error: "sketch is not active" };
+ }
+
+ const promotedIds: string[] = [];
+ for (const actionId of sketch.actionIds) {
+ const action = await kv.get<Action>(KV.actions, actionId);
+ if (action) {
+ delete action.sketchId;
+ if (data.project) {
+ action.project = data.project;
+ }
+ action.updatedAt = new Date().toISOString();
+ await kv.set(KV.actions, action.id, action);
+ promotedIds.push(action.id);
+ }
+ }
+
+ sketch.status = "promoted";
+ sketch.promotedAt = new Date().toISOString();
+ await kv.set(KV.sketches, sketch.id, sketch);
+
+ return { success: true, promotedIds };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sketch-discard" },
+ async (data: { sketchId: string }) => {
+ if (!data.sketchId) {
+ return { success: false, error: "sketchId is required" };
+ }
+
+ return withKeyedLock(`mem:sketch:${data.sketchId}`, async () => {
+ const sketch = await kv.get<Sketch>(KV.sketches, data.sketchId);
+ if (!sketch) {
+ return { success: false, error: "sketch not found" };
+ }
+ if (sketch.status !== "active") {
+ return { success: false, error: "sketch is not active" };
+ }
+
+ const actionIdSet = new Set(sketch.actionIds);
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ for (const edge of allEdges) {
+ if (
+ actionIdSet.has(edge.sourceActionId) ||
+ actionIdSet.has(edge.targetActionId)
+ ) {
+ await kv.delete(KV.actionEdges, edge.id);
+ }
+ }
+
+ for (const actionId of sketch.actionIds) {
+ await kv.delete(KV.actions, actionId);
+ }
+
+ sketch.status = "discarded";
+ sketch.discardedAt = new Date().toISOString();
+ await kv.set(KV.sketches, sketch.id, sketch);
+
+ return { success: true, discardedCount: sketch.actionIds.length };
+ });
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sketch-list" },
+ async (data: { status?: string; project?: string }) => {
+ let sketches = await kv.list<Sketch>(KV.sketches);
+
+ if (data.status) {
+ sketches = sketches.filter((s) => s.status === data.status);
+ }
+ if (data.project) {
+ sketches = sketches.filter((s) => s.project === data.project);
+ }
+
+ sketches.sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
+ );
+
+ const results = sketches.map((s) => ({
+ ...s,
+ actionCount: s.actionIds.length,
+ }));
+
+ return { success: true, sketches: results };
+ },
+ );
+
+ sdk.registerFunction(
+ { id: "mem::sketch-gc" },
+ async () => {
+ const sketches = await kv.list<Sketch>(KV.sketches);
+ const now = Date.now();
+ let collected = 0;
+
+ for (const sketch of sketches) {
+ if (
+ sketch.status !== "active" ||
+ new Date(sketch.expiresAt).getTime() > now
+ ) {
+ continue;
+ }
+
+ await withKeyedLock(`mem:sketch:${sketch.id}`, async () => {
+ const current = await kv.get<Sketch>(KV.sketches, sketch.id);
+ if (
+ !current ||
+ current.status !== "active" ||
+ new Date(current.expiresAt).getTime() > now
+ ) {
+ return;
+ }
+
+ const actionIdSet = new Set(current.actionIds);
+
+ const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
+ for (const edge of allEdges) {
+ if (
+ actionIdSet.has(edge.sourceActionId) ||
+ actionIdSet.has(edge.targetActionId)
+ ) {
+ await kv.delete(KV.actionEdges, edge.id);
+ }
+ }
+
+ for (const actionId of current.actionIds) {
+ await kv.delete(KV.actions, actionId);
+ }
+
+ current.status = "discarded";
+ current.discardedAt = new Date().toISOString();
+ await kv.set(KV.sketches, current.id, current);
+ collected++;
+ });
+ }
+
+ return { success: true, collected };
+ },
+ );
+}
diff --git a/src/index.ts b/src/index.ts
index 86be25fe..767ed806 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -48,6 +48,20 @@ import { registerConsolidationPipelineFunction } from "./functions/consolidation
import { registerTeamFunction } from "./functions/team.js";
import { registerGovernanceFunction } from "./functions/governance.js";
import { registerSnapshotFunction } from "./functions/snapshot.js";
+import { registerActionsFunction } from "./functions/actions.js";
+import { registerFrontierFunction } from "./functions/frontier.js";
+import { registerLeasesFunction } from "./functions/leases.js";
+import { registerRoutinesFunction } from "./functions/routines.js";
+import { registerSignalsFunction } from "./functions/signals.js";
+import { registerCheckpointsFunction } from "./functions/checkpoints.js";
+import { registerFlowCompressFunction } from "./functions/flow-compress.js";
+import { registerMeshFunction } from "./functions/mesh.js";
+import { registerBranchAwareFunction } from "./functions/branch-aware.js";
+import { registerSentinelsFunction } from "./functions/sentinels.js";
+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 { registerApiTriggers } from "./triggers/api.js";
import { registerEventTriggers } from "./triggers/events.js";
import { registerMcpEndpoints } from "./mcp/server.js";
@@ -157,6 +171,24 @@ async function main() {
registerGovernanceFunction(sdk, kv);
+ registerActionsFunction(sdk, kv);
+ registerFrontierFunction(sdk, kv);
+ registerLeasesFunction(sdk, kv);
+ registerRoutinesFunction(sdk, kv);
+ registerSignalsFunction(sdk, kv);
+ registerCheckpointsFunction(sdk, kv);
+ registerMeshFunction(sdk, kv);
+ registerBranchAwareFunction(sdk, kv);
+ registerFlowCompressFunction(sdk, kv, provider);
+ registerSentinelsFunction(sdk, kv);
+ registerSketchesFunction(sdk, kv);
+ registerCrystallizeFunction(sdk, kv, provider);
+ registerDiagnosticsFunction(sdk, kv);
+ registerFacetsFunction(sdk, kv);
+ console.log(
+ `[agentmemory] Orchestration layer: actions, frontier, leases, routines, signals, checkpoints, flow-compress, mesh, branch-aware, sentinels, sketches, crystallize, diagnostics, facets`,
+ );
+
const snapshotConfig = loadSnapshotConfig();
if (snapshotConfig.enabled) {
registerSnapshotFunction(sdk, kv, snapshotConfig.dir);
@@ -223,7 +255,7 @@ async function main() {
`[agentmemory] Ready. ${embeddingProvider ? "Hybrid" : "BM25"} search active.`,
);
console.log(
- `[agentmemory] Endpoints: 49 REST + 18 MCP tools + 6 MCP resources + 3 MCP prompts + 33 functions`,
+ `[agentmemory] Endpoints: 93 REST + 37 MCP tools + 6 MCP resources + 3 MCP prompts`,
);
const viewerPort = config.restPort + 2;
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 2b7193b1..db6516a6 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -94,14 +94,14 @@ export function registerMcpEndpoints(
};
}
const type = (args.type as string) || "fact";
- const concepts = args.concepts
- ? (args.concepts as string)
- .split(",")
- .map((c: string) => c.trim())
- : [];
- const files = args.files
- ? (args.files as string).split(",").map((f: string) => f.trim())
- : [];
+ const concepts =
+ typeof args.concepts === "string"
+ ? args.concepts.split(",").map((c: string) => c.trim()).filter(Boolean)
+ : [];
+ const files =
+ typeof args.files === "string"
+ ? args.files.split(",").map((f: string) => f.trim()).filter(Boolean)
+ : [];
const result = await sdk.trigger("mem::remember", {
content: args.content,
@@ -179,12 +179,10 @@ export function registerMcpEndpoints(
body: { error: "query is required for memory_smart_search" },
};
}
- const expandIds = args.expandIds
- ? (args.expandIds as string)
- .split(",")
- .map((id: string) => id.trim())
- .slice(0, 20)
- : [];
+ const expandIds =
+ typeof args.expandIds === "string"
+ ? args.expandIds.split(",").map((id: string) => id.trim()).slice(0, 20)
+ : [];
const result = await sdk.trigger("mem::smart-search", {
query: args.query,
expandIds,
@@ -526,6 +524,397 @@ export function registerMcpEndpoints(
}
}
+ case "memory_action_create": {
+ if (typeof args.title !== "string" || !args.title.trim()) {
+ return {
+ status_code: 400,
+ body: { error: "title is required" },
+ };
+ }
+ const edges: Array<{ type: string; targetActionId: string }> = [];
+ if (typeof args.requires === "string" && args.requires.trim()) {
+ for (const id of args.requires.split(",").map((s: string) => s.trim()).filter(Boolean)) {
+ edges.push({ type: "requires", targetActionId: id });
+ }
+ }
+ const tags = typeof args.tags === "string" && args.tags.trim()
+ ? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean)
+ : [];
+ const actionResult = await sdk.trigger("mem::action-create", {
+ title: args.title,
+ description: args.description,
+ priority: args.priority,
+ project: args.project,
+ tags,
+ parentId: args.parentId,
+ edges: edges.length > 0 ? edges : undefined,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(actionResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_action_update": {
+ if (typeof args.actionId !== "string" || !args.actionId.trim()) {
+ return {
+ status_code: 400,
+ body: { error: "actionId is required" },
+ };
+ }
+ const updateResult = await sdk.trigger("mem::action-update", {
+ actionId: args.actionId,
+ status: args.status,
+ result: args.result,
+ priority: args.priority,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(updateResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_frontier": {
+ const frontierResult = await sdk.trigger("mem::frontier", {
+ project: args.project,
+ agentId: args.agentId,
+ limit: args.limit,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(frontierResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_next": {
+ const nextResult = await sdk.trigger("mem::next", {
+ project: args.project,
+ agentId: args.agentId,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(nextResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_lease": {
+ if (
+ typeof args.actionId !== "string" ||
+ typeof args.agentId !== "string" ||
+ typeof args.operation !== "string"
+ ) {
+ return {
+ status_code: 400,
+ body: { error: "actionId, agentId, and operation are required" },
+ };
+ }
+ const op = args.operation as string;
+ let leaseResult;
+ if (op === "acquire") {
+ leaseResult = await sdk.trigger("mem::lease-acquire", {
+ actionId: args.actionId,
+ agentId: args.agentId,
+ ttlMs: args.ttlMs,
+ });
+ } else if (op === "release") {
+ leaseResult = await sdk.trigger("mem::lease-release", {
+ actionId: args.actionId,
+ agentId: args.agentId,
+ result: args.result,
+ });
+ } else if (op === "renew") {
+ leaseResult = await sdk.trigger("mem::lease-renew", {
+ actionId: args.actionId,
+ agentId: args.agentId,
+ ttlMs: args.ttlMs,
+ });
+ } else {
+ return {
+ status_code: 400,
+ body: { error: "operation must be acquire, release, or renew" },
+ };
+ }
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(leaseResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_routine_run": {
+ if (typeof args.routineId !== "string") {
+ return {
+ status_code: 400,
+ body: { error: "routineId is required" },
+ };
+ }
+ const runResult = await sdk.trigger("mem::routine-run", {
+ routineId: args.routineId,
+ project: args.project,
+ initiatedBy: args.initiatedBy,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(runResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_signal_send": {
+ if (
+ typeof args.from !== "string" ||
+ typeof args.content !== "string"
+ ) {
+ return {
+ status_code: 400,
+ body: { error: "from and content are required" },
+ };
+ }
+ const sigResult = await sdk.trigger("mem::signal-send", {
+ from: args.from,
+ to: args.to,
+ content: args.content,
+ type: args.type,
+ replyTo: args.replyTo,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(sigResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_signal_read": {
+ if (typeof args.agentId !== "string") {
+ return {
+ status_code: 400,
+ body: { error: "agentId is required" },
+ };
+ }
+ const readResult = await sdk.trigger("mem::signal-read", {
+ agentId: args.agentId,
+ unreadOnly: args.unreadOnly === true || args.unreadOnly === "true",
+ threadId: args.threadId,
+ limit: args.limit,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(readResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_checkpoint": {
+ const cpOp = args.operation as string;
+ if (!cpOp) {
+ return {
+ status_code: 400,
+ body: { error: "operation is required" },
+ };
+ }
+ let cpResult;
+ if (cpOp === "create") {
+ const linkedIds = typeof args.linkedActionIds === "string" && args.linkedActionIds.trim()
+ ? args.linkedActionIds.split(",").map((s: string) => s.trim())
+ : [];
+ cpResult = await sdk.trigger("mem::checkpoint-create", {
+ name: args.name,
+ description: args.description,
+ type: args.type,
+ linkedActionIds: linkedIds,
+ });
+ } else if (cpOp === "resolve") {
+ if (typeof args.checkpointId !== "string" || !args.checkpointId.trim()) {
+ return {
+ status_code: 400,
+ body: { error: "checkpointId is required for resolve operation" },
+ };
+ }
+ cpResult = await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: args.checkpointId,
+ status: args.status,
+ });
+ } else if (cpOp === "list") {
+ cpResult = await sdk.trigger("mem::checkpoint-list", {
+ status: args.status,
+ type: args.type,
+ });
+ } else {
+ return {
+ status_code: 400,
+ body: { error: "operation must be create, resolve, or list" },
+ };
+ }
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(cpResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_mesh_sync": {
+ const meshResult = await sdk.trigger("mem::mesh-sync", {
+ peerId: args.peerId,
+ direction: args.direction,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(meshResult, null, 2) },
+ ],
+ },
+ };
+ }
+
+ case "memory_sentinel_create": {
+ let snlConfig: Record<string, unknown> = {};
+ if (typeof args.config === "object" && args.config !== null) {
+ snlConfig = args.config as Record<string, unknown>;
+ } else if (typeof args.config === "string" && args.config.trim()) {
+ try { snlConfig = JSON.parse(args.config); } catch { return { status_code: 400, body: { error: "invalid config JSON" } }; }
+ }
+ const snlLinked = typeof args.linkedActionIds === "string" && args.linkedActionIds.trim()
+ ? args.linkedActionIds.split(",").map((s: string) => s.trim()).filter(Boolean)
+ : undefined;
+ const snlResult = await sdk.trigger("mem::sentinel-create", {
+ name: args.name,
+ type: args.type,
+ config: snlConfig,
+ linkedActionIds: snlLinked,
+ expiresInMs: args.expiresInMs,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlResult, null, 2) }] } };
+ }
+
+ case "memory_sentinel_trigger": {
+ let snlTrigPayload: unknown;
+ if (args.result !== undefined && args.result !== null) {
+ if (typeof args.result === "string") {
+ try { snlTrigPayload = JSON.parse(args.result); } catch { return { status_code: 400, body: { error: "invalid result JSON" } }; }
+ } else {
+ snlTrigPayload = args.result;
+ }
+ }
+ const snlTrigResult = await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: args.sentinelId,
+ result: snlTrigPayload,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlTrigResult, null, 2) }] } };
+ }
+
+ case "memory_sketch_create": {
+ const skResult = await sdk.trigger("mem::sketch-create", {
+ title: args.title,
+ description: args.description,
+ expiresInMs: args.expiresInMs,
+ project: args.project,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skResult, null, 2) }] } };
+ }
+
+ case "memory_sketch_promote": {
+ const skpResult = await sdk.trigger("mem::sketch-promote", {
+ sketchId: args.sketchId,
+ project: args.project,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skpResult, null, 2) }] } };
+ }
+
+ case "memory_crystallize": {
+ if (typeof args.actionIds !== "string" || !args.actionIds.trim()) {
+ return { status_code: 400, body: { error: "actionIds is required" } };
+ }
+ const crysIds = args.actionIds.split(",").map((s: string) => s.trim()).filter(Boolean);
+ const crysResult = await sdk.trigger("mem::crystallize", {
+ actionIds: crysIds,
+ project: args.project,
+ sessionId: args.sessionId,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(crysResult, null, 2) }] } };
+ }
+
+ case "memory_diagnose": {
+ const diagCats = typeof args.categories === "string" && args.categories.trim()
+ ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean)
+ : undefined;
+ const diagResult = await sdk.trigger("mem::diagnose", { categories: diagCats });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(diagResult, null, 2) }] } };
+ }
+
+ case "memory_heal": {
+ const healCats = typeof args.categories === "string" && args.categories.trim()
+ ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean)
+ : undefined;
+ const healResult = await sdk.trigger("mem::heal", {
+ categories: healCats,
+ dryRun: args.dryRun === true || args.dryRun === "true",
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(healResult, null, 2) }] } };
+ }
+
+ case "memory_facet_tag": {
+ const fctResult = await sdk.trigger("mem::facet-tag", {
+ targetId: args.targetId,
+ targetType: args.targetType,
+ dimension: args.dimension,
+ value: args.value,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fctResult, null, 2) }] } };
+ }
+
+ case "memory_facet_query": {
+ if (args.matchAll !== undefined && typeof args.matchAll !== "string") {
+ return { status_code: 400, body: { error: "matchAll must be a string" } };
+ }
+ if (args.matchAny !== undefined && typeof args.matchAny !== "string") {
+ return { status_code: 400, body: { error: "matchAny must be a string" } };
+ }
+ const fqAll = typeof args.matchAll === "string" && args.matchAll.trim()
+ ? args.matchAll.split(",").map((s: string) => s.trim()).filter(Boolean)
+ : undefined;
+ const fqAny = typeof args.matchAny === "string" && args.matchAny.trim()
+ ? args.matchAny.split(",").map((s: string) => s.trim()).filter(Boolean)
+ : undefined;
+ const fqResult = await sdk.trigger("mem::facet-query", {
+ matchAll: fqAll,
+ matchAny: fqAny,
+ targetType: args.targetType,
+ });
+ return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fqResult, null, 2) }] } };
+ }
+
default:
return {
status_code: 400,
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index 3f9f3b26..9732ab53 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -286,6 +286,386 @@ export const V040_TOOLS: McpToolDef[] = [
},
];
+export const V050_TOOLS: McpToolDef[] = [
+ {
+ name: "memory_action_create",
+ description:
+ "Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Action title" },
+ description: {
+ type: "string",
+ description: "Detailed description of the work",
+ },
+ priority: {
+ type: "number",
+ description: "Priority 1-10 (10 highest)",
+ },
+ project: { type: "string", description: "Project path" },
+ tags: {
+ type: "string",
+ description: "Comma-separated tags",
+ },
+ parentId: {
+ type: "string",
+ description: "Parent action ID for hierarchical actions",
+ },
+ requires: {
+ type: "string",
+ description:
+ "Comma-separated action IDs that must complete before this",
+ },
+ },
+ required: ["title"],
+ },
+ },
+ {
+ name: "memory_action_update",
+ description:
+ "Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ actionId: { type: "string", description: "Action ID to update" },
+ status: {
+ type: "string",
+ description: "New status: pending, active, done, blocked, cancelled",
+ },
+ result: {
+ type: "string",
+ description: "Outcome description (when completing)",
+ },
+ priority: { type: "number", description: "New priority 1-10" },
+ },
+ required: ["actionId"],
+ },
+ },
+ {
+ name: "memory_frontier",
+ description:
+ "Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project: { type: "string", description: "Filter by project" },
+ agentId: {
+ type: "string",
+ description: "Agent ID to check lease conflicts",
+ },
+ limit: { type: "number", description: "Max results (default 20)" },
+ },
+ },
+ },
+ {
+ name: "memory_next",
+ description:
+ "Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project: { type: "string", description: "Filter by project" },
+ agentId: { type: "string", description: "Current agent ID" },
+ },
+ },
+ },
+ {
+ name: "memory_lease",
+ description:
+ "Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ actionId: { type: "string", description: "Action ID" },
+ agentId: { type: "string", description: "Agent claiming the action" },
+ operation: {
+ type: "string",
+ description: "acquire, release, or renew",
+ },
+ result: {
+ type: "string",
+ description: "Result when releasing (marks action done)",
+ },
+ ttlMs: {
+ type: "number",
+ description: "Lease duration in ms (default 10min, max 1hr)",
+ },
+ },
+ required: ["actionId", "agentId", "operation"],
+ },
+ },
+ {
+ name: "memory_routine_run",
+ description:
+ "Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ routineId: { type: "string", description: "Routine template ID" },
+ project: { type: "string", description: "Project context" },
+ initiatedBy: { type: "string", description: "Agent starting the run" },
+ },
+ required: ["routineId"],
+ },
+ },
+ {
+ name: "memory_signal_send",
+ description:
+ "Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ from: { type: "string", description: "Sender agent ID" },
+ to: {
+ type: "string",
+ description: "Recipient agent ID (omit for broadcast)",
+ },
+ content: { type: "string", description: "Message content" },
+ type: {
+ type: "string",
+ description: "Message type: info, request, response, alert, handoff",
+ },
+ replyTo: {
+ type: "string",
+ description: "Signal ID to reply to (auto-threads)",
+ },
+ },
+ required: ["from", "content"],
+ },
+ },
+ {
+ name: "memory_signal_read",
+ description:
+ "Read messages for an agent. Marks delivered messages as read.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ agentId: { type: "string", description: "Agent to read messages for" },
+ unreadOnly: {
+ type: "string",
+ description: "Set to 'true' for unread only",
+ },
+ threadId: {
+ type: "string",
+ description: "Filter by conversation thread",
+ },
+ limit: { type: "number", description: "Max messages (default 50)" },
+ },
+ required: ["agentId"],
+ },
+ },
+ {
+ name: "memory_checkpoint",
+ description:
+ "Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ description: "create, resolve, or list",
+ },
+ name: { type: "string", description: "Checkpoint name (for create)" },
+ checkpointId: {
+ type: "string",
+ description: "Checkpoint ID (for resolve)",
+ },
+ status: {
+ type: "string",
+ description: "passed or failed (for resolve)",
+ },
+ type: {
+ type: "string",
+ description: "Checkpoint type: ci, approval, deploy, external, timer",
+ },
+ linkedActionIds: {
+ type: "string",
+ description:
+ "Comma-separated action IDs this checkpoint gates (for create)",
+ },
+ },
+ required: ["operation"],
+ },
+ },
+ {
+ name: "memory_mesh_sync",
+ description:
+ "Sync memories and actions with peer agentmemory instances for multi-agent collaboration.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ peerId: {
+ type: "string",
+ description: "Specific peer ID (omit for all)",
+ },
+ direction: {
+ type: "string",
+ description: "push, pull, or both (default both)",
+ },
+ },
+ },
+ },
+];
+
+export const V051_TOOLS: McpToolDef[] = [
+ {
+ name: "memory_sentinel_create",
+ description:
+ "Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "Sentinel name" },
+ type: {
+ type: "string",
+ description: "Type: webhook, timer, threshold, pattern, approval, custom",
+ },
+ config: {
+ type: "string",
+ description: "JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})",
+ },
+ linkedActionIds: {
+ type: "string",
+ description: "Comma-separated action IDs to gate",
+ },
+ expiresInMs: { type: "number", description: "Auto-expire after ms" },
+ },
+ required: ["name", "type"],
+ },
+ },
+ {
+ name: "memory_sentinel_trigger",
+ description:
+ "Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ sentinelId: { type: "string", description: "Sentinel ID to trigger" },
+ result: { type: "string", description: "JSON result payload" },
+ },
+ required: ["sentinelId"],
+ },
+ },
+ {
+ name: "memory_sketch_create",
+ description:
+ "Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Sketch title" },
+ description: { type: "string", description: "What this sketch explores" },
+ expiresInMs: { type: "number", description: "TTL in ms (default 1 hour)" },
+ project: { type: "string", description: "Project context" },
+ },
+ required: ["title"],
+ },
+ },
+ {
+ name: "memory_sketch_promote",
+ description:
+ "Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ sketchId: { type: "string", description: "Sketch ID to promote" },
+ project: { type: "string", description: "Override project for promoted actions" },
+ },
+ required: ["sketchId"],
+ },
+ },
+ {
+ name: "memory_crystallize",
+ description:
+ "Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ actionIds: {
+ type: "string",
+ description: "Comma-separated completed action IDs to crystallize",
+ },
+ project: { type: "string", description: "Project context" },
+ sessionId: { type: "string", description: "Session context" },
+ },
+ required: ["actionIds"],
+ },
+ },
+ {
+ name: "memory_diagnose",
+ description:
+ "Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ categories: {
+ type: "string",
+ description: "Comma-separated categories to check (default all)",
+ },
+ },
+ },
+ },
+ {
+ name: "memory_heal",
+ description:
+ "Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ categories: {
+ type: "string",
+ description: "Comma-separated categories to heal (default all)",
+ },
+ dryRun: {
+ type: "string",
+ description: "Set to 'true' for dry run (report but don't fix)",
+ },
+ },
+ },
+ },
+ {
+ name: "memory_facet_tag",
+ description:
+ "Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ targetId: { type: "string", description: "ID of the target to tag" },
+ targetType: {
+ type: "string",
+ description: "Type: action, memory, or observation",
+ },
+ dimension: { type: "string", description: "Tag dimension (e.g., priority, team, status)" },
+ value: { type: "string", description: "Tag value (e.g., urgent, backend, reviewed)" },
+ },
+ required: ["targetId", "targetType", "dimension", "value"],
+ },
+ },
+ {
+ name: "memory_facet_query",
+ description:
+ "Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ matchAll: {
+ type: "string",
+ description: "Comma-separated dimension:value pairs (AND logic)",
+ },
+ matchAny: {
+ type: "string",
+ description: "Comma-separated dimension:value pairs (OR logic)",
+ },
+ targetType: {
+ type: "string",
+ description: "Filter by type: action, memory, or observation",
+ },
+ },
+ },
+ },
+];
+
export function getAllTools(): McpToolDef[] {
- return [...CORE_TOOLS, ...V040_TOOLS];
+ return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS];
}
diff --git a/src/state/schema.ts b/src/state/schema.ts
index 8eaca918..1d9366ee 100644
--- a/src/state/schema.ts
+++ b/src/state/schema.ts
@@ -1,3 +1,5 @@
+import { createHash } from "node:crypto";
+
export const KV = {
sessions: "mem:sessions",
observations: (sessionId: string) => `mem:obs:${sessionId}`,
@@ -20,6 +22,18 @@ export const KV = {
`mem:team:${teamId}:users:${userId}`,
teamProfile: (teamId: string) => `mem:team:${teamId}:profile`,
audit: "mem:audit",
+ actions: "mem:actions",
+ actionEdges: "mem:action-edges",
+ leases: "mem:leases",
+ routines: "mem:routines",
+ routineRuns: "mem:routine-runs",
+ signals: "mem:signals",
+ checkpoints: "mem:checkpoints",
+ mesh: "mem:mesh",
+ sketches: "mem:sketches",
+ facets: "mem:facets",
+ sentinels: "mem:sentinels",
+ crystals: "mem:crystals",
} as const;
export const STREAM = {
@@ -34,6 +48,11 @@ export function generateId(prefix: string): string {
return `${prefix}_${ts}_${rand}`;
}
+export function fingerprintId(prefix: string, content: string): string {
+ const hash = createHash("sha256").update(content).digest("hex");
+ return `${prefix}_${hash.slice(0, 16)}`;
+}
+
export function jaccardSimilarity(a: string, b: string): number {
const setA = new Set(a.split(/\s+/).filter((t) => t.length > 2));
const setB = new Set(b.split(/\s+/).filter((t) => t.length > 2));
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index af39497e..2526a8f9 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -991,6 +991,591 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/memories", http_method: "GET" },
});
+ sdk.registerFunction(
+ { id: "api::action-create" },
+ async (
+ req: ApiRequest<{
+ title: string;
+ description?: string;
+ priority?: number;
+ createdBy?: string;
+ project?: string;
+ tags?: string[];
+ parentId?: string;
+ edges?: Array<{ type: string; targetActionId: string }>;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.title) {
+ return { status_code: 400, body: { error: "title is required" } };
+ }
+ const result = await sdk.trigger("mem::action-create", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::action-create",
+ config: { api_path: "/agentmemory/actions", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::action-update" },
+ async (
+ req: ApiRequest<{
+ actionId: string;
+ status?: string;
+ title?: string;
+ description?: string;
+ priority?: number;
+ result?: string;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.actionId) {
+ return { status_code: 400, body: { error: "actionId is required" } };
+ }
+ const result = await sdk.trigger("mem::action-update", req.body);
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::action-update",
+ config: { api_path: "/agentmemory/actions/update", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::action-list" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::action-list", {
+ status: req.query_params?.["status"],
+ project: req.query_params?.["project"],
+ parentId: req.query_params?.["parentId"],
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::action-list",
+ config: { api_path: "/agentmemory/actions", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::action-get" },
+ async (req: ApiRequest<{ actionId: string }>): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const actionId = req.query_params?.["actionId"] as string;
+ if (!actionId) {
+ return { status_code: 400, body: { error: "actionId required" } };
+ }
+ const result = await sdk.trigger("mem::action-get", { actionId });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::action-get",
+ config: { api_path: "/agentmemory/actions/get", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::action-edge" },
+ async (
+ req: ApiRequest<{
+ sourceActionId: string;
+ targetActionId: string;
+ type: string;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) {
+ return { status_code: 400, body: { error: "sourceActionId, targetActionId, and type are required" } };
+ }
+ const result = await sdk.trigger("mem::action-edge-create", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::action-edge",
+ config: { api_path: "/agentmemory/actions/edges", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::frontier" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::frontier", {
+ project: req.query_params?.["project"],
+ agentId: req.query_params?.["agentId"],
+ limit: parseInt(req.query_params?.["limit"] as string) || undefined,
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::frontier",
+ config: { api_path: "/agentmemory/frontier", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::next" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::next", {
+ project: req.query_params?.["project"],
+ agentId: req.query_params?.["agentId"],
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::next",
+ config: { api_path: "/agentmemory/next", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::lease-acquire" },
+ async (
+ req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.actionId || !req.body?.agentId) {
+ return { status_code: 400, body: { error: "actionId and agentId are required" } };
+ }
+ const result = await sdk.trigger("mem::lease-acquire", req.body);
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::lease-acquire",
+ config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::lease-release" },
+ async (
+ req: ApiRequest<{ actionId: string; agentId: string; result?: string }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.actionId || !req.body?.agentId) {
+ return { status_code: 400, body: { error: "actionId and agentId are required" } };
+ }
+ const result = await sdk.trigger("mem::lease-release", req.body);
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::lease-release",
+ config: { api_path: "/agentmemory/leases/release", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::lease-renew" },
+ async (
+ req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.actionId || !req.body?.agentId) {
+ return { status_code: 400, body: { error: "actionId and agentId are required" } };
+ }
+ const result = await sdk.trigger("mem::lease-renew", req.body);
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::lease-renew",
+ config: { api_path: "/agentmemory/leases/renew", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::routine-create" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.name) {
+ return { status_code: 400, body: { error: "name is required" } };
+ }
+ const result = await sdk.trigger("mem::routine-create", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::routine-create",
+ config: { api_path: "/agentmemory/routines", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::routine-list" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::routine-list", {
+ frozen: req.query_params?.["frozen"] === "true" ? true : undefined,
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::routine-list",
+ config: { api_path: "/agentmemory/routines", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::routine-run" },
+ async (
+ req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.routineId) {
+ return { status_code: 400, body: { error: "routineId is required" } };
+ }
+ const result = await sdk.trigger("mem::routine-run", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::routine-run",
+ config: { api_path: "/agentmemory/routines/run", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::routine-status" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const runId = req.query_params?.["runId"] as string;
+ if (!runId) {
+ return { status_code: 400, body: { error: "runId query param required" } };
+ }
+ const result = await sdk.trigger("mem::routine-status", { runId });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::routine-status",
+ config: { api_path: "/agentmemory/routines/status", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::signal-send" },
+ async (
+ req: ApiRequest<{
+ from: string;
+ to?: string;
+ content: string;
+ type?: string;
+ replyTo?: string;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.from || !req.body?.content) {
+ return { status_code: 400, body: { error: "from and content are required" } };
+ }
+ const result = await sdk.trigger("mem::signal-send", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::signal-send",
+ config: { api_path: "/agentmemory/signals/send", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::signal-read" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const agentId = req.query_params?.["agentId"] as string;
+ if (!agentId) {
+ return { status_code: 400, body: { error: "agentId query param required" } };
+ }
+ const result = await sdk.trigger("mem::signal-read", {
+ agentId,
+ unreadOnly: req.query_params?.["unreadOnly"] === "true",
+ threadId: req.query_params?.["threadId"],
+ limit: parseInt(req.query_params?.["limit"] as string) || undefined,
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::signal-read",
+ config: { api_path: "/agentmemory/signals", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::checkpoint-create" },
+ async (
+ req: ApiRequest<{
+ name: string;
+ description?: string;
+ type?: string;
+ linkedActionIds?: string[];
+ expiresInMs?: number;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.name) {
+ return { status_code: 400, body: { error: "name is required" } };
+ }
+ const result = await sdk.trigger("mem::checkpoint-create", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::checkpoint-create",
+ config: { api_path: "/agentmemory/checkpoints", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::checkpoint-resolve" },
+ async (
+ req: ApiRequest<{
+ checkpointId: string;
+ status: string;
+ resolvedBy?: string;
+ result?: unknown;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.checkpointId || !req.body?.status) {
+ return { status_code: 400, body: { error: "checkpointId and status are required" } };
+ }
+ const result = await sdk.trigger("mem::checkpoint-resolve", req.body);
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::checkpoint-resolve",
+ config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::checkpoint-list" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::checkpoint-list", {
+ status: req.query_params?.["status"],
+ type: req.query_params?.["type"],
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::checkpoint-list",
+ config: { api_path: "/agentmemory/checkpoints", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::mesh-register" },
+ async (
+ req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ if (!req.body?.url || !req.body?.name) {
+ return { status_code: 400, body: { error: "url and name are required" } };
+ }
+ const result = await sdk.trigger("mem::mesh-register", req.body);
+ return { status_code: 201, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::mesh-register",
+ config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::mesh-list" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::mesh-list", {});
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::mesh-list",
+ config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::mesh-sync" },
+ async (
+ req: ApiRequest<{ peerId?: string; direction?: string }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::mesh-sync", req.body || {});
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::mesh-sync",
+ config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::mesh-receive" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger("mem::mesh-receive", req.body || {});
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::mesh-receive",
+ config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::mesh-export" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const since = req.query_params?.["since"] as string;
+ if (since) {
+ const parsed = new Date(since).getTime();
+ if (Number.isNaN(parsed)) {
+ 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 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,
+ ),
+ },
+ };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::mesh-export",
+ config: { api_path: "/agentmemory/mesh/export", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::flow-compress" },
+ async (
+ req: ApiRequest<{
+ runId?: string;
+ actionIds?: string[];
+ project?: string;
+ }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ try {
+ const result = await sdk.trigger("mem::flow-compress", req.body || {});
+ return { status_code: 200, body: result };
+ } catch {
+ return {
+ status_code: 404,
+ body: { error: "Flow compression requires a provider" },
+ };
+ }
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::flow-compress",
+ config: { api_path: "/agentmemory/flow/compress", http_method: "POST" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::branch-detect" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const cwd = (req.query_params?.["cwd"] as string) || process.cwd();
+ const result = await sdk.trigger("mem::detect-worktree", { cwd });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::branch-detect",
+ config: { api_path: "/agentmemory/branch/detect", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::branch-worktrees" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const cwd = (req.query_params?.["cwd"] as string) || process.cwd();
+ const result = await sdk.trigger("mem::list-worktrees", { cwd });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::branch-worktrees",
+ config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" },
+ });
+
+ sdk.registerFunction(
+ { id: "api::branch-sessions" },
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const cwd = (req.query_params?.["cwd"] as string) || process.cwd();
+ const result = await sdk.trigger("mem::branch-sessions", { cwd });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::branch-sessions",
+ config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" },
+ });
+
sdk.registerFunction({ id: "api::viewer" }, async (): Promise<Response> => {
const headers = {
"Content-Type": "text/html",
@@ -1019,4 +1604,202 @@ export function registerApiTriggers(
function_id: "api::viewer",
config: { api_path: "/agentmemory/viewer", http_method: "GET" },
});
+
+ sdk.registerFunction({ id: "api::sentinel-create" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.name) return { status_code: 400, body: { error: "name is required" } };
+ const result = await sdk.trigger("mem::sentinel-create", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sentinel-trigger" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } };
+ const result = await sdk.trigger("mem::sentinel-trigger", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sentinel-check" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const result = await sdk.trigger("mem::sentinel-check", {});
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sentinel-cancel" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } };
+ const result = await sdk.trigger("mem::sentinel-cancel", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sentinel-list" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ const result = await sdk.trigger("mem::sentinel-list", { status: params.status, type: params.type });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::sketch-create" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.title) return { status_code: 400, body: { error: "title is required" } };
+ const result = await sdk.trigger("mem::sketch-create", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sketch-add" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.sketchId || !body?.title) return { status_code: 400, body: { error: "sketchId and title are required" } };
+ const result = await sdk.trigger("mem::sketch-add", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sketch-promote" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } };
+ const result = await sdk.trigger("mem::sketch-promote", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sketch-discard" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } };
+ const result = await sdk.trigger("mem::sketch-discard", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::sketch-list" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ const result = await sdk.trigger("mem::sketch-list", { status: params.status, project: params.project });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::sketch-gc" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const result = await sdk.trigger("mem::sketch-gc", {});
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::crystallize" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.actionIds) return { status_code: 400, body: { error: "actionIds is required" } };
+ const result = await sdk.trigger("mem::crystallize", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::crystal-list" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ const result = await sdk.trigger("mem::crystal-list", { project: params.project, sessionId: params.sessionId, limit: params.limit ? parseInt(params.limit as string) : undefined });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::auto-crystallize" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ const result = await sdk.trigger("mem::auto-crystallize", body || {});
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::diagnose" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ const result = await sdk.trigger("mem::diagnose", body || {});
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::heal" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ const result = await sdk.trigger("mem::heal", body || {});
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::facet-tag" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.targetId || !body?.dimension || !body?.value) return { status_code: 400, body: { error: "targetId, dimension, and value are required" } };
+ const result = await sdk.trigger("mem::facet-tag", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::facet-untag" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ if (!body?.targetId || !body?.dimension) return { status_code: 400, body: { error: "targetId and dimension are required" } };
+ const result = await sdk.trigger("mem::facet-untag", body);
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::facet-query" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const body = req.body as Record<string, unknown>;
+ const result = await sdk.trigger("mem::facet-query", body || {});
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } });
+
+ sdk.registerFunction({ id: "api::facet-get" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ if (!params.targetId) return { status_code: 400, body: { error: "targetId query param is required" } };
+ const result = await sdk.trigger("mem::facet-get", { targetId: params.targetId });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } });
+
+ sdk.registerFunction({ id: "api::facet-stats" }, async (req: ApiRequest) => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const params = req.query_params || {};
+ const result = await sdk.trigger("mem::facet-stats", { targetType: params.targetType });
+ return { status_code: 200, body: result };
+ });
+ sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } });
}
diff --git a/src/types.ts b/src/types.ts
index 90c78913..c638160e 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -237,7 +237,7 @@ export interface ProjectProfile {
}
export interface ExportData {
- version: "0.3.0" | "0.4.0";
+ version: "0.3.0" | "0.4.0" | "0.5.0";
exportedAt: string;
sessions: Session[];
observations: Record<string, CompressedObservation[]>;
@@ -248,6 +248,15 @@ export interface ExportData {
graphEdges?: GraphEdge[];
semanticMemories?: SemanticMemory[];
proceduralMemories?: ProceduralMemory[];
+ actions?: Action[];
+ actionEdges?: ActionEdge[];
+ routines?: Routine[];
+ signals?: Signal[];
+ checkpoints?: Checkpoint[];
+ sentinels?: Sentinel[];
+ sketches?: Sketch[];
+ crystals?: Crystal[];
+ facets?: Facet[];
}
export interface EmbeddingConfig {
@@ -383,7 +392,24 @@ export interface AuditEntry {
| "share"
| "delete"
| "import"
- | "export";
+ | "export"
+ | "action_create"
+ | "action_update"
+ | "lease_acquire"
+ | "lease_release"
+ | "routine_run"
+ | "signal_send"
+ | "checkpoint_resolve"
+ | "mesh_sync"
+ | "sentinel_create"
+ | "sentinel_trigger"
+ | "sketch_create"
+ | "sketch_promote"
+ | "sketch_discard"
+ | "crystallize"
+ | "diagnose"
+ | "heal"
+ | "facet_tag";
userId?: string;
functionId: string;
targetIds: string[];
@@ -418,3 +444,174 @@ export interface SnapshotDiff {
added: { memories: number; observations: number; graphNodes: number };
removed: { memories: number; observations: number; graphNodes: number };
}
+
+export interface Action {
+ id: string;
+ title: string;
+ description: string;
+ status: "pending" | "active" | "done" | "blocked" | "cancelled";
+ priority: number;
+ createdAt: string;
+ updatedAt: string;
+ createdBy: string;
+ assignedTo?: string;
+ project?: string;
+ tags: string[];
+ sourceObservationIds: string[];
+ sourceMemoryIds: string[];
+ result?: string;
+ parentId?: string;
+ metadata?: Record<string, unknown>;
+ sketchId?: string;
+ crystallizedInto?: string;
+}
+
+export type ActionEdgeType =
+ | "requires"
+ | "unlocks"
+ | "spawned_by"
+ | "gated_by"
+ | "conflicts_with";
+
+export interface ActionEdge {
+ id: string;
+ type: ActionEdgeType;
+ sourceActionId: string;
+ targetActionId: string;
+ createdAt: string;
+ metadata?: Record<string, unknown>;
+}
+
+export interface Lease {
+ id: string;
+ actionId: string;
+ agentId: string;
+ acquiredAt: string;
+ expiresAt: string;
+ renewedAt?: string;
+ status: "active" | "expired" | "released";
+}
+
+export interface Routine {
+ id: string;
+ name: string;
+ description: string;
+ steps: RoutineStep[];
+ createdAt: string;
+ updatedAt: string;
+ frozen: boolean;
+ tags: string[];
+ sourceProceduralIds: string[];
+}
+
+export interface RoutineStep {
+ order: number;
+ title: string;
+ description: string;
+ actionTemplate: Partial<Action>;
+ dependsOn: number[];
+}
+
+export interface RoutineRun {
+ id: string;
+ routineId: string;
+ status: "running" | "completed" | "failed" | "paused";
+ startedAt: string;
+ completedAt?: string;
+ actionIds: string[];
+ stepStatus: Record<number, "pending" | "active" | "done" | "failed">;
+ initiatedBy: string;
+}
+
+export interface Signal {
+ id: string;
+ from: string;
+ to?: string;
+ threadId?: string;
+ replyTo?: string;
+ type: "info" | "request" | "response" | "alert" | "handoff";
+ content: string;
+ metadata?: Record<string, unknown>;
+ createdAt: string;
+ readAt?: string;
+ expiresAt?: string;
+}
+
+export interface Checkpoint {
+ id: string;
+ name: string;
+ description: string;
+ status: "pending" | "passed" | "failed" | "expired";
+ type: "ci" | "approval" | "deploy" | "external" | "timer";
+ createdAt: string;
+ resolvedAt?: string;
+ resolvedBy?: string;
+ result?: unknown;
+ expiresAt?: string;
+ linkedActionIds: string[];
+}
+
+export interface Sketch {
+ id: string;
+ title: string;
+ description: string;
+ status: "active" | "promoted" | "discarded";
+ actionIds: string[];
+ project?: string;
+ createdAt: string;
+ expiresAt: string;
+ promotedAt?: string;
+ discardedAt?: string;
+}
+
+export interface Facet {
+ id: string;
+ targetId: string;
+ targetType: "action" | "memory" | "observation";
+ dimension: string;
+ value: string;
+ createdAt: string;
+}
+
+export interface Sentinel {
+ id: string;
+ name: string;
+ type: "webhook" | "timer" | "threshold" | "pattern" | "approval" | "custom";
+ status: "watching" | "triggered" | "cancelled" | "expired";
+ config: Record<string, unknown>;
+ result?: unknown;
+ createdAt: string;
+ triggeredAt?: string;
+ expiresAt?: string;
+ linkedActionIds: string[];
+ escalatedAt?: string;
+}
+
+export interface Crystal {
+ id: string;
+ narrative: string;
+ keyOutcomes: string[];
+ filesAffected: string[];
+ lessons: string[];
+ sourceActionIds: string[];
+ sessionId?: string;
+ project?: string;
+ createdAt: string;
+}
+
+export interface DiagnosticCheck {
+ name: string;
+ category: string;
+ status: "pass" | "warn" | "fail";
+ message: string;
+ fixable: boolean;
+}
+
+export interface MeshPeer {
+ id: string;
+ url: string;
+ name: string;
+ lastSyncAt?: string;
+ status: "connected" | "disconnected" | "syncing" | "error";
+ sharedScopes: string[];
+}
diff --git a/src/version.ts b/src/version.ts
index d155091a..c4df4e88 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1 @@
-export const VERSION: "0.3.0" | "0.4.0" = "0.4.0";
+export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" = "0.5.0";
diff --git a/src/viewer/index.html b/src/viewer/index.html
index 611deac6..4366bf01 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -727,7 +727,7 @@
<div class="app-header">
<div class="brand">
<h1>agentmemory</h1>
- <span class="version">v0.4.0</span>
+ <span class="version">v0.5.0</span>
</div>
<div class="header-right">
<span class="dateline" id="dateline"></span>
diff --git a/src/viewer/server.ts b/src/viewer/server.ts
index b0b597fb..3f26725e 100644
--- a/src/viewer/server.ts
+++ b/src/viewer/server.ts
@@ -498,7 +498,7 @@ async function handleApiRoute(
{
status,
service: "agentmemory",
- version: "0.4.0",
+ version: "0.5.0",
health: health || null,
functionMetrics,
circuitBreaker,
@@ -512,7 +512,7 @@ async function handleApiRoute(
{
status: "healthy",
service: "agentmemory",
- version: "0.4.0",
+ version: "0.5.0",
health: null,
functionMetrics: [],
circuitBreaker: null,
diff --git a/test/actions.test.ts b/test/actions.test.ts
new file mode 100644
index 00000000..d6b2b2f8
--- /dev/null
+++ b/test/actions.test.ts
@@ -0,0 +1,490 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerActionsFunction } from "../src/functions/actions.js";
+import type { Action, ActionEdge } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Actions Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerActionsFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::action-create", () => {
+ it("creates an action with valid data", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Fix login bug",
+ description: "Users cannot log in with SSO",
+ priority: 7,
+ createdBy: "agent-1",
+ project: "webapp",
+ tags: ["bug", "auth"],
+ })) as { success: boolean; action: Action; edges: ActionEdge[] };
+
+ expect(result.success).toBe(true);
+ expect(result.action.id).toMatch(/^act_/);
+ expect(result.action.title).toBe("Fix login bug");
+ expect(result.action.description).toBe("Users cannot log in with SSO");
+ expect(result.action.status).toBe("pending");
+ expect(result.action.priority).toBe(7);
+ expect(result.action.createdBy).toBe("agent-1");
+ expect(result.action.project).toBe("webapp");
+ expect(result.action.tags).toEqual(["bug", "auth"]);
+ expect(result.action.createdAt).toBeDefined();
+ expect(result.action.updatedAt).toBeDefined();
+ expect(result.edges).toEqual([]);
+ });
+
+ it("returns error when title is missing", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ description: "No title provided",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("title is required");
+ });
+
+ it("clamps priority 0 to default 5 (falsy fallback)", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Zero priority task",
+ priority: 0,
+ })) as { success: boolean; action: Action };
+
+ expect(result.success).toBe(true);
+ expect(result.action.priority).toBe(5);
+ });
+
+ it("clamps negative priority to 1", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Negative priority task",
+ priority: -3,
+ })) as { success: boolean; action: Action };
+
+ expect(result.success).toBe(true);
+ expect(result.action.priority).toBe(1);
+ });
+
+ it("clamps priority 15 to 10", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "High priority task",
+ priority: 15,
+ })) as { success: boolean; action: Action };
+
+ expect(result.success).toBe(true);
+ expect(result.action.priority).toBe(10);
+ });
+
+ it("validates parent action exists", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Child task",
+ parentId: "nonexistent_parent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("parent action not found");
+ });
+
+ it("creates action with valid parent", async () => {
+ const parentResult = (await sdk.trigger("mem::action-create", {
+ title: "Parent task",
+ })) as { success: boolean; action: Action };
+
+ const childResult = (await sdk.trigger("mem::action-create", {
+ title: "Child task",
+ parentId: parentResult.action.id,
+ })) as { success: boolean; action: Action };
+
+ expect(childResult.success).toBe(true);
+ expect(childResult.action.parentId).toBe(parentResult.action.id);
+ });
+
+ it("creates inline edges with valid types", async () => {
+ const targetResult = (await sdk.trigger("mem::action-create", {
+ title: "Target action",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Source action",
+ edges: [
+ { type: "requires", targetActionId: targetResult.action.id },
+ { type: "unlocks", targetActionId: targetResult.action.id },
+ ],
+ })) as { success: boolean; action: Action; edges: ActionEdge[] };
+
+ expect(result.success).toBe(true);
+ expect(result.edges.length).toBe(2);
+ expect(result.edges[0].id).toMatch(/^ae_/);
+ expect(result.edges[0].type).toBe("requires");
+ expect(result.edges[0].sourceActionId).toBe(result.action.id);
+ expect(result.edges[0].targetActionId).toBe(targetResult.action.id);
+ expect(result.edges[1].type).toBe("unlocks");
+ });
+
+ it("returns error for inline edge with invalid type", async () => {
+ const targetResult = (await sdk.trigger("mem::action-create", {
+ title: "Target action",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Source action",
+ edges: [
+ { type: "invalid_type", targetActionId: targetResult.action.id },
+ ],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("invalid edge type");
+ });
+
+ it("returns error for inline edge with nonexistent target", async () => {
+ const result = (await sdk.trigger("mem::action-create", {
+ title: "Source action",
+ edges: [{ type: "requires", targetActionId: "nonexistent_id" }],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("target action not found");
+ });
+ });
+
+ describe("mem::action-update", () => {
+ it("updates an action with valid data", async () => {
+ const createResult = (await sdk.trigger("mem::action-create", {
+ title: "Original title",
+ priority: 5,
+ })) as { success: boolean; action: Action };
+
+ const updateResult = (await sdk.trigger("mem::action-update", {
+ actionId: createResult.action.id,
+ title: "Updated title",
+ priority: 8,
+ status: "active",
+ assignedTo: "agent-2",
+ tags: ["updated"],
+ })) as { success: boolean; action: Action };
+
+ expect(updateResult.success).toBe(true);
+ expect(updateResult.action.title).toBe("Updated title");
+ expect(updateResult.action.priority).toBe(8);
+ expect(updateResult.action.status).toBe("active");
+ expect(updateResult.action.assignedTo).toBe("agent-2");
+ expect(updateResult.action.tags).toEqual(["updated"]);
+ });
+
+ it("returns error when actionId is missing", async () => {
+ const result = (await sdk.trigger("mem::action-update", {
+ title: "no id",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("actionId is required");
+ });
+
+ it("returns error for nonexistent action", async () => {
+ const result = (await sdk.trigger("mem::action-update", {
+ actionId: "nonexistent_id",
+ status: "done",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("action not found");
+ });
+
+ it("propagates completion when status set to done", async () => {
+ const actionB = (await sdk.trigger("mem::action-create", {
+ title: "Dependency B",
+ })) as { success: boolean; action: Action };
+
+ const actionA = (await sdk.trigger("mem::action-create", {
+ title: "Action A depends on B",
+ edges: [{ type: "requires", targetActionId: actionB.action.id }],
+ })) as { success: boolean; action: Action };
+
+ await sdk.trigger("mem::action-update", {
+ actionId: actionA.action.id,
+ status: "blocked",
+ });
+
+ await sdk.trigger("mem::action-update", {
+ actionId: actionB.action.id,
+ status: "done",
+ });
+
+ const getResult = (await sdk.trigger("mem::action-get", {
+ actionId: actionA.action.id,
+ })) as { success: boolean; action: Action };
+
+ expect(getResult.action.status).toBe("pending");
+ });
+ });
+
+ describe("mem::action-edge-create", () => {
+ it("creates an edge between two actions", async () => {
+ const source = (await sdk.trigger("mem::action-create", {
+ title: "Source",
+ })) as { success: boolean; action: Action };
+
+ const target = (await sdk.trigger("mem::action-create", {
+ title: "Target",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::action-edge-create", {
+ sourceActionId: source.action.id,
+ targetActionId: target.action.id,
+ type: "requires",
+ })) as { success: boolean; edge: ActionEdge };
+
+ expect(result.success).toBe(true);
+ expect(result.edge.id).toMatch(/^ae_/);
+ expect(result.edge.type).toBe("requires");
+ expect(result.edge.sourceActionId).toBe(source.action.id);
+ expect(result.edge.targetActionId).toBe(target.action.id);
+ expect(result.edge.createdAt).toBeDefined();
+ });
+
+ it("returns error when required fields are missing", async () => {
+ const result = (await sdk.trigger("mem::action-edge-create", {
+ sourceActionId: "some_id",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("required");
+ });
+
+ it("returns error for invalid edge type", async () => {
+ const source = (await sdk.trigger("mem::action-create", {
+ title: "Source",
+ })) as { success: boolean; action: Action };
+
+ const target = (await sdk.trigger("mem::action-create", {
+ title: "Target",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::action-edge-create", {
+ sourceActionId: source.action.id,
+ targetActionId: target.action.id,
+ type: "invalid_type",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("type must be one of");
+ });
+
+ it("returns error for nonexistent source action", async () => {
+ const target = (await sdk.trigger("mem::action-create", {
+ title: "Target",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::action-edge-create", {
+ sourceActionId: "nonexistent",
+ targetActionId: target.action.id,
+ type: "requires",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("source action not found");
+ });
+
+ it("returns error for nonexistent target action", async () => {
+ const source = (await sdk.trigger("mem::action-create", {
+ title: "Source",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::action-edge-create", {
+ sourceActionId: source.action.id,
+ targetActionId: "nonexistent",
+ type: "requires",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("target action not found");
+ });
+ });
+
+ describe("mem::action-list", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::action-create", {
+ title: "Task A",
+ status: "pending",
+ project: "alpha",
+ tags: ["frontend"],
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ await sdk.trigger("mem::action-create", {
+ title: "Task B",
+ project: "alpha",
+ tags: ["backend"],
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ await sdk.trigger("mem::action-create", {
+ title: "Task C",
+ project: "beta",
+ tags: ["frontend", "backend"],
+ });
+ });
+
+ it("returns all actions", async () => {
+ const result = (await sdk.trigger("mem::action-list", {})) as {
+ success: boolean;
+ actions: Action[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.actions.length).toBe(3);
+ });
+
+ it("filters by status", async () => {
+ const all = (await sdk.trigger("mem::action-list", {})) as {
+ actions: Action[];
+ };
+ const firstAction = all.actions[0];
+
+ await sdk.trigger("mem::action-update", {
+ actionId: firstAction.id,
+ status: "done",
+ });
+
+ const result = (await sdk.trigger("mem::action-list", {
+ status: "done",
+ })) as { success: boolean; actions: Action[] };
+
+ expect(result.success).toBe(true);
+ expect(result.actions.length).toBe(1);
+ expect(result.actions[0].status).toBe("done");
+ });
+
+ it("filters by project", async () => {
+ const result = (await sdk.trigger("mem::action-list", {
+ project: "alpha",
+ })) as { success: boolean; actions: Action[] };
+
+ expect(result.success).toBe(true);
+ expect(result.actions.length).toBe(2);
+ expect(result.actions.every((a) => a.project === "alpha")).toBe(true);
+ });
+
+ it("filters by tags", async () => {
+ const result = (await sdk.trigger("mem::action-list", {
+ tags: ["backend"],
+ })) as { success: boolean; actions: Action[] };
+
+ expect(result.success).toBe(true);
+ expect(result.actions.length).toBe(2);
+ expect(
+ result.actions.every((a) => a.tags.includes("backend")),
+ ).toBe(true);
+ });
+
+ it("respects limit", async () => {
+ const result = (await sdk.trigger("mem::action-list", {
+ limit: 2,
+ })) as { success: boolean; actions: Action[] };
+
+ expect(result.success).toBe(true);
+ expect(result.actions.length).toBe(2);
+ });
+ });
+
+ describe("mem::action-get", () => {
+ it("returns action with edges and children", async () => {
+ const parent = (await sdk.trigger("mem::action-create", {
+ title: "Parent",
+ })) as { success: boolean; action: Action };
+
+ const child = (await sdk.trigger("mem::action-create", {
+ title: "Child",
+ parentId: parent.action.id,
+ })) as { success: boolean; action: Action };
+
+ const other = (await sdk.trigger("mem::action-create", {
+ title: "Other",
+ })) as { success: boolean; action: Action };
+
+ await sdk.trigger("mem::action-edge-create", {
+ sourceActionId: parent.action.id,
+ targetActionId: other.action.id,
+ type: "unlocks",
+ });
+
+ const result = (await sdk.trigger("mem::action-get", {
+ actionId: parent.action.id,
+ })) as {
+ success: boolean;
+ action: Action;
+ edges: ActionEdge[];
+ children: Action[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.action.id).toBe(parent.action.id);
+ expect(result.edges.length).toBe(1);
+ expect(result.edges[0].type).toBe("unlocks");
+ expect(result.children.length).toBe(1);
+ expect(result.children[0].id).toBe(child.action.id);
+ });
+
+ it("returns error for missing actionId", async () => {
+ const result = (await sdk.trigger("mem::action-get", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("actionId is required");
+ });
+
+ it("returns error for nonexistent action", async () => {
+ const result = (await sdk.trigger("mem::action-get", {
+ actionId: "nonexistent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("action not found");
+ });
+ });
+});
diff --git a/test/checkpoints.test.ts b/test/checkpoints.test.ts
new file mode 100644
index 00000000..bdb62972
--- /dev/null
+++ b/test/checkpoints.test.ts
@@ -0,0 +1,493 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerCheckpointsFunction } from "../src/functions/checkpoints.js";
+import type { Action, ActionEdge, Checkpoint } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+function makeAction(
+ id: string,
+ status: Action["status"] = "blocked",
+): Action {
+ return {
+ id,
+ title: `Action ${id}`,
+ description: `Description for ${id}`,
+ status,
+ priority: 5,
+ createdAt: "2026-02-01T00:00:00Z",
+ updatedAt: "2026-02-01T00:00:00Z",
+ createdBy: "agent-setup",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ };
+}
+
+describe("Checkpoint Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(async () => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerCheckpointsFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::checkpoint-create", () => {
+ it("creates a checkpoint with valid name", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-create", {
+ name: "CI Build",
+ description: "Wait for CI to pass",
+ type: "ci",
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoint.name).toBe("CI Build");
+ expect(result.checkpoint.description).toBe("Wait for CI to pass");
+ expect(result.checkpoint.status).toBe("pending");
+ expect(result.checkpoint.type).toBe("ci");
+ expect(result.checkpoint.id).toMatch(/^ckpt_/);
+ });
+
+ it("returns error when name is missing", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-create", {
+ name: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("name is required");
+ });
+
+ it("defaults type to external when not specified", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-create", {
+ name: "External Gate",
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoint.type).toBe("external");
+ });
+
+ it("sets expiresAt when expiresInMs is provided", async () => {
+ const before = Date.now();
+ const result = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Timed Gate",
+ expiresInMs: 60000,
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoint.expiresAt).toBeDefined();
+ const expiresAt = new Date(result.checkpoint.expiresAt!).getTime();
+ expect(expiresAt).toBeGreaterThanOrEqual(before + 60000);
+ });
+
+ it("creates action edges for linkedActionIds", async () => {
+ await kv.set("mem:actions", "act_1", makeAction("act_1"));
+ await kv.set("mem:actions", "act_2", makeAction("act_2"));
+
+ const result = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Deployment Gate",
+ type: "deploy",
+ linkedActionIds: ["act_1", "act_2"],
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoint.linkedActionIds).toEqual(["act_1", "act_2"]);
+
+ const edges = await kv.list<ActionEdge>("mem:action-edges");
+ expect(edges.length).toBe(2);
+ expect(edges[0].type).toBe("gated_by");
+ expect(edges[0].targetActionId).toBe(result.checkpoint.id);
+ expect(edges.map((e) => e.sourceActionId).sort()).toEqual(["act_1", "act_2"]);
+ });
+
+ it("creates no edges when linkedActionIds is empty", async () => {
+ await sdk.trigger("mem::checkpoint-create", {
+ name: "No Links",
+ linkedActionIds: [],
+ });
+
+ const edges = await kv.list<ActionEdge>("mem:action-edges");
+ expect(edges.length).toBe(0);
+ });
+ });
+
+ describe("mem::checkpoint-resolve", () => {
+ it("resolves a pending checkpoint to passed", async () => {
+ const created = (await sdk.trigger("mem::checkpoint-create", {
+ name: "CI Gate",
+ type: "ci",
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: created.checkpoint.id,
+ status: "passed",
+ resolvedBy: "ci-bot",
+ result: { buildId: 123 },
+ })) as { success: boolean; checkpoint: Checkpoint; unblockedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoint.status).toBe("passed");
+ expect(result.checkpoint.resolvedBy).toBe("ci-bot");
+ expect(result.checkpoint.resolvedAt).toBeDefined();
+ expect(result.checkpoint.result).toEqual({ buildId: 123 });
+ });
+
+ it("resolves a pending checkpoint to failed", async () => {
+ const created = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Approval Gate",
+ type: "approval",
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: created.checkpoint.id,
+ status: "failed",
+ resolvedBy: "reviewer",
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoint.status).toBe("failed");
+ });
+
+ it("returns error when checkpoint is already resolved", async () => {
+ const created = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Already Done",
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: created.checkpoint.id,
+ status: "passed",
+ });
+
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: created.checkpoint.id,
+ status: "failed",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("checkpoint already passed");
+ });
+
+ it("returns error for nonexistent checkpoint", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: "ckpt_nonexistent",
+ status: "passed",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("checkpoint not found");
+ });
+
+ it("returns error when checkpointId or status is missing", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: "",
+ status: "passed",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("checkpointId and status are required");
+ });
+
+ it("unblocks gated actions when all checkpoints pass", async () => {
+ await kv.set("mem:actions", "act_1", makeAction("act_1", "blocked"));
+
+ const cp1 = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Gate 1",
+ type: "ci",
+ linkedActionIds: ["act_1"],
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ const cp2 = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Gate 2",
+ type: "approval",
+ linkedActionIds: ["act_1"],
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: cp1.checkpoint.id,
+ status: "passed",
+ });
+
+ const actionAfterFirst = await kv.get<Action>("mem:actions", "act_1");
+ expect(actionAfterFirst!.status).toBe("blocked");
+
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: cp2.checkpoint.id,
+ status: "passed",
+ })) as { success: boolean; unblockedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.unblockedCount).toBe(1);
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("pending");
+ });
+
+ it("does not unblock actions when checkpoint fails", async () => {
+ await kv.set("mem:actions", "act_1", makeAction("act_1", "blocked"));
+
+ const cp = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Failing Gate",
+ linkedActionIds: ["act_1"],
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: cp.checkpoint.id,
+ status: "failed",
+ })) as { success: boolean; unblockedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.unblockedCount).toBe(0);
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("blocked");
+ });
+
+ it("does not unblock actions that are not in blocked status", async () => {
+ await kv.set("mem:actions", "act_1", makeAction("act_1", "active"));
+
+ const cp = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Gate for non-blocked",
+ linkedActionIds: ["act_1"],
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ const result = (await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: cp.checkpoint.id,
+ status: "passed",
+ })) as { success: boolean; unblockedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.unblockedCount).toBe(0);
+ });
+ });
+
+ describe("mem::checkpoint-list", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::checkpoint-create", {
+ name: "CI Check",
+ type: "ci",
+ });
+ await sdk.trigger("mem::checkpoint-create", {
+ name: "Approval Check",
+ type: "approval",
+ });
+ await sdk.trigger("mem::checkpoint-create", {
+ name: "Deploy Check",
+ type: "deploy",
+ });
+ });
+
+ it("lists all checkpoints when no filters applied", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-list", {})) as {
+ success: boolean;
+ checkpoints: Checkpoint[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoints.length).toBe(3);
+ });
+
+ it("filters checkpoints by status", async () => {
+ const all = (await sdk.trigger("mem::checkpoint-list", {})) as {
+ checkpoints: Checkpoint[];
+ };
+ const firstId = all.checkpoints[0].id;
+
+ await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: firstId,
+ status: "passed",
+ });
+
+ const pending = (await sdk.trigger("mem::checkpoint-list", {
+ status: "pending",
+ })) as { success: boolean; checkpoints: Checkpoint[] };
+
+ expect(pending.success).toBe(true);
+ expect(pending.checkpoints.length).toBe(2);
+ expect(pending.checkpoints.every((c) => c.status === "pending")).toBe(true);
+
+ const passed = (await sdk.trigger("mem::checkpoint-list", {
+ status: "passed",
+ })) as { success: boolean; checkpoints: Checkpoint[] };
+
+ expect(passed.checkpoints.length).toBe(1);
+ expect(passed.checkpoints[0].status).toBe("passed");
+ });
+
+ it("filters checkpoints by type", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-list", {
+ type: "ci",
+ })) as { success: boolean; checkpoints: Checkpoint[] };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoints.length).toBe(1);
+ expect(result.checkpoints[0].type).toBe("ci");
+ expect(result.checkpoints[0].name).toBe("CI Check");
+ });
+
+ it("returns empty list when no checkpoints match filter", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-list", {
+ type: "external",
+ })) as { success: boolean; checkpoints: Checkpoint[] };
+
+ expect(result.success).toBe(true);
+ expect(result.checkpoints.length).toBe(0);
+ });
+
+ it("sorts checkpoints by createdAt descending", async () => {
+ const result = (await sdk.trigger("mem::checkpoint-list", {})) as {
+ success: boolean;
+ checkpoints: Checkpoint[];
+ };
+
+ for (let i = 0; i < result.checkpoints.length - 1; i++) {
+ const current = new Date(result.checkpoints[i].createdAt).getTime();
+ const next = new Date(result.checkpoints[i + 1].createdAt).getTime();
+ expect(current).toBeGreaterThanOrEqual(next);
+ }
+ });
+ });
+
+ describe("mem::checkpoint-expire", () => {
+ it("expires pending checkpoints past their expiresAt", async () => {
+ const created = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Expiring Gate",
+ expiresInMs: 1,
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ created.checkpoint.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:checkpoints", created.checkpoint.id, created.checkpoint);
+
+ const result = (await sdk.trigger("mem::checkpoint-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(1);
+
+ const cp = await kv.get<Checkpoint>("mem:checkpoints", created.checkpoint.id);
+ expect(cp!.status).toBe("expired");
+ expect(cp!.resolvedAt).toBeDefined();
+ });
+
+ it("does not expire non-pending checkpoints", async () => {
+ const created = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Already Passed",
+ expiresInMs: 1,
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ await sdk.trigger("mem::checkpoint-resolve", {
+ checkpointId: created.checkpoint.id,
+ status: "passed",
+ });
+
+ const cp = await kv.get<Checkpoint>("mem:checkpoints", created.checkpoint.id);
+ cp!.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:checkpoints", created.checkpoint.id, cp);
+
+ const result = (await sdk.trigger("mem::checkpoint-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+ });
+
+ it("does not expire checkpoints without expiresAt", async () => {
+ await sdk.trigger("mem::checkpoint-create", {
+ name: "No Expiry",
+ });
+
+ const result = (await sdk.trigger("mem::checkpoint-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+ });
+
+ it("does not expire checkpoints whose expiresAt is in the future", async () => {
+ await sdk.trigger("mem::checkpoint-create", {
+ name: "Future Gate",
+ expiresInMs: 3600000,
+ });
+
+ const result = (await sdk.trigger("mem::checkpoint-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+ });
+
+ it("handles multiple expired checkpoints", async () => {
+ const cp1 = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Expired 1",
+ expiresInMs: 1,
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ const cp2 = (await sdk.trigger("mem::checkpoint-create", {
+ name: "Expired 2",
+ expiresInMs: 1,
+ })) as { success: boolean; checkpoint: Checkpoint };
+
+ cp1.checkpoint.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:checkpoints", cp1.checkpoint.id, cp1.checkpoint);
+
+ cp2.checkpoint.expiresAt = new Date(Date.now() - 30000).toISOString();
+ await kv.set("mem:checkpoints", cp2.checkpoint.id, cp2.checkpoint);
+
+ const result = (await sdk.trigger("mem::checkpoint-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(2);
+ });
+ });
+});
diff --git a/test/crystallize.test.ts b/test/crystallize.test.ts
new file mode 100644
index 00000000..d76450eb
--- /dev/null
+++ b/test/crystallize.test.ts
@@ -0,0 +1,521 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerCrystallizeFunction } from "../src/functions/crystallize.js";
+import type { Action, Crystal, MemoryProvider } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+function mockProvider(): MemoryProvider {
+ return {
+ name: "test",
+ compress: vi.fn(),
+ summarize: vi.fn().mockResolvedValue(
+ '{"narrative":"test","keyOutcomes":["done"],"filesAffected":["a.ts"],"lessons":["learned"]}',
+ ),
+ };
+}
+
+function makeAction(overrides: Partial<Action> & { id: string }): Action {
+ return {
+ title: "Test action",
+ description: "A test action",
+ status: "done",
+ priority: 5,
+ createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
+ updatedAt: new Date().toISOString(),
+ createdBy: "agent-1",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ ...overrides,
+ };
+}
+
+describe("Crystallize Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+ let provider: MemoryProvider;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ provider = mockProvider();
+ registerCrystallizeFunction(sdk as never, kv as never, provider);
+ });
+
+ describe("mem::crystallize", () => {
+ it("crystallizes completed actions with valid JSON response", async () => {
+ const action = makeAction({ id: "act_1", title: "Fix bug", status: "done" });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_1"],
+ project: "webapp",
+ sessionId: "sess_1",
+ })) as { success: boolean; crystal: Crystal };
+
+ expect(result.success).toBe(true);
+ expect(result.crystal.id).toMatch(/^crys_/);
+ expect(result.crystal.narrative).toBe("test");
+ expect(result.crystal.keyOutcomes).toEqual(["done"]);
+ expect(result.crystal.filesAffected).toEqual(["a.ts"]);
+ expect(result.crystal.lessons).toEqual(["learned"]);
+ expect(result.crystal.sourceActionIds).toEqual(["act_1"]);
+ expect(result.crystal.project).toBe("webapp");
+ expect(result.crystal.sessionId).toBe("sess_1");
+ expect(result.crystal.createdAt).toBeDefined();
+ });
+
+ it("marks source actions with crystallizedInto", async () => {
+ const action = makeAction({ id: "act_mark", status: "done" });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_mark"],
+ })) as { success: boolean; crystal: Crystal };
+
+ expect(result.success).toBe(true);
+
+ const updated = await kv.get<Action>("mem:actions", "act_mark");
+ expect(updated!.crystallizedInto).toBe(result.crystal.id);
+ });
+
+ it("falls back to raw text when provider returns non-JSON", async () => {
+ (provider.summarize as ReturnType<typeof vi.fn>).mockResolvedValue(
+ "Just a plain text summary with no JSON.",
+ );
+
+ const action = makeAction({ id: "act_nojson", status: "done" });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_nojson"],
+ })) as { success: boolean; crystal: Crystal };
+
+ expect(result.success).toBe(true);
+ expect(result.crystal.narrative).toBe(
+ "Just a plain text summary with no JSON.",
+ );
+ expect(result.crystal.keyOutcomes).toEqual([]);
+ expect(result.crystal.filesAffected).toEqual([]);
+ expect(result.crystal.lessons).toEqual([]);
+ });
+
+ it("returns error for non-existent action", async () => {
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_ghost"],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("action not found: act_ghost");
+ });
+
+ it("returns error for non-done action", async () => {
+ const action = makeAction({ id: "act_pending", status: "pending" });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_pending"],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('status "pending"');
+ });
+
+ it("returns error for empty actionIds", async () => {
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: [],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("actionIds is required");
+ });
+
+ it("returns error when actionIds is missing", async () => {
+ const result = (await sdk.trigger("mem::crystallize", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("actionIds is required");
+ });
+
+ it("accepts cancelled actions", async () => {
+ const action = makeAction({ id: "act_cancel", status: "cancelled" });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_cancel"],
+ })) as { success: boolean; crystal: Crystal };
+
+ expect(result.success).toBe(true);
+ expect(result.crystal.sourceActionIds).toEqual(["act_cancel"]);
+ });
+
+ it("crystallizes multiple actions in one call", async () => {
+ const a1 = makeAction({ id: "act_m1", status: "done", title: "First" });
+ const a2 = makeAction({ id: "act_m2", status: "done", title: "Second" });
+ await kv.set("mem:actions", a1.id, a1);
+ await kv.set("mem:actions", a2.id, a2);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_m1", "act_m2"],
+ })) as { success: boolean; crystal: Crystal };
+
+ expect(result.success).toBe(true);
+ expect(result.crystal.sourceActionIds).toEqual(["act_m1", "act_m2"]);
+ });
+
+ it("returns failure when provider throws", async () => {
+ (provider.summarize as ReturnType<typeof vi.fn>).mockRejectedValue(
+ new Error("API down"),
+ );
+
+ const action = makeAction({ id: "act_fail", status: "done" });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::crystallize", {
+ actionIds: ["act_fail"],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("crystallization failed");
+ expect(result.error).toContain("API down");
+ });
+ });
+
+ describe("mem::crystal-list", () => {
+ beforeEach(async () => {
+ const c1: Crystal = {
+ id: "crys_1",
+ narrative: "First crystal",
+ keyOutcomes: [],
+ filesAffected: [],
+ lessons: [],
+ sourceActionIds: ["act_1"],
+ project: "alpha",
+ sessionId: "sess_a",
+ createdAt: new Date("2025-01-01").toISOString(),
+ };
+ const c2: Crystal = {
+ id: "crys_2",
+ narrative: "Second crystal",
+ keyOutcomes: [],
+ filesAffected: [],
+ lessons: [],
+ sourceActionIds: ["act_2"],
+ project: "beta",
+ sessionId: "sess_b",
+ createdAt: new Date("2025-02-01").toISOString(),
+ };
+ const c3: Crystal = {
+ id: "crys_3",
+ narrative: "Third crystal",
+ keyOutcomes: [],
+ filesAffected: [],
+ lessons: [],
+ sourceActionIds: ["act_3"],
+ project: "alpha",
+ sessionId: "sess_a",
+ createdAt: new Date("2025-03-01").toISOString(),
+ };
+ await kv.set("mem:crystals", c1.id, c1);
+ await kv.set("mem:crystals", c2.id, c2);
+ await kv.set("mem:crystals", c3.id, c3);
+ });
+
+ it("returns all crystals sorted by createdAt desc", async () => {
+ const result = (await sdk.trigger("mem::crystal-list", {})) as {
+ success: boolean;
+ crystals: Crystal[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.crystals.length).toBe(3);
+ expect(result.crystals[0].id).toBe("crys_3");
+ expect(result.crystals[1].id).toBe("crys_2");
+ expect(result.crystals[2].id).toBe("crys_1");
+ });
+
+ it("filters by project", async () => {
+ const result = (await sdk.trigger("mem::crystal-list", {
+ project: "alpha",
+ })) as { success: boolean; crystals: Crystal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.crystals.length).toBe(2);
+ expect(result.crystals.every((c) => c.project === "alpha")).toBe(true);
+ });
+
+ it("filters by sessionId", async () => {
+ const result = (await sdk.trigger("mem::crystal-list", {
+ sessionId: "sess_b",
+ })) as { success: boolean; crystals: Crystal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.crystals.length).toBe(1);
+ expect(result.crystals[0].id).toBe("crys_2");
+ });
+
+ it("respects limit", async () => {
+ const result = (await sdk.trigger("mem::crystal-list", {
+ limit: 1,
+ })) as { success: boolean; crystals: Crystal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.crystals.length).toBe(1);
+ expect(result.crystals[0].id).toBe("crys_3");
+ });
+ });
+
+ describe("mem::crystal-get", () => {
+ it("returns crystal by id", async () => {
+ const crystal: Crystal = {
+ id: "crys_get_1",
+ narrative: "Found it",
+ keyOutcomes: ["yes"],
+ filesAffected: ["b.ts"],
+ lessons: ["test"],
+ sourceActionIds: ["act_x"],
+ createdAt: new Date().toISOString(),
+ };
+ await kv.set("mem:crystals", crystal.id, crystal);
+
+ const result = (await sdk.trigger("mem::crystal-get", {
+ crystalId: "crys_get_1",
+ })) as { success: boolean; crystal: Crystal };
+
+ expect(result.success).toBe(true);
+ expect(result.crystal.id).toBe("crys_get_1");
+ expect(result.crystal.narrative).toBe("Found it");
+ });
+
+ it("returns error for non-existent crystal", async () => {
+ const result = (await sdk.trigger("mem::crystal-get", {
+ crystalId: "crys_missing",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("crystal not found");
+ });
+
+ it("returns error when crystalId is missing", async () => {
+ const result = (await sdk.trigger("mem::crystal-get", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("crystalId is required");
+ });
+ });
+
+ describe("mem::auto-crystallize", () => {
+ it("returns group summaries in dryRun mode", async () => {
+ const action = makeAction({
+ id: "act_dry",
+ status: "done",
+ project: "proj",
+ });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {
+ dryRun: true,
+ })) as {
+ success: boolean;
+ dryRun: boolean;
+ groupCount: number;
+ groups: { groupKey: string; actionCount: number; actionIds: string[] }[];
+ crystalIds: string[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.dryRun).toBe(true);
+ expect(result.groupCount).toBe(1);
+ expect(result.groups[0].actionIds).toContain("act_dry");
+ expect(result.crystalIds).toEqual([]);
+ });
+
+ it("groups by parentId when present", async () => {
+ const parent = makeAction({
+ id: "act_parent",
+ status: "done",
+ parentId: undefined,
+ });
+ const child1 = makeAction({
+ id: "act_child1",
+ status: "done",
+ parentId: "act_parent",
+ });
+ const child2 = makeAction({
+ id: "act_child2",
+ status: "done",
+ parentId: "act_parent",
+ });
+ await kv.set("mem:actions", parent.id, parent);
+ await kv.set("mem:actions", child1.id, child1);
+ await kv.set("mem:actions", child2.id, child2);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {
+ dryRun: true,
+ })) as {
+ success: boolean;
+ groups: { groupKey: string; actionCount: number; actionIds: string[] }[];
+ };
+
+ expect(result.success).toBe(true);
+ const parentGroup = result.groups.find((g) => g.groupKey === "act_parent");
+ expect(parentGroup).toBeDefined();
+ expect(parentGroup!.actionCount).toBe(2);
+ });
+
+ it("groups by project when no parentId", async () => {
+ const a1 = makeAction({ id: "act_proj1", status: "done", project: "webapp" });
+ const a2 = makeAction({ id: "act_proj2", status: "done", project: "webapp" });
+ const a3 = makeAction({ id: "act_proj3", status: "done", project: "api" });
+ await kv.set("mem:actions", a1.id, a1);
+ await kv.set("mem:actions", a2.id, a2);
+ await kv.set("mem:actions", a3.id, a3);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {
+ dryRun: true,
+ })) as {
+ success: boolean;
+ groups: { groupKey: string; actionCount: number }[];
+ };
+
+ expect(result.success).toBe(true);
+ const webGroup = result.groups.find((g) => g.groupKey === "webapp");
+ const apiGroup = result.groups.find((g) => g.groupKey === "api");
+ expect(webGroup).toBeDefined();
+ expect(webGroup!.actionCount).toBe(2);
+ expect(apiGroup).toBeDefined();
+ expect(apiGroup!.actionCount).toBe(1);
+ });
+
+ it("skips already-crystallized actions", async () => {
+ const action = makeAction({
+ id: "act_already",
+ status: "done",
+ crystallizedInto: "crys_existing",
+ });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {
+ dryRun: true,
+ })) as { success: boolean; groupCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.groupCount).toBe(0);
+ });
+
+ it("skips actions newer than threshold", async () => {
+ const recentAction = makeAction({
+ id: "act_recent",
+ status: "done",
+ createdAt: new Date().toISOString(),
+ });
+ await kv.set("mem:actions", recentAction.id, recentAction);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {
+ olderThanDays: 7,
+ dryRun: true,
+ })) as { success: boolean; groupCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.groupCount).toBe(0);
+ });
+
+ it("creates crystals for each group in non-dryRun mode", async () => {
+ const a1 = makeAction({ id: "act_auto1", status: "done", project: "proj1" });
+ const a2 = makeAction({ id: "act_auto2", status: "done", project: "proj2" });
+ await kv.set("mem:actions", a1.id, a1);
+ await kv.set("mem:actions", a2.id, a2);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {})) as {
+ success: boolean;
+ groupCount: number;
+ crystalIds: string[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.groupCount).toBe(2);
+ expect(result.crystalIds.length).toBe(2);
+ expect(result.crystalIds[0]).toMatch(/^crys_/);
+ expect(result.crystalIds[1]).toMatch(/^crys_/);
+ });
+
+ it("filters by project when specified", async () => {
+ const a1 = makeAction({ id: "act_fp1", status: "done", project: "keep" });
+ const a2 = makeAction({ id: "act_fp2", status: "done", project: "skip" });
+ await kv.set("mem:actions", a1.id, a1);
+ await kv.set("mem:actions", a2.id, a2);
+
+ const result = (await sdk.trigger("mem::auto-crystallize", {
+ project: "keep",
+ dryRun: true,
+ })) as {
+ success: boolean;
+ groupCount: number;
+ groups: { groupKey: string; actionCount: number }[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.groupCount).toBe(1);
+ expect(result.groups[0].groupKey).toBe("keep");
+ });
+
+ it("returns empty when no qualifying actions exist", async () => {
+ const result = (await sdk.trigger("mem::auto-crystallize", {})) as {
+ success: boolean;
+ groupCount: number;
+ crystalIds: string[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.groupCount).toBe(0);
+ expect(result.crystalIds).toEqual([]);
+ });
+ });
+});
diff --git a/test/diagnostics.test.ts b/test/diagnostics.test.ts
new file mode 100644
index 00000000..0872f6ca
--- /dev/null
+++ b/test/diagnostics.test.ts
@@ -0,0 +1,638 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerDiagnosticsFunction } from "../src/functions/diagnostics.js";
+import type {
+ Action,
+ ActionEdge,
+ DiagnosticCheck,
+ Lease,
+ Sentinel,
+ Sketch,
+ Signal,
+ Session,
+ Memory,
+ MeshPeer,
+} from "../src/types.js";
+import { KV } from "../src/state/schema.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+function makeAction(overrides: Partial<Action> = {}): Action {
+ return {
+ id: `act_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ title: "Test action",
+ description: "",
+ status: "pending",
+ priority: 5,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ createdBy: "agent-1",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ ...overrides,
+ };
+}
+
+function makeLease(overrides: Partial<Lease> = {}): Lease {
+ return {
+ id: `lease_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ actionId: "act_missing",
+ agentId: "agent-1",
+ acquiredAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ status: "active",
+ ...overrides,
+ };
+}
+
+function makeEdge(overrides: Partial<ActionEdge> = {}): ActionEdge {
+ return {
+ id: `ae_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ type: "requires",
+ sourceActionId: "src",
+ targetActionId: "tgt",
+ createdAt: new Date().toISOString(),
+ ...overrides,
+ };
+}
+
+function makeSentinel(overrides: Partial<Sentinel> = {}): Sentinel {
+ return {
+ id: `sen_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ name: "Test sentinel",
+ type: "timer",
+ status: "watching",
+ config: {},
+ createdAt: new Date().toISOString(),
+ linkedActionIds: [],
+ ...overrides,
+ };
+}
+
+function makeSketch(overrides: Partial<Sketch> = {}): Sketch {
+ return {
+ id: `sk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ title: "Test sketch",
+ description: "",
+ status: "active",
+ actionIds: [],
+ createdAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ ...overrides,
+ };
+}
+
+function makeSignal(overrides: Partial<Signal> = {}): Signal {
+ return {
+ id: `sig_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ from: "agent-1",
+ type: "info",
+ content: "test",
+ createdAt: new Date().toISOString(),
+ ...overrides,
+ };
+}
+
+function makeSession(overrides: Partial<Session> = {}): Session {
+ return {
+ id: `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ project: "test",
+ cwd: "/tmp",
+ startedAt: new Date().toISOString(),
+ status: "active",
+ observationCount: 0,
+ ...overrides,
+ };
+}
+
+function makeMemory(overrides: Partial<Memory> = {}): Memory {
+ return {
+ id: `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ type: "fact",
+ title: "Test memory",
+ content: "content",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 1,
+ version: 1,
+ isLatest: true,
+ ...overrides,
+ };
+}
+
+function makePeer(overrides: Partial<MeshPeer> = {}): MeshPeer {
+ return {
+ id: `peer_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ url: "http://localhost:3111",
+ name: "Test peer",
+ status: "connected",
+ sharedScopes: [],
+ ...overrides,
+ };
+}
+
+describe("Diagnostics Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerDiagnosticsFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::diagnose", () => {
+ it("empty system passes all checks", async () => {
+ const result = (await sdk.trigger("mem::diagnose", {})) as {
+ success: boolean;
+ checks: DiagnosticCheck[];
+ summary: { pass: number; warn: number; fail: number; fixable: number };
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.summary.pass).toBe(8);
+ expect(result.summary.warn).toBe(0);
+ expect(result.summary.fail).toBe(0);
+ expect(result.summary.fixable).toBe(0);
+ expect(result.checks.every((c) => c.status === "pass")).toBe(true);
+ });
+
+ it("active action with no lease produces warn", async () => {
+ const action = makeAction({ status: "active" });
+ await kv.set(KV.actions, action.id, action);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["actions"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("active-no-lease:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("warn");
+ expect(check!.fixable).toBe(false);
+ });
+
+ it("blocked action with all deps done produces fail (fixable)", async () => {
+ const dep = makeAction({ status: "done" });
+ const blocked = makeAction({ status: "blocked" });
+ const edge = makeEdge({
+ sourceActionId: blocked.id,
+ targetActionId: dep.id,
+ type: "requires",
+ });
+ await kv.set(KV.actions, dep.id, dep);
+ await kv.set(KV.actions, blocked.id, blocked);
+ await kv.set(KV.actionEdges, edge.id, edge);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["actions"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("blocked-deps-done:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("pending action with unsatisfied deps produces fail (fixable)", async () => {
+ const dep = makeAction({ status: "active" });
+ const pending = makeAction({ status: "pending" });
+ const edge = makeEdge({
+ sourceActionId: pending.id,
+ targetActionId: dep.id,
+ type: "requires",
+ });
+ await kv.set(KV.actions, dep.id, dep);
+ await kv.set(KV.actions, pending.id, pending);
+ await kv.set(KV.actionEdges, edge.id, edge);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["actions"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("pending-unsatisfied-deps:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("expired active lease produces fail (fixable)", async () => {
+ const action = makeAction({ status: "active" });
+ const lease = makeLease({
+ actionId: action.id,
+ status: "active",
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.actions, action.id, action);
+ await kv.set(KV.leases, lease.id, lease);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["leases"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("expired-lease:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("orphaned lease (action gone) produces fail (fixable)", async () => {
+ const lease = makeLease({
+ actionId: "act_gone",
+ status: "active",
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ });
+ await kv.set(KV.leases, lease.id, lease);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["leases"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("orphaned-lease:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("expired watching sentinel produces fail (fixable)", async () => {
+ const sentinel = makeSentinel({
+ status: "watching",
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["sentinels"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("expired-sentinel:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("sentinel referencing missing action produces warn", async () => {
+ const sentinel = makeSentinel({
+ linkedActionIds: ["act_nonexistent"],
+ });
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["sentinels"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("sentinel-missing-action:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("warn");
+ expect(check!.fixable).toBe(false);
+ });
+
+ it("expired active sketch produces fail (fixable)", async () => {
+ const sketch = makeSketch({
+ status: "active",
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.sketches, sketch.id, sketch);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["sketches"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("expired-sketch:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("expired signal produces fail (fixable)", async () => {
+ const signal = makeSignal({
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.signals, signal.id, signal);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["signals"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("expired-signal:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("active session older than 24h produces warn", async () => {
+ const session = makeSession({
+ status: "active",
+ startedAt: new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(),
+ });
+ await kv.set(KV.sessions, session.id, session);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["sessions"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("abandoned-session:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("warn");
+ expect(check!.fixable).toBe(false);
+ });
+
+ it("memory with stale isLatest produces fail (fixable)", async () => {
+ const oldMemory = makeMemory({ isLatest: true });
+ const newMemory = makeMemory({ supersedes: [oldMemory.id] });
+ await kv.set(KV.memories, oldMemory.id, oldMemory);
+ await kv.set(KV.memories, newMemory.id, newMemory);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["memories"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("memory-stale-latest:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("fail");
+ expect(check!.fixable).toBe(true);
+ });
+
+ it("memory superseding non-existent produces warn", async () => {
+ const memory = makeMemory({ supersedes: ["mem_gone"] });
+ await kv.set(KV.memories, memory.id, memory);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["memories"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("memory-missing-supersedes:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("warn");
+ expect(check!.fixable).toBe(false);
+ });
+
+ it("stale mesh peer produces warn", async () => {
+ const peer = makePeer({
+ lastSyncAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
+ });
+ await kv.set(KV.mesh, peer.id, peer);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["mesh"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("stale-peer:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("warn");
+ expect(check!.fixable).toBe(false);
+ });
+
+ it("error mesh peer produces warn", async () => {
+ const peer = makePeer({ status: "error" });
+ await kv.set(KV.mesh, peer.id, peer);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["mesh"],
+ })) as { checks: DiagnosticCheck[] };
+
+ const check = result.checks.find((c) =>
+ c.name.startsWith("error-peer:"),
+ );
+ expect(check).toBeDefined();
+ expect(check!.status).toBe("warn");
+ expect(check!.fixable).toBe(false);
+ });
+
+ it("filters by categories", async () => {
+ const action = makeAction({ status: "active" });
+ await kv.set(KV.actions, action.id, action);
+
+ const signal = makeSignal({
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.signals, signal.id, signal);
+
+ const result = (await sdk.trigger("mem::diagnose", {
+ categories: ["signals"],
+ })) as { checks: DiagnosticCheck[] };
+
+ expect(result.checks.every((c) => c.category === "signals")).toBe(true);
+ expect(
+ result.checks.some((c) => c.category === "actions"),
+ ).toBe(false);
+ });
+ });
+
+ describe("mem::heal", () => {
+ it("unblocks stuck blocked action", async () => {
+ const dep = makeAction({ status: "done" });
+ const blocked = makeAction({ status: "blocked", title: "Stuck task" });
+ const edge = makeEdge({
+ sourceActionId: blocked.id,
+ targetActionId: dep.id,
+ type: "requires",
+ });
+ await kv.set(KV.actions, dep.id, dep);
+ await kv.set(KV.actions, blocked.id, blocked);
+ await kv.set(KV.actionEdges, edge.id, edge);
+
+ const result = (await sdk.trigger("mem::heal", {
+ categories: ["actions"],
+ })) as { success: boolean; fixed: number; details: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.fixed).toBe(1);
+ expect(result.details[0]).toContain("Unblocked");
+
+ const updated = await kv.get<Action>(KV.actions, blocked.id);
+ expect(updated!.status).toBe("pending");
+ });
+
+ it("blocks pending action with unsatisfied deps", async () => {
+ const dep = makeAction({ status: "active" });
+ const pending = makeAction({
+ status: "pending",
+ title: "Should be blocked",
+ });
+ const edge = makeEdge({
+ sourceActionId: pending.id,
+ targetActionId: dep.id,
+ type: "requires",
+ });
+ await kv.set(KV.actions, dep.id, dep);
+ await kv.set(KV.actions, pending.id, pending);
+ await kv.set(KV.actionEdges, edge.id, edge);
+
+ const result = (await sdk.trigger("mem::heal", {
+ categories: ["actions"],
+ })) as { success: boolean; fixed: number; details: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.fixed).toBe(1);
+ expect(result.details[0]).toContain("Blocked");
+
+ const updated = await kv.get<Action>(KV.actions, pending.id);
+ expect(updated!.status).toBe("blocked");
+ });
+
+ it("expires stale lease and resets action", async () => {
+ const action = makeAction({
+ status: "active",
+ assignedTo: "agent-1",
+ });
+ const lease = makeLease({
+ actionId: action.id,
+ agentId: "agent-1",
+ status: "active",
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.actions, action.id, action);
+ await kv.set(KV.leases, lease.id, lease);
+
+ const result = (await sdk.trigger("mem::heal", {
+ categories: ["leases"],
+ })) as { success: boolean; fixed: number; details: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.fixed).toBe(1);
+ expect(result.details[0]).toContain("Expired lease");
+
+ const updatedLease = await kv.get<Lease>(KV.leases, lease.id);
+ expect(updatedLease!.status).toBe("expired");
+
+ const updatedAction = await kv.get<Action>(KV.actions, action.id);
+ expect(updatedAction!.status).toBe("pending");
+ expect(updatedAction!.assignedTo).toBeUndefined();
+ });
+
+ it("deletes orphaned lease", async () => {
+ const lease = makeLease({
+ actionId: "act_gone",
+ status: "released",
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
+ });
+ await kv.set(KV.leases, lease.id, lease);
+
+ const result = (await sdk.trigger("mem::heal", {
+ categories: ["leases"],
+ })) as { success: boolean; fixed: number; details: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.fixed).toBe(1);
+ expect(result.details[0]).toContain("Deleted orphaned lease");
+
+ const deleted = await kv.get<Lease>(KV.leases, lease.id);
+ expect(deleted).toBeNull();
+ });
+
+ it("expires stale sentinel", async () => {
+ const sentinel = makeSentinel({
+ status: "watching",
+ name: "Stale watcher",
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ await kv.set(KV.sentinels, sentinel.id, sentinel);
+
+ const result = (await sdk.trigger("mem::heal", {
+ categories: ["sentinels"],
+ })) as { success: boolean; fixed: number; details: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.fixed).toBe(1);
+ expect(result.details[0]).toContain("Expired sentinel");
+
+ const updated = await kv.get<Sentinel>(KV.sentinels, sentinel.id);
+ expect(updated!.status).toBe("expired");
+ });
+
+ it("dry run reports but does not fix", async () => {
+ const dep = makeAction({ status: "done" });
+ const blocked = makeAction({ status: "blocked", title: "Stuck task" });
+ const edge = makeEdge({
+ sourceActionId: blocked.id,
+ targetActionId: dep.id,
+ type: "requires",
+ });
+ await kv.set(KV.actions, dep.id, dep);
+ await kv.set(KV.actions, blocked.id, blocked);
+ await kv.set(KV.actionEdges, edge.id, edge);
+
+ const result = (await sdk.trigger("mem::heal", {
+ categories: ["actions"],
+ dryRun: true,
+ })) as { success: boolean; fixed: number; details: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.fixed).toBe(1);
+ expect(result.details[0]).toContain("[dry-run]");
+
+ const unchanged = await kv.get<Action>(KV.actions, blocked.id);
+ expect(unchanged!.status).toBe("blocked");
+ });
+ });
+});
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index f3aa3ce2..265b4efb 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.4.0");
+ expect(result.version).toBe("0.5.0");
expect(result.exportedAt).toBeDefined();
expect(result.sessions.length).toBe(1);
expect(result.sessions[0].id).toBe("ses_1");
diff --git a/test/facets.test.ts b/test/facets.test.ts
new file mode 100644
index 00000000..85b36fde
--- /dev/null
+++ b/test/facets.test.ts
@@ -0,0 +1,448 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerFacetsFunction } from "../src/functions/facets.js";
+import type { Facet } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Facets Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerFacetsFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::facet-tag", () => {
+ it("tags a target with a facet", async () => {
+ const result = (await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ })) as { success: boolean; facet: Facet };
+
+ expect(result.success).toBe(true);
+ expect(result.facet.id).toMatch(/^fct_/);
+ expect(result.facet.targetId).toBe("act_123");
+ expect(result.facet.targetType).toBe("action");
+ expect(result.facet.dimension).toBe("priority");
+ expect(result.facet.value).toBe("high");
+ expect(result.facet.createdAt).toBeDefined();
+ });
+
+ it("returns error when dimension is empty", async () => {
+ const result = (await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: " ",
+ value: "high",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("dimension is required");
+ });
+
+ it("returns error when value is empty", async () => {
+ const result = (await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("value is required");
+ });
+
+ it("returns error for invalid targetType", async () => {
+ const result = (await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "invalid",
+ dimension: "priority",
+ value: "high",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("targetType must be one of");
+ });
+
+ it("skips duplicate tag", async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+
+ const result = (await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ })) as { success: boolean; facet: Facet; skipped: boolean };
+
+ expect(result.success).toBe(true);
+ expect(result.skipped).toBe(true);
+ });
+ });
+
+ describe("mem::facet-untag", () => {
+ it("removes a specific value from a dimension", async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "urgent",
+ });
+
+ const result = (await sdk.trigger("mem::facet-untag", {
+ targetId: "act_123",
+ dimension: "priority",
+ value: "high",
+ })) as { success: boolean; removed: number };
+
+ expect(result.success).toBe(true);
+ expect(result.removed).toBe(1);
+
+ const remaining = (await sdk.trigger("mem::facet-get", {
+ targetId: "act_123",
+ })) as { success: boolean; dimensions: Array<{ dimension: string; values: string[] }> };
+
+ expect(remaining.dimensions[0].values).toEqual(["urgent"]);
+ });
+
+ it("removes all values in a dimension when value is omitted", async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_123",
+ targetType: "action",
+ dimension: "priority",
+ value: "urgent",
+ });
+
+ const result = (await sdk.trigger("mem::facet-untag", {
+ targetId: "act_123",
+ dimension: "priority",
+ })) as { success: boolean; removed: number };
+
+ expect(result.success).toBe(true);
+ expect(result.removed).toBe(2);
+
+ const remaining = (await sdk.trigger("mem::facet-get", {
+ targetId: "act_123",
+ })) as { success: boolean; dimensions: Array<{ dimension: string; values: string[] }> };
+
+ expect(remaining.dimensions).toEqual([]);
+ });
+ });
+
+ describe("mem::facet-query", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "status",
+ value: "active",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_2",
+ targetType: "action",
+ dimension: "priority",
+ value: "low",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_2",
+ targetType: "action",
+ dimension: "status",
+ value: "active",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "mem_1",
+ targetType: "memory",
+ dimension: "priority",
+ value: "high",
+ });
+ });
+
+ it("queries with matchAll (AND logic)", async () => {
+ const result = (await sdk.trigger("mem::facet-query", {
+ matchAll: ["priority:high", "status:active"],
+ })) as { success: boolean; results: Array<{ targetId: string }> };
+
+ expect(result.success).toBe(true);
+ expect(result.results.length).toBe(1);
+ expect(result.results[0].targetId).toBe("act_1");
+ });
+
+ it("queries with matchAny (OR logic)", async () => {
+ const result = (await sdk.trigger("mem::facet-query", {
+ matchAny: ["priority:high", "priority:low"],
+ })) as { success: boolean; results: Array<{ targetId: string }> };
+
+ expect(result.success).toBe(true);
+ expect(result.results.length).toBe(3);
+ });
+
+ it("queries with both matchAll and matchAny", async () => {
+ const result = (await sdk.trigger("mem::facet-query", {
+ matchAll: ["status:active"],
+ matchAny: ["priority:high"],
+ })) as { success: boolean; results: Array<{ targetId: string; matchedFacets: string[] }> };
+
+ expect(result.success).toBe(true);
+ expect(result.results.length).toBe(1);
+ expect(result.results[0].targetId).toBe("act_1");
+ expect(result.results[0].matchedFacets).toContain("status:active");
+ expect(result.results[0].matchedFacets).toContain("priority:high");
+ });
+
+ it("returns error when neither matchAll nor matchAny provided", async () => {
+ const result = (await sdk.trigger("mem::facet-query", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("at least one of matchAll or matchAny is required");
+ });
+
+ it("filters by targetType", async () => {
+ const result = (await sdk.trigger("mem::facet-query", {
+ matchAny: ["priority:high"],
+ targetType: "memory",
+ })) as { success: boolean; results: Array<{ targetId: string; targetType: string }> };
+
+ expect(result.success).toBe(true);
+ expect(result.results.length).toBe(1);
+ expect(result.results[0].targetId).toBe("mem_1");
+ expect(result.results[0].targetType).toBe("memory");
+ });
+
+ it("respects limit", async () => {
+ const result = (await sdk.trigger("mem::facet-query", {
+ matchAny: ["priority:high", "priority:low"],
+ limit: 1,
+ })) as { success: boolean; results: Array<{ targetId: string }> };
+
+ expect(result.success).toBe(true);
+ expect(result.results.length).toBe(1);
+ });
+ });
+
+ describe("mem::facet-get", () => {
+ it("returns facets grouped by dimension", async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "priority",
+ value: "urgent",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "status",
+ value: "active",
+ });
+
+ const result = (await sdk.trigger("mem::facet-get", {
+ targetId: "act_1",
+ })) as { success: boolean; dimensions: Array<{ dimension: string; values: string[] }> };
+
+ expect(result.success).toBe(true);
+ expect(result.dimensions.length).toBe(2);
+
+ const priorityDim = result.dimensions.find((d) => d.dimension === "priority");
+ expect(priorityDim).toBeDefined();
+ expect(priorityDim!.values).toEqual(["high", "urgent"]);
+
+ const statusDim = result.dimensions.find((d) => d.dimension === "status");
+ expect(statusDim).toBeDefined();
+ expect(statusDim!.values).toEqual(["active"]);
+ });
+
+ it("returns empty dimensions for target with no facets", async () => {
+ const result = (await sdk.trigger("mem::facet-get", {
+ targetId: "nonexistent",
+ })) as { success: boolean; dimensions: Array<{ dimension: string; values: string[] }> };
+
+ expect(result.success).toBe(true);
+ expect(result.dimensions).toEqual([]);
+ });
+ });
+
+ describe("mem::facet-stats", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_2",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_3",
+ targetType: "action",
+ dimension: "priority",
+ value: "low",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "mem_1",
+ targetType: "memory",
+ dimension: "category",
+ value: "bugfix",
+ });
+ });
+
+ it("returns dimensions with value counts", async () => {
+ const result = (await sdk.trigger("mem::facet-stats", {})) as {
+ success: boolean;
+ dimensions: Array<{
+ dimension: string;
+ values: Array<{ value: string; count: number }>;
+ }>;
+ totalFacets: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.totalFacets).toBe(4);
+ expect(result.dimensions.length).toBe(2);
+
+ const priorityDim = result.dimensions.find((d) => d.dimension === "priority");
+ expect(priorityDim).toBeDefined();
+ const highVal = priorityDim!.values.find((v) => v.value === "high");
+ expect(highVal!.count).toBe(2);
+ const lowVal = priorityDim!.values.find((v) => v.value === "low");
+ expect(lowVal!.count).toBe(1);
+ });
+
+ it("filters by targetType", async () => {
+ const result = (await sdk.trigger("mem::facet-stats", {
+ targetType: "memory",
+ })) as {
+ success: boolean;
+ dimensions: Array<{
+ dimension: string;
+ values: Array<{ value: string; count: number }>;
+ }>;
+ totalFacets: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.totalFacets).toBe(1);
+ expect(result.dimensions.length).toBe(1);
+ expect(result.dimensions[0].dimension).toBe("category");
+ expect(result.dimensions[0].values[0].value).toBe("bugfix");
+ expect(result.dimensions[0].values[0].count).toBe(1);
+ });
+ });
+
+ describe("mem::facet-dimensions", () => {
+ it("returns unique dimension names with counts", async () => {
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "priority",
+ value: "high",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_2",
+ targetType: "action",
+ dimension: "priority",
+ value: "low",
+ });
+ await sdk.trigger("mem::facet-tag", {
+ targetId: "act_1",
+ targetType: "action",
+ dimension: "status",
+ value: "active",
+ });
+
+ const result = (await sdk.trigger("mem::facet-dimensions", {})) as {
+ success: boolean;
+ dimensions: Array<{ dimension: string; count: number }>;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.dimensions.length).toBe(2);
+
+ const priorityDim = result.dimensions.find((d) => d.dimension === "priority");
+ expect(priorityDim).toBeDefined();
+ expect(priorityDim!.count).toBe(2);
+
+ const statusDim = result.dimensions.find((d) => d.dimension === "status");
+ expect(statusDim).toBeDefined();
+ expect(statusDim!.count).toBe(1);
+ });
+ });
+});
diff --git a/test/frontier.test.ts b/test/frontier.test.ts
new file mode 100644
index 00000000..f46685b5
--- /dev/null
+++ b/test/frontier.test.ts
@@ -0,0 +1,485 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerFrontierFunction } from "../src/functions/frontier.js";
+import { registerActionsFunction } from "../src/functions/actions.js";
+import type { Action, ActionEdge, Checkpoint, Lease } from "../src/types.js";
+import type { FrontierItem } from "../src/functions/frontier.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+function makeAction(overrides: Partial<Action>): Action {
+ const now = new Date().toISOString();
+ return {
+ id: overrides.id || `act_${Math.random().toString(36).slice(2, 10)}`,
+ title: overrides.title || "Test action",
+ description: overrides.description || "",
+ status: overrides.status || "pending",
+ priority: overrides.priority || 5,
+ createdAt: overrides.createdAt || now,
+ updatedAt: overrides.updatedAt || now,
+ createdBy: overrides.createdBy || "agent-1",
+ assignedTo: overrides.assignedTo,
+ project: overrides.project,
+ tags: overrides.tags || [],
+ sourceObservationIds: overrides.sourceObservationIds || [],
+ sourceMemoryIds: overrides.sourceMemoryIds || [],
+ result: overrides.result,
+ parentId: overrides.parentId,
+ metadata: overrides.metadata,
+ };
+}
+
+describe("Frontier Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerActionsFunction(sdk as never, kv as never);
+ registerFrontierFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::frontier", () => {
+ it("returns empty frontier when no actions exist", async () => {
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ totalActions: number;
+ totalUnblocked: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.frontier).toEqual([]);
+ expect(result.totalActions).toBe(0);
+ expect(result.totalUnblocked).toBe(0);
+ });
+
+ it("returns pending actions sorted by score", async () => {
+ const lowPriority = makeAction({
+ id: "act_low",
+ title: "Low priority",
+ priority: 2,
+ });
+ const highPriority = makeAction({
+ id: "act_high",
+ title: "High priority",
+ priority: 9,
+ });
+
+ await kv.set("mem:actions", lowPriority.id, lowPriority);
+ await kv.set("mem:actions", highPriority.id, highPriority);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.frontier.length).toBe(2);
+ expect(result.frontier[0].action.id).toBe("act_high");
+ expect(result.frontier[1].action.id).toBe("act_low");
+ expect(result.frontier[0].score).toBeGreaterThan(
+ result.frontier[1].score,
+ );
+ });
+
+ it("excludes done and cancelled actions", async () => {
+ const pending = makeAction({
+ id: "act_pending",
+ title: "Pending",
+ status: "pending",
+ });
+ const done = makeAction({
+ id: "act_done",
+ title: "Done",
+ status: "done",
+ });
+ const cancelled = makeAction({
+ id: "act_cancelled",
+ title: "Cancelled",
+ status: "cancelled",
+ });
+
+ await kv.set("mem:actions", pending.id, pending);
+ await kv.set("mem:actions", done.id, done);
+ await kv.set("mem:actions", cancelled.id, cancelled);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ totalActions: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.frontier.length).toBe(1);
+ expect(result.frontier[0].action.id).toBe("act_pending");
+ expect(result.totalActions).toBe(3);
+ });
+
+ it("excludes blocked actions with unsatisfied requires edge", async () => {
+ const dependency = makeAction({
+ id: "act_dep",
+ title: "Dependency",
+ status: "pending",
+ });
+ const blocked = makeAction({
+ id: "act_blocked",
+ title: "Blocked",
+ status: "blocked",
+ });
+
+ await kv.set("mem:actions", dependency.id, dependency);
+ await kv.set("mem:actions", blocked.id, blocked);
+
+ const edge: ActionEdge = {
+ id: "ae_1",
+ type: "requires",
+ sourceActionId: blocked.id,
+ targetActionId: dependency.id,
+ createdAt: new Date().toISOString(),
+ };
+ await kv.set("mem:action-edges", edge.id, edge);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ };
+
+ expect(result.success).toBe(true);
+ const ids = result.frontier.map((f) => f.action.id);
+ expect(ids).toContain("act_dep");
+ expect(ids).not.toContain("act_blocked");
+ });
+
+ it("respects project filter", async () => {
+ const alphaAction = makeAction({
+ id: "act_alpha",
+ title: "Alpha task",
+ project: "alpha",
+ });
+ const betaAction = makeAction({
+ id: "act_beta",
+ title: "Beta task",
+ project: "beta",
+ });
+
+ await kv.set("mem:actions", alphaAction.id, alphaAction);
+ await kv.set("mem:actions", betaAction.id, betaAction);
+
+ const result = (await sdk.trigger("mem::frontier", {
+ project: "alpha",
+ })) as { success: boolean; frontier: FrontierItem[] };
+
+ expect(result.success).toBe(true);
+ expect(result.frontier.length).toBe(1);
+ expect(result.frontier[0].action.project).toBe("alpha");
+ });
+
+ it("higher priority scores higher", async () => {
+ const low = makeAction({
+ id: "act_low",
+ title: "Low",
+ priority: 1,
+ createdAt: new Date().toISOString(),
+ });
+ const high = makeAction({
+ id: "act_high",
+ title: "High",
+ priority: 10,
+ createdAt: new Date().toISOString(),
+ });
+
+ await kv.set("mem:actions", low.id, low);
+ await kv.set("mem:actions", high.id, high);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ };
+
+ expect(result.frontier[0].action.id).toBe("act_high");
+ expect(result.frontier[0].score).toBeGreaterThan(
+ result.frontier[1].score,
+ );
+ });
+
+ it("excludes actions gated by pending checkpoint", async () => {
+ const gatedAction = makeAction({
+ id: "act_gated",
+ title: "Gated action",
+ status: "pending",
+ });
+
+ const checkpoint: Checkpoint = {
+ id: "ckpt_1",
+ name: "CI check",
+ description: "Waiting for CI",
+ status: "pending",
+ type: "ci",
+ createdAt: new Date().toISOString(),
+ linkedActionIds: ["act_gated"],
+ };
+
+ await kv.set("mem:actions", gatedAction.id, gatedAction);
+ await kv.set("mem:checkpoints", checkpoint.id, checkpoint);
+
+ const gateEdge: ActionEdge = {
+ id: "ae_gate",
+ type: "gated_by",
+ sourceActionId: gatedAction.id,
+ targetActionId: checkpoint.id,
+ createdAt: new Date().toISOString(),
+ };
+ await kv.set("mem:action-edges", gateEdge.id, gateEdge);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ };
+
+ expect(result.frontier.length).toBe(0);
+ });
+
+ it("excludes actions conflicting with active actions", async () => {
+ const activeAction = makeAction({
+ id: "act_active",
+ title: "Active task",
+ status: "active",
+ });
+ const conflictAction = makeAction({
+ id: "act_conflict",
+ title: "Conflicting task",
+ status: "pending",
+ });
+
+ await kv.set("mem:actions", activeAction.id, activeAction);
+ await kv.set("mem:actions", conflictAction.id, conflictAction);
+
+ const conflictEdge: ActionEdge = {
+ id: "ae_conflict",
+ type: "conflicts_with",
+ sourceActionId: conflictAction.id,
+ targetActionId: activeAction.id,
+ createdAt: new Date().toISOString(),
+ };
+ await kv.set("mem:action-edges", conflictEdge.id, conflictEdge);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ };
+
+ const ids = result.frontier.map((f) => f.action.id);
+ expect(ids).toContain("act_active");
+ expect(ids).not.toContain("act_conflict");
+ });
+
+ it("active actions get score bonus", async () => {
+ const pendingAction = makeAction({
+ id: "act_pending",
+ title: "Pending",
+ status: "pending",
+ priority: 5,
+ createdAt: new Date().toISOString(),
+ });
+ const activeAction = makeAction({
+ id: "act_active",
+ title: "Active",
+ status: "active",
+ priority: 5,
+ createdAt: new Date().toISOString(),
+ });
+
+ await kv.set("mem:actions", pendingAction.id, pendingAction);
+ await kv.set("mem:actions", activeAction.id, activeAction);
+
+ const result = (await sdk.trigger("mem::frontier", {})) as {
+ success: boolean;
+ frontier: FrontierItem[];
+ };
+
+ const activeItem = result.frontier.find(
+ (f) => f.action.id === "act_active",
+ )!;
+ const pendingItem = result.frontier.find(
+ (f) => f.action.id === "act_pending",
+ )!;
+
+ expect(activeItem.score).toBeGreaterThan(pendingItem.score);
+ });
+ });
+
+ describe("mem::next", () => {
+ it("returns top suggestion when actions exist", async () => {
+ const action = makeAction({
+ id: "act_1",
+ title: "Top task",
+ priority: 8,
+ tags: ["urgent"],
+ });
+ await kv.set("mem:actions", action.id, action);
+
+ const result = (await sdk.trigger("mem::next", {})) as {
+ success: boolean;
+ suggestion: {
+ actionId: string;
+ title: string;
+ description: string;
+ priority: number;
+ score: number;
+ tags: string[];
+ } | null;
+ message: string;
+ totalActions: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.suggestion).not.toBeNull();
+ expect(result.suggestion!.actionId).toBe("act_1");
+ expect(result.suggestion!.title).toBe("Top task");
+ expect(result.suggestion!.priority).toBe(8);
+ expect(result.suggestion!.tags).toEqual(["urgent"]);
+ expect(result.message).toContain("Top task");
+ expect(result.totalActions).toBe(1);
+ });
+
+ it("returns null suggestion when no actions exist", async () => {
+ const result = (await sdk.trigger("mem::next", {})) as {
+ success: boolean;
+ suggestion: null;
+ message: string;
+ totalActions: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.suggestion).toBeNull();
+ expect(result.message).toContain("No actionable work");
+ expect(result.totalActions).toBe(0);
+ });
+
+ it("returns null when all actions are done", async () => {
+ const doneAction = makeAction({
+ id: "act_done",
+ title: "Completed",
+ status: "done",
+ });
+ await kv.set("mem:actions", doneAction.id, doneAction);
+
+ const result = (await sdk.trigger("mem::next", {})) as {
+ success: boolean;
+ suggestion: null;
+ message: string;
+ totalActions: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.suggestion).toBeNull();
+ expect(result.totalActions).toBe(1);
+ });
+
+ it("propagates failure when frontier fails", async () => {
+ const originalFunctions = new Map<string, Function>();
+
+ const failSdk = {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ originalFunctions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ if (id === "mem::frontier") {
+ return { success: false, error: "internal failure" };
+ }
+ const fn = originalFunctions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+
+ const failKv = mockKV();
+ registerFrontierFunction(failSdk as never, failKv as never);
+
+ const nextFn = originalFunctions.get("mem::next")!;
+ const result = (await nextFn({})) as {
+ success: boolean;
+ suggestion: null;
+ message: string;
+ totalActions: number;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.suggestion).toBeNull();
+ expect(result.message).toContain("Failed to compute frontier");
+ expect(result.totalActions).toBe(0);
+ });
+
+ it("respects project filter", async () => {
+ const alphaAction = makeAction({
+ id: "act_alpha",
+ title: "Alpha task",
+ project: "alpha",
+ priority: 5,
+ });
+ const betaAction = makeAction({
+ id: "act_beta",
+ title: "Beta task",
+ project: "beta",
+ priority: 10,
+ });
+
+ await kv.set("mem:actions", alphaAction.id, alphaAction);
+ await kv.set("mem:actions", betaAction.id, betaAction);
+
+ const result = (await sdk.trigger("mem::next", {
+ project: "alpha",
+ })) as {
+ success: boolean;
+ suggestion: { actionId: string; title: string } | null;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.suggestion).not.toBeNull();
+ expect(result.suggestion!.actionId).toBe("act_alpha");
+ });
+ });
+});
diff --git a/test/leases.test.ts b/test/leases.test.ts
new file mode 100644
index 00000000..46861f5b
--- /dev/null
+++ b/test/leases.test.ts
@@ -0,0 +1,399 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerLeasesFunction } from "../src/functions/leases.js";
+import type { Action, Lease } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+function makeAction(
+ id: string,
+ status: Action["status"] = "pending",
+): Action {
+ return {
+ id,
+ title: `Action ${id}`,
+ description: `Description for ${id}`,
+ status,
+ priority: 5,
+ createdAt: "2026-02-01T00:00:00Z",
+ updatedAt: "2026-02-01T00:00:00Z",
+ createdBy: "agent-setup",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ };
+}
+
+describe("Lease Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(async () => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerLeasesFunction(sdk as never, kv as never);
+
+ await kv.set("mem:actions", "act_1", makeAction("act_1", "pending"));
+ await kv.set("mem:actions", "act_2", makeAction("act_2", "done"));
+ await kv.set("mem:actions", "act_3", makeAction("act_3", "cancelled"));
+ await kv.set("mem:actions", "act_4", makeAction("act_4", "pending"));
+ });
+
+ describe("mem::lease-acquire", () => {
+ it("acquires a lease for a valid action", async () => {
+ const result = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease; renewed: boolean };
+
+ expect(result.success).toBe(true);
+ expect(result.lease.actionId).toBe("act_1");
+ expect(result.lease.agentId).toBe("agent-a");
+ expect(result.lease.status).toBe("active");
+ expect(result.renewed).toBe(false);
+ expect(result.lease.id).toMatch(/^lse_/);
+ });
+
+ it("returns error when actionId or agentId is missing", async () => {
+ const r1 = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "",
+ })) as { success: boolean; error: string };
+ expect(r1.success).toBe(false);
+ expect(r1.error).toBe("actionId and agentId are required");
+
+ const r2 = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+ expect(r2.success).toBe(false);
+ expect(r2.error).toBe("actionId and agentId are required");
+ });
+
+ it("returns error for nonexistent action", async () => {
+ const result = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_nonexistent",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("action not found");
+ });
+
+ it("returns error for done action", async () => {
+ const result = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_2",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("action already completed");
+ });
+
+ it("returns error for cancelled action", async () => {
+ const result = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_3",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("action already completed");
+ });
+
+ it("returns existing lease when same agent already holds it", async () => {
+ const first = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ const second = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease; renewed: boolean; message: string };
+
+ expect(second.success).toBe(true);
+ expect(second.lease.id).toBe(first.lease.id);
+ expect(second.renewed).toBe(false);
+ expect(second.message).toBe("Already holding this lease");
+ });
+
+ it("returns conflict error when different agent holds the lease", async () => {
+ await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ const result = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-b",
+ })) as { success: boolean; error: string; heldBy: string; expiresAt: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("action already leased");
+ expect(result.heldBy).toBe("agent-a");
+ expect(result.expiresAt).toBeDefined();
+ });
+
+ it("sets action status to active after acquire", async () => {
+ await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("active");
+ expect(action!.assignedTo).toBe("agent-a");
+ });
+ });
+
+ describe("mem::lease-release", () => {
+ it("releases an active lease", async () => {
+ await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ const result = (await sdk.trigger("mem::lease-release", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; released: boolean };
+
+ expect(result.success).toBe(true);
+ expect(result.released).toBe(true);
+ });
+
+ it("sets action to done when result is provided", async () => {
+ await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ await sdk.trigger("mem::lease-release", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ result: "completed successfully",
+ });
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("done");
+ expect(action!.result).toBe("completed successfully");
+ expect(action!.assignedTo).toBeUndefined();
+ });
+
+ it("sets action to pending when no result is provided", async () => {
+ await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ await sdk.trigger("mem::lease-release", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("pending");
+ expect(action!.assignedTo).toBeUndefined();
+ });
+
+ it("returns error when no active lease exists for agent", async () => {
+ const result = (await sdk.trigger("mem::lease-release", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("no active lease found for this agent");
+ });
+
+ it("returns error when actionId or agentId is missing", async () => {
+ const result = (await sdk.trigger("mem::lease-release", {
+ actionId: "",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("actionId and agentId are required");
+ });
+ });
+
+ describe("mem::lease-renew", () => {
+ it("renews an active non-expired lease", async () => {
+ const acquired = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ const originalExpiry = acquired.lease.expiresAt;
+
+ const result = (await sdk.trigger("mem::lease-renew", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ expect(result.success).toBe(true);
+ expect(result.lease.renewedAt).toBeDefined();
+ expect(
+ new Date(result.lease.expiresAt).getTime(),
+ ).toBeGreaterThanOrEqual(new Date(originalExpiry).getTime());
+ });
+
+ it("returns error when lease is expired", async () => {
+ const acquired = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ acquired.lease.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:leases", acquired.lease.id, acquired.lease);
+
+ const result = (await sdk.trigger("mem::lease-renew", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("no active (non-expired) lease to renew");
+ });
+
+ it("returns error when actionId or agentId is missing", async () => {
+ const result = (await sdk.trigger("mem::lease-renew", {
+ actionId: "",
+ agentId: "agent-a",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("actionId and agentId are required");
+ });
+ });
+
+ describe("mem::lease-cleanup", () => {
+ it("expires active leases past their expiresAt and resets actions to pending", async () => {
+ const acquired = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ acquired.lease.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:leases", acquired.lease.id, acquired.lease);
+
+ const result = (await sdk.trigger("mem::lease-cleanup", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(1);
+
+ const lease = await kv.get<Lease>("mem:leases", acquired.lease.id);
+ expect(lease!.status).toBe("expired");
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("pending");
+ expect(action!.assignedTo).toBeUndefined();
+ });
+
+ it("does not expire non-expired active leases", async () => {
+ await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ });
+
+ const result = (await sdk.trigger("mem::lease-cleanup", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ expect(action!.status).toBe("active");
+ });
+
+ it("handles multiple expired leases across different actions", async () => {
+ const a1 = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ const a4 = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_4",
+ agentId: "agent-b",
+ })) as { success: boolean; lease: Lease };
+
+ a1.lease.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:leases", a1.lease.id, a1.lease);
+
+ a4.lease.expiresAt = new Date(Date.now() - 30000).toISOString();
+ await kv.set("mem:leases", a4.lease.id, a4.lease);
+
+ const result = (await sdk.trigger("mem::lease-cleanup", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(2);
+ });
+
+ it("does not reset action when action is no longer active", async () => {
+ const acquired = (await sdk.trigger("mem::lease-acquire", {
+ actionId: "act_1",
+ agentId: "agent-a",
+ })) as { success: boolean; lease: Lease };
+
+ acquired.lease.expiresAt = new Date(Date.now() - 60000).toISOString();
+ await kv.set("mem:leases", acquired.lease.id, acquired.lease);
+
+ const action = await kv.get<Action>("mem:actions", "act_1");
+ action!.status = "done";
+ await kv.set("mem:actions", "act_1", action);
+
+ await sdk.trigger("mem::lease-cleanup", {});
+
+ const updatedAction = await kv.get<Action>("mem:actions", "act_1");
+ expect(updatedAction!.status).toBe("done");
+ });
+ });
+});
diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts
index 69752f3e..6afb0f1e 100644
--- a/test/mcp-standalone.test.ts
+++ b/test/mcp-standalone.test.ts
@@ -22,9 +22,9 @@ import { InMemoryKV } from "../src/mcp/in-memory-kv.js";
import { writeFileSync } from "node:fs";
describe("Tools Registry", () => {
- it("getAllTools returns 18 tools", () => {
+ it("getAllTools returns 37 tools", () => {
const tools = getAllTools();
- expect(tools.length).toBe(18);
+ expect(tools.length).toBe(37);
});
it("CORE_TOOLS has 10 items", () => {
diff --git a/test/mesh.test.ts b/test/mesh.test.ts
new file mode 100644
index 00000000..89dd48ee
--- /dev/null
+++ b/test/mesh.test.ts
@@ -0,0 +1,486 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerMeshFunction } from "../src/functions/mesh.js";
+import type { MeshPeer, Memory, Action } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Mesh Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ vi.clearAllMocks();
+ registerMeshFunction(sdk as never, kv as never);
+ });
+
+ describe("mesh-register", () => {
+ it("registers a valid peer", async () => {
+ const result = (await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ name: "peer-1",
+ sharedScopes: ["memories"],
+ })) as { success: boolean; peer: MeshPeer };
+
+ expect(result.success).toBe(true);
+ expect(result.peer.url).toBe("https://peer1.example.com");
+ expect(result.peer.name).toBe("peer-1");
+ expect(result.peer.status).toBe("disconnected");
+ expect(result.peer.sharedScopes).toEqual(["memories"]);
+ expect(result.peer.id).toMatch(/^peer_/);
+
+ const peers = await kv.list<MeshPeer>("mem:mesh");
+ expect(peers.length).toBe(1);
+ });
+
+ it("uses 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"]);
+ });
+
+ it("returns error when url is missing", async () => {
+ const result = (await sdk.trigger("mem::mesh-register", {
+ name: "peer-1",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("url and name are required");
+ });
+
+ it("returns error when name is missing", async () => {
+ const result = (await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("url and name are required");
+ });
+
+ it("returns error for duplicate url", async () => {
+ await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ name: "peer-1",
+ });
+
+ const result = (await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ name: "peer-1-duplicate",
+ })) as { success: boolean; error: string; peerId: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("peer already registered");
+ expect(result.peerId).toBeDefined();
+ });
+ });
+
+ describe("mesh-list", () => {
+ it("returns empty list when no peers registered", async () => {
+ const result = (await sdk.trigger("mem::mesh-list", {})) as {
+ success: boolean;
+ peers: MeshPeer[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.peers).toEqual([]);
+ });
+
+ it("returns all registered peers", async () => {
+ await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ name: "peer-1",
+ });
+ await sdk.trigger("mem::mesh-register", {
+ url: "https://peer2.example.com",
+ name: "peer-2",
+ });
+
+ const result = (await sdk.trigger("mem::mesh-list", {})) as {
+ success: boolean;
+ peers: MeshPeer[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.peers.length).toBe(2);
+ expect(result.peers.map((p) => p.name).sort()).toEqual(["peer-1", "peer-2"]);
+ });
+ });
+
+ describe("mesh-receive", () => {
+ it("accepts new memories", async () => {
+ const mem: Memory = {
+ id: "mem_1",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "pattern",
+ title: "Test memory",
+ content: "Test content",
+ concepts: ["test"],
+ files: [],
+ sessionIds: ["ses_1"],
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [mem],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+
+ const stored = await kv.get<Memory>("mem:memories", "mem_1");
+ expect(stored).toBeDefined();
+ expect(stored!.title).toBe("Test memory");
+ });
+
+ it("accepts newer memory over existing (last-write-wins)", async () => {
+ const older: Memory = {
+ id: "mem_1",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "pattern",
+ title: "Old title",
+ content: "Old content",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ };
+ await kv.set("mem:memories", "mem_1", older);
+
+ const newer: Memory = {
+ ...older,
+ updatedAt: "2026-03-02T00:00:00Z",
+ title: "New title",
+ content: "New content",
+ version: 2,
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [newer],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+
+ const stored = await kv.get<Memory>("mem:memories", "mem_1");
+ expect(stored!.title).toBe("New title");
+ });
+
+ it("rejects older memory than existing", async () => {
+ const existing: Memory = {
+ id: "mem_1",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-02T00:00:00Z",
+ type: "pattern",
+ title: "Existing title",
+ content: "Existing content",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 5,
+ version: 2,
+ isLatest: true,
+ };
+ await kv.set("mem:memories", "mem_1", existing);
+
+ const older: Memory = {
+ ...existing,
+ updatedAt: "2026-03-01T00:00:00Z",
+ title: "Old title",
+ version: 1,
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [older],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+
+ const stored = await kv.get<Memory>("mem:memories", "mem_1");
+ expect(stored!.title).toBe("Existing title");
+ });
+
+ it("skips memory entries with missing id", async () => {
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [
+ { updatedAt: "2026-03-01T00:00:00Z", title: "No ID" } as unknown as Memory,
+ ],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+ });
+
+ it("skips memory entries with invalid date", async () => {
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [
+ {
+ id: "mem_bad_date",
+ updatedAt: "not-a-date",
+ title: "Bad date",
+ } as unknown as Memory,
+ ],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+ });
+
+ it("accepts new actions", async () => {
+ const action: Action = {
+ id: "act_1",
+ title: "Fix bug",
+ description: "Fix the login bug",
+ status: "pending",
+ priority: 1,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ createdBy: "agent-1",
+ tags: ["bug"],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ actions: [action],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+
+ const stored = await kv.get<Action>("mem:actions", "act_1");
+ expect(stored).toBeDefined();
+ expect(stored!.title).toBe("Fix bug");
+ });
+
+ it("accepts newer action over existing (last-write-wins)", async () => {
+ const older: Action = {
+ id: "act_1",
+ title: "Old action",
+ description: "Old desc",
+ status: "pending",
+ priority: 1,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ createdBy: "agent-1",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ };
+ await kv.set("mem:actions", "act_1", older);
+
+ const newer: Action = {
+ ...older,
+ updatedAt: "2026-03-02T00:00:00Z",
+ title: "Updated action",
+ status: "done",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ actions: [newer],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(1);
+
+ const stored = await kv.get<Action>("mem:actions", "act_1");
+ expect(stored!.title).toBe("Updated action");
+ expect(stored!.status).toBe("done");
+ });
+
+ it("rejects older action than existing", async () => {
+ const existing: Action = {
+ id: "act_1",
+ title: "Current action",
+ description: "Current desc",
+ status: "active",
+ priority: 1,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-02T00:00:00Z",
+ createdBy: "agent-1",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ };
+ await kv.set("mem:actions", "act_1", existing);
+
+ const older: Action = {
+ ...existing,
+ updatedAt: "2026-03-01T00:00:00Z",
+ title: "Stale action",
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ actions: [older],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+
+ const stored = await kv.get<Action>("mem:actions", "act_1");
+ expect(stored!.title).toBe("Current action");
+ });
+
+ it("skips action entries with missing id", async () => {
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ actions: [
+ { updatedAt: "2026-03-01T00:00:00Z", title: "No ID" } as unknown as Action,
+ ],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+ });
+
+ it("skips action entries with invalid date", async () => {
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ actions: [
+ {
+ id: "act_bad_date",
+ updatedAt: "invalid-date-string",
+ title: "Bad date",
+ } as unknown as Action,
+ ],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+ });
+
+ it("accepts both memories and actions in one call", async () => {
+ const mem: Memory = {
+ id: "mem_combo",
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ type: "fact",
+ title: "Combo memory",
+ content: "Content",
+ concepts: [],
+ files: [],
+ sessionIds: [],
+ strength: 3,
+ version: 1,
+ isLatest: true,
+ };
+ const action: Action = {
+ id: "act_combo",
+ title: "Combo action",
+ description: "Desc",
+ status: "pending",
+ priority: 2,
+ createdAt: "2026-03-01T00:00:00Z",
+ updatedAt: "2026-03-01T00:00:00Z",
+ createdBy: "agent-1",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ };
+
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [mem],
+ actions: [action],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(2);
+ });
+
+ it("returns zero accepted for empty arrays", async () => {
+ const result = (await sdk.trigger("mem::mesh-receive", {
+ memories: [],
+ actions: [],
+ })) as { success: boolean; accepted: number };
+
+ expect(result.success).toBe(true);
+ expect(result.accepted).toBe(0);
+ });
+ });
+
+ describe("mesh-remove", () => {
+ it("removes a registered peer", async () => {
+ const regResult = (await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ name: "peer-1",
+ })) as { success: boolean; peer: MeshPeer };
+
+ const result = (await sdk.trigger("mem::mesh-remove", {
+ peerId: regResult.peer.id,
+ })) as { success: boolean };
+
+ expect(result.success).toBe(true);
+
+ const peers = await kv.list<MeshPeer>("mem:mesh");
+ expect(peers.length).toBe(0);
+ });
+
+ it("returns error when peerId is missing", async () => {
+ const result = (await sdk.trigger("mem::mesh-remove", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("peerId is required");
+ });
+
+ it("succeeds silently for non-existent peerId", async () => {
+ const result = (await sdk.trigger("mem::mesh-remove", {
+ peerId: "peer_nonexistent",
+ })) as { success: boolean };
+
+ expect(result.success).toBe(true);
+ });
+ });
+});
diff --git a/test/routines.test.ts b/test/routines.test.ts
new file mode 100644
index 00000000..f62b8664
--- /dev/null
+++ b/test/routines.test.ts
@@ -0,0 +1,497 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerRoutinesFunction } from "../src/functions/routines.js";
+import type { Action, Routine, RoutineRun } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Routines Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerRoutinesFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::routine-create", () => {
+ it("creates a routine with valid data", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Deploy Pipeline",
+ description: "Standard deploy steps",
+ steps: [
+ { title: "Build", description: "Run build", actionTemplate: {}, dependsOn: [] },
+ { title: "Test", description: "Run tests", actionTemplate: {}, dependsOn: [0] },
+ ],
+ tags: ["deploy", "ci"],
+ })) as { success: boolean; routine: Routine };
+
+ expect(result.success).toBe(true);
+ expect(result.routine.id).toMatch(/^rtn_/);
+ expect(result.routine.name).toBe("Deploy Pipeline");
+ expect(result.routine.description).toBe("Standard deploy steps");
+ expect(result.routine.steps.length).toBe(2);
+ expect(result.routine.tags).toEqual(["deploy", "ci"]);
+ expect(result.routine.createdAt).toBeDefined();
+ expect(result.routine.updatedAt).toBeDefined();
+ expect(result.routine.frozen).toBe(true);
+ });
+
+ it("returns error when name is missing", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "",
+ steps: [{ title: "Step 1", description: "", actionTemplate: {}, dependsOn: [] }],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("name and steps are required");
+ });
+
+ it("returns error when steps array is empty", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Empty Routine",
+ steps: [],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("name and steps are required");
+ });
+
+ it("returns error when a step has no title", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Bad Steps",
+ steps: [
+ { title: "Good Step", description: "ok", actionTemplate: {}, dependsOn: [] },
+ { title: " ", description: "no title", actionTemplate: {}, dependsOn: [] },
+ ],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("step 1 must have a title");
+ });
+
+ it("assigns correct order to steps", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Ordered Routine",
+ steps: [
+ { title: "First", description: "", actionTemplate: {}, dependsOn: [] },
+ { title: "Second", description: "", actionTemplate: {}, dependsOn: [] },
+ { title: "Third", description: "", actionTemplate: {}, dependsOn: [] },
+ ],
+ })) as { success: boolean; routine: Routine };
+
+ expect(result.success).toBe(true);
+ expect(result.routine.steps[0].order).toBe(0);
+ expect(result.routine.steps[1].order).toBe(1);
+ expect(result.routine.steps[2].order).toBe(2);
+ });
+
+ it("preserves explicit order values", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Custom Order",
+ steps: [
+ { order: 10, title: "First", description: "", actionTemplate: {}, dependsOn: [] },
+ { order: 20, title: "Second", description: "", actionTemplate: {}, dependsOn: [] },
+ ],
+ })) as { success: boolean; routine: Routine };
+
+ expect(result.success).toBe(true);
+ expect(result.routine.steps[0].order).toBe(10);
+ expect(result.routine.steps[1].order).toBe(20);
+ });
+
+ it("defaults frozen to true when not specified", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Default Frozen",
+ steps: [{ title: "Step", description: "", actionTemplate: {}, dependsOn: [] }],
+ })) as { success: boolean; routine: Routine };
+
+ expect(result.success).toBe(true);
+ expect(result.routine.frozen).toBe(true);
+ });
+
+ it("respects frozen=false when explicitly set", async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Unfrozen",
+ steps: [{ title: "Step", description: "", actionTemplate: {}, dependsOn: [] }],
+ frozen: false,
+ })) as { success: boolean; routine: Routine };
+
+ expect(result.success).toBe(true);
+ expect(result.routine.frozen).toBe(false);
+ });
+ });
+
+ describe("mem::routine-list", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::routine-create", {
+ name: "Routine A",
+ steps: [{ title: "S1", description: "", actionTemplate: {}, dependsOn: [] }],
+ tags: ["deploy"],
+ frozen: true,
+ });
+ await sdk.trigger("mem::routine-create", {
+ name: "Routine B",
+ steps: [{ title: "S1", description: "", actionTemplate: {}, dependsOn: [] }],
+ tags: ["test", "ci"],
+ frozen: false,
+ });
+ await sdk.trigger("mem::routine-create", {
+ name: "Routine C",
+ steps: [{ title: "S1", description: "", actionTemplate: {}, dependsOn: [] }],
+ tags: ["deploy", "ci"],
+ frozen: true,
+ });
+ });
+
+ it("lists all routines", async () => {
+ const result = (await sdk.trigger("mem::routine-list", {})) as {
+ success: boolean;
+ routines: Routine[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.routines.length).toBe(3);
+ });
+
+ it("filters by frozen=true", async () => {
+ const result = (await sdk.trigger("mem::routine-list", {
+ frozen: true,
+ })) as { success: boolean; routines: Routine[] };
+
+ expect(result.success).toBe(true);
+ expect(result.routines.length).toBe(2);
+ expect(result.routines.every((r) => r.frozen === true)).toBe(true);
+ });
+
+ it("filters by frozen=false", async () => {
+ const result = (await sdk.trigger("mem::routine-list", {
+ frozen: false,
+ })) as { success: boolean; routines: Routine[] };
+
+ expect(result.success).toBe(true);
+ expect(result.routines.length).toBe(1);
+ expect(result.routines[0].name).toBe("Routine B");
+ });
+
+ it("filters by tags", async () => {
+ const result = (await sdk.trigger("mem::routine-list", {
+ tags: ["deploy"],
+ })) as { success: boolean; routines: Routine[] };
+
+ expect(result.success).toBe(true);
+ expect(result.routines.length).toBe(2);
+ const names = result.routines.map((r) => r.name);
+ expect(names).toContain("Routine A");
+ expect(names).toContain("Routine C");
+ });
+
+ it("filters by tags with multiple matches", async () => {
+ const result = (await sdk.trigger("mem::routine-list", {
+ tags: ["ci"],
+ })) as { success: boolean; routines: Routine[] };
+
+ expect(result.success).toBe(true);
+ expect(result.routines.length).toBe(2);
+ const names = result.routines.map((r) => r.name);
+ expect(names).toContain("Routine B");
+ expect(names).toContain("Routine C");
+ });
+ });
+
+ describe("mem::routine-run", () => {
+ let routineId: string;
+
+ beforeEach(async () => {
+ const result = (await sdk.trigger("mem::routine-create", {
+ name: "Test Pipeline",
+ steps: [
+ { order: 0, title: "Build", description: "Build step", actionTemplate: { priority: 3 }, dependsOn: [] },
+ { order: 1, title: "Test", description: "Test step", actionTemplate: { priority: 5 }, dependsOn: [0] },
+ { order: 2, title: "Deploy", description: "Deploy step", actionTemplate: {}, dependsOn: [0, 1] },
+ ],
+ })) as { success: boolean; routine: Routine };
+ routineId = result.routine.id;
+ });
+
+ it("creates actions for each step", async () => {
+ const result = (await sdk.trigger("mem::routine-run", {
+ routineId,
+ initiatedBy: "user-1",
+ })) as { success: boolean; run: RoutineRun; actionsCreated: number };
+
+ expect(result.success).toBe(true);
+ expect(result.actionsCreated).toBe(3);
+ expect(result.run.actionIds.length).toBe(3);
+ expect(result.run.status).toBe("running");
+ expect(result.run.initiatedBy).toBe("user-1");
+
+ const actions = await kv.list<Action>("mem:actions");
+ expect(actions.length).toBe(3);
+ const titles = actions.map((a) => a.title);
+ expect(titles).toContain("Build");
+ expect(titles).toContain("Test");
+ expect(titles).toContain("Deploy");
+ });
+
+ it("creates dependency edges between steps", async () => {
+ const result = (await sdk.trigger("mem::routine-run", {
+ routineId,
+ })) as { success: boolean; run: RoutineRun; actionsCreated: number };
+
+ expect(result.success).toBe(true);
+
+ const edges = await kv.list<{
+ id: string;
+ type: string;
+ sourceActionId: string;
+ targetActionId: string;
+ }>("mem:action-edges");
+
+ expect(edges.length).toBe(3);
+ expect(edges.every((e) => e.type === "requires")).toBe(true);
+ });
+
+ it("creates routine run tracking object", async () => {
+ const result = (await sdk.trigger("mem::routine-run", {
+ routineId,
+ initiatedBy: "agent-x",
+ })) as { success: boolean; run: RoutineRun };
+
+ expect(result.run.id).toMatch(/^run_/);
+ expect(result.run.routineId).toBe(routineId);
+ expect(result.run.status).toBe("running");
+ expect(result.run.startedAt).toBeDefined();
+ expect(result.run.actionIds.length).toBe(3);
+ expect(result.run.initiatedBy).toBe("agent-x");
+
+ const stored = await kv.get<RoutineRun>("mem:routine-runs", result.run.id);
+ expect(stored).not.toBeNull();
+ expect(stored!.routineId).toBe(routineId);
+ });
+
+ it("preserves priority 0 via nullish coalescing", async () => {
+ const createResult = (await sdk.trigger("mem::routine-create", {
+ name: "Zero Priority",
+ steps: [
+ { order: 0, title: "Step Zero", description: "", actionTemplate: { priority: 0 }, dependsOn: [] },
+ ],
+ })) as { success: boolean; routine: Routine };
+
+ const runResult = (await sdk.trigger("mem::routine-run", {
+ routineId: createResult.routine.id,
+ })) as { success: boolean; run: RoutineRun };
+
+ const actionId = runResult.run.actionIds[0];
+ const action = await kv.get<Action>("mem:actions", actionId);
+ expect(action!.priority).toBe(0);
+ });
+
+ it("tags actions with routine id", async () => {
+ const result = (await sdk.trigger("mem::routine-run", {
+ routineId,
+ })) as { success: boolean; run: RoutineRun };
+
+ for (const actionId of result.run.actionIds) {
+ const action = await kv.get<Action>("mem:actions", actionId);
+ expect(action!.tags).toContain(`routine:${routineId}`);
+ }
+ });
+
+ it("returns error when routineId is missing", async () => {
+ const result = (await sdk.trigger("mem::routine-run", {
+ routineId: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("routineId is required");
+ });
+
+ it("returns error when routine is not found", async () => {
+ const result = (await sdk.trigger("mem::routine-run", {
+ routineId: "rtn_nonexistent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("routine not found");
+ });
+ });
+
+ describe("mem::routine-status", () => {
+ let runId: string;
+ let actionIds: string[];
+
+ beforeEach(async () => {
+ const createResult = (await sdk.trigger("mem::routine-create", {
+ name: "Status Test",
+ steps: [
+ { order: 0, title: "Step A", description: "", actionTemplate: {}, dependsOn: [] },
+ { order: 1, title: "Step B", description: "", actionTemplate: {}, dependsOn: [] },
+ { order: 2, title: "Step C", description: "", actionTemplate: {}, dependsOn: [] },
+ ],
+ })) as { success: boolean; routine: Routine };
+
+ const runResult = (await sdk.trigger("mem::routine-run", {
+ routineId: createResult.routine.id,
+ })) as { success: boolean; run: RoutineRun };
+
+ runId = runResult.run.id;
+ actionIds = runResult.run.actionIds;
+ });
+
+ it("reports running status when actions are in progress", async () => {
+ const result = (await sdk.trigger("mem::routine-status", {
+ runId,
+ })) as { success: boolean; run: RoutineRun; progress: { total: number; pending: number } };
+
+ expect(result.success).toBe(true);
+ expect(result.run.status).toBe("running");
+ expect(result.progress.total).toBe(3);
+ expect(result.progress.pending).toBe(3);
+ });
+
+ it("marks run completed when all actions are done", async () => {
+ for (const actionId of actionIds) {
+ const action = await kv.get<Action>("mem:actions", actionId);
+ action!.status = "done";
+ await kv.set("mem:actions", actionId, action);
+ }
+
+ const result = (await sdk.trigger("mem::routine-status", {
+ runId,
+ })) as { success: boolean; run: RoutineRun; progress: { done: number; total: number } };
+
+ expect(result.success).toBe(true);
+ expect(result.run.status).toBe("completed");
+ expect(result.run.completedAt).toBeDefined();
+ expect(result.progress.done).toBe(3);
+ });
+
+ it("marks run failed when any action is cancelled", async () => {
+ const action = await kv.get<Action>("mem:actions", actionIds[0]);
+ action!.status = "cancelled";
+ await kv.set("mem:actions", actionIds[0], action);
+
+ const result = (await sdk.trigger("mem::routine-status", {
+ runId,
+ })) as { success: boolean; run: RoutineRun };
+
+ expect(result.success).toBe(true);
+ expect(result.run.status).toBe("failed");
+ });
+
+ it("marks run failed when any action is cancelled (mixed statuses)", async () => {
+ const action = await kv.get<Action>("mem:actions", actionIds[1]);
+ (action as Action).status = "done";
+ await kv.set("mem:actions", actionIds[1], action);
+
+ const action2 = await kv.get<Action>("mem:actions", actionIds[2]);
+ (action2 as Action).status = "cancelled";
+ await kv.set("mem:actions", actionIds[2], action2);
+
+ const result = (await sdk.trigger("mem::routine-status", {
+ runId,
+ })) as { success: boolean; run: RoutineRun };
+
+ expect(result.success).toBe(true);
+ expect(result.run.status).toBe("failed");
+ });
+
+ it("returns error when runId is missing", async () => {
+ const result = (await sdk.trigger("mem::routine-status", {
+ runId: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("runId is required");
+ });
+
+ it("returns error when run is not found", async () => {
+ const result = (await sdk.trigger("mem::routine-status", {
+ runId: "run_nonexistent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("run not found");
+ });
+ });
+
+ describe("mem::routine-freeze", () => {
+ it("freezes a routine", async () => {
+ const createResult = (await sdk.trigger("mem::routine-create", {
+ name: "Unfreeze Me",
+ steps: [{ title: "Step", description: "", actionTemplate: {}, dependsOn: [] }],
+ frozen: false,
+ })) as { success: boolean; routine: Routine };
+
+ expect(createResult.routine.frozen).toBe(false);
+
+ const result = (await sdk.trigger("mem::routine-freeze", {
+ routineId: createResult.routine.id,
+ })) as { success: boolean; routine: Routine };
+
+ expect(result.success).toBe(true);
+ expect(result.routine.frozen).toBe(true);
+ expect(result.routine.updatedAt).toBeDefined();
+ });
+
+ it("returns error when routineId is missing", async () => {
+ const result = (await sdk.trigger("mem::routine-freeze", {
+ routineId: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("routineId is required");
+ });
+
+ it("returns error when routine is not found", async () => {
+ const result = (await sdk.trigger("mem::routine-freeze", {
+ routineId: "rtn_nonexistent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("routine not found");
+ });
+ });
+});
diff --git a/test/schema-fingerprint.test.ts b/test/schema-fingerprint.test.ts
new file mode 100644
index 00000000..f56af2c1
--- /dev/null
+++ b/test/schema-fingerprint.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from "vitest";
+import { fingerprintId, KV } from "../src/state/schema.js";
+
+describe("fingerprintId", () => {
+ it("returns string with correct prefix", () => {
+ const id = fingerprintId("mem", "some content");
+ expect(id).toMatch(/^mem_/);
+ });
+
+ it("same content produces same ID (deterministic)", () => {
+ const id1 = fingerprintId("obs", "identical content here");
+ const id2 = fingerprintId("obs", "identical content here");
+ expect(id1).toBe(id2);
+ });
+
+ it("different content produces different IDs", () => {
+ const id1 = fingerprintId("obs", "content alpha");
+ const id2 = fingerprintId("obs", "content beta");
+ expect(id1).not.toBe(id2);
+ });
+
+ it("different prefixes produce different IDs", () => {
+ const id1 = fingerprintId("mem", "same content");
+ const id2 = fingerprintId("obs", "same content");
+ expect(id1).not.toBe(id2);
+ });
+
+ it("ID has sufficient length (prefix + underscore + 16 hex chars)", () => {
+ const id = fingerprintId("mem", "test");
+ const parts = id.split("_");
+ expect(parts.length).toBe(2);
+ expect(parts[0]).toBe("mem");
+ expect(parts[1]).toHaveLength(16);
+ expect(parts[1]).toMatch(/^[0-9a-f]{16}$/);
+ });
+
+ it("handles empty content", () => {
+ const id = fingerprintId("x", "");
+ expect(id).toMatch(/^x_[0-9a-f]{16}$/);
+ });
+
+ it("handles long content", () => {
+ const longContent = "a".repeat(10000);
+ const id = fingerprintId("long", longContent);
+ expect(id).toMatch(/^long_[0-9a-f]{16}$/);
+ });
+});
+
+describe("KV scopes", () => {
+ it("has actions scope", () => {
+ expect(KV.actions).toBe("mem:actions");
+ });
+
+ it("has actionEdges scope", () => {
+ expect(KV.actionEdges).toBe("mem:action-edges");
+ });
+
+ it("has leases scope", () => {
+ expect(KV.leases).toBe("mem:leases");
+ });
+
+ it("has routines scope", () => {
+ expect(KV.routines).toBe("mem:routines");
+ });
+
+ it("has routineRuns scope", () => {
+ expect(KV.routineRuns).toBe("mem:routine-runs");
+ });
+
+ it("has signals scope", () => {
+ expect(KV.signals).toBe("mem:signals");
+ });
+
+ it("has checkpoints scope", () => {
+ expect(KV.checkpoints).toBe("mem:checkpoints");
+ });
+
+ it("has mesh scope", () => {
+ expect(KV.mesh).toBe("mem:mesh");
+ });
+});
diff --git a/test/sentinels.test.ts b/test/sentinels.test.ts
new file mode 100644
index 00000000..726d7764
--- /dev/null
+++ b/test/sentinels.test.ts
@@ -0,0 +1,626 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerSentinelsFunction } from "../src/functions/sentinels.js";
+import { registerActionsFunction } from "../src/functions/actions.js";
+import type { Action, ActionEdge, Sentinel } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Sentinels Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerSentinelsFunction(sdk as never, kv as never);
+ registerActionsFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::sentinel-create", () => {
+ it("creates a webhook sentinel with valid config", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "deploy-hook",
+ type: "webhook",
+ config: { path: "/hooks/deploy" },
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.id).toMatch(/^snl_/);
+ expect(result.sentinel.name).toBe("deploy-hook");
+ expect(result.sentinel.type).toBe("webhook");
+ expect(result.sentinel.status).toBe("watching");
+ expect(result.sentinel.config).toEqual({ path: "/hooks/deploy" });
+ expect(result.sentinel.linkedActionIds).toEqual([]);
+ expect(result.sentinel.createdAt).toBeDefined();
+ });
+
+ it("creates a timer sentinel with valid config", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "timeout-check",
+ type: "timer",
+ config: { durationMs: 5000 },
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.type).toBe("timer");
+ expect(result.sentinel.status).toBe("watching");
+ });
+
+ it("creates a threshold sentinel with valid config", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "high-calls",
+ type: "threshold",
+ config: { metric: "api_calls", operator: "gt", value: 100 },
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.type).toBe("threshold");
+ });
+
+ it("creates a pattern sentinel with valid config", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "error-watcher",
+ type: "pattern",
+ config: { pattern: "error|fail" },
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.type).toBe("pattern");
+ });
+
+ it("creates an approval sentinel without config", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "needs-approval",
+ type: "approval",
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.type).toBe("approval");
+ expect(result.sentinel.config).toEqual({});
+ });
+
+ it("creates a custom sentinel without config", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "custom-gate",
+ type: "custom",
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.type).toBe("custom");
+ });
+
+ it("returns error when name is missing", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ type: "webhook",
+ config: { path: "/hooks/deploy" },
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("name is required");
+ });
+
+ it("returns error for invalid type", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-type",
+ type: "invalid_type",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("type must be one of");
+ });
+
+ it("returns error for timer config missing durationMs", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-timer",
+ type: "timer",
+ config: {},
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("positive durationMs");
+ });
+
+ it("returns error for timer config with negative durationMs", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "neg-timer",
+ type: "timer",
+ config: { durationMs: -100 },
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("positive durationMs");
+ });
+
+ it("returns error for threshold config missing metric", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-threshold",
+ type: "threshold",
+ config: { operator: "gt", value: 10 },
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("threshold config requires");
+ });
+
+ it("returns error for threshold config with invalid operator", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-op",
+ type: "threshold",
+ config: { metric: "calls", operator: "gte", value: 10 },
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("threshold config requires");
+ });
+
+ it("returns error for threshold config missing value", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "no-val",
+ type: "threshold",
+ config: { metric: "calls", operator: "gt" },
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("threshold config requires");
+ });
+
+ it("returns error for pattern config missing pattern", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-pattern",
+ type: "pattern",
+ config: {},
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("pattern config requires");
+ });
+
+ it("returns error for webhook config missing path", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-webhook",
+ type: "webhook",
+ config: {},
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("webhook config requires");
+ });
+
+ it("creates gated_by edges for linkedActionIds", async () => {
+ const action = (await sdk.trigger("mem::action-create", {
+ title: "Gated task",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "gate-sentinel",
+ type: "approval",
+ linkedActionIds: [action.action.id],
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.linkedActionIds).toEqual([action.action.id]);
+
+ const edges = await kv.list<ActionEdge>("mem:action-edges");
+ const gatedEdges = edges.filter(
+ (e) =>
+ e.type === "gated_by" &&
+ e.sourceActionId === action.action.id &&
+ e.targetActionId === result.sentinel.id,
+ );
+ expect(gatedEdges.length).toBe(1);
+ });
+
+ it("returns error for non-existent linkedActionId", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "bad-link",
+ type: "approval",
+ linkedActionIds: ["nonexistent_action"],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("linked action not found");
+ });
+
+ it("sets expiresAt when expiresInMs is provided", async () => {
+ const result = (await sdk.trigger("mem::sentinel-create", {
+ name: "expiring",
+ type: "custom",
+ expiresInMs: 60000,
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.expiresAt).toBeDefined();
+ const created = new Date(result.sentinel.createdAt).getTime();
+ const expires = new Date(result.sentinel.expiresAt!).getTime();
+ expect(expires - created).toBeCloseTo(60000, -2);
+ });
+ });
+
+ describe("mem::sentinel-trigger", () => {
+ it("triggers a watching sentinel", async () => {
+ const sentinel = (await sdk.trigger("mem::sentinel-create", {
+ name: "trigger-me",
+ type: "approval",
+ })) as { success: boolean; sentinel: Sentinel };
+
+ const result = (await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: sentinel.sentinel.id,
+ result: { approvedBy: "admin" },
+ })) as { success: boolean; sentinel: Sentinel; unblockedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.status).toBe("triggered");
+ expect(result.sentinel.triggeredAt).toBeDefined();
+ expect(result.sentinel.result).toEqual({ approvedBy: "admin" });
+ expect(result.unblockedCount).toBe(0);
+ });
+
+ it("returns error when triggering already-triggered sentinel", async () => {
+ const sentinel = (await sdk.trigger("mem::sentinel-create", {
+ name: "already-fired",
+ type: "custom",
+ })) as { success: boolean; sentinel: Sentinel };
+
+ await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: sentinel.sentinel.id,
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: sentinel.sentinel.id,
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("already triggered");
+ });
+
+ it("returns error for non-existent sentinel", async () => {
+ const result = (await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: "nonexistent_sentinel",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sentinel not found");
+ });
+
+ it("returns error when sentinelId is missing", async () => {
+ const result = (await sdk.trigger("mem::sentinel-trigger", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sentinelId is required");
+ });
+
+ it("unblocks gated actions when triggered", async () => {
+ const action = (await sdk.trigger("mem::action-create", {
+ title: "Blocked task",
+ })) as { success: boolean; action: Action };
+
+ const sentinel = (await sdk.trigger("mem::sentinel-create", {
+ name: "gate",
+ type: "approval",
+ linkedActionIds: [action.action.id],
+ })) as { success: boolean; sentinel: Sentinel };
+
+ await sdk.trigger("mem::action-update", {
+ actionId: action.action.id,
+ status: "blocked",
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: sentinel.sentinel.id,
+ })) as { success: boolean; sentinel: Sentinel; unblockedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.unblockedCount).toBe(1);
+
+ const updated = (await sdk.trigger("mem::action-get", {
+ actionId: action.action.id,
+ })) as { success: boolean; action: Action };
+
+ expect(updated.action.status).toBe("pending");
+ });
+ });
+
+ describe("mem::sentinel-cancel", () => {
+ it("cancels a watching sentinel", async () => {
+ const sentinel = (await sdk.trigger("mem::sentinel-create", {
+ name: "cancel-me",
+ type: "custom",
+ })) as { success: boolean; sentinel: Sentinel };
+
+ const result = (await sdk.trigger("mem::sentinel-cancel", {
+ sentinelId: sentinel.sentinel.id,
+ })) as { success: boolean; sentinel: Sentinel };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinel.status).toBe("cancelled");
+ });
+
+ it("returns error when cancelling non-watching sentinel", async () => {
+ const sentinel = (await sdk.trigger("mem::sentinel-create", {
+ name: "already-triggered",
+ type: "custom",
+ })) as { success: boolean; sentinel: Sentinel };
+
+ await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: sentinel.sentinel.id,
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-cancel", {
+ sentinelId: sentinel.sentinel.id,
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("cannot cancel sentinel with status");
+ });
+
+ it("returns error for non-existent sentinel", async () => {
+ const result = (await sdk.trigger("mem::sentinel-cancel", {
+ sentinelId: "nonexistent_sentinel",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sentinel not found");
+ });
+
+ it("returns error when sentinelId is missing", async () => {
+ const result = (await sdk.trigger("mem::sentinel-cancel", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sentinelId is required");
+ });
+ });
+
+ describe("mem::sentinel-list", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::sentinel-create", {
+ name: "webhook-1",
+ type: "webhook",
+ config: { path: "/a" },
+ });
+ await sdk.trigger("mem::sentinel-create", {
+ name: "timer-1",
+ type: "timer",
+ config: { durationMs: 1000 },
+ });
+ await sdk.trigger("mem::sentinel-create", {
+ name: "approval-1",
+ type: "approval",
+ });
+ });
+
+ it("returns all sentinels", async () => {
+ const result = (await sdk.trigger("mem::sentinel-list", {})) as {
+ success: boolean;
+ sentinels: Sentinel[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinels.length).toBe(3);
+ });
+
+ it("filters by status", async () => {
+ const all = (await sdk.trigger("mem::sentinel-list", {})) as {
+ sentinels: Sentinel[];
+ };
+ await sdk.trigger("mem::sentinel-trigger", {
+ sentinelId: all.sentinels[0].id,
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-list", {
+ status: "triggered",
+ })) as { success: boolean; sentinels: Sentinel[] };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinels.length).toBe(1);
+ expect(result.sentinels[0].status).toBe("triggered");
+ });
+
+ it("filters by type", async () => {
+ const result = (await sdk.trigger("mem::sentinel-list", {
+ type: "webhook",
+ })) as { success: boolean; sentinels: Sentinel[] };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinels.length).toBe(1);
+ expect(result.sentinels[0].type).toBe("webhook");
+ });
+
+ it("filters by both status and type", async () => {
+ const result = (await sdk.trigger("mem::sentinel-list", {
+ status: "watching",
+ type: "approval",
+ })) as { success: boolean; sentinels: Sentinel[] };
+
+ expect(result.success).toBe(true);
+ expect(result.sentinels.length).toBe(1);
+ expect(result.sentinels[0].type).toBe("approval");
+ expect(result.sentinels[0].status).toBe("watching");
+ });
+ });
+
+ describe("mem::sentinel-expire", () => {
+ it("expires sentinels past their expiresAt", async () => {
+ await sdk.trigger("mem::sentinel-create", {
+ name: "will-expire",
+ type: "custom",
+ expiresInMs: 1,
+ });
+
+ await new Promise((r) => setTimeout(r, 10));
+
+ const result = (await sdk.trigger("mem::sentinel-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(1);
+
+ const list = (await sdk.trigger("mem::sentinel-list", {
+ status: "expired",
+ })) as { sentinels: Sentinel[] };
+ expect(list.sentinels.length).toBe(1);
+ });
+
+ it("skips sentinels that have not expired", async () => {
+ await sdk.trigger("mem::sentinel-create", {
+ name: "not-expired",
+ type: "custom",
+ expiresInMs: 600000,
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+ });
+
+ it("skips sentinels without expiresAt", async () => {
+ await sdk.trigger("mem::sentinel-create", {
+ name: "no-expiry",
+ type: "custom",
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+ });
+
+ it("skips non-watching sentinels even if expired", async () => {
+ const sentinel = (await sdk.trigger("mem::sentinel-create", {
+ name: "already-cancelled",
+ type: "custom",
+ expiresInMs: 1,
+ })) as { success: boolean; sentinel: Sentinel };
+
+ await sdk.trigger("mem::sentinel-cancel", {
+ sentinelId: sentinel.sentinel.id,
+ });
+
+ await new Promise((r) => setTimeout(r, 10));
+
+ const result = (await sdk.trigger("mem::sentinel-expire", {})) as {
+ success: boolean;
+ expired: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.expired).toBe(0);
+ });
+ });
+
+ describe("mem::sentinel-check", () => {
+ it("triggers threshold sentinel when condition is met", async () => {
+ await kv.set("mem:metrics", "api_calls", {
+ totalCalls: 150,
+ errorCount: 0,
+ avgDurationMs: 50,
+ });
+
+ await sdk.trigger("mem::sentinel-create", {
+ name: "high-traffic",
+ type: "threshold",
+ config: { metric: "api_calls", operator: "gt", value: 100 },
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-check", {})) as {
+ success: boolean;
+ triggered: string[];
+ checkedCount: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.triggered.length).toBe(1);
+ expect(result.checkedCount).toBe(1);
+ });
+
+ it("does not trigger threshold sentinel when condition is not met", async () => {
+ await kv.set("mem:metrics", "api_calls", {
+ totalCalls: 50,
+ errorCount: 0,
+ avgDurationMs: 50,
+ });
+
+ await sdk.trigger("mem::sentinel-create", {
+ name: "low-traffic",
+ type: "threshold",
+ config: { metric: "api_calls", operator: "gt", value: 100 },
+ });
+
+ const result = (await sdk.trigger("mem::sentinel-check", {})) as {
+ success: boolean;
+ triggered: string[];
+ checkedCount: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.triggered.length).toBe(0);
+ });
+
+ it("returns empty triggered list when no active sentinels", async () => {
+ const result = (await sdk.trigger("mem::sentinel-check", {})) as {
+ success: boolean;
+ triggered: string[];
+ checkedCount: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.triggered).toEqual([]);
+ expect(result.checkedCount).toBe(0);
+ });
+ });
+});
diff --git a/test/signals.test.ts b/test/signals.test.ts
new file mode 100644
index 00000000..3e43e46e
--- /dev/null
+++ b/test/signals.test.ts
@@ -0,0 +1,410 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerSignalsFunction } from "../src/functions/signals.js";
+import type { Signal } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Signals Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerSignalsFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::signal-send", () => {
+ it("sends a signal with valid data", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ to: "agent-b",
+ content: "Hello there",
+ type: "info",
+ })) as { success: boolean; signal: Signal };
+
+ expect(result.success).toBe(true);
+ expect(result.signal.id).toMatch(/^sig_/);
+ expect(result.signal.from).toBe("agent-a");
+ expect(result.signal.to).toBe("agent-b");
+ expect(result.signal.content).toBe("Hello there");
+ expect(result.signal.type).toBe("info");
+ expect(result.signal.threadId).toMatch(/^thr_/);
+ expect(result.signal.createdAt).toBeDefined();
+ });
+
+ it("returns error when from is missing", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "",
+ content: "Hello",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("from and non-empty content are required");
+ });
+
+ it("returns error when content is whitespace only", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ content: " ",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("from and non-empty content are required");
+ });
+
+ it("returns error when content is empty string", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ content: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("from and non-empty content are required");
+ });
+
+ it("auto-threads replies from parent signal", async () => {
+ const parent = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ to: "agent-b",
+ content: "Initial message",
+ })) as { success: boolean; signal: Signal };
+
+ const reply = (await sdk.trigger("mem::signal-send", {
+ from: "agent-b",
+ to: "agent-a",
+ content: "Reply message",
+ replyTo: parent.signal.id,
+ })) as { success: boolean; signal: Signal };
+
+ expect(reply.success).toBe(true);
+ expect(reply.signal.threadId).toBe(parent.signal.threadId);
+ expect(reply.signal.replyTo).toBe(parent.signal.id);
+ });
+
+ it("sets expiresAt when expiresInMs is provided", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ content: "Temporary message",
+ expiresInMs: 60000,
+ })) as { success: boolean; signal: Signal };
+
+ expect(result.success).toBe(true);
+ expect(result.signal.expiresAt).toBeDefined();
+ const expiresAt = new Date(result.signal.expiresAt!).getTime();
+ const createdAt = new Date(result.signal.createdAt).getTime();
+ expect(expiresAt - createdAt).toBeCloseTo(60000, -2);
+ });
+
+ it("defaults type to info when not specified", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ content: "No type specified",
+ })) as { success: boolean; signal: Signal };
+
+ expect(result.success).toBe(true);
+ expect(result.signal.type).toBe("info");
+ });
+
+ it("trims content whitespace", async () => {
+ const result = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ content: " padded content ",
+ })) as { success: boolean; signal: Signal };
+
+ expect(result.success).toBe(true);
+ expect(result.signal.content).toBe("padded content");
+ });
+ });
+
+ describe("mem::signal-read", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ to: "agent-b",
+ content: "Message 1",
+ type: "info",
+ });
+ await sdk.trigger("mem::signal-send", {
+ from: "agent-c",
+ to: "agent-b",
+ content: "Message 2",
+ type: "request",
+ });
+ await sdk.trigger("mem::signal-send", {
+ from: "agent-b",
+ to: "agent-a",
+ content: "Message 3",
+ type: "response",
+ });
+ });
+
+ it("reads signals for an agent", async () => {
+ const result = (await sdk.trigger("mem::signal-read", {
+ agentId: "agent-b",
+ })) as { success: boolean; signals: Signal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.signals.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it("marks signals as read", async () => {
+ await sdk.trigger("mem::signal-read", {
+ agentId: "agent-b",
+ });
+
+ const signals = await kv.list<Signal>("mem:signals");
+ const toAgentB = signals.filter((s) => s.to === "agent-b");
+ expect(toAgentB.every((s) => s.readAt !== undefined)).toBe(true);
+ });
+
+ it("filters by unreadOnly", async () => {
+ await sdk.trigger("mem::signal-read", {
+ agentId: "agent-b",
+ });
+
+ const result = (await sdk.trigger("mem::signal-read", {
+ agentId: "agent-b",
+ unreadOnly: true,
+ })) as { success: boolean; signals: Signal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.signals.length).toBe(0);
+ });
+
+ it("filters by threadId", async () => {
+ const sent = (await sdk.trigger("mem::signal-send", {
+ from: "agent-x",
+ to: "agent-b",
+ content: "Thread-specific message",
+ threadId: "thr_specific",
+ })) as { success: boolean; signal: Signal };
+
+ const result = (await sdk.trigger("mem::signal-read", {
+ agentId: "agent-b",
+ threadId: "thr_specific",
+ })) as { success: boolean; signals: Signal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.signals.length).toBe(1);
+ expect(result.signals[0].threadId).toBe("thr_specific");
+ });
+
+ it("filters by type", async () => {
+ const result = (await sdk.trigger("mem::signal-read", {
+ agentId: "agent-b",
+ type: "request",
+ })) as { success: boolean; signals: Signal[] };
+
+ expect(result.success).toBe(true);
+ expect(result.signals.every((s) => s.type === "request")).toBe(true);
+ });
+
+ it("returns error when agentId is missing", async () => {
+ const result = (await sdk.trigger("mem::signal-read", {
+ agentId: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("agentId is required");
+ });
+ });
+
+ describe("mem::signal-threads", () => {
+ it("groups signals by thread", async () => {
+ const first = (await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ to: "agent-b",
+ content: "Thread 1 message 1",
+ })) as { success: boolean; signal: Signal };
+
+ await sdk.trigger("mem::signal-send", {
+ from: "agent-b",
+ to: "agent-a",
+ content: "Thread 1 message 2",
+ replyTo: first.signal.id,
+ });
+
+ await sdk.trigger("mem::signal-send", {
+ from: "agent-a",
+ to: "agent-b",
+ content: "Different thread",
+ });
+
+ const result = (await sdk.trigger("mem::signal-threads", {
+ agentId: "agent-a",
+ })) as {
+ success: boolean;
+ threads: Array<{
+ threadId: string;
+ messages: number;
+ participants: string[];
+ }>;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.threads.length).toBe(2);
+
+ const firstThread = result.threads.find(
+ (t) => t.threadId === first.signal.threadId,
+ );
+ expect(firstThread).toBeDefined();
+ expect(firstThread!.messages).toBe(2);
+ expect(firstThread!.participants).toContain("agent-a");
+ expect(firstThread!.participants).toContain("agent-b");
+ });
+
+ it("returns error when agentId is missing", async () => {
+ const result = (await sdk.trigger("mem::signal-threads", {
+ agentId: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("agentId is required");
+ });
+ });
+
+ describe("mem::signal-cleanup", () => {
+ it("removes expired signals", async () => {
+ const now = Date.now();
+ const expiredSignal: Signal = {
+ id: "sig_expired",
+ from: "agent-a",
+ to: "agent-b",
+ content: "Expired",
+ type: "info",
+ threadId: "thr_1",
+ createdAt: new Date(now - 120000).toISOString(),
+ expiresAt: new Date(now - 60000).toISOString(),
+ };
+ await kv.set("mem:signals", expiredSignal.id, expiredSignal);
+
+ const validSignal: Signal = {
+ id: "sig_valid",
+ from: "agent-a",
+ to: "agent-b",
+ content: "Still valid",
+ type: "info",
+ threadId: "thr_2",
+ createdAt: new Date(now).toISOString(),
+ expiresAt: new Date(now + 60000).toISOString(),
+ };
+ await kv.set("mem:signals", validSignal.id, validSignal);
+
+ const result = (await sdk.trigger("mem::signal-cleanup", {})) as {
+ success: boolean;
+ removed: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.removed).toBe(1);
+
+ const remaining = await kv.list<Signal>("mem:signals");
+ expect(remaining.length).toBe(1);
+ expect(remaining[0].id).toBe("sig_valid");
+ });
+
+ it("keeps signals without expiration", async () => {
+ const noExpiry: Signal = {
+ id: "sig_noexpiry",
+ from: "agent-a",
+ content: "No expiration",
+ type: "info",
+ threadId: "thr_3",
+ createdAt: new Date().toISOString(),
+ };
+ await kv.set("mem:signals", noExpiry.id, noExpiry);
+
+ const result = (await sdk.trigger("mem::signal-cleanup", {})) as {
+ success: boolean;
+ removed: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.removed).toBe(0);
+
+ const remaining = await kv.list<Signal>("mem:signals");
+ expect(remaining.length).toBe(1);
+ });
+
+ it("removes multiple expired signals at once", async () => {
+ const now = Date.now();
+
+ for (let i = 0; i < 5; i++) {
+ const sig: Signal = {
+ id: `sig_exp_${i}`,
+ from: "agent-a",
+ content: `Expired ${i}`,
+ type: "info",
+ threadId: `thr_${i}`,
+ createdAt: new Date(now - 200000).toISOString(),
+ expiresAt: new Date(now - 100000).toISOString(),
+ };
+ await kv.set("mem:signals", sig.id, sig);
+ }
+
+ const keepSig: Signal = {
+ id: "sig_keep",
+ from: "agent-b",
+ content: "Keep me",
+ type: "alert",
+ threadId: "thr_keep",
+ createdAt: new Date(now).toISOString(),
+ };
+ await kv.set("mem:signals", keepSig.id, keepSig);
+
+ const result = (await sdk.trigger("mem::signal-cleanup", {})) as {
+ success: boolean;
+ removed: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.removed).toBe(5);
+
+ const remaining = await kv.list<Signal>("mem:signals");
+ expect(remaining.length).toBe(1);
+ expect(remaining[0].id).toBe("sig_keep");
+ });
+ });
+});
diff --git a/test/sketches.test.ts b/test/sketches.test.ts
new file mode 100644
index 00000000..2404f3ad
--- /dev/null
+++ b/test/sketches.test.ts
@@ -0,0 +1,549 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ }),
+}));
+
+import { registerSketchesFunction } from "../src/functions/sketches.js";
+import type { Action, ActionEdge, Sketch } from "../src/types.js";
+
+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[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (opts: { id: string }, handler: Function) => {
+ functions.set(opts.id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (id: string, data: unknown) => {
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function: ${id}`);
+ return fn(data);
+ },
+ };
+}
+
+describe("Sketches Functions", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerSketchesFunction(sdk as never, kv as never);
+ });
+
+ describe("mem::sketch-create", () => {
+ it("creates a sketch with valid title", async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {
+ title: "Refactor auth module",
+ })) as { success: boolean; sketch: Sketch };
+
+ expect(result.success).toBe(true);
+ expect(result.sketch.id).toMatch(/^sk_/);
+ expect(result.sketch.title).toBe("Refactor auth module");
+ expect(result.sketch.status).toBe("active");
+ expect(result.sketch.actionIds).toEqual([]);
+ expect(result.sketch.createdAt).toBeDefined();
+ expect(result.sketch.expiresAt).toBeDefined();
+ });
+
+ it("returns error when title is empty", async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {
+ title: "",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("title is required");
+ });
+
+ it("returns error when title is missing", async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {})) as {
+ success: boolean;
+ error: string;
+ };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("title is required");
+ });
+
+ it("creates a sketch with custom TTL", async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {
+ title: "Short-lived sketch",
+ expiresInMs: 60000,
+ })) as { success: boolean; sketch: Sketch };
+
+ expect(result.success).toBe(true);
+ const created = new Date(result.sketch.createdAt).getTime();
+ const expires = new Date(result.sketch.expiresAt).getTime();
+ expect(expires - created).toBe(60000);
+ });
+
+ it("defaults TTL to one hour", async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {
+ title: "Default TTL",
+ })) as { success: boolean; sketch: Sketch };
+
+ expect(result.success).toBe(true);
+ const created = new Date(result.sketch.createdAt).getTime();
+ const expires = new Date(result.sketch.expiresAt).getTime();
+ expect(expires - created).toBe(3600000);
+ });
+
+ it("stores project on sketch", async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {
+ title: "Project sketch",
+ project: "webapp",
+ })) as { success: boolean; sketch: Sketch };
+
+ expect(result.success).toBe(true);
+ expect(result.sketch.project).toBe("webapp");
+ });
+ });
+
+ describe("mem::sketch-add", () => {
+ let sketchId: string;
+
+ beforeEach(async () => {
+ const result = (await sdk.trigger("mem::sketch-create", {
+ title: "Test sketch",
+ project: "myproject",
+ })) as { success: boolean; sketch: Sketch };
+ sketchId = result.sketch.id;
+ });
+
+ it("adds an action to the sketch", async () => {
+ const result = (await sdk.trigger("mem::sketch-add", {
+ sketchId,
+ title: "Implement login",
+ description: "Add SSO support",
+ priority: 8,
+ })) as { success: boolean; action: Action; edges: ActionEdge[] };
+
+ expect(result.success).toBe(true);
+ expect(result.action.id).toMatch(/^act_/);
+ expect(result.action.title).toBe("Implement login");
+ expect(result.action.description).toBe("Add SSO support");
+ expect(result.action.priority).toBe(8);
+ expect(result.action.sketchId).toBe(sketchId);
+ expect(result.action.project).toBe("myproject");
+ expect(result.action.createdBy).toBe("sketch");
+ expect(result.edges).toEqual([]);
+ });
+
+ it("returns error for non-existent sketch", async () => {
+ const result = (await sdk.trigger("mem::sketch-add", {
+ sketchId: "nonexistent",
+ title: "Some action",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketch not found");
+ });
+
+ it("returns error for non-active sketch", async () => {
+ await sdk.trigger("mem::sketch-promote", { sketchId });
+
+ const result = (await sdk.trigger("mem::sketch-add", {
+ sketchId,
+ title: "Late action",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketch is not active");
+ });
+
+ it("adds action with dependsOn within sketch", async () => {
+ const first = (await sdk.trigger("mem::sketch-add", {
+ sketchId,
+ title: "First step",
+ })) as { success: boolean; action: Action };
+
+ const second = (await sdk.trigger("mem::sketch-add", {
+ sketchId,
+ title: "Second step",
+ dependsOn: [first.action.id],
+ })) as { success: boolean; action: Action; edges: ActionEdge[] };
+
+ expect(second.success).toBe(true);
+ expect(second.edges.length).toBe(1);
+ expect(second.edges[0].type).toBe("requires");
+ expect(second.edges[0].sourceActionId).toBe(second.action.id);
+ expect(second.edges[0].targetActionId).toBe(first.action.id);
+ });
+
+ it("returns error for dependsOn referencing action outside sketch", async () => {
+ const result = (await sdk.trigger("mem::sketch-add", {
+ sketchId,
+ title: "Depends on external",
+ dependsOn: ["act_outside"],
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("not found in this sketch");
+ });
+
+ it("returns error when sketchId is missing", async () => {
+ const result = (await sdk.trigger("mem::sketch-add", {
+ title: "No sketch",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketchId is required");
+ });
+
+ it("returns error when title is missing", async () => {
+ const result = (await sdk.trigger("mem::sketch-add", {
+ sketchId,
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("title is required");
+ });
+ });
+
+ describe("mem::sketch-promote", () => {
+ it("promotes sketch and removes sketchId from actions", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Promotable sketch",
+ project: "alpha",
+ })) as { success: boolean; sketch: Sketch };
+
+ const a1 = (await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Action 1",
+ })) as { success: boolean; action: Action };
+
+ const a2 = (await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Action 2",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::sketch-promote", {
+ sketchId: sketch.sketch.id,
+ })) as { success: boolean; promotedIds: string[] };
+
+ expect(result.success).toBe(true);
+ expect(result.promotedIds).toContain(a1.action.id);
+ expect(result.promotedIds).toContain(a2.action.id);
+ expect(result.promotedIds.length).toBe(2);
+
+ const stored = await kv.get<Action>("mem:actions", a1.action.id);
+ expect(stored!.sketchId).toBeUndefined();
+ expect(stored!.project).toBe("alpha");
+ });
+
+ it("promotes sketch with project override", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Override project",
+ project: "original",
+ })) as { success: boolean; sketch: Sketch };
+
+ const a = (await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Task",
+ })) as { success: boolean; action: Action };
+
+ const result = (await sdk.trigger("mem::sketch-promote", {
+ sketchId: sketch.sketch.id,
+ project: "newproject",
+ })) as { success: boolean; promotedIds: string[] };
+
+ expect(result.success).toBe(true);
+
+ const stored = await kv.get<Action>("mem:actions", a.action.id);
+ expect(stored!.project).toBe("newproject");
+ expect(stored!.sketchId).toBeUndefined();
+ });
+
+ it("returns error for non-active sketch", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "To be discarded",
+ })) as { success: boolean; sketch: Sketch };
+
+ await sdk.trigger("mem::sketch-discard", {
+ sketchId: sketch.sketch.id,
+ });
+
+ const result = (await sdk.trigger("mem::sketch-promote", {
+ sketchId: sketch.sketch.id,
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketch is not active");
+ });
+
+ it("returns error for non-existent sketch", async () => {
+ const result = (await sdk.trigger("mem::sketch-promote", {
+ sketchId: "nonexistent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketch not found");
+ });
+
+ it("sets sketch status to promoted", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Promote me",
+ })) as { success: boolean; sketch: Sketch };
+
+ await sdk.trigger("mem::sketch-promote", {
+ sketchId: sketch.sketch.id,
+ });
+
+ const stored = await kv.get<Sketch>("mem:sketches", sketch.sketch.id);
+ expect(stored!.status).toBe("promoted");
+ expect(stored!.promotedAt).toBeDefined();
+ });
+ });
+
+ describe("mem::sketch-discard", () => {
+ it("discards sketch and deletes actions and edges", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Discard me",
+ })) as { success: boolean; sketch: Sketch };
+
+ const a1 = (await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Action 1",
+ })) as { success: boolean; action: Action };
+
+ const a2 = (await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Action 2",
+ dependsOn: [a1.action.id],
+ })) as { success: boolean; action: Action; edges: ActionEdge[] };
+
+ const result = (await sdk.trigger("mem::sketch-discard", {
+ sketchId: sketch.sketch.id,
+ })) as { success: boolean; discardedCount: number };
+
+ expect(result.success).toBe(true);
+ expect(result.discardedCount).toBe(2);
+
+ const storedA1 = await kv.get<Action>("mem:actions", a1.action.id);
+ expect(storedA1).toBeNull();
+
+ const storedA2 = await kv.get<Action>("mem:actions", a2.action.id);
+ expect(storedA2).toBeNull();
+
+ const storedEdge = await kv.get<ActionEdge>(
+ "mem:action-edges",
+ a2.edges[0].id,
+ );
+ expect(storedEdge).toBeNull();
+
+ const storedSketch = await kv.get<Sketch>(
+ "mem:sketches",
+ sketch.sketch.id,
+ );
+ expect(storedSketch!.status).toBe("discarded");
+ expect(storedSketch!.discardedAt).toBeDefined();
+ });
+
+ it("returns error for non-active sketch", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Promote first",
+ })) as { success: boolean; sketch: Sketch };
+
+ await sdk.trigger("mem::sketch-promote", {
+ sketchId: sketch.sketch.id,
+ });
+
+ const result = (await sdk.trigger("mem::sketch-discard", {
+ sketchId: sketch.sketch.id,
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketch is not active");
+ });
+
+ it("returns error for non-existent sketch", async () => {
+ const result = (await sdk.trigger("mem::sketch-discard", {
+ sketchId: "nonexistent",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("sketch not found");
+ });
+ });
+
+ describe("mem::sketch-list", () => {
+ beforeEach(async () => {
+ await sdk.trigger("mem::sketch-create", {
+ title: "Active alpha",
+ project: "alpha",
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ await sdk.trigger("mem::sketch-create", {
+ title: "Active beta",
+ project: "beta",
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ const toPromote = (await sdk.trigger("mem::sketch-create", {
+ title: "Promoted alpha",
+ project: "alpha",
+ })) as { success: boolean; sketch: Sketch };
+ await sdk.trigger("mem::sketch-promote", {
+ sketchId: toPromote.sketch.id,
+ });
+ });
+
+ it("returns all sketches", async () => {
+ const result = (await sdk.trigger("mem::sketch-list", {})) as {
+ success: boolean;
+ sketches: (Sketch & { actionCount: number })[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.sketches.length).toBe(3);
+ });
+
+ it("filters by status", async () => {
+ const result = (await sdk.trigger("mem::sketch-list", {
+ status: "active",
+ })) as {
+ success: boolean;
+ sketches: (Sketch & { actionCount: number })[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.sketches.length).toBe(2);
+ expect(result.sketches.every((s) => s.status === "active")).toBe(true);
+ });
+
+ it("filters by project", async () => {
+ const result = (await sdk.trigger("mem::sketch-list", {
+ project: "alpha",
+ })) as {
+ success: boolean;
+ sketches: (Sketch & { actionCount: number })[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.sketches.length).toBe(2);
+ expect(result.sketches.every((s) => s.project === "alpha")).toBe(true);
+ });
+
+ it("includes actionCount in results", async () => {
+ const result = (await sdk.trigger("mem::sketch-list", {})) as {
+ success: boolean;
+ sketches: (Sketch & { actionCount: number })[];
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.sketches[0].actionCount).toBe(0);
+ });
+ });
+
+ describe("mem::sketch-gc", () => {
+ it("collects expired active sketches", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Expired sketch",
+ expiresInMs: 1,
+ })) as { success: boolean; sketch: Sketch };
+
+ await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Doomed action",
+ });
+
+ await new Promise((r) => setTimeout(r, 10));
+
+ const result = (await sdk.trigger("mem::sketch-gc", {})) as {
+ success: boolean;
+ collected: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.collected).toBe(1);
+
+ const stored = await kv.get<Sketch>("mem:sketches", sketch.sketch.id);
+ expect(stored!.status).toBe("discarded");
+ expect(stored!.discardedAt).toBeDefined();
+ });
+
+ it("skips non-expired sketches", async () => {
+ await sdk.trigger("mem::sketch-create", {
+ title: "Still alive",
+ expiresInMs: 3600000,
+ });
+
+ const result = (await sdk.trigger("mem::sketch-gc", {})) as {
+ success: boolean;
+ collected: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.collected).toBe(0);
+ });
+
+ it("skips non-active sketches", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "Already promoted",
+ expiresInMs: 1,
+ })) as { success: boolean; sketch: Sketch };
+
+ await sdk.trigger("mem::sketch-promote", {
+ sketchId: sketch.sketch.id,
+ });
+
+ await new Promise((r) => setTimeout(r, 10));
+
+ const result = (await sdk.trigger("mem::sketch-gc", {})) as {
+ success: boolean;
+ collected: number;
+ };
+
+ expect(result.success).toBe(true);
+ expect(result.collected).toBe(0);
+ });
+
+ it("deletes actions and edges of expired sketches", async () => {
+ const sketch = (await sdk.trigger("mem::sketch-create", {
+ title: "GC with cleanup",
+ expiresInMs: 1,
+ })) as { success: boolean; sketch: Sketch };
+
+ const a1 = (await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Step 1",
+ })) as { success: boolean; action: Action };
+
+ await sdk.trigger("mem::sketch-add", {
+ sketchId: sketch.sketch.id,
+ title: "Step 2",
+ dependsOn: [a1.action.id],
+ });
+
+ await new Promise((r) => setTimeout(r, 10));
+
+ await sdk.trigger("mem::sketch-gc", {});
+
+ const storedAction = await kv.get<Action>("mem:actions", a1.action.id);
+ expect(storedAction).toBeNull();
+ });
+ });
+});