= {};
const secret = process.env.AGENTMEMORY_SECRET;
- guardPlaintextBearerAuth(baseUrl, secret);
+ const agentId = process.env.AGENT_ID;
+ const callerToken = process.env.AGENTMEMORY_CALLER_TOKEN;
+ guardPlaintextBearerAuth(baseUrl, secret || callerToken);
if (options?.body !== undefined) headers["Content-Type"] = "application/json";
if (secret) headers.Authorization = `Bearer ${secret}`;
+ if (agentId) headers["X-AgentMemory-Agent-Id"] = agentId;
+ if (callerToken) headers["X-AgentMemory-Caller-Token"] = callerToken;
try {
const response = await fetch(url, {
@@ -116,7 +120,8 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {
if (process.env.AGENTMEMORY_REQUIRE_HTTPS === "1") {
guardPlaintextBearerAuth(
normalizeBaseUrl(process.env.AGENTMEMORY_URL || DEFAULT_URL),
- process.env.AGENTMEMORY_SECRET,
+ process.env.AGENTMEMORY_SECRET ||
+ process.env.AGENTMEMORY_CALLER_TOKEN,
);
}
let sessionId = `ephemeral-${crypto.randomUUID().slice(0, 8)}`;
diff --git a/integrations/pi/security.ts b/integrations/pi/security.ts
index 4db0e5295c..c34d95161f 100644
--- a/integrations/pi/security.ts
+++ b/integrations/pi/security.ts
@@ -15,7 +15,7 @@ export function usesPlaintextBearerAuth(baseUrl: string, secret?: string): boole
}
export function plaintextBearerAuthMessage(baseUrl: string): string {
- return `agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to ${baseUrl}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.`;
+ return `agentmemory: an AGENTMEMORY_SECRET or AGENTMEMORY_CALLER_TOKEN credential is configured for plaintext HTTP to ${baseUrl}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.`;
}
export function createPlaintextBearerAuthGuard(
diff --git a/package.json b/package.json
index 4e2bc8c4c3..8d19d3e687 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
"import": "./dist/index.mjs"
},
"./dist/standalone.mjs": "./dist/standalone.mjs",
+ "./dist/http.mjs": "./dist/http.mjs",
"./package.json": "./package.json"
},
"bin": {
@@ -18,6 +19,7 @@
},
"scripts": {
"build": "tsdown && (cp iii-config.yaml dist/ 2>/dev/null || true) && (cp iii-config.docker.yaml dist/ 2>/dev/null || true) && (cp docker-compose.yml dist/ 2>/dev/null || true) && (cp .env.example dist/ 2>/dev/null || true) && mkdir -p dist/viewer && cp src/viewer/index.html dist/viewer/ && cp src/viewer/favicon.svg dist/viewer/",
+ "prepack": "npm run build",
"dev": "tsx src/index.ts",
"start": "node dist/cli.mjs",
"migrate": "node dist/functions/migrate.js",
@@ -60,6 +62,7 @@
"url": "https://github.com/rohitg00/agentmemory"
},
"dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
"@anthropic-ai/claude-agent-sdk": "^0.3.142",
"@anthropic-ai/sdk": "^0.100.1",
"@clack/prompts": "^1.2.0",
diff --git a/packages/mcp/README.md b/packages/mcp/README.md
index abd57a752a..21480c6e70 100644
--- a/packages/mcp/README.md
+++ b/packages/mcp/README.md
@@ -13,6 +13,13 @@ without installing the full package first.
npx -y @agentmemory/mcp
```
+To expose the running AgentMemory engine through a stateless Streamable HTTP endpoint instead of stdio:
+
+```bash
+npx -y @agentmemory/mcp --http
+# http://127.0.0.1:3114/mcp
+```
+
Or wire it into your MCP client (Claude Desktop, OpenClaw, Cursor, Codex, etc.):
```json
@@ -34,7 +41,7 @@ installed, you can call the same entrypoint directly:
npx @agentmemory/agentmemory mcp
```
-Both commands do the same thing.
+The two stdio commands do the same thing. The `--http` form requires the full AgentMemory engine at `AGENTMEMORY_URL` and never creates a separate local fallback store. Set `AGENTMEMORY_SECRET` for bridge-to-engine authentication and, independently, `AGENTMEMORY_MCP_HTTP_TOKEN` if the MCP listener itself should require a bearer token.
## Why does this package exist?
diff --git a/packages/mcp/bin.mjs b/packages/mcp/bin.mjs
index 7df452d56e..971f04d9d3 100755
--- a/packages/mcp/bin.mjs
+++ b/packages/mcp/bin.mjs
@@ -1,7 +1,15 @@
#!/usr/bin/env node
-import("@agentmemory/agentmemory/dist/standalone.mjs").catch((err) => {
+const entrypoint = process.argv.slice(2).some((arg) => arg === "--http" || arg === "http")
+ ? "@agentmemory/agentmemory/dist/http.mjs"
+ : "@agentmemory/agentmemory/dist/standalone.mjs";
+
+import(entrypoint).then(async (module) => {
+ if (entrypoint.endsWith("/http.mjs")) {
+ await module.runMcpHttpServer();
+ }
+}).catch((err) => {
console.error(
- "[@agentmemory/mcp] Failed to load standalone entrypoint from @agentmemory/agentmemory.",
+ `[@agentmemory/mcp] Failed to load ${entrypoint} from @agentmemory/agentmemory.`,
);
console.error(
"[@agentmemory/mcp] Try installing manually: npm i -g @agentmemory/agentmemory",
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index cb4e6df7b8..567945c102 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "agentmemory",
"version": "0.9.27",
- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 8 skills, real-time viewer.",
+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 60 MCP tools, 8 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
"url": "https://github.com/rohitg00"
diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json
index 7c42f13094..3089279085 100644
--- a/plugin/.codex-plugin/plugin.json
+++ b/plugin/.codex-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "agentmemory",
"version": "0.9.27",
- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 53 MCP tools, 8 skills, real-time viewer.",
+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 60 MCP tools, 8 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
"url": "https://github.com/rohitg00"
diff --git a/plugin/.mcp.copilot.json b/plugin/.mcp.copilot.json
index 827330add9..d0c1b0c713 100644
--- a/plugin/.mcp.copilot.json
+++ b/plugin/.mcp.copilot.json
@@ -7,6 +7,8 @@
"env": {
"AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}",
"AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}",
+ "AGENT_ID": "${AGENT_ID:-}",
+ "AGENTMEMORY_CALLER_TOKEN": "${AGENTMEMORY_CALLER_TOKEN:-}",
"AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}"
},
"tools": ["*"]
diff --git a/plugin/.mcp.json b/plugin/.mcp.json
index 37f7754fff..669a1762b9 100644
--- a/plugin/.mcp.json
+++ b/plugin/.mcp.json
@@ -6,6 +6,8 @@
"env": {
"AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}",
"AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}",
+ "AGENT_ID": "${AGENT_ID:-}",
+ "AGENTMEMORY_CALLER_TOKEN": "${AGENTMEMORY_CALLER_TOKEN:-}",
"AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}"
}
}
diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md
index 60f5e5bb94..8c3fe582f8 100644
--- a/plugin/opencode/README.md
+++ b/plugin/opencode/README.md
@@ -9,7 +9,7 @@
-
+
diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts
index 056d53d38d..df28537763 100644
--- a/plugin/opencode/agentmemory-capture.ts
+++ b/plugin/opencode/agentmemory-capture.ts
@@ -7,10 +7,16 @@ const MAX_STASHED_FILES = 20;
const DEBUG = process.env.OPENCODE_AGENTMEMORY_DEBUG === "1";
const SECRET = process.env.AGENTMEMORY_SECRET || "";
+const AGENT_ID = process.env.AGENT_ID || "";
+const CALLER_TOKEN = process.env.AGENTMEMORY_CALLER_TOKEN || "";
function authHeaders(): Record {
const headers: Record = { "Content-Type": "application/json" };
if (SECRET) headers["Authorization"] = `Bearer ${SECRET}`;
+ if (AGENT_ID) headers["X-AgentMemory-Agent-Id"] = AGENT_ID;
+ if (CALLER_TOKEN) {
+ headers["X-AgentMemory-Caller-Token"] = CALLER_TOKEN;
+ }
return headers;
}
diff --git a/plugin/plugin.json b/plugin/plugin.json
index 9d0751a7ab..be1baedba1 100644
--- a/plugin/plugin.json
+++ b/plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "agentmemory",
"version": "0.9.27",
- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 15 skills, real-time viewer.",
+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 60 MCP tools, 15 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
"url": "https://github.com/rohitg00"
diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjs
index 3967158c92..0084ea1db9 100755
--- a/plugin/scripts/notification.mjs
+++ b/plugin/scripts/notification.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/notification.ts
function isSdkChildContext(payload) {
@@ -29,13 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -49,28 +144,20 @@ async function main() {
const notificationType = data.notification_type ?? data.notificationType;
if (notificationType !== "permission_prompt") return;
const rawSessionId = data.session_id ?? data.sessionId;
- const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown";
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "notification",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: {
- notification_type: notificationType,
- title: data.title,
- message: data.message
- }
- }),
- signal: AbortSignal.timeout(2e3)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "notification",
+ sessionId: typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown",
+ ...resolveProjectContext(data.cwd),
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: {
+ notification_type: notificationType,
+ title: data.title,
+ message: data.message
+ }
+ });
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=notification.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/post-commit.mjs b/plugin/scripts/post-commit.mjs
index 8552cd614e..5318184f85 100755
--- a/plugin/scripts/post-commit.mjs
+++ b/plugin/scripts/post-commit.mjs
@@ -1,7 +1,6 @@
#!/usr/bin/env node
import { execFile } from "node:child_process";
import { promisify } from "node:util";
-
//#region src/hooks/post-commit.ts
const exec = promisify(execFile);
function isSdkChildContext(payload) {
@@ -96,7 +95,7 @@ async function main() {
} catch {}
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=post-commit.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjs
index 6fdad8d9d9..640c782c38 100755
--- a/plugin/scripts/post-tool-failure.mjs
+++ b/plugin/scripts/post-tool-failure.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/post-tool-failure.ts
function isSdkChildContext(payload) {
@@ -29,13 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -49,29 +144,23 @@ async function main() {
if (data.is_interrupt || data.isInterrupt) return;
const sessionId = data.session_id || data.sessionId || "unknown";
const toolName = data.tool_name ?? data.toolName;
+ if (typeof toolName === "string" && (toolName.toLowerCase().startsWith("mcp__agentmemory__") || toolName.toLowerCase().startsWith("memory_"))) return;
const toolInput = data.tool_input ?? data.toolArgs;
const error = data.error ?? data.errorMessage;
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "post_tool_failure",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: {
- tool_name: toolName,
- tool_input: typeof toolInput === "string" ? toolInput.slice(0, 4e3) : JSON.stringify(toolInput ?? "").slice(0, 4e3),
- error: typeof error === "string" ? error.slice(0, 4e3) : JSON.stringify(error ?? "").slice(0, 4e3)
- }
- }),
- signal: AbortSignal.timeout(3e3)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "post_tool_failure",
+ sessionId,
+ ...resolveProjectContext(data.cwd),
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: {
+ tool_name: toolName,
+ tool_input: typeof toolInput === "string" ? toolInput.slice(0, 4e3) : JSON.stringify(toolInput ?? "").slice(0, 4e3),
+ error: typeof error === "string" ? error.slice(0, 4e3) : JSON.stringify(error ?? "").slice(0, 4e3)
+ }
+ });
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=post-tool-failure.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjs
index b4aef9c942..b602c97a5a 100755
--- a/plugin/scripts/post-tool-use.mjs
+++ b/plugin/scripts/post-tool-use.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/post-tool-use.ts
function isSdkChildContext(payload) {
@@ -29,13 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -49,26 +144,33 @@ async function main() {
const sessionId = data.session_id || data.sessionId || "unknown";
const toolName = data.tool_name ?? data.toolName;
const toolInput = data.tool_input ?? data.toolArgs;
+ if (shouldSkipTool(toolName)) return;
+ const context = resolveProjectContext(data.cwd);
+ const maxChars = maxCaptureChars();
const { imageData, cleanOutput } = extractImageData(toolOutput(data));
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "post_tool_use",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: {
- tool_name: toolName,
- tool_input: toolInput,
- tool_output: truncate(cleanOutput, 8e3),
- ...imageData ? { image_data: imageData } : {}
- }
- }),
- signal: AbortSignal.timeout(3e3)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "post_tool_use",
+ sessionId,
+ ...context,
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: {
+ tool_name: toolName,
+ tool_input: truncate(toolInput, maxChars),
+ tool_output: truncate(cleanOutput, maxChars),
+ ...imageData ? { image_data: imageData } : {}
+ }
+ });
+}
+function shouldSkipTool(value) {
+ const name = typeof value === "string" ? value.trim().toLowerCase() : "";
+ if (!name) return false;
+ if (name.startsWith("mcp__agentmemory__") || name.startsWith("memory_")) return true;
+ return (process.env["AGENTMEMORY_SKIP_TOOLS"] || "").split(",").map((item) => item.trim().toLowerCase()).filter(Boolean).some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
+}
+function maxCaptureChars() {
+ const value = Number(process.env["AGENTMEMORY_MAX_TOOL_CAPTURE_CHARS"] || "8000");
+ if (!Number.isFinite(value) || value < 0) return 8e3;
+ return Math.min(Math.floor(value), 32e3);
}
function toolOutput(data) {
if (data.tool_response !== void 0) return data.tool_response;
@@ -116,7 +218,7 @@ function truncate(value, max) {
return value;
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=post-tool-use.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjs
index 0afdcb0b4e..bde2fbe9fe 100755
--- a/plugin/scripts/pre-compact.mjs
+++ b/plugin/scripts/pre-compact.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,93 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
- } catch {}
- return basename(dir);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+function resolveProject(cwd) {
+ return resolveProjectContext(cwd).project;
}
-
//#endregion
//#region src/hooks/pre-compact.ts
function isSdkChildContext(payload) {
@@ -31,9 +110,13 @@ function isSdkChildContext(payload) {
}
const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
+const AGENT_ID = process.env["AGENT_ID"] || "";
+const CALLER_TOKEN = process.env["AGENTMEMORY_CALLER_TOKEN"] || "";
function authHeaders() {
const h = { "Content-Type": "application/json" };
if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
+ if (AGENT_ID) h["X-AgentMemory-Agent-Id"] = AGENT_ID;
+ if (CALLER_TOKEN) h["X-AgentMemory-Caller-Token"] = CALLER_TOKEN;
return h;
}
async function main() {
@@ -74,7 +157,7 @@ async function main() {
} catch {}
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=pre-compact.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs
index d70c166ed2..a0d6e95832 100755
--- a/plugin/scripts/pre-tool-use.mjs
+++ b/plugin/scripts/pre-tool-use.mjs
@@ -78,7 +78,7 @@ async function main() {
} catch {}
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=pre-tool-use.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjs
index 1a4147e6ab..1a831dd6c2 100755
--- a/plugin/scripts/prompt-submit.mjs
+++ b/plugin/scripts/prompt-submit.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/prompt-submit.ts
function isSdkChildContext(payload) {
@@ -29,13 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -47,23 +142,29 @@ async function main() {
}
if (isSdkChildContext(data)) return;
const sessionId = data.session_id || data.sessionId || "unknown";
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "prompt_submit",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: { prompt: data.prompt ?? data.userPrompt }
- }),
- signal: AbortSignal.timeout(3e3)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ const context = resolveProjectContext(data.cwd);
+ const promptData = promptCapture(data.prompt ?? data.userPrompt);
+ await submitObservation({
+ hookType: "prompt_submit",
+ sessionId,
+ ...context,
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: promptData
+ });
+}
+function promptCapture(value) {
+ const text = typeof value === "string" ? value : "";
+ const mode = (process.env["AGENTMEMORY_CAPTURE_PROMPTS"] || "full").toLowerCase();
+ if (mode === "off" || mode === "metadata") return {
+ prompt_length: text.length,
+ prompt_capture: mode
+ };
+ const max = Number(process.env["AGENTMEMORY_MAX_PROMPT_CAPTURE_CHARS"] || "4000");
+ const limit = Number.isFinite(max) && max >= 0 ? Math.min(Math.floor(max), 16e3) : 4e3;
+ return { prompt: text.slice(0, limit) };
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=prompt-submit.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs
index 019149c309..0ba564be58 100755
--- a/plugin/scripts/session-end.mjs
+++ b/plugin/scripts/session-end.mjs
@@ -54,7 +54,7 @@ async function main() {
setTimeout(() => process.exit(0), 1500).unref();
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=session-end.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjs
index 51b70eb4c2..b6dd890682 100755
--- a/plugin/scripts/session-start.mjs
+++ b/plugin/scripts/session-start.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,90 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
- } catch {}
- return basename(dir);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
}
-
//#endregion
//#region src/hooks/session-start.ts
function isSdkChildContext(payload) {
@@ -32,11 +108,15 @@ function isSdkChildContext(payload) {
const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";
const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
+const AGENT_ID = process.env["AGENT_ID"] || "";
+const CALLER_TOKEN = process.env["AGENTMEMORY_CALLER_TOKEN"] || "";
const INJECT_TIMEOUT_MS = 1500;
const REGISTER_TIMEOUT_MS = 800;
function authHeaders() {
const h = { "Content-Type": "application/json" };
if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
+ if (AGENT_ID) h["X-AgentMemory-Agent-Id"] = AGENT_ID;
+ if (CALLER_TOKEN) h["X-AgentMemory-Caller-Token"] = CALLER_TOKEN;
return h;
}
async function main() {
@@ -50,16 +130,14 @@ async function main() {
}
if (isSdkChildContext(data)) return;
const sessionId = data.session_id || data.sessionId || `ses_${Date.now().toString(36)}`;
- const cwd = data.cwd || process.cwd();
- const project = resolveProject(data.cwd);
+ const context = resolveProjectContext(data.cwd);
const url = `${REST_URL}/agentmemory/session/start`;
const init = {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({
sessionId,
- project,
- cwd
+ ...context
})
};
if (!INJECT_CONTEXT) {
@@ -81,7 +159,7 @@ async function main() {
} catch {}
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=session-start.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjs
index 03d30c64f3..63051c8309 100755
--- a/plugin/scripts/stop.mjs
+++ b/plugin/scripts/stop.mjs
@@ -38,7 +38,7 @@ async function main() {
setTimeout(() => process.exit(0), 1500).unref();
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=stop.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjs
index 2359a1c62f..9dab7f9d29 100755
--- a/plugin/scripts/subagent-start.mjs
+++ b/plugin/scripts/subagent-start.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/subagent-start.ts
function isSdkChildContext(payload) {
@@ -29,14 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-const TIMEOUT_MS = 800;
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -50,26 +144,19 @@ async function main() {
const sessionId = data.session_id || data.sessionId || "unknown";
const agentId = data.agent_id || data.agentName;
const agentType = data.agent_type || data.agentDisplayName || data.agentName;
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "subagent_start",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: {
- agent_id: agentId,
- agent_type: agentType
- }
- }),
- signal: AbortSignal.timeout(TIMEOUT_MS)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "subagent_start",
+ sessionId,
+ ...resolveProjectContext(data.cwd),
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: {
+ agent_id: agentId,
+ agent_type: agentType
+ }
+ });
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=subagent-start.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjs
index 2ba1b002c9..d002786abf 100755
--- a/plugin/scripts/subagent-stop.mjs
+++ b/plugin/scripts/subagent-stop.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/subagent-stop.ts
function isSdkChildContext(payload) {
@@ -29,13 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -50,27 +145,20 @@ async function main() {
const agentId = data.agent_id || data.agentName;
const agentType = data.agent_type || data.agentDisplayName || data.agentName;
const lastMsg = typeof data.last_assistant_message === "string" ? data.last_assistant_message.slice(0, 4e3) : "";
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "subagent_stop",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: {
- agent_id: agentId,
- agent_type: agentType,
- last_message: lastMsg
- }
- }),
- signal: AbortSignal.timeout(2e3)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "subagent_stop",
+ sessionId,
+ ...resolveProjectContext(data.cwd),
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: {
+ agent_id: agentId,
+ agent_type: agentType,
+ last_message: lastMsg
+ }
+ });
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=subagent-stop.mjs.map
\ No newline at end of file
diff --git a/plugin/scripts/task-completed.mjs b/plugin/scripts/task-completed.mjs
index 478f0688e8..d1f1e6048a 100755
--- a/plugin/scripts/task-completed.mjs
+++ b/plugin/scripts/task-completed.mjs
@@ -1,15 +1,12 @@
#!/usr/bin/env node
-import { execSync } from "node:child_process";
-import { basename } from "node:path";
-
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, parse, resolve } from "node:path";
//#region src/hooks/_project.ts
-function resolveProject(cwd) {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+function git(cwd, args) {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: [
"ignore",
"pipe",
@@ -17,11 +14,116 @@ function resolveProject(cwd) {
],
timeout: 500
}).toString().trim();
- if (top) return basename(top);
+ } catch {
+ return "";
+ }
+}
+function canonicalExistingPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+function nearestProjectFile(cwd, boundary) {
+ let current = canonicalExistingPath(cwd);
+ const filesystemRoot = parse(current).root;
+ const root = boundary ? canonicalExistingPath(boundary) : filesystemRoot;
+ while (true) {
+ const candidate = resolve(current, ".agentmemory", "project.json");
+ if (existsSync(candidate)) return candidate;
+ if (current === root || current === filesystemRoot) return void 0;
+ const parent = dirname(current);
+ if (parent === current) return void 0;
+ current = parent;
+ }
+}
+function readProjectFile(cwd, boundary) {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return void 0;
+ try {
+ return {
+ file,
+ data: JSON.parse(readFileSync(file, "utf8"))
+ };
+ } catch {
+ return;
+ }
+}
+function remoteProjectName(remote) {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ return normalized.split(/[/:]/).filter(Boolean).at(-1) || "";
+}
+function nonEmpty(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
+}
+function resolveProjectContext(cwd) {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ if (process.platform !== "win32" && (/^[A-Za-z]:[\\/]/.test(rawDir) || rawDir.startsWith("\\\\"))) {
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ return {
+ project: explicitProject || basename(rawDir),
+ cwd: rawDir,
+ repoRoot: nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]) || rawDir,
+ scopeType: nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) || "directory",
+ ...taskSlug ? { taskSlug } : {}
+ };
+ }
+ const dir = resolve(rawDir);
+ const gitTop = git(dir, ["rev-parse", "--show-toplevel"]);
+ const projectFile = readProjectFile(dir, gitTop || void 0);
+ const remoteName = remoteProjectName(git(dir, [
+ "config",
+ "--get",
+ "remote.origin.url"
+ ]));
+ const fileProject = projectFile ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId) : void 0;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot) : void 0;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : void 0;
+ const repoRoot = configuredRepoRoot ? resolve(configuredRepoRoot) : rawRepoRoot ? resolve(projectFileRoot || dir, rawRepoRoot) : gitTop || dir;
+ const scopeType = nonEmpty(process.env["AGENTMEMORY_SCOPE_TYPE"]) ?? (projectFile ? nonEmpty(projectFile.data.scope_type) ?? nonEmpty(projectFile.data.scopeType) : void 0) ?? (gitTop ? "repo" : "directory");
+ const taskSlug = nonEmpty(process.env["AGENTMEMORY_TASK_SLUG"]);
+ const branch = gitTop ? git(dir, ["branch", "--show-current"]) : "";
+ return {
+ project: (explicitProject ?? fileProject ?? remoteName) || basename(gitTop || dir),
+ cwd: dir,
+ repoRoot,
+ scopeType,
+ ...gitTop ? { worktree: gitTop } : {},
+ ...branch ? { branch } : {},
+ ...taskSlug ? { taskSlug } : {}
+ };
+}
+//#endregion
+//#region src/hooks/_observe.ts
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5e3;
+function ackTimeoutMs() {
+ const configured = Number(process.env["AGENTMEMORY_HOOK_ACK_TIMEOUT_MS"] ?? DEFAULT_ACK_TIMEOUT_MS);
+ if (!Number.isFinite(configured) || configured <= 0) return DEFAULT_ACK_TIMEOUT_MS;
+ return Math.max(1, Math.min(Math.floor(configured), MAX_ACK_TIMEOUT_MS));
+}
+function authHeaders() {
+ const headers = { "Content-Type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+async function submitObservation(payload) {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ await (await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs())
+ })).arrayBuffer();
} catch {}
- return basename(dir);
}
-
//#endregion
//#region src/hooks/task-completed.ts
function isSdkChildContext(payload) {
@@ -29,13 +131,6 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-function authHeaders() {
- const h = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
async function main() {
let input = "";
for await (const chunk of process.stdin) input += chunk;
@@ -46,30 +141,22 @@ async function main() {
return;
}
if (isSdkChildContext(data)) return;
- const sessionId = data.session_id || "unknown";
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "task_completed",
- sessionId,
- project: resolveProject(data.cwd),
- cwd: data.cwd || process.cwd(),
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
- data: {
- task_id: data.task_id,
- task_subject: data.task_subject,
- task_description: typeof data.task_description === "string" ? data.task_description.slice(0, 2e3) : "",
- teammate_name: data.teammate_name,
- team_name: data.team_name
- }
- }),
- signal: AbortSignal.timeout(2e3)
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "task_completed",
+ sessionId: data.session_id || "unknown",
+ ...resolveProjectContext(data.cwd),
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ data: {
+ task_id: data.task_id,
+ task_subject: data.task_subject,
+ task_description: typeof data.task_description === "string" ? data.task_description.slice(0, 2e3) : "",
+ teammate_name: data.teammate_name,
+ team_name: data.team_name
+ }
+ });
}
main();
-
//#endregion
-export { };
+export {};
+
//# sourceMappingURL=task-completed.mjs.map
\ No newline at end of file
diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md
index 08c873a444..53eaf06a9e 100644
--- a/plugin/skills/agentmemory-config/REFERENCE.md
+++ b/plugin/skills/agentmemory-config/REFERENCE.md
@@ -3,40 +3,66 @@
Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded.
-Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 34 recognized variables:
+Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 60 recognized variables:
- `AGENTMEMORY_AGENT_SCOPE`
- `AGENTMEMORY_ALLOW_AGENT_SDK`
- `AGENTMEMORY_AUTO_COMPRESS`
+- `AGENTMEMORY_BUILD_ID`
+- `AGENTMEMORY_CALLER_TOKEN`
+- `AGENTMEMORY_CAPTURE_PROMPTS`
- `AGENTMEMORY_COMMIT_SHA`
- `AGENTMEMORY_COPILOT_MCP_BLOCK`
- `AGENTMEMORY_CWD`
- `AGENTMEMORY_DEBUG`
+- `AGENTMEMORY_DISABLED_TOOLS`
+- `AGENTMEMORY_DISABLE_LLM_TOOLS`
- `AGENTMEMORY_DROP_STALE_INDEX`
- `AGENTMEMORY_EXPORT_ROOT`
- `AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS`
- `AGENTMEMORY_FORCE_PROXY`
- `AGENTMEMORY_GRAPH_WEIGHT`
+- `AGENTMEMORY_HOOK_ACK_TIMEOUT_MS`
- `AGENTMEMORY_III_CONFIG`
- `AGENTMEMORY_III_VERSION`
- `AGENTMEMORY_IMAGE_EMBEDDINGS`
- `AGENTMEMORY_IMAGE_STORE_MAX_BYTES`
- `AGENTMEMORY_INJECT_CONTEXT`
+- `AGENTMEMORY_LESSON_ACCESS_MODE`
+- `AGENTMEMORY_LESSON_CALLER_POLICY_FILE`
+- `AGENTMEMORY_LESSON_EMBED_MAX_SENSITIVITY`
+- `AGENTMEMORY_LESSON_REMOTE_EMBEDDINGS`
+- `AGENTMEMORY_LLM_OK`
- `AGENTMEMORY_LLM_TIMEOUT_MS`
+- `AGENTMEMORY_MAX_PROMPT_CAPTURE_CHARS`
+- `AGENTMEMORY_MAX_TOOL_CAPTURE_CHARS`
- `AGENTMEMORY_MCP_BLOCK`
+- `AGENTMEMORY_MCP_HTTP_ALLOWED_ORIGINS`
+- `AGENTMEMORY_MCP_HTTP_ALLOW_REMOTE`
+- `AGENTMEMORY_MCP_HTTP_HOST`
+- `AGENTMEMORY_MCP_HTTP_PORT`
+- `AGENTMEMORY_MCP_HTTP_TOKEN`
- `AGENTMEMORY_PROBE_TIMEOUT_MS`
- `AGENTMEMORY_PROJECT_NAME`
- `AGENTMEMORY_PROVIDER`
- `AGENTMEMORY_REFLECT`
+- `AGENTMEMORY_REPO_ROOT`
+- `AGENTMEMORY_REQUIRE_HTTPS`
+- `AGENTMEMORY_SCOPE_TYPE`
- `AGENTMEMORY_SDK_CHILD`
- `AGENTMEMORY_SECRET`
- `AGENTMEMORY_SESSION_ID`
+- `AGENTMEMORY_SKIP_TOOLS`
- `AGENTMEMORY_SLOTS`
+- `AGENTMEMORY_SOURCE_REVISION`
- `AGENTMEMORY_SUPPRESS_COST_WARNING`
+- `AGENTMEMORY_TASK_SLUG`
- `AGENTMEMORY_TOOLS`
- `AGENTMEMORY_URL`
- `AGENTMEMORY_USE_DOCKER`
- `AGENTMEMORY_VERBOSE`
+- `AGENTMEMORY_VIEWER_AGENT_ID`
+- `AGENTMEMORY_VIEWER_CALLER_TOKEN`
- `AGENTMEMORY_VIEWER_HOST`
- `AGENTMEMORY_VIEWER_URL`
diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
index 0c556fc77f..9ed4026d25 100644
--- a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
+++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
@@ -3,46 +3,53 @@
Generated from `src/mcp/tools-registry.ts`. Do not edit the block below by hand; run `npm run skills:gen` after changing the registry.
-agentmemory exposes 53 MCP tools. 8 are in the lean core set (`--tools core` or `AGENTMEMORY_TOOLS=core`); the rest load with `--tools all` (default).
+agentmemory exposes 60 MCP tools. 7 are in the lean core set (`--tools core` or `AGENTMEMORY_TOOLS=core`); the rest load with `--tools all` (default).
| Tool | Core | Parameters | Purpose |
| --- | --- | --- | --- |
-| `memory_action_create` | | `title`*: string, `description`: string, `priority`: number, `project`: string, `tags`: string, `parentId`: string, `requires`: string | Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other. |
-| `memory_action_update` | | `actionId`*: string, `status`: string, `result`: string, `priority`: number | Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions. |
+| `memory_action_create` | | `title`*: string, `description`: string, `priority`: number, `project`: string, `projectId`: string, `projectAliases`: string, `tags`: string, `parentId`: string, `requires`: string, `lifecycle`: string, `owner`: string, `notBefore`: string, `dueAt`: string, `awaitingHuman`: boolean, `approvalState`: string, `blockedReason`: string, `repoRoot`: string, `worktree`: string, `branch`: string, `taskSlug`: string, `actor`: string | Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other. |
+| `memory_action_list` | | `project`: string, `status`: string, `view`: string, `owner`: string, `tags`: string, `agentId`: string, `limit`: number, `cursor`: string, `revision`: number | List actions through revision-bound actionable, scheduled, waiting, blocked, completed, or cancelled views. |
+| `memory_action_update` | | `actionId`*: string, `status`: string, `lifecycle`: string, `title`: string, `description`: string, `result`: string, `priority`: number, `assignedTo`: string, `owner`: string, `tags`: string, `project`: string, `projectId`: string, `projectAliases`: string, `notBefore`: string, `dueAt`: string, `awaitingHuman`: boolean, `approvalState`: string, `blockedReason`: string, `repoRoot`: string, `worktree`: string, `branch`: string, `taskSlug`: string, `actor`: string, `correctionOf`: string, `correctionReason`: string | Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions. |
| `memory_audit` | | `operation`: string, `limit`: number | View the audit trail of memory operations. |
| `memory_checkpoint` | | `operation`*: string, `name`: string, `checkpointId`: string, `status`: string, `type`: string, `linkedActionIds`: string | Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress. |
| `memory_claude_bridge_sync` | | `direction`*: string | Sync memory state to/from Claude Code's native MEMORY.md file. |
| `memory_commit_lookup` | | `sha`*: string | Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions. |
| `memory_commits` | | `branch`: string, `repo`: string, `limit`: number | List recent commits linked to agent sessions, optionally filtered by branch or repo. |
| `memory_compress_file` | | `filePath`*: string | Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing. |
-| `memory_consolidate` | yes | `tier`: string | Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural). |
+| `memory_consolidate` | | `tier`: string | Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural). |
| `memory_crystallize` | | `actionIds`*: string, `project`: string, `sessionId`: string | Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons. |
| `memory_diagnose` | yes | `categories`: string | Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state. |
-| `memory_export` | | none | Export all memory data as JSON. |
+| `memory_diagnostic_followup` | | none | Read the smart-search follow-up-rate diagnostic counters. This is a read-only directional signal and may overcount legitimate query refinement. |
+| `memory_enrich_session` | | `sessionId`*: string, `lookback`: number, `lookahead`: number, `minImportance`: number | LLM-enrich qualifying observations in a session and persist enriched chunks. This is a state-changing, paid-provider operation. |
+| `memory_export` | | none | Export all memory data as JSON. In lesson enforcement mode this is an operator-only operation requiring restricted clearance, lesson:all-scopes, and lesson:export. |
| `memory_facet_query` | | `matchAll`: string, `matchAny`: string, `targetType`: string | Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend. |
| `memory_facet_tag` | | `targetId`*: string, `targetType`*: string, `dimension`*: string, `value`*: string | Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization. |
| `memory_file_history` | | `files`*: string, `sessionId`: string | Get past observations about specific files. |
+| `memory_flow_compress` | | `runId`: string, `actionIds`: string, `project`: string | LLM-summarize a completed action flow and persist it as workflow memory. Provide a run ID, comma-separated action IDs, or a project. |
| `memory_frontier` | | `project`: string, `agentId`: string, `limit`: number | Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies. |
| `memory_governance_delete` | | `memoryIds`*: string, `reason`: string | Delete specific memories with audit trail. |
| `memory_graph_query` | | `startNodeId`: string, `nodeType`: string, `maxDepth`: number, `query`: string | Query the knowledge graph for entities and relationships. |
| `memory_heal` | | `categories`: string, `dryRun`: string | Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data. |
| `memory_insight_list` | | `project`: string, `minConfidence`: number, `limit`: number | List synthesized insights, higher-order observations derived from patterns across memories, lessons, and crystals. |
| `memory_lease` | | `actionId`*: string, `agentId`*: string, `operation`*: string, `result`: string, `ttlMs`: number | Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing. |
-| `memory_lesson_recall` | | `query`*: string, `project`: string, `minConfidence`: number, `limit`: number | Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions. |
-| `memory_lesson_save` | yes | `content`*: string, `context`: string, `confidence`: number, `project`: string, `tags`: string | Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson. |
+| `memory_lesson_delete` | | `lessonId`*: string, `reason`*: string, `project`: string, `expectedUpdatedAt`: string, `actor`: string | Retract one lesson by exact ID when its evidence is invalid, preserving the legacy tombstone fields, correction metadata, and audit trail. Requires a human-readable reason. |
+| `memory_lesson_recall` | yes | `query`*: string, `project`: string, `minConfidence`: number, `limit`: integer, `retrievalMode`: string, `compact`: boolean, `mechanismId`: string, `claimType`: string, `evidenceVerdicts`: array, `structuredFacets`: object, `tags`: array, `scopeRing`: string, `sensitivity`: string | Search causal lessons. Legacy-compatible lexical ranking is the default; retrievalMode=hybrid adds semantic similarity after authorization and exact structured prefilters, with deterministic lexical fallback. Use compact=true to inject bounded causal lessons instead of full evidence rows. |
+| `memory_lesson_save` | yes | `content`*: string, `context`: string, `confidence`: number, `project`: string, `tags`: string, `mechanismId`: string, `mechanismVersion`: string, `mechanismAliases`: array, `claim`: string, `claimType`: string, `evidenceVerdict`: string, `lifecycle`: string, `applicabilityConditions`: array, `nonApplicabilityConditions`: array, `falsificationConditions`: array, `structuredFacets`: object, `evidenceRefs`: array, `scope`: object, `sensitivity`: string, `reviewAfter`: string, `contradictedByLessonIds`: array | Save a legacy prose lesson or a structured causal lesson. Reinforcement tracks reuse without changing evidence confidence; structured inputs support verdict, lifecycle, durable evidence, scope, sensitivity, and deterministic fingerprints. |
+| `memory_lesson_supersede` | | `lessonId`*: string, `replacementLessonId`*: string, `reason`*: string, `project`: string, `expectedUpdatedAt`: string, `actor`: string | Mark one lesson superseded in favor of an active replacement in the same durable scope, preserving legacy tombstone fields, lineage, and an audit trail. An optional project guard applies only to the original lesson; replacement compatibility follows durable scope rules. |
+| `memory_llm_smoke` | | none | Run a fixed, non-sensitive LLM connectivity probe. Returns provider/model evidence and performs no persistent AgentMemory or filesystem writes. |
| `memory_mesh_sync` | | `peerId`: string, `direction`: string | Sync memories and actions with peer agentmemory instances for multi-agent collaboration. |
| `memory_next` | | `project`: string, `agentId`: string | Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score. |
-| `memory_obsidian_export` | | `vaultDir`: string, `types`: string | Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view. |
+| `memory_obsidian_export` | | `vaultDir`: string, `types`: string | Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view. In lesson enforcement mode, lesson/crystal exports require restricted clearance, lesson:all-scopes, and lesson:export. |
| `memory_patterns` | | `project`: string | Detect recurring patterns across sessions. |
| `memory_profile` | | `project`*: string, `refresh`: string | User/project profile with top concepts and file patterns. |
| `memory_recall` | yes | `query`*: string, `limit`: number, `format`: string, `token_budget`: number | Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before. |
-| `memory_reflect` | yes | `project`: string, `maxClusters`: number | Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights. |
+| `memory_reflect` | | `project`: string, `maxClusters`: number | Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights. |
| `memory_relations` | | `memoryId`*: string, `maxHops`: number, `minConfidence`: number | Query the memory relationship graph. |
| `memory_routine_run` | | `routineId`*: string, `project`: string, `initiatedBy`: string | Instantiate a frozen workflow routine, creating actions for each step with proper dependencies. |
| `memory_save` | yes | `content`*: string, `type`: string, `concepts`: string, `files`: string, `project`: string | Explicitly save an important insight, decision, or pattern to long-term memory. |
| `memory_sentinel_create` | | `name`*: string, `type`*: string, `config`: string, `linkedActionIds`: string, `expiresInMs`: number | Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered. |
| `memory_sentinel_trigger` | | `sentinelId`*: string, `result`: string | Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions. |
-| `memory_sessions` | yes | none | List recent sessions with their status and observation counts. |
+| `memory_sessions` | yes | `limit`: number, `cursor`: string, `project`: string, `status`: string, `since`: string, `format`: string, `includePrompt`: boolean, `includeMalformed`: boolean | List recent sessions with bounded pagination. Compact output omits prompts by default. |
| `memory_signal_read` | | `agentId`*: string, `unreadOnly`: string, `threadId`: string, `limit`: number | Read messages for an agent. Marks delivered messages as read. |
| `memory_signal_send` | | `from`*: string, `to`: string, `content`*: string, `type`: string, `replyTo`: string | Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration. |
| `memory_sketch_create` | | `title`*: string, `description`: string, `expiresInMs`: number, `project`: string | Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded. |
diff --git a/plugin/skills/agentmemory-rest-api/REFERENCE.md b/plugin/skills/agentmemory-rest-api/REFERENCE.md
index d36171defe..64ef269ec8 100644
--- a/plugin/skills/agentmemory-rest-api/REFERENCE.md
+++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md
@@ -5,13 +5,15 @@ Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run `
The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). When `AGENTMEMORY_SECRET` is set, send `Authorization: Bearer $AGENTMEMORY_SECRET`; localhost is otherwise open.
-117 registered endpoints:
+124 registered endpoints:
| Method | Path |
| --- | --- |
| POST | `/agentmemory/actions` |
| POST | `/agentmemory/actions/edges` |
+| POST | `/agentmemory/actions/gc` |
| GET | `/agentmemory/actions/get` |
+| GET | `/agentmemory/actions/graph` |
| POST | `/agentmemory/actions/update` |
| GET | `/agentmemory/audit` |
| POST | `/agentmemory/auto-forget` |
@@ -36,6 +38,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`
| GET | `/agentmemory/diagnostics/followup` |
| POST | `/agentmemory/diagnostics/heal` |
| POST | `/agentmemory/enrich` |
+| POST | `/agentmemory/enrich-session` |
| POST | `/agentmemory/evict` |
| POST | `/agentmemory/evolve` |
| GET | `/agentmemory/export` |
@@ -66,7 +69,9 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`
| POST | `/agentmemory/lessons` |
| POST | `/agentmemory/lessons/search` |
| POST | `/agentmemory/lessons/strengthen` |
+| POST | `/agentmemory/lessons/supersede` |
| GET | `/agentmemory/livez` |
+| POST | `/agentmemory/llm/smoke` |
| GET | `/agentmemory/memories` |
| GET | `/agentmemory/memories/:id` |
| GET | `/agentmemory/mesh/export` |
@@ -77,6 +82,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`
| GET | `/agentmemory/next` |
| GET | `/agentmemory/observations` |
| POST | `/agentmemory/observe` |
+| POST | `/agentmemory/observe/async` |
| POST | `/agentmemory/obsidian/export` |
| POST | `/agentmemory/patterns` |
| GET | `/agentmemory/procedural` |
@@ -98,6 +104,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`
| POST | `/agentmemory/sentinels/trigger` |
| GET | `/agentmemory/session/by-commit` |
| POST | `/agentmemory/session/commit` |
+| POST | `/agentmemory/session/context` |
| POST | `/agentmemory/session/end` |
| POST | `/agentmemory/session/start` |
| GET | `/agentmemory/sessions` |
diff --git a/src/cli.ts b/src/cli.ts
index 93b907491d..2d13eab11d 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -182,6 +182,7 @@ Commands:
the engine was started natively but state file is missing).
mcp Start standalone MCP shim — opt-in surface for MCP-only clients
(Cursor, Gemini CLI, etc). REST always available at :3111.
+ mcp-http Start stateless Streamable HTTP MCP bridge on 127.0.0.1:3114/mcp.
import-jsonl [p] Import Claude Code JSONL transcripts (default: ~/.claude/projects)
--max-files | --max-files=: override scan cap (default 200, max 1000;
out-of-range is rejected; for trees >1000 files, batch by subdirectory)
@@ -190,7 +191,9 @@ Options:
--help, -h Show this help
--verbose, -v Show engine stderr, boot log, and diagnostic info
--reset Wipe ~/.agentmemory/preferences.json and re-run onboarding
- --tools all|core Tool visibility (default: all = ${ALL_TOOLS_COUNT} tools; core = ${CORE_TOOLS_COUNT} essentials)
+ --tools all|core|workstation|workstation-llm
+ Tool visibility (default: all = ${ALL_TOOLS_COUNT}; core = ${CORE_TOOLS_COUNT};
+ workstation = curated coordination; workstation-llm = curated + 7 LLM tools)
--no-engine Skip auto-starting iii-engine
--port Override REST port (default: 3111). Streams (N+1), viewer
(N+2), and iii engine (N+46023) auto-derive from N so a
@@ -202,6 +205,9 @@ Options:
Environment:
AGENTMEMORY_URL Full REST base URL (e.g. http://localhost:3111).
Honored by status, doctor, and MCP shim commands.
+ AGENTMEMORY_MCP_HTTP_HOST Streamable HTTP bind host (default 127.0.0.1).
+ AGENTMEMORY_MCP_HTTP_PORT Streamable HTTP port (default 3114).
+ AGENTMEMORY_MCP_HTTP_TOKEN Optional bearer token for the MCP listener.
AGENTMEMORY_USE_DOCKER=1 Prefer the bundled docker-compose path over the
native iii-engine binary on first run.
AGENTMEMORY_III_VERSION Override pinned iii-engine version (default ${IIPINNED_VERSION}).
@@ -216,6 +222,7 @@ Quick start:
npx @agentmemory/agentmemory status # health + memory count + flags
npx @agentmemory/agentmemory upgrade # upgrade agentmemory + iii runtime
npx @agentmemory/agentmemory mcp # standalone MCP server (no engine)
+ npx @agentmemory/agentmemory mcp-http # loopback Streamable HTTP MCP bridge
npx @agentmemory/mcp # same as above (shim package)
`);
process.exit(0);
@@ -224,12 +231,17 @@ Quick start:
const toolsIdx = args.indexOf("--tools");
if (toolsIdx !== -1 && args[toolsIdx + 1]) {
const toolsMode = args[toolsIdx + 1]!;
- if (toolsMode !== "all" && toolsMode !== "core") {
+ if (
+ !["all", "core", "workstation", "workstation-llm"].includes(toolsMode) &&
+ !toolsMode.includes(",")
+ ) {
p.log.warn(
- `Unknown --tools value "${toolsMode}" (valid: all, core); falling back to all.`,
+ `Unknown --tools value "${toolsMode}" (valid: all, core, workstation, workstation-llm, or a comma-separated allowlist); falling back to the safe core set.`,
);
+ process.env["AGENTMEMORY_TOOLS"] = "core";
+ } else {
+ process.env["AGENTMEMORY_TOOLS"] = toolsMode;
}
- process.env["AGENTMEMORY_TOOLS"] = toolsMode;
}
const portIdx = args.indexOf("--port");
@@ -1197,6 +1209,27 @@ async function main() {
resetPrefs();
}
+ if (await isAgentmemoryReady()) {
+ p.log.info(c.ok(`agentmemory is already running at ${getBaseUrl()}`));
+ return;
+ }
+
+ const existingWorkerPid = readWorkerPidfile();
+ if (
+ existingWorkerPid !== null &&
+ existingWorkerPid !== process.pid &&
+ pidAlive(existingWorkerPid)
+ ) {
+ p.log.error(
+ `agentmemory worker pid ${existingWorkerPid} is already running, but its livez endpoint is unavailable. Refusing to register a duplicate worker.`,
+ );
+ p.log.info(
+ "Restart the existing service or run `agentmemory stop` before starting another worker.",
+ );
+ process.exitCode = 1;
+ return;
+ }
+
const firstRun = isFirstRun();
const prefs = readPrefs();
// Show the splash on the first run, on --reset, or whenever the user
@@ -1397,7 +1430,7 @@ async function runStatus() {
try {
const [healthRes, sessionsRes, graphRes, memoriesRes, flagsRes, followupRes] = await Promise.all([
apiFetch(base, "health"),
- apiFetch(base, "sessions"),
+ apiFetch(base, "sessions?limit=500&format=compact"),
apiFetch(base, "graph/stats"),
apiFetch(base, "memories?count=true"),
apiFetch(base, "config/flags"),
@@ -1411,7 +1444,7 @@ async function runStatus() {
const status = healthRes?.status || "unknown";
const version = healthRes?.version || "?";
const sessionList = Array.isArray(sessionsRes?.sessions) ? sessionsRes.sessions : [];
- const sessions = sessionList.length;
+ const sessions = sessionsRes?.pagination?.total ?? sessionList.length;
const nodes = Number(graphRes?.totalNodes ?? graphRes?.nodes ?? graphRes?.nodeCount ?? 0);
const edges = Number(graphRes?.totalEdges ?? graphRes?.edges ?? graphRes?.edgeCount ?? 0);
const cb = healthRes?.circuitBreaker?.state || "closed";
@@ -2004,6 +2037,21 @@ function buildDemoSessions(): DemoSession[] {
];
}
+function cliJsonHeaders(): Record {
+ const headers: Record = {
+ "Content-Type": "application/json",
+ };
+ const secret = process.env["AGENTMEMORY_SECRET"];
+ const agentId = process.env["AGENT_ID"];
+ const callerToken = process.env["AGENTMEMORY_CALLER_TOKEN"];
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ if (agentId) headers["X-AgentMemory-Agent-Id"] = agentId;
+ if (callerToken) {
+ headers["X-AgentMemory-Caller-Token"] = callerToken;
+ }
+ return headers;
+}
+
async function postJson(
url: string,
body: unknown,
@@ -2012,7 +2060,7 @@ async function postJson(
try {
const res = await fetch(url, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: cliJsonHeaders(),
body: JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
});
@@ -2030,7 +2078,7 @@ async function postJsonStrict(
): Promise {
const res = await fetch(url, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: cliJsonHeaders(),
body: JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
});
@@ -2072,7 +2120,7 @@ async function seedDemoSession(
try {
const res = await fetch(url, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: cliJsonHeaders(),
body: JSON.stringify(payload),
signal: AbortSignal.timeout(5000),
});
@@ -2649,6 +2697,11 @@ async function runMcp(): Promise {
await import("./mcp/standalone.js");
}
+async function runMcpHttp(): Promise {
+ const { runMcpHttpServer } = await import("./mcp/http.js");
+ await runMcpHttpServer();
+}
+
async function runConnectCmd(): Promise {
const { runConnect } = await import("./cli/connect/index.js");
await runConnect(args.slice(1));
@@ -2725,9 +2778,7 @@ async function runImportJsonl(): Promise {
if (pathArg) body["path"] = pathArg;
if (maxFiles !== undefined) body["maxFiles"] = maxFiles;
- const headers: Record = { "content-type": "application/json" };
- const secret = process.env["AGENTMEMORY_SECRET"];
- if (secret) headers["authorization"] = `Bearer ${secret}`;
+ const headers = cliJsonHeaders();
p.log.info(`Importing JSONL from ${pathArg || "~/.claude/projects"}…`);
const spinner = p.spinner();
@@ -2982,6 +3033,7 @@ const commands: Record Promise> = {
stop: runStop,
remove: runRemove,
mcp: runMcp,
+ "mcp-http": runMcpHttp,
"import-jsonl": runImportJsonl,
};
diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts
index 580cd4ee72..96d9f053cb 100644
--- a/src/cli/connect/util.ts
+++ b/src/cli/connect/util.ts
@@ -11,7 +11,7 @@ import { homedir } from "node:os";
import * as p from "@clack/prompts";
// Env values use ${VAR:-default} expansion so the wired MCP entry
-// inherits AGENTMEMORY_URL / AGENTMEMORY_SECRET / AGENTMEMORY_TOOLS
+// inherits endpoint, caller identity, auth, and tool-selection settings
// from the user's shell, but never fails parse when the var is unset
// (#510). Earlier `${VAR}` form caused Claude Code to silently drop the
// server when no shell-level export existed — per the Claude Code MCP
@@ -28,6 +28,8 @@ export const AGENTMEMORY_MCP_BLOCK = {
env: {
AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",
+ AGENT_ID: "${AGENT_ID:-}",
+ AGENTMEMORY_CALLER_TOKEN: "${AGENTMEMORY_CALLER_TOKEN:-}",
AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}",
},
};
@@ -49,6 +51,8 @@ export const AGENTMEMORY_COPILOT_MCP_BLOCK = {
env: {
AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",
+ AGENT_ID: "${AGENT_ID:-}",
+ AGENTMEMORY_CALLER_TOKEN: "${AGENTMEMORY_CALLER_TOKEN:-}",
AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}",
},
tools: ["*"],
diff --git a/src/config.ts b/src/config.ts
index 3348ac2267..17b9e0c723 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -9,6 +9,7 @@ import type {
FallbackConfig,
ClaudeBridgeConfig,
TeamConfig,
+ MemoryProvider,
} from "./types.js";
function safeParseInt(value: string | undefined, fallback: number): number {
@@ -208,13 +209,39 @@ export function detectLlmProviderKind(): "llm" | "noop" {
hasRealValue(env["OPENROUTER_API_KEY"]) ||
hasRealValue(env["MINIMAX_API_KEY"]) ||
(hasRealValue(env["OPENAI_API_KEY"]) &&
- env["OPENAI_API_KEY_FOR_LLM"] !== "false")
+ env["OPENAI_API_KEY_FOR_LLM"] !== "false") ||
+ env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true"
) {
return "llm";
}
return "noop";
}
+export type LlmExecutionState = "enabled" | "disabled" | "unavailable";
+
+export const LLM_METRIC_FUNCTION_IDS = new Set([
+ "mem::compress",
+ "mem::summarize",
+]);
+
+export function isLlmToolsDisabled(): boolean {
+ return getMergedEnv()["AGENTMEMORY_DISABLE_LLM_TOOLS"] === "true";
+}
+
+export function getLlmExecutionState(
+ provider?: Pick,
+): LlmExecutionState {
+ if (isLlmToolsDisabled()) return "disabled";
+ if (provider) {
+ const providerIsNoop =
+ provider.kind === "noop" ||
+ provider.name === "noop" ||
+ provider.name.endsWith("(noop)");
+ return providerIsNoop ? "unavailable" : "enabled";
+ }
+ return detectLlmProviderKind() === "llm" ? "enabled" : "unavailable";
+}
+
export function loadEmbeddingConfig(): EmbeddingConfig {
const env = getMergedEnv();
let bm25Weight = parseFloat(env["BM25_WEIGHT"] || "0.4");
@@ -349,6 +376,7 @@ export function getFollowupWindowSeconds(): number {
export function isConsolidationEnabled(): boolean {
const env = getMergedEnv();
+ if (env["AGENTMEMORY_DISABLE_LLM_TOOLS"] === "true") return false;
const explicit = env["CONSOLIDATION_ENABLED"];
if (explicit === "false" || explicit === "0") return false;
if (explicit === "true" || explicit === "1") return true;
@@ -380,7 +408,10 @@ function hasLLMProviderConfigured(env: Record): bool
// ~/.agentmemory/.env — but should expect their Claude API token usage to
// climb proportionally with session tool-use frequency.
export function isAutoCompressEnabled(): boolean {
- return getMergedEnv()["AGENTMEMORY_AUTO_COMPRESS"] === "true";
+ return (
+ getMergedEnv()["AGENTMEMORY_AUTO_COMPRESS"] === "true" &&
+ getLlmExecutionState() === "enabled"
+ );
}
// Hook-level context injection into Claude Code's conversation is OFF by
diff --git a/src/eval/metrics-store.ts b/src/eval/metrics-store.ts
index 1d381ff95b..c926e22924 100644
--- a/src/eval/metrics-store.ts
+++ b/src/eval/metrics-store.ts
@@ -1,6 +1,15 @@
import type { FunctionMetrics } from "../types.js";
import type { StateKV } from "../state/kv.js";
import { KV } from "../state/schema.js";
+import { withKeyedLock } from "../state/keyed-mutex.js";
+
+type FunctionOutcome =
+ | "success"
+ | "failure"
+ | "skipped_disabled"
+ | "skipped_unavailable";
+
+type SkipReason = "llm_tools_disabled" | "no_llm_provider";
export class MetricsStore {
private cache = new Map();
@@ -8,49 +17,99 @@ export class MetricsStore {
constructor(private kv: StateKV) {}
- async record(
- functionId: string,
- latencyMs: number,
- success: boolean,
- qualityScore?: number,
- ): Promise {
- let m = this.cache.get(functionId);
- if (!m) {
- m = (await this.kv.get(KV.metrics, functionId)) ?? {
+ private normalize(metric: FunctionMetrics): FunctionMetrics {
+ return {
+ ...metric,
+ skippedCount: metric.skippedCount ?? 0,
+ };
+ }
+
+ private async load(functionId: string): Promise {
+ const cached = this.cache.get(functionId);
+ if (cached) return this.normalize(cached);
+ const stored = await this.kv.get(KV.metrics, functionId);
+ return this.normalize(
+ stored ?? {
functionId,
totalCalls: 0,
successCount: 0,
failureCount: 0,
+ skippedCount: 0,
avgLatencyMs: 0,
avgQualityScore: 0,
- };
- }
+ },
+ );
+ }
+
+ private async recordOutcome(
+ functionId: string,
+ latencyMs: number,
+ outcome: FunctionOutcome,
+ qualityScore?: number,
+ skipReason?: SkipReason,
+ ): Promise {
+ await withKeyedLock(`metrics:${functionId}`, async () => {
+ const previous = await this.load(functionId);
+ const metric: FunctionMetrics = { ...previous };
+ const previousCalls = metric.totalCalls;
+ metric.totalCalls += 1;
+ metric.avgLatencyMs =
+ (metric.avgLatencyMs * previousCalls + latencyMs) / metric.totalCalls;
+ metric.lastOutcome = outcome;
+ if (outcome === "success") metric.successCount += 1;
+ if (outcome === "failure") metric.failureCount += 1;
+ if (outcome === "skipped_disabled" || outcome === "skipped_unavailable") {
+ metric.skippedCount += 1;
+ metric.lastSkipReason = skipReason;
+ }
+ if (qualityScore !== undefined) {
+ const previousQualityCalls = this.qualityCallCounts.get(functionId) || 0;
+ metric.avgQualityScore =
+ (metric.avgQualityScore * previousQualityCalls + qualityScore) /
+ (previousQualityCalls + 1);
+ this.qualityCallCounts.set(functionId, previousQualityCalls + 1);
+ }
+
+ this.cache.set(functionId, metric);
+ await this.kv.set(KV.metrics, functionId, metric).catch(() => {});
+ });
+ }
- const prev = m.totalCalls;
- m.totalCalls += 1;
- m.avgLatencyMs = (m.avgLatencyMs * prev + latencyMs) / m.totalCalls;
- if (success) {
- m.successCount += 1;
- } else {
- m.failureCount += 1;
- }
- if (qualityScore !== undefined) {
- const prevQualityCalls = this.qualityCallCounts.get(functionId) || 0;
- m.avgQualityScore =
- (m.avgQualityScore * prevQualityCalls + qualityScore) /
- (prevQualityCalls + 1);
- this.qualityCallCounts.set(functionId, prevQualityCalls + 1);
- }
+ async record(
+ functionId: string,
+ latencyMs: number,
+ success: boolean,
+ qualityScore?: number,
+ ): Promise {
+ await this.recordOutcome(
+ functionId,
+ latencyMs,
+ success ? "success" : "failure",
+ qualityScore,
+ );
+ }
- this.cache.set(functionId, m);
- await this.kv.set(KV.metrics, functionId, m).catch(() => {});
+ async recordSkipped(
+ functionId: string,
+ latencyMs: number,
+ reason: SkipReason,
+ ): Promise {
+ await this.recordOutcome(
+ functionId,
+ latencyMs,
+ reason === "llm_tools_disabled"
+ ? "skipped_disabled"
+ : "skipped_unavailable",
+ undefined,
+ reason,
+ );
}
async get(functionId: string): Promise {
- return (
+ const metric =
this.cache.get(functionId) ??
- (await this.kv.get(KV.metrics, functionId))
- );
+ (await this.kv.get(KV.metrics, functionId));
+ return metric ? this.normalize(metric) : null;
}
async getAll(): Promise {
@@ -58,8 +117,8 @@ export class MetricsStore {
.list(KV.metrics)
.catch(() => []);
const merged = new Map();
- for (const m of kvMetrics) merged.set(m.functionId, m);
- for (const [id, m] of this.cache) merged.set(id, m);
+ for (const m of kvMetrics) merged.set(m.functionId, this.normalize(m));
+ for (const [id, m] of this.cache) merged.set(id, this.normalize(m));
return Array.from(merged.values());
}
}
diff --git a/src/functions/action-model.ts b/src/functions/action-model.ts
new file mode 100644
index 0000000000..8f410a7d6b
--- /dev/null
+++ b/src/functions/action-model.ts
@@ -0,0 +1,790 @@
+import { createHash } from "node:crypto";
+import { basename, isAbsolute, win32 } from "node:path";
+import type {
+ Action,
+ ActionApproval,
+ ActionApprovalState,
+ ActionBlocker,
+ ActionEdge,
+ ActionLifecycle,
+ ActionReadinessView,
+ ActionViewItem,
+ Checkpoint,
+ Lease,
+ Sentinel,
+} from "../types.js";
+
+export const ACTION_SCHEMA_VERSION = 2 as const;
+export const DEFAULT_ACTION_PROJECT_ID = "workstation";
+
+const LIFECYCLES = new Set([
+ "pending",
+ "active",
+ "done",
+ "cancelled",
+]);
+const APPROVAL_STATES = new Set([
+ "not_required",
+ "pending",
+ "approved",
+ "rejected",
+]);
+const HUMAN_WAIT_TAGS = new Set([
+ "requires-confirmation",
+ "awaiting-human",
+ "approval-required",
+]);
+const PROJECT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+export interface NormalizeActionOptions {
+ projectAliases?: Record;
+ defaultProjectId?: string;
+ hasDerivedBlockers?: boolean;
+ revision?: number;
+}
+
+export interface NormalizeActionResult {
+ action: Action;
+ changed: boolean;
+ warnings: string[];
+ conflicts: string[];
+}
+
+export interface ActionViewContext {
+ actions: Action[];
+ edges: ActionEdge[];
+ checkpoints: Checkpoint[];
+ sentinels: Sentinel[];
+ leases: Lease[];
+ agentId?: string;
+ now?: number;
+ index?: ActionViewIndex;
+}
+
+export interface ActionViewIndex {
+ actionMap: Map;
+ edgesByActionId: Map;
+ checkpointMap: Map;
+ sentinelMap: Map;
+ activeLeaseMap: Map;
+}
+
+interface ActionCursorPayload {
+ v: 1;
+ revision: number;
+ offset: number;
+ filter: string;
+ asOf: number;
+}
+
+export function isActionLifecycle(value: unknown): value is ActionLifecycle {
+ return typeof value === "string" && LIFECYCLES.has(value as ActionLifecycle);
+}
+
+export function isActionApprovalState(
+ value: unknown,
+): value is ActionApprovalState {
+ return (
+ typeof value === "string" &&
+ APPROVAL_STATES.has(value as ActionApprovalState)
+ );
+}
+
+export function isCanonicalProjectId(value: unknown): value is string {
+ return (
+ typeof value === "string" &&
+ PROJECT_ID_PATTERN.test(value) &&
+ !isProjectPath(value)
+ );
+}
+
+export function isValidActionTimestamp(value: unknown): value is string {
+ return (
+ typeof value === "string" &&
+ value.trim().length > 0 &&
+ !Number.isNaN(Date.parse(value))
+ );
+}
+
+export function normalizeActionTags(value: unknown): string[] {
+ const input = Array.isArray(value)
+ ? value
+ : typeof value === "string"
+ ? value.split(",")
+ : [];
+ return [
+ ...new Set(
+ input
+ .filter((tag): tag is string => typeof tag === "string")
+ .map((tag) => tag.trim())
+ .filter(Boolean),
+ ),
+ ];
+}
+
+export function normalizeActionV2(
+ input: Action,
+ options: NormalizeActionOptions = {},
+): NormalizeActionResult {
+ const raw = input as Action & { tags?: unknown };
+ const warnings: string[] = [];
+ const conflicts: string[] = [];
+ const tags = normalizeActionTags(raw.tags);
+ if (!Array.isArray(raw.tags)) warnings.push("tags_normalized");
+
+ const tagProjectIds = uniqueTagValues(tags, "projectId");
+ const validTagProjectIds = tagProjectIds.filter(isCanonicalProjectId);
+ const invalidTagProjectIds = tagProjectIds.filter(
+ (value) => !isCanonicalProjectId(value),
+ );
+
+ const legacyProject = nonEmpty(raw.project);
+ const explicitProjectId = nonEmpty(raw.projectId);
+ const mappedProject = legacyProject
+ ? nonEmpty(options.projectAliases?.[legacyProject])
+ : undefined;
+ let projectId: string | undefined;
+
+ if (explicitProjectId) {
+ if (!isCanonicalProjectId(explicitProjectId)) {
+ conflicts.push("invalid_explicit_project_id");
+ } else {
+ projectId = explicitProjectId;
+ }
+ }
+ if (mappedProject) {
+ if (!isCanonicalProjectId(mappedProject)) {
+ conflicts.push("invalid_mapped_project_id");
+ } else if (projectId && mappedProject !== projectId) {
+ conflicts.push("conflicting_project_mapping");
+ } else {
+ projectId = mappedProject;
+ warnings.push("project_resolved_from_alias_map");
+ }
+ }
+ if (!projectId && legacyProject && !isProjectPath(legacyProject)) {
+ if (isCanonicalProjectId(legacyProject)) {
+ projectId = legacyProject;
+ } else {
+ conflicts.push("invalid_legacy_project_id");
+ }
+ }
+ const projectResolvedWithoutTags = projectId !== undefined;
+ if (!projectId) {
+ if (validTagProjectIds.length > 1) {
+ conflicts.push("conflicting_project_tags");
+ } else if (validTagProjectIds[0]) {
+ projectId = validTagProjectIds[0];
+ warnings.push("project_resolved_from_tag");
+ }
+ if (invalidTagProjectIds.length > 0) {
+ conflicts.push("invalid_project_tag");
+ }
+ } else {
+ const contextualProjectTags = tagProjectIds.filter(
+ (value) => value !== projectId,
+ );
+ if (contextualProjectTags.length > 0) {
+ warnings.push("project_tags_retained_as_context");
+ }
+ if (invalidTagProjectIds.length > 0) {
+ warnings.push("invalid_project_tag_ignored");
+ }
+ }
+ if (!projectId && legacyProject && isProjectPath(legacyProject)) {
+ const trimmedPath = legacyProject.replace(/[\\/]+$/, "");
+ const inferred = win32.isAbsolute(legacyProject)
+ ? win32.basename(trimmedPath)
+ : basename(trimmedPath);
+ if (isCanonicalProjectId(inferred)) {
+ projectId = inferred;
+ warnings.push("project_inferred_from_path");
+ } else {
+ conflicts.push("unresolved_project_path");
+ }
+ }
+ if (!projectId) {
+ const fallback = options.defaultProjectId ?? DEFAULT_ACTION_PROJECT_ID;
+ if (isCanonicalProjectId(fallback)) {
+ projectId = fallback;
+ warnings.push("project_defaulted");
+ } else {
+ conflicts.push("invalid_default_project_id");
+ projectId = DEFAULT_ACTION_PROJECT_ID;
+ }
+ }
+
+ if (
+ !projectResolvedWithoutTags &&
+ projectId &&
+ invalidTagProjectIds.length > 0 &&
+ conflicts.includes("invalid_project_tag")
+ ) {
+ // An invalid tag remains a hard conflict when it was part of identity
+ // resolution. Path inference or fallback must not silently hide it.
+ warnings.push("project_identity_requires_review");
+ }
+
+ const projectAliases = new Set(
+ normalizeStringArray(raw.projectAliases).filter(
+ (alias) => alias !== projectId,
+ ),
+ );
+ if (legacyProject && legacyProject !== projectId) {
+ projectAliases.add(legacyProject);
+ }
+
+ const lifecycle = isActionLifecycle(raw.lifecycle)
+ ? raw.lifecycle
+ : lifecycleFromLegacyStatus(raw.status);
+
+ const owner =
+ nonEmpty(raw.owner) ??
+ (raw.schemaVersion === ACTION_SCHEMA_VERSION
+ ? undefined
+ : nonEmpty(raw.assignedTo) ??
+ firstTagValue(tags, "agent") ??
+ (nonEmpty(raw.createdBy) === "unknown"
+ ? undefined
+ : nonEmpty(raw.createdBy)));
+
+ const notBefore = typedOrTaggedTimestamp(
+ raw.notBefore,
+ raw.schemaVersion === ACTION_SCHEMA_VERSION
+ ? undefined
+ : firstTagValue(tags, "not-before"),
+ "not_before",
+ warnings,
+ conflicts,
+ );
+ const dueAt = typedOrTaggedTimestamp(
+ raw.dueAt,
+ raw.schemaVersion === ACTION_SCHEMA_VERSION
+ ? undefined
+ : firstTagValue(tags, "due"),
+ "due_at",
+ warnings,
+ conflicts,
+ );
+
+ const approval = normalizeApproval(raw.approval, warnings, conflicts);
+ const waitTag = tags.some((tag) => HUMAN_WAIT_TAGS.has(tag.toLowerCase()));
+ let awaitingHuman =
+ typeof raw.awaitingHuman === "boolean" ? raw.awaitingHuman : waitTag;
+ let normalizedApproval = approval;
+ if (normalizedApproval?.state === "pending") awaitingHuman = true;
+ if (
+ normalizedApproval &&
+ normalizedApproval.state !== "pending"
+ ) {
+ awaitingHuman = false;
+ }
+ if (awaitingHuman && !normalizedApproval) {
+ normalizedApproval = {
+ state: "pending",
+ requestedAt: isValidActionTimestamp(raw.createdAt)
+ ? raw.createdAt
+ : undefined,
+ };
+ warnings.push("approval_inferred_from_wait_state");
+ }
+
+ let blockedReason = nonEmpty(raw.blockedReason);
+ if (
+ raw.schemaVersion !== ACTION_SCHEMA_VERSION &&
+ raw.status === "blocked" &&
+ !blockedReason &&
+ !awaitingHuman &&
+ !options.hasDerivedBlockers
+ ) {
+ blockedReason = "Legacy blocked state";
+ warnings.push("manual_block_inferred");
+ }
+
+ const repoRoot =
+ nonEmpty(raw.repoRoot) ??
+ (legacyProject && isProjectPath(legacyProject)
+ ? legacyProject
+ : undefined);
+ const worktree =
+ nonEmpty(raw.worktree) ??
+ (raw.schemaVersion === ACTION_SCHEMA_VERSION
+ ? undefined
+ : firstTagValue(tags, "worktree"));
+ const branch =
+ nonEmpty(raw.branch) ??
+ (raw.schemaVersion === ACTION_SCHEMA_VERSION
+ ? undefined
+ : firstTagValue(tags, "branch"));
+ const taskSlug =
+ nonEmpty(raw.taskSlug) ??
+ (raw.schemaVersion === ACTION_SCHEMA_VERSION
+ ? undefined
+ : firstTagValue(tags, "task_slug") ??
+ firstTagValue(tags, "task-slug"));
+
+ const action: Action = {
+ ...raw,
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision:
+ options.revision ??
+ (Number.isInteger(raw.revision) && (raw.revision ?? -1) >= 0
+ ? raw.revision
+ : 0),
+ lifecycle,
+ projectId,
+ project: projectId,
+ projectAliases: [...projectAliases].sort(),
+ owner,
+ notBefore,
+ dueAt,
+ awaitingHuman,
+ approval: normalizedApproval,
+ blockedReason,
+ repoRoot,
+ worktree,
+ branch,
+ taskSlug,
+ status: legacyStatusFor({
+ lifecycle,
+ blockedReason,
+ awaitingHuman,
+ approval: normalizedApproval,
+ hasDerivedBlockers: options.hasDerivedBlockers === true,
+ }),
+ tags,
+ sourceObservationIds: normalizeStringArray(raw.sourceObservationIds),
+ sourceMemoryIds: normalizeStringArray(raw.sourceMemoryIds),
+ };
+
+ return {
+ action,
+ changed: canonicalJson(action) !== canonicalJson(input),
+ warnings: [...new Set(warnings)],
+ conflicts: [...new Set(conflicts)],
+ };
+}
+
+function canonicalJson(value: unknown): string {
+ return JSON.stringify(value, (_key, nested) => {
+ if (!nested || typeof nested !== "object" || Array.isArray(nested)) {
+ return nested;
+ }
+ return Object.fromEntries(
+ Object.entries(nested)
+ .filter(([, item]) => item !== undefined)
+ .sort(([left], [right]) =>
+ left < right ? -1 : left > right ? 1 : 0,
+ ),
+ );
+ });
+}
+
+export function classifyAction(
+ input: Action,
+ context: ActionViewContext,
+): ActionViewItem {
+ const now = context.now ?? Date.now();
+ const index = context.index ?? buildActionViewIndex(context);
+ const actionEdges = index.edgesByActionId.get(input.id) ?? [];
+ const { actionMap, checkpointMap, sentinelMap } = index;
+ const hasDerivedBlockers = actionEdges.some(
+ (edge) => {
+ if (edge.sourceActionId !== input.id) return false;
+ if (edge.type === "requires") {
+ const dependency = actionMap.get(edge.targetActionId);
+ return (dependency?.lifecycle ?? dependency?.status) !== "done";
+ }
+ if (edge.type === "gated_by") {
+ return (
+ checkpointMap.get(edge.targetActionId)?.status !== "passed" &&
+ sentinelMap.get(edge.targetActionId)?.status !== "triggered"
+ );
+ }
+ return false;
+ },
+ );
+ const action = normalizeActionV2(input, { hasDerivedBlockers }).action;
+ const lifecycle = action.lifecycle ?? lifecycleFromLegacyStatus(action.status);
+ if (lifecycle === "done") {
+ return { action, view: "completed", blockers: [], leased: false };
+ }
+ if (lifecycle === "cancelled") {
+ return { action, view: "cancelled", blockers: [], leased: false };
+ }
+
+ const blockers: ActionBlocker[] = [];
+
+ if (action.blockedReason) {
+ blockers.push({ type: "manual", message: action.blockedReason });
+ }
+ if (action.approval?.state === "rejected") {
+ blockers.push({
+ type: "approval",
+ message: action.approval.note || "Human approval was rejected",
+ });
+ }
+ for (const edge of actionEdges) {
+ if (edge.sourceActionId !== action.id) continue;
+ if (edge.type === "requires") {
+ const dependency = actionMap.get(edge.targetActionId);
+ const dependencyLifecycle = dependency
+ ? normalizeActionV2(dependency).action.lifecycle
+ : undefined;
+ if (dependencyLifecycle !== "done") {
+ blockers.push({
+ type: "requires",
+ id: edge.targetActionId,
+ message: dependency
+ ? `Requires ${dependency.title}`
+ : `Required action ${edge.targetActionId} is missing`,
+ });
+ }
+ }
+ if (edge.type === "gated_by") {
+ const checkpoint = checkpointMap.get(edge.targetActionId);
+ const sentinel = sentinelMap.get(edge.targetActionId);
+ const passed =
+ checkpoint?.status === "passed" || sentinel?.status === "triggered";
+ if (!passed) {
+ blockers.push({
+ type: "checkpoint",
+ id: edge.targetActionId,
+ message: checkpoint
+ ? `Checkpoint ${checkpoint.name} is ${checkpoint.status}`
+ : sentinel
+ ? `Sentinel ${sentinel.name} is ${sentinel.status}`
+ : `Gate ${edge.targetActionId} is missing`,
+ });
+ }
+ }
+ }
+ for (const edge of actionEdges) {
+ if (edge.type !== "conflicts_with") continue;
+ const otherId =
+ edge.sourceActionId === action.id
+ ? edge.targetActionId
+ : edge.sourceActionId;
+ const other = actionMap.get(otherId);
+ const otherLifecycle = other
+ ? normalizeActionV2(other).action.lifecycle
+ : undefined;
+ if (other && otherLifecycle === "active") {
+ blockers.push({
+ type: "conflict",
+ id: other.id,
+ message: `Conflicts with active action ${other.title}`,
+ });
+ }
+ }
+
+ const activeLease = index.activeLeaseMap.get(action.id);
+ const leased = activeLease !== undefined;
+ if (
+ activeLease &&
+ context.agentId &&
+ activeLease.agentId !== context.agentId
+ ) {
+ blockers.push({
+ type: "lease",
+ id: activeLease.id,
+ message: `Leased by ${activeLease.agentId}`,
+ });
+ }
+
+ if (blockers.length > 0) {
+ return { action, view: "blocked", blockers, leased };
+ }
+ if (action.awaitingHuman || action.approval?.state === "pending") {
+ return { action, view: "waiting", blockers: [], leased };
+ }
+ if (action.notBefore) {
+ const scheduledAt = Date.parse(action.notBefore);
+ if (Number.isNaN(scheduledAt)) {
+ return {
+ action,
+ view: "blocked",
+ blockers: [
+ {
+ type: "schedule",
+ message: "notBefore is not a valid timestamp",
+ },
+ ],
+ leased,
+ };
+ }
+ if (scheduledAt > now) {
+ return { action, view: "scheduled", blockers: [], leased };
+ }
+ }
+ return { action, view: "actionable", blockers: [], leased };
+}
+
+export function buildActionViewIndex(
+ context: Omit,
+): ActionViewIndex {
+ const now = context.now ?? Date.now();
+ const edgesByActionId = new Map();
+ for (const edge of context.edges) {
+ const sourceEdges = edgesByActionId.get(edge.sourceActionId) ?? [];
+ sourceEdges.push(edge);
+ edgesByActionId.set(edge.sourceActionId, sourceEdges);
+ if (edge.targetActionId !== edge.sourceActionId) {
+ const targetEdges = edgesByActionId.get(edge.targetActionId) ?? [];
+ targetEdges.push(edge);
+ edgesByActionId.set(edge.targetActionId, targetEdges);
+ }
+ }
+ const activeLeaseMap = new Map();
+ for (const lease of context.leases) {
+ if (
+ lease.status === "active" &&
+ Date.parse(lease.expiresAt) > now
+ ) {
+ activeLeaseMap.set(lease.actionId, lease);
+ }
+ }
+ return {
+ actionMap: new Map(
+ context.actions.map((candidate) => [candidate.id, candidate]),
+ ),
+ edgesByActionId,
+ checkpointMap: new Map(
+ context.checkpoints.map((checkpoint) => [checkpoint.id, checkpoint]),
+ ),
+ sentinelMap: new Map(
+ context.sentinels.map((sentinel) => [sentinel.id, sentinel]),
+ ),
+ activeLeaseMap,
+ };
+}
+
+export function computeActionScore(
+ action: Action,
+ edges: ActionEdge[],
+ now: number,
+): number {
+ let score = action.priority * 10;
+ const createdAt = Date.parse(action.createdAt);
+ if (!Number.isNaN(createdAt)) {
+ const ageHours = (now - createdAt) / (1000 * 60 * 60);
+ score += Math.min(Math.max(ageHours, 0) * 0.5, 20);
+ }
+ const unlockCount = edges.filter(
+ (edge) => edge.sourceActionId === action.id && edge.type === "unlocks",
+ ).length;
+ score += unlockCount * 5;
+ if (
+ edges.some(
+ (edge) =>
+ edge.sourceActionId === action.id && edge.type === "spawned_by",
+ )
+ ) {
+ score += 3;
+ }
+ if ((action.lifecycle ?? lifecycleFromLegacyStatus(action.status)) === "active") {
+ score += 15;
+ }
+ if (action.dueAt) {
+ const dueAt = Date.parse(action.dueAt);
+ if (!Number.isNaN(dueAt)) {
+ const remainingHours = (dueAt - now) / (1000 * 60 * 60);
+ if (remainingHours <= 0) {
+ score += 20;
+ } else if (remainingHours <= 24) {
+ score += 15 * (1 - remainingHours / 24);
+ }
+ }
+ }
+ return Math.round(score * 100) / 100;
+}
+
+export function actionFilterFingerprint(filters: Record): string {
+ const stable = Object.keys(filters)
+ .sort()
+ .reduce>((result, key) => {
+ const value = filters[key];
+ if (value !== undefined) result[key] = value;
+ return result;
+ }, {});
+ return createHash("sha256")
+ .update(JSON.stringify(stable))
+ .digest("hex")
+ .slice(0, 16);
+}
+
+export function encodeActionCursor(
+ revision: number,
+ offset: number,
+ filter: string,
+ asOf: number,
+): string {
+ const payload: ActionCursorPayload = { v: 1, revision, offset, filter, asOf };
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
+}
+
+export function decodeActionCursor(cursor: string): ActionCursorPayload {
+ try {
+ const parsed = JSON.parse(
+ Buffer.from(cursor, "base64url").toString("utf8"),
+ ) as Partial;
+ if (
+ parsed.v !== 1 ||
+ !Number.isInteger(parsed.revision) ||
+ parsed.revision! < 0 ||
+ !Number.isInteger(parsed.offset) ||
+ parsed.offset! < 0 ||
+ typeof parsed.filter !== "string" ||
+ !parsed.filter ||
+ !Number.isFinite(parsed.asOf) ||
+ parsed.asOf! < 0
+ ) {
+ throw new Error("invalid payload");
+ }
+ return parsed as ActionCursorPayload;
+ } catch {
+ throw new Error("invalid_cursor");
+ }
+}
+
+function lifecycleFromLegacyStatus(status: Action["status"]): ActionLifecycle {
+ if (status === "active" || status === "done" || status === "cancelled") {
+ return status;
+ }
+ return "pending";
+}
+
+function legacyStatusFor(input: {
+ lifecycle: ActionLifecycle;
+ blockedReason?: string;
+ awaitingHuman: boolean;
+ approval?: ActionApproval;
+ hasDerivedBlockers: boolean;
+}): Action["status"] {
+ if (input.lifecycle !== "pending") return input.lifecycle;
+ if (
+ input.blockedReason ||
+ input.awaitingHuman ||
+ input.approval?.state === "pending" ||
+ input.approval?.state === "rejected" ||
+ input.hasDerivedBlockers
+ ) {
+ return "blocked";
+ }
+ return "pending";
+}
+
+function normalizeApproval(
+ value: unknown,
+ warnings: string[],
+ conflicts: string[],
+): ActionApproval | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== "object" || Array.isArray(value)) {
+ conflicts.push("invalid_approval");
+ return undefined;
+ }
+ const approval = value as Partial;
+ if (!isActionApprovalState(approval.state)) {
+ conflicts.push("invalid_approval_state");
+ return undefined;
+ }
+ const timestampFields = ["requestedAt", "decidedAt"] as const;
+ for (const field of timestampFields) {
+ const timestamp = approval[field];
+ if (timestamp !== undefined && !isValidActionTimestamp(timestamp)) {
+ conflicts.push(`invalid_approval_${field}`);
+ }
+ }
+ if (
+ approval.state === "pending" &&
+ (approval.decidedAt || approval.decidedBy)
+ ) {
+ warnings.push("pending_approval_has_decision_metadata");
+ }
+ return {
+ state: approval.state,
+ requestedAt: nonEmpty(approval.requestedAt),
+ requestedBy: nonEmpty(approval.requestedBy),
+ decidedAt: nonEmpty(approval.decidedAt),
+ decidedBy: nonEmpty(approval.decidedBy),
+ note: nonEmpty(approval.note),
+ };
+}
+
+function typedOrTaggedTimestamp(
+ typed: unknown,
+ tagged: string | undefined,
+ field: string,
+ warnings: string[],
+ conflicts: string[],
+): string | undefined {
+ if (typed !== undefined) {
+ if (isValidActionTimestamp(typed)) return typed;
+ conflicts.push(`invalid_${field}`);
+ return typeof typed === "string" ? typed : undefined;
+ }
+ if (!tagged) return undefined;
+ if (isValidActionTimestamp(tagged)) {
+ warnings.push(`${field}_migrated_from_tag`);
+ return tagged;
+ }
+ warnings.push(`invalid_${field}_tag`);
+ return undefined;
+}
+
+function uniqueTagValues(tags: string[], prefix: string): string[] {
+ return [
+ ...new Set(
+ tags
+ .map((tag) => tagValue(tag, prefix))
+ .filter((value): value is string => value !== undefined),
+ ),
+ ];
+}
+
+function firstTagValue(tags: string[], prefix: string): string | undefined {
+ return uniqueTagValues(tags, prefix)[0];
+}
+
+function tagValue(tag: string, prefix: string): string | undefined {
+ const marker = `${prefix}:`;
+ if (!tag.toLowerCase().startsWith(marker.toLowerCase())) return undefined;
+ return nonEmpty(tag.slice(marker.length));
+}
+
+function normalizeStringArray(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return [
+ ...new Set(
+ value
+ .filter((item): item is string => typeof item === "string")
+ .map((item) => item.trim())
+ .filter(Boolean),
+ ),
+ ];
+}
+
+function isProjectPath(value: string): boolean {
+ return isAbsolute(value) || win32.isAbsolute(value);
+}
+
+function nonEmpty(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+export function isActionReadinessView(
+ value: unknown,
+): value is ActionReadinessView {
+ return (
+ typeof value === "string" &&
+ [
+ "actionable",
+ "scheduled",
+ "waiting",
+ "blocked",
+ "completed",
+ "cancelled",
+ ].includes(value)
+ );
+}
diff --git a/src/functions/action-query.ts b/src/functions/action-query.ts
new file mode 100644
index 0000000000..3750e5dda0
--- /dev/null
+++ b/src/functions/action-query.ts
@@ -0,0 +1,191 @@
+import type {
+ Action,
+ ActionReadinessView,
+ ActionViewItem,
+ Checkpoint,
+ Lease,
+ Sentinel,
+} from "../types.js";
+import {
+ actionFilterFingerprint,
+ buildActionViewIndex,
+ classifyAction,
+ decodeActionCursor,
+ encodeActionCursor,
+ normalizeActionTags,
+} from "./action-model.js";
+import type { ActionStoreSnapshot } from "./action-store.js";
+
+const DEFAULT_ACTION_LIMIT = 50;
+const MAX_ACTION_LIMIT = 500;
+
+export interface ActionListOptions {
+ status?: string;
+ project?: string;
+ parentId?: string;
+ tags?: string[];
+ owner?: string;
+ view?: ActionReadinessView;
+ agentId?: string;
+ limit?: number;
+ offset?: number;
+ cursor?: string;
+ revision?: number;
+}
+
+export interface ActionPage {
+ success: true;
+ actions: Action[];
+ views: ActionViewItem[];
+ total: number;
+ limit: number;
+ offset: number;
+ hasMore: boolean;
+ revision: number;
+ nextCursor: string | null;
+ asOf: string;
+}
+
+export class ActionQueryError extends Error {
+ constructor(
+ readonly code: "invalid_cursor" | "revision_conflict",
+ message: string,
+ ) {
+ super(message);
+ this.name = "ActionQueryError";
+ }
+}
+
+export function selectActionPage(
+ snapshot: ActionStoreSnapshot,
+ checkpoints: Checkpoint[],
+ sentinels: Sentinel[],
+ leases: Lease[],
+ options: ActionListOptions = {},
+): ActionPage {
+ const limit = normalizedLimit(options.limit);
+ const filter = actionFilterFingerprint({
+ status: options.status,
+ project: options.project,
+ parentId: options.parentId,
+ tags: options.tags ? [...options.tags].sort() : undefined,
+ owner: options.owner,
+ view: options.view,
+ agentId: options.agentId,
+ });
+ let offset = normalizedOffset(options.offset);
+ let expectedRevision = options.revision;
+ let asOf = Date.now();
+ if (options.cursor) {
+ let decoded;
+ try {
+ decoded = decodeActionCursor(options.cursor);
+ } catch {
+ throw new ActionQueryError("invalid_cursor", "cursor is invalid");
+ }
+ if (decoded.filter !== filter) {
+ throw new ActionQueryError(
+ "invalid_cursor",
+ "cursor does not match the requested filters",
+ );
+ }
+ offset = decoded.offset;
+ asOf = decoded.asOf;
+ if (
+ expectedRevision !== undefined &&
+ expectedRevision !== decoded.revision
+ ) {
+ throw new ActionQueryError(
+ "revision_conflict",
+ "cursor and explicit revision do not match",
+ );
+ }
+ expectedRevision = decoded.revision;
+ }
+ if (
+ expectedRevision !== undefined &&
+ expectedRevision !== snapshot.state.revision
+ ) {
+ throw new ActionQueryError(
+ "revision_conflict",
+ `action collection changed from revision ${expectedRevision} to ${snapshot.state.revision}`,
+ );
+ }
+
+ const viewContext = {
+ actions: snapshot.actions,
+ edges: snapshot.edges,
+ checkpoints,
+ sentinels,
+ leases,
+ agentId: options.agentId,
+ now: asOf,
+ };
+ const index = buildActionViewIndex(viewContext);
+ const views = snapshot.actions
+ .map((action) =>
+ classifyAction(action, {
+ ...viewContext,
+ index,
+ }),
+ )
+ .filter((item) => {
+ const action = item.action;
+ if (options.status && action.status !== options.status) return false;
+ if (options.project && !matchesActionProject(action, options.project)) {
+ return false;
+ }
+ if (options.parentId && action.parentId !== options.parentId) return false;
+ if (options.owner && action.owner !== options.owner) return false;
+ if (options.view && item.view !== options.view) return false;
+ if (options.tags && options.tags.length > 0) {
+ const actionTags = normalizeActionTags(action.tags);
+ if (!options.tags.some((tag) => actionTags.includes(tag))) return false;
+ }
+ return true;
+ })
+ .sort((left, right) => {
+ const byUpdatedAt = String(right.action.updatedAt || "").localeCompare(
+ String(left.action.updatedAt || ""),
+ );
+ return byUpdatedAt || left.action.id.localeCompare(right.action.id);
+ });
+
+ const pageViews = views.slice(offset, offset + limit);
+ const nextOffset = offset + pageViews.length;
+ const hasMore = nextOffset < views.length;
+ return {
+ success: true,
+ actions: pageViews.map((item) => item.action),
+ views: pageViews,
+ total: views.length,
+ limit,
+ offset,
+ hasMore,
+ revision: snapshot.state.revision,
+ asOf: new Date(asOf).toISOString(),
+ nextCursor: hasMore
+ ? encodeActionCursor(snapshot.state.revision, nextOffset, filter, asOf)
+ : null,
+ };
+}
+
+export function matchesActionProject(action: Action, project: string): boolean {
+ return (
+ action.projectId === project ||
+ action.project === project ||
+ (Array.isArray(action.projectAliases) &&
+ action.projectAliases.includes(project))
+ );
+}
+
+function normalizedLimit(value?: number): number {
+ if (!Number.isInteger(value) || !value || value < 1) {
+ return DEFAULT_ACTION_LIMIT;
+ }
+ return Math.min(value, MAX_ACTION_LIMIT);
+}
+
+function normalizedOffset(value?: number): number {
+ return Number.isInteger(value) && (value ?? -1) >= 0 ? value! : 0;
+}
diff --git a/src/functions/action-readiness-refresh.ts b/src/functions/action-readiness-refresh.ts
new file mode 100644
index 0000000000..5cbe9e548c
--- /dev/null
+++ b/src/functions/action-readiness-refresh.ts
@@ -0,0 +1,90 @@
+import type { StateKV } from "../state/kv.js";
+import { withKeyedLock } from "../state/keyed-mutex.js";
+import { KV } from "../state/schema.js";
+import type {
+ Action,
+ ActionEdge,
+ Checkpoint,
+ Sentinel,
+} from "../types.js";
+import { persistAction } from "./action-store.js";
+
+/**
+ * Re-project linked actions after a checkpoint or sentinel changes state.
+ * The touch event is deliberate: readiness-view cursors are bound to the
+ * action collection revision, so an external gate transition must advance it.
+ */
+export async function refreshLinkedActionReadiness(
+ kv: StateKV,
+ actionIds: string[],
+ actor: string,
+ reason: string,
+): Promise {
+ const uniqueActionIds = [...new Set(actionIds)];
+ if (uniqueActionIds.length === 0) return 0;
+ const [edges, actions, checkpoints, sentinels] = await Promise.all([
+ kv.list(KV.actionEdges).catch(() => []),
+ kv.list(KV.actions).catch(() => []),
+ kv.list(KV.checkpoints).catch(() => []),
+ kv.list(KV.sentinels).catch(() => []),
+ ]);
+ const actionMap = new Map(actions.map((action) => [action.id, action]));
+ const checkpointMap = new Map(
+ checkpoints.map((checkpoint) => [checkpoint.id, checkpoint]),
+ );
+ const sentinelMap = new Map(
+ sentinels.map((sentinel) => [sentinel.id, sentinel]),
+ );
+ let unblockedCount = 0;
+
+ for (const actionId of uniqueActionIds) {
+ await withKeyedLock(`mem:action:${actionId}`, async () => {
+ const action = await kv.get(KV.actions, actionId);
+ if (!action) return;
+ const lifecycle =
+ action.lifecycle ??
+ (action.status === "active" ||
+ action.status === "done" ||
+ action.status === "cancelled"
+ ? action.status
+ : "pending");
+ if (lifecycle === "done" || lifecycle === "cancelled") return;
+
+ const relevantEdges = edges.filter(
+ (edge) => edge.sourceActionId === actionId,
+ );
+ const hasDerivedBlockers = relevantEdges.some((edge) => {
+ if (edge.type === "requires") {
+ const dependency = actionMap.get(edge.targetActionId);
+ return (dependency?.lifecycle ?? dependency?.status) !== "done";
+ }
+ if (edge.type === "gated_by") {
+ return (
+ checkpointMap.get(edge.targetActionId)?.status !== "passed" &&
+ sentinelMap.get(edge.targetActionId)?.status !== "triggered"
+ );
+ }
+ return false;
+ });
+
+ const before = structuredClone(action);
+ if (lifecycle === "pending") {
+ action.lifecycle = "pending";
+ action.status = hasDerivedBlockers ? "blocked" : "pending";
+ }
+ action.updatedAt = new Date().toISOString();
+ const persisted = await persistAction(kv, action, {
+ actor,
+ before,
+ hasDerivedBlockers,
+ reason,
+ });
+ actionMap.set(action.id, persisted.action);
+ if (before.status === "blocked" && persisted.action.status !== "blocked") {
+ unblockedCount += 1;
+ }
+ });
+ }
+
+ return unblockedCount;
+}
diff --git a/src/functions/action-store.ts b/src/functions/action-store.ts
new file mode 100644
index 0000000000..2d477c4161
--- /dev/null
+++ b/src/functions/action-store.ts
@@ -0,0 +1,448 @@
+import { isDeepStrictEqual } from "node:util";
+import type { StateKV } from "../state/kv.js";
+import { withKeyedLock } from "../state/keyed-mutex.js";
+import { KV, generateId } from "../state/schema.js";
+import type {
+ Action,
+ ActionCollectionState,
+ ActionEdge,
+ ActionEvent,
+ ActionEventType,
+ Checkpoint,
+ Sentinel,
+} from "../types.js";
+import {
+ ACTION_SCHEMA_VERSION,
+ normalizeActionV2,
+ type NormalizeActionOptions,
+ type NormalizeActionResult,
+} from "./action-model.js";
+
+const ACTION_STATE_KEY = "current";
+const ACTION_STORE_LOCK = "mem:actions:v2";
+
+export interface ActionStoreSnapshot {
+ state: ActionCollectionState;
+ actions: Action[];
+ edges: ActionEdge[];
+ events: ActionEvent[];
+}
+
+export interface PersistActionOptions extends NormalizeActionOptions {
+ actor?: string;
+ type?: ActionEventType;
+ reason?: string;
+ correctionOf?: string;
+ before?: Action | null;
+}
+
+export interface PersistActionResult extends NormalizeActionResult {
+ event: ActionEvent;
+ state: ActionCollectionState;
+}
+
+export class ActionNormalizationError extends Error {
+ constructor(readonly conflicts: string[]) {
+ super(`Action normalization failed: ${conflicts.join(", ")}`);
+ this.name = "ActionNormalizationError";
+ }
+}
+
+export class ActionRevisionConflictError extends Error {
+ constructor(
+ readonly actionId: string,
+ readonly fields: string[],
+ ) {
+ super(
+ fields.length > 0
+ ? `Action ${actionId} changed concurrently in: ${fields.join(", ")}`
+ : `Action ${actionId} changed concurrently`,
+ );
+ this.name = "ActionRevisionConflictError";
+ }
+}
+
+export function withActionStoreLock(fn: () => Promise): Promise {
+ return withKeyedLock(ACTION_STORE_LOCK, fn);
+}
+
+export async function readActionStoreSnapshot(
+ kv: StateKV,
+ options: { includeEvents?: boolean } = {},
+): Promise {
+ return withActionStoreLock(async () => {
+ const state = await recoverActionStoreUnlocked(kv);
+ const [actions, edges, events] = await Promise.all([
+ kv.list(KV.actions).catch(() => []),
+ kv.list(KV.actionEdges).catch(() => []),
+ options.includeEvents
+ ? kv.list(KV.actionEvents).catch(() => [])
+ : Promise.resolve([] as ActionEvent[]),
+ ]);
+ return { state, actions, edges, events };
+ });
+}
+
+export async function persistAction(
+ kv: StateKV,
+ input: Action,
+ options: PersistActionOptions = {},
+): Promise {
+ return withActionStoreLock(() =>
+ persistActionUnlocked(kv, input, options),
+ );
+}
+
+export async function persistActionUnlocked(
+ kv: StateKV,
+ input: Action,
+ options: PersistActionOptions = {},
+): Promise {
+ const state = await recoverActionStoreUnlocked(kv);
+ const current = await kv.get(KV.actions, input.id);
+ const candidate =
+ options.before === undefined
+ ? input
+ : rebaseActionMutation(input, options.before, current);
+ const before = current;
+ const revision = state.revision + 1;
+ const hasDerivedBlockers =
+ options.hasDerivedBlockers ??
+ (await actionHasUnresolvedDerivedBlockers(kv, input.id));
+ const normalization = normalizeActionV2(candidate, {
+ projectAliases: options.projectAliases,
+ defaultProjectId: options.defaultProjectId,
+ hasDerivedBlockers,
+ revision,
+ });
+ if (normalization.conflicts.length > 0) {
+ throw new ActionNormalizationError(normalization.conflicts);
+ }
+ const action = normalization.action;
+ const timestamp = new Date().toISOString();
+ const event: ActionEvent = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ id: generateId("aev"),
+ actionId: action.id,
+ entityType: "action",
+ revision,
+ type:
+ options.type ??
+ inferActionEventType(before, action, options.correctionOf),
+ actor:
+ options.actor ||
+ action.owner ||
+ action.assignedTo ||
+ action.createdBy ||
+ "unknown",
+ timestamp,
+ reason: options.reason,
+ correctionOf: options.correctionOf,
+ before: before ? clone(before) : undefined,
+ after: clone(action),
+ };
+ const nextState = await commitEventUnlocked(kv, state, event);
+ return { ...normalization, action, event, state: nextState };
+}
+
+export async function deleteAction(
+ kv: StateKV,
+ actionId: string,
+ options: {
+ actor?: string;
+ reason?: string;
+ correctionOf?: string;
+ } = {},
+): Promise<{ deleted: boolean; event?: ActionEvent; state: ActionCollectionState }> {
+ return withActionStoreLock(async () => {
+ const state = await recoverActionStoreUnlocked(kv);
+ const before = await kv.get(KV.actions, actionId);
+ if (!before) return { deleted: false, state };
+ const event: ActionEvent = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ id: generateId("aev"),
+ actionId,
+ entityType: "action",
+ revision: state.revision + 1,
+ type: "deleted",
+ actor: options.actor || before.owner || before.createdBy || "unknown",
+ timestamp: new Date().toISOString(),
+ reason: options.reason,
+ correctionOf: options.correctionOf,
+ before: clone(before),
+ };
+ const nextState = await commitEventUnlocked(kv, state, event);
+ return { deleted: true, event, state: nextState };
+ });
+}
+
+export async function persistActionEdge(
+ kv: StateKV,
+ edge: ActionEdge,
+ options: {
+ actor?: string;
+ reason?: string;
+ before?: ActionEdge | null;
+ } = {},
+): Promise<{ edge: ActionEdge; event: ActionEvent; state: ActionCollectionState }> {
+ return withActionStoreLock(() =>
+ persistActionEdgeUnlocked(kv, edge, options),
+ );
+}
+
+export async function persistActionEdgeUnlocked(
+ kv: StateKV,
+ edge: ActionEdge,
+ options: {
+ actor?: string;
+ reason?: string;
+ before?: ActionEdge | null;
+ } = {},
+): Promise<{ edge: ActionEdge; event: ActionEvent; state: ActionCollectionState }> {
+ const state = await recoverActionStoreUnlocked(kv);
+ const before =
+ options.before === undefined
+ ? await kv.get(KV.actionEdges, edge.id)
+ : options.before;
+ const event: ActionEvent = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ id: generateId("aev"),
+ actionId: edge.sourceActionId,
+ entityType: "edge",
+ revision: state.revision + 1,
+ type: before ? "fields_changed" : "edge_created",
+ actor: options.actor || "unknown",
+ timestamp: new Date().toISOString(),
+ reason: options.reason,
+ before: before ? clone(before) : undefined,
+ after: clone(edge),
+ };
+ const nextState = await commitEventUnlocked(kv, state, event);
+ return { edge, event, state: nextState };
+}
+
+export async function deleteActionEdge(
+ kv: StateKV,
+ edgeId: string,
+ options: { actor?: string; reason?: string } = {},
+): Promise<{ deleted: boolean; event?: ActionEvent; state: ActionCollectionState }> {
+ return withActionStoreLock(async () => {
+ const state = await recoverActionStoreUnlocked(kv);
+ const before = await kv.get(KV.actionEdges, edgeId);
+ if (!before) return { deleted: false, state };
+ const event: ActionEvent = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ id: generateId("aev"),
+ actionId: before.sourceActionId,
+ entityType: "edge",
+ revision: state.revision + 1,
+ type: "edge_deleted",
+ actor: options.actor || "unknown",
+ timestamp: new Date().toISOString(),
+ reason: options.reason,
+ before: clone(before),
+ };
+ const nextState = await commitEventUnlocked(kv, state, event);
+ return { deleted: true, event, state: nextState };
+ });
+}
+
+export async function recoverActionStore(kv: StateKV): Promise {
+ return withActionStoreLock(() => recoverActionStoreUnlocked(kv));
+}
+
+/** Read collection metadata without repairing a pending write. */
+export async function peekActionCollectionState(
+ kv: StateKV,
+): Promise {
+ return readActionCollectionState(kv);
+}
+
+export async function recoverActionStoreUnlocked(
+ kv: StateKV,
+): Promise {
+ const state = await readActionCollectionState(kv);
+ if (!state.pending) return state;
+ const event = await kv.get(KV.actionEvents, state.pending.eventId);
+ if (event && event.revision === state.pending.revision) {
+ await applyEventProjection(kv, event);
+ const recovered: ActionCollectionState = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision: Math.max(state.revision, event.revision),
+ updatedAt: new Date().toISOString(),
+ };
+ await kv.set(KV.actionState, ACTION_STATE_KEY, recovered);
+ return recovered;
+ }
+ const cleared: ActionCollectionState = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision: state.revision,
+ updatedAt: new Date().toISOString(),
+ };
+ await kv.set(KV.actionState, ACTION_STATE_KEY, cleared);
+ return cleared;
+}
+
+async function commitEventUnlocked(
+ kv: StateKV,
+ state: ActionCollectionState,
+ event: ActionEvent,
+): Promise {
+ const pendingState: ActionCollectionState = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision: state.revision,
+ updatedAt: event.timestamp,
+ pending: { revision: event.revision, eventId: event.id },
+ };
+ await kv.set(KV.actionState, ACTION_STATE_KEY, pendingState);
+ await kv.set(KV.actionEvents, event.id, event);
+ await applyEventProjection(kv, event);
+ const committed: ActionCollectionState = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision: event.revision,
+ updatedAt: event.timestamp,
+ };
+ await kv.set(KV.actionState, ACTION_STATE_KEY, committed);
+ return committed;
+}
+
+async function applyEventProjection(
+ kv: StateKV,
+ event: ActionEvent,
+): Promise {
+ if (event.entityType === "action") {
+ if (event.after) {
+ await kv.set(KV.actions, event.actionId, event.after as Action);
+ } else {
+ await kv.delete(KV.actions, event.actionId);
+ }
+ return;
+ }
+ const edge = (event.after ?? event.before) as ActionEdge | undefined;
+ if (!edge) return;
+ if (event.after) {
+ await kv.set(KV.actionEdges, edge.id, event.after as ActionEdge);
+ } else {
+ await kv.delete(KV.actionEdges, edge.id);
+ }
+}
+
+async function readActionCollectionState(
+ kv: StateKV,
+): Promise {
+ const state = await kv.get(KV.actionState, ACTION_STATE_KEY);
+ if (
+ state?.schemaVersion === ACTION_SCHEMA_VERSION &&
+ Number.isInteger(state.revision) &&
+ state.revision >= 0
+ ) {
+ return state;
+ }
+ return {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision: 0,
+ updatedAt: new Date(0).toISOString(),
+ };
+}
+
+function inferActionEventType(
+ before: Action | null,
+ after: Action,
+ correctionOf?: string,
+): ActionEventType {
+ if (!before) return "created";
+ if (correctionOf) return "corrected";
+ if (before.result !== after.result) return "result_recorded";
+ if (
+ before.lifecycle !== after.lifecycle ||
+ before.status !== after.status
+ ) {
+ return "lifecycle_changed";
+ }
+ return "fields_changed";
+}
+
+async function actionHasUnresolvedDerivedBlockers(
+ kv: StateKV,
+ actionId: string,
+): Promise {
+ const edges = (await kv.list(KV.actionEdges).catch(() => []))
+ .filter(
+ (edge) =>
+ edge.sourceActionId === actionId &&
+ (edge.type === "requires" || edge.type === "gated_by"),
+ );
+ for (const edge of edges) {
+ if (edge.type === "requires") {
+ const dependency = await kv.get(KV.actions, edge.targetActionId);
+ if ((dependency?.lifecycle ?? dependency?.status) !== "done") return true;
+ continue;
+ }
+ const [checkpoint, sentinel] = await Promise.all([
+ kv.get(KV.checkpoints, edge.targetActionId),
+ kv.get(KV.sentinels, edge.targetActionId),
+ ]);
+ if (
+ checkpoint?.status !== "passed" &&
+ sentinel?.status !== "triggered"
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function clone(value: T): T {
+ return structuredClone(value);
+}
+
+function rebaseActionMutation(
+ input: Action,
+ expectedBefore: Action | null,
+ current: Action | null,
+): Action {
+ if (!expectedBefore || !current) {
+ if (expectedBefore === current) return input;
+ throw new ActionRevisionConflictError(input.id, []);
+ }
+
+ const managedFields = new Set([
+ "schemaVersion",
+ "revision",
+ "updatedAt",
+ ]);
+ const keys = new Set([
+ ...(Object.keys(expectedBefore) as Array),
+ ...(Object.keys(input) as Array),
+ ...(Object.keys(current) as Array),
+ ]);
+ const intendedFields = [...keys].filter(
+ (field) =>
+ !managedFields.has(field) &&
+ !isDeepStrictEqual(expectedBefore[field], input[field]),
+ );
+ const conflicts = intendedFields.filter(
+ (field) =>
+ !isDeepStrictEqual(expectedBefore[field], current[field]) &&
+ !isDeepStrictEqual(input[field], current[field]),
+ );
+ if (conflicts.length > 0) {
+ throw new ActionRevisionConflictError(
+ input.id,
+ conflicts.map(String).sort(),
+ );
+ }
+
+ const rebased = structuredClone(current) as Action &
+ Record;
+ const source = input as Action & Record;
+ for (const field of intendedFields) {
+ if (Object.prototype.hasOwnProperty.call(source, field)) {
+ rebased[field] = structuredClone(source[field]);
+ } else {
+ delete rebased[field];
+ }
+ }
+ rebased.updatedAt = input.updatedAt;
+ return rebased;
+}
diff --git a/src/functions/actions-v2-migration.ts b/src/functions/actions-v2-migration.ts
new file mode 100644
index 0000000000..a685c967b1
--- /dev/null
+++ b/src/functions/actions-v2-migration.ts
@@ -0,0 +1,281 @@
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import type { Action, ActionEdge, Checkpoint, Sentinel } from "../types.js";
+import {
+ isCanonicalProjectId,
+ normalizeActionV2,
+ type NormalizeActionResult,
+} from "./action-model.js";
+import {
+ peekActionCollectionState,
+ persistActionUnlocked,
+ recoverActionStoreUnlocked,
+ withActionStoreLock,
+} from "./action-store.js";
+import { safeAudit } from "./audit.js";
+
+const DEFAULT_MIGRATION_LIMIT = 100;
+const MAX_MIGRATION_LIMIT = 500;
+
+export interface ActionsV2MigrationInput {
+ dryRun?: boolean;
+ projectAliases?: Record;
+ defaultProjectId?: string;
+ limit?: number;
+ cursor?: string;
+ actor?: string;
+}
+
+interface MigrationCandidate {
+ action: Action;
+ normalized: NormalizeActionResult;
+ hasDerivedBlockers: boolean;
+}
+
+export async function migrateActionsV2(
+ kv: StateKV,
+ input: ActionsV2MigrationInput = {},
+) {
+ return withActionStoreLock(async () => {
+ const configurationErrors = validateMigrationInput(input);
+ if (configurationErrors.length > 0) {
+ return {
+ success: false,
+ step: "actions-v2",
+ dryRun: input.dryRun !== false,
+ error: "invalid_migration_config",
+ configurationErrors,
+ };
+ }
+ const dryRun = input.dryRun !== false;
+ const initialState = dryRun
+ ? await peekActionCollectionState(kv)
+ : await recoverActionStoreUnlocked(kv);
+ const [actions, edges, checkpoints, sentinels] = await Promise.all([
+ kv.list(KV.actions).catch(() => []),
+ kv.list(KV.actionEdges).catch(() => []),
+ kv.list(KV.checkpoints).catch(() => []),
+ kv.list(KV.sentinels).catch(() => []),
+ ]);
+ const limit = normalizeLimit(input.limit);
+ const afterId = decodeMigrationCursor(input.cursor);
+ const ordered = [...actions].sort((left, right) =>
+ left.id.localeCompare(right.id),
+ );
+ const eligible = afterId
+ ? ordered.filter((action) => action.id > afterId)
+ : ordered;
+ const page = eligible.slice(0, limit);
+ const unresolvedDerivedActionIds = collectUnresolvedDerivedActionIds(
+ actions,
+ edges,
+ checkpoints,
+ sentinels,
+ );
+ const candidates: MigrationCandidate[] = page.map((action) => {
+ const hasDerivedBlockers = unresolvedDerivedActionIds.has(action.id);
+ return {
+ action,
+ hasDerivedBlockers,
+ normalized: normalizeActionV2(action, {
+ projectAliases: input.projectAliases,
+ defaultProjectId: input.defaultProjectId,
+ hasDerivedBlockers,
+ }),
+ };
+ });
+
+ const conflicts = candidates.filter(
+ (candidate) => candidate.normalized.conflicts.length > 0,
+ );
+ const changed = candidates.filter(
+ (candidate) => candidate.normalized.changed,
+ );
+ const preview = candidates.map((candidate) => ({
+ actionId: candidate.action.id,
+ changed: candidate.normalized.changed,
+ warnings: candidate.normalized.warnings,
+ conflicts: candidate.normalized.conflicts,
+ projectId: candidate.normalized.action.projectId,
+ }));
+ const hasMore = eligible.length > page.length;
+ const nextCursor =
+ hasMore && page.length > 0
+ ? encodeMigrationCursor(page[page.length - 1].id)
+ : null;
+ const baseResult = {
+ step: "actions-v2",
+ dryRun,
+ scanned: page.length,
+ changed: changed.length,
+ skipped: page.length - changed.length,
+ warningCount: candidates.reduce(
+ (count, candidate) => count + candidate.normalized.warnings.length,
+ 0,
+ ),
+ conflictCount: conflicts.reduce(
+ (count, candidate) => count + candidate.normalized.conflicts.length,
+ 0,
+ ),
+ unresolvedActionIds: conflicts.map((candidate) => candidate.action.id),
+ preview,
+ revisionBefore: initialState.revision,
+ hasMore,
+ nextCursor,
+ };
+
+ if (dryRun) {
+ return {
+ success: conflicts.length === 0 && !initialState.pending,
+ ...(initialState.pending
+ ? {
+ error: "pending_action_store_recovery",
+ message:
+ "A pending action-store write must be recovered before migration",
+ }
+ : {}),
+ ...baseResult,
+ revisionAfter: initialState.revision,
+ };
+ }
+ if (conflicts.length > 0) {
+ return {
+ success: false,
+ error: "migration_conflict",
+ message: "Resolve conflicting action identities before mutation",
+ ...baseResult,
+ revisionAfter: initialState.revision,
+ };
+ }
+
+ let revisionAfter = initialState.revision;
+ for (const candidate of changed) {
+ const persisted = await persistActionUnlocked(kv, candidate.action, {
+ actor: input.actor || "migration:actions-v2",
+ type: "migrated",
+ reason: candidate.normalized.warnings.join(",") || "Actions v2 normalization",
+ before: candidate.action,
+ projectAliases: input.projectAliases,
+ defaultProjectId: input.defaultProjectId,
+ hasDerivedBlockers: candidate.hasDerivedBlockers,
+ });
+ revisionAfter = persisted.state.revision;
+ }
+ if (changed.length > 0) {
+ await safeAudit(
+ kv,
+ "action_update",
+ "mem::migrate",
+ changed.map((candidate) => candidate.action.id),
+ {
+ actor: input.actor || "migration:actions-v2",
+ step: "actions-v2",
+ scanned: page.length,
+ changed: changed.length,
+ revisionBefore: initialState.revision,
+ revisionAfter,
+ },
+ );
+ }
+ return { success: true, ...baseResult, revisionAfter };
+ });
+}
+
+function validateMigrationInput(input: ActionsV2MigrationInput): string[] {
+ const errors: string[] = [];
+ if (input.dryRun !== undefined && typeof input.dryRun !== "boolean") {
+ errors.push("dryRun must be boolean");
+ }
+ if (
+ input.defaultProjectId !== undefined &&
+ !isCanonicalProjectId(input.defaultProjectId)
+ ) {
+ errors.push("defaultProjectId must be a canonical non-path identifier");
+ }
+ if (
+ input.projectAliases !== undefined &&
+ (!input.projectAliases ||
+ typeof input.projectAliases !== "object" ||
+ Array.isArray(input.projectAliases))
+ ) {
+ errors.push("projectAliases must be an object");
+ } else {
+ for (const [alias, projectId] of Object.entries(
+ input.projectAliases ?? {},
+ )) {
+ if (!alias.trim()) errors.push("projectAliases cannot contain empty keys");
+ if (!isCanonicalProjectId(projectId)) {
+ errors.push(`projectAliases[${alias}] must map to a canonical project ID`);
+ }
+ }
+ }
+ if (
+ input.limit !== undefined &&
+ (!Number.isInteger(input.limit) || input.limit < 1)
+ ) {
+ errors.push("limit must be a positive integer");
+ }
+ return [...new Set(errors)];
+}
+
+function collectUnresolvedDerivedActionIds(
+ actions: Action[],
+ edges: ActionEdge[],
+ checkpoints: Checkpoint[],
+ sentinels: Sentinel[],
+): Set {
+ const actionMap = new Map(actions.map((action) => [action.id, action]));
+ const checkpointMap = new Map(
+ checkpoints.map((checkpoint) => [checkpoint.id, checkpoint]),
+ );
+ const sentinelMap = new Map(
+ sentinels.map((sentinel) => [sentinel.id, sentinel]),
+ );
+ const unresolved = new Set();
+ for (const edge of edges) {
+ if (edge.type === "requires") {
+ const dependency = actionMap.get(edge.targetActionId);
+ if ((dependency?.lifecycle ?? dependency?.status) !== "done") {
+ unresolved.add(edge.sourceActionId);
+ }
+ continue;
+ }
+ if (edge.type === "gated_by") {
+ if (
+ checkpointMap.get(edge.targetActionId)?.status !== "passed" &&
+ sentinelMap.get(edge.targetActionId)?.status !== "triggered"
+ ) {
+ unresolved.add(edge.sourceActionId);
+ }
+ }
+ }
+ return unresolved;
+}
+
+function normalizeLimit(value?: number): number {
+ if (!Number.isInteger(value) || !value || value < 1) {
+ return DEFAULT_MIGRATION_LIMIT;
+ }
+ return Math.min(value, MAX_MIGRATION_LIMIT);
+}
+
+function encodeMigrationCursor(afterId: string): string {
+ return Buffer.from(JSON.stringify({ v: 1, afterId }), "utf8").toString(
+ "base64url",
+ );
+}
+
+function decodeMigrationCursor(cursor?: string): string | undefined {
+ if (!cursor) return undefined;
+ try {
+ const parsed = JSON.parse(
+ Buffer.from(cursor, "base64url").toString("utf8"),
+ ) as { v?: unknown; afterId?: unknown };
+ if (parsed.v !== 1 || typeof parsed.afterId !== "string" || !parsed.afterId) {
+ throw new Error("invalid cursor");
+ }
+ return parsed.afterId;
+ } catch {
+ throw new Error("cursor must be a valid actions-v2 migration cursor");
+ }
+}
diff --git a/src/functions/actions.ts b/src/functions/actions.ts
index 12d12df39b..72980051fb 100644
--- a/src/functions/actions.ts
+++ b/src/functions/actions.ts
@@ -1,46 +1,120 @@
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";
+import type {
+ Action,
+ ActionApproval,
+ ActionEdge,
+ ActionLifecycle,
+ ActionReadinessView,
+ Checkpoint,
+ Lease,
+ Sentinel,
+} from "../types.js";
import { recordAudit } from "./audit.js";
+import {
+ isActionApprovalState,
+ isActionLifecycle,
+ isActionReadinessView,
+ isCanonicalProjectId,
+ isValidActionTimestamp,
+ normalizeActionTags,
+} from "./action-model.js";
+import {
+ ActionNormalizationError,
+ ActionRevisionConflictError,
+ deleteAction,
+ persistActionEdgeUnlocked,
+ persistActionUnlocked,
+ readActionStoreSnapshot,
+ recoverActionStoreUnlocked,
+ withActionStoreLock,
+} from "./action-store.js";
+import {
+ ActionQueryError,
+ selectActionPage,
+ type ActionListOptions,
+} from "./action-query.js";
-export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction("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" };
- }
+const VALID_EDGE_TYPES: ActionEdge["type"][] = [
+ "requires",
+ "unlocks",
+ "spawned_by",
+ "gated_by",
+ "conflicts_with",
+];
+const LEGACY_STATUSES = new Set([
+ "pending",
+ "active",
+ "done",
+ "blocked",
+ "cancelled",
+]);
+const MAX_ACTION_GRAPH_ACTIONS = 5_000;
- 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,
- };
+interface ActionCreateInput {
+ title: string;
+ description?: string;
+ priority?: number;
+ createdBy?: string;
+ actor?: string;
+ project?: string;
+ projectId?: string;
+ projectAliases?: string[];
+ tags?: string[] | string;
+ parentId?: string;
+ sourceObservationIds?: string[];
+ sourceMemoryIds?: string[];
+ edges?: Array<{ type: string; targetActionId: string }>;
+ lifecycle?: ActionLifecycle;
+ owner?: string;
+ notBefore?: string;
+ dueAt?: string;
+ awaitingHuman?: boolean;
+ approval?: ActionApproval;
+ blockedReason?: string;
+ repoRoot?: string;
+ worktree?: string;
+ branch?: string;
+ taskSlug?: string;
+}
+
+interface ActionUpdateInput {
+ actionId: string;
+ status?: Action["status"];
+ lifecycle?: ActionLifecycle;
+ title?: string;
+ description?: string;
+ priority?: number;
+ assignedTo?: string;
+ owner?: string;
+ result?: string;
+ tags?: string[] | string;
+ project?: string;
+ projectId?: string;
+ projectAliases?: string[];
+ notBefore?: string;
+ dueAt?: string;
+ awaitingHuman?: boolean;
+ approval?: ActionApproval;
+ blockedReason?: string;
+ repoRoot?: string;
+ worktree?: string;
+ branch?: string;
+ taskSlug?: string;
+ actor?: string;
+ correctionOf?: string;
+ correctionReason?: string;
+}
+export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction("mem::action-create", async (data: ActionCreateInput) => {
+ const validationError = validateCreateInput(data);
+ if (validationError) return { success: false, error: validationError };
+
+ try {
+ return await withActionStoreLock(async () => {
+ await recoverActionStoreUnlocked(kv);
if (data.parentId) {
const parent = await kv.get(KV.actions, data.parentId);
if (!parent) {
@@ -48,110 +122,170 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
}
}
- const validEdgeTypes = [
- "requires",
- "unlocks",
- "spawned_by",
- "gated_by",
- "conflicts_with",
- ];
+ const now = new Date().toISOString();
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(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,
- });
+ for (const requestedEdge of data.edges ?? []) {
+ if (!isValidEdgeType(requestedEdge.type)) {
+ return {
+ success: false,
+ error: `invalid edge type: ${requestedEdge.type}`,
+ };
}
+ const targetExists =
+ requestedEdge.type === "gated_by"
+ ? await actionGateExists(kv, requestedEdge.targetActionId)
+ : Boolean(
+ await kv.get(
+ KV.actions,
+ requestedEdge.targetActionId,
+ ),
+ );
+ if (!targetExists) {
+ return {
+ success: false,
+ error:
+ requestedEdge.type === "gated_by"
+ ? `gate not found: ${requestedEdge.targetActionId}`
+ : `target action not found: ${requestedEdge.targetActionId}`,
+ };
+ }
+ pendingEdges.push({
+ id: generateId("ae"),
+ type: requestedEdge.type,
+ sourceActionId: "",
+ targetActionId: requestedEdge.targetActionId,
+ createdAt: now,
+ });
}
- if (hasRequires) {
- action.status = "blocked";
- }
-
- await kv.set(KV.actions, action.id, action);
- await recordAudit(kv, "action_create", "mem::action-create", [action.id], {
- actor: data.createdBy || "unknown",
- action,
- edges: pendingEdges,
+ const actor = data.actor || data.createdBy || data.owner || "unknown";
+ const actionId = generateId("act");
+ for (const edge of pendingEdges) edge.sourceActionId = actionId;
+ const hasDerivedBlockers = pendingEdges.some(
+ (edge) => edge.type === "requires" || edge.type === "gated_by",
+ );
+ const action: Action = {
+ id: actionId,
+ title: data.title.trim(),
+ description: (data.description || "").trim(),
+ status: hasDerivedBlockers ? "blocked" : "pending",
+ lifecycle: data.lifecycle ?? "pending",
+ priority: normalizePriority(data.priority),
+ createdAt: now,
+ updatedAt: now,
+ createdBy: data.createdBy || actor,
+ project: data.project || data.projectId,
+ projectId: data.projectId,
+ projectAliases: data.projectAliases,
+ tags: normalizeActionTags(data.tags),
+ sourceObservationIds: data.sourceObservationIds || [],
+ sourceMemoryIds: data.sourceMemoryIds || [],
+ parentId: data.parentId,
+ owner: data.owner,
+ notBefore: data.notBefore,
+ dueAt: data.dueAt,
+ awaitingHuman: data.awaitingHuman,
+ approval: data.approval,
+ blockedReason: data.blockedReason,
+ repoRoot: data.repoRoot,
+ worktree: data.worktree,
+ branch: data.branch,
+ taskSlug: data.taskSlug,
+ };
+ const persisted = await persistActionUnlocked(kv, action, {
+ actor,
+ type: "created",
+ hasDerivedBlockers,
+ before: null,
});
-
+ let finalState = persisted.state;
for (const edge of pendingEdges) {
- await kv.set(KV.actionEdges, edge.id, edge);
+ const persistedEdge = await persistActionEdgeUnlocked(kv, edge, {
+ actor,
+ reason: "inline action dependency",
+ before: null,
+ });
+ finalState = persistedEdge.state;
}
-
- return { success: true, action, edges: pendingEdges };
+ await recordAudit(
+ kv,
+ "action_create",
+ "mem::action-create",
+ [persisted.action.id],
+ { actor, action: persisted.action, edges: pendingEdges },
+ );
+ return {
+ success: true,
+ action: persisted.action,
+ edges: pendingEdges,
+ revision: finalState.revision,
+ warnings: persisted.warnings,
+ };
});
- },
- );
+ } catch (error) {
+ return actionStoreError(error);
+ }
+ });
- sdk.registerFunction("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" };
- }
+ sdk.registerFunction("mem::action-update", async (data: ActionUpdateInput) => {
+ const validationError = validateUpdateInput(data);
+ if (validationError) return { success: false, error: validationError };
- return withKeyedLock(`mem:action:${data.actionId}`, async () => {
- const action = await kv.get(KV.actions, data.actionId);
- if (!action) {
- return { success: false, error: "action not found" };
- }
- const before = { ...action };
-
- 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;
+ try {
+ return await withActionStoreLock(async () => {
+ await recoverActionStoreUnlocked(kv);
+ const existing = await kv.get(KV.actions, data.actionId);
+ if (!existing) return { success: false, error: "action not found" };
+ const before = structuredClone(existing);
+ const edges = await kv.list(KV.actionEdges);
+ const hasDerivedBlockers = await hasUnsatisfiedDerivedBlockers(
+ kv,
+ existing.id,
+ edges,
+ );
+ const action = applyActionUpdate(existing, data, hasDerivedBlockers);
action.updatedAt = new Date().toISOString();
-
- await kv.set(KV.actions, action.id, action);
- await recordAudit(kv, "action_update", "mem::action-update", [action.id], {
- actor: data.assignedTo || "unknown",
+ const actor =
+ data.actor || data.assignedTo || data.owner || existing.owner || "unknown";
+ const persisted = await persistActionUnlocked(kv, action, {
+ actor,
+ reason: data.correctionReason,
+ correctionOf: data.correctionOf,
before,
- after: action,
+ hasDerivedBlockers,
});
-
- if (data.status === "done") {
- await propagateCompletion(kv, action.id);
+ await recordAudit(
+ kv,
+ "action_update",
+ "mem::action-update",
+ [action.id],
+ { actor, before, after: persisted.action },
+ );
+ if (persisted.action.lifecycle === "done") {
+ await propagateCompletionUnlocked(kv, persisted.action.id, actor);
}
-
- return { success: true, action };
+ const finalState = await recoverActionStoreUnlocked(kv);
+ return {
+ success: true,
+ action: persisted.action,
+ event: persisted.event,
+ revision: finalState.revision,
+ warnings: persisted.warnings,
+ };
});
- },
- );
+ } catch (error) {
+ return actionStoreError(error);
+ }
+ });
- sdk.registerFunction("mem::action-edge-create",
+ sdk.registerFunction(
+ "mem::action-edge-create",
async (data: {
sourceActionId: string;
targetActionId: string;
type: string;
metadata?: Record;
+ actor?: string;
}) => {
if (!data.sourceActionId || !data.targetActionId || !data.type) {
return {
@@ -159,141 +293,699 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
error: "sourceActionId, targetActionId, and type are required",
};
}
-
- const validTypes = [
- "requires",
- "unlocks",
- "spawned_by",
- "gated_by",
- "conflicts_with",
- ];
- if (!validTypes.includes(data.type)) {
+ if (!isValidEdgeType(data.type)) {
return {
success: false,
- error: `type must be one of: ${validTypes.join(", ")}`,
+ error: `type must be one of: ${VALID_EDGE_TYPES.join(", ")}`,
};
}
- const sourceAction = await kv.get(KV.actions, data.sourceActionId);
- if (!sourceAction) {
- return { success: false, error: "source action not found" };
- }
- const targetAction = await kv.get(KV.actions, data.targetActionId);
- if (!targetAction) {
- return { success: false, error: "target action not found" };
+ try {
+ return await withActionStoreLock(async () => {
+ await recoverActionStoreUnlocked(kv);
+ const sourceAction = await kv.get(
+ KV.actions,
+ data.sourceActionId,
+ );
+ if (!sourceAction) {
+ return { success: false, error: "source action not found" };
+ }
+ const targetExists =
+ data.type === "gated_by"
+ ? await actionGateExists(kv, data.targetActionId)
+ : Boolean(
+ await kv.get(KV.actions, data.targetActionId),
+ );
+ if (!targetExists) {
+ return {
+ success: false,
+ error:
+ data.type === "gated_by"
+ ? "gate not found"
+ : "target action not found",
+ };
+ }
+ const edge: ActionEdge = {
+ id: generateId("ae"),
+ type: data.type,
+ sourceActionId: data.sourceActionId,
+ targetActionId: data.targetActionId,
+ createdAt: new Date().toISOString(),
+ metadata: data.metadata,
+ };
+ const actor = data.actor || "unknown";
+ const persistedEdge = await persistActionEdgeUnlocked(kv, edge, {
+ actor,
+ before: null,
+ });
+ let finalState = persistedEdge.state;
+ if (edge.type === "requires" || edge.type === "gated_by") {
+ const before = structuredClone(sourceAction);
+ sourceAction.status = "blocked";
+ sourceAction.lifecycle = sourceAction.lifecycle ?? "pending";
+ sourceAction.updatedAt = new Date().toISOString();
+ const persistedSource = await persistActionUnlocked(kv, sourceAction, {
+ actor,
+ before,
+ hasDerivedBlockers: true,
+ reason: `${edge.type} edge added`,
+ });
+ finalState = persistedSource.state;
+ }
+ await recordAudit(
+ kv,
+ "action_create",
+ "mem::action-edge-create",
+ [edge.id],
+ { actor, edge },
+ );
+ return {
+ success: true,
+ edge,
+ event: persistedEdge.event,
+ revision: finalState.revision,
+ };
+ });
+ } catch (error) {
+ return actionStoreError(error);
}
+ },
+ );
- 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,
+ sdk.registerFunction("mem::action-list", async (data: ActionListOptions) => {
+ if (data.view !== undefined && !isActionReadinessView(data.view)) {
+ return {
+ success: false,
+ error: "view must be actionable, scheduled, waiting, blocked, completed, or cancelled",
};
+ }
+ if (
+ data.status !== undefined &&
+ !LEGACY_STATUSES.has(data.status as Action["status"])
+ ) {
+ return {
+ success: false,
+ error: "status must be pending, active, done, blocked, or cancelled",
+ };
+ }
+ try {
+ const [snapshot, checkpoints, sentinels, leases] = await Promise.all([
+ readActionStoreSnapshot(kv),
+ kv.list(KV.checkpoints).catch(() => []),
+ kv.list(KV.sentinels).catch(() => []),
+ kv.list(KV.leases).catch(() => []),
+ ]);
+ return selectActionPage(snapshot, checkpoints, sentinels, leases, data);
+ } catch (error) {
+ if (error instanceof ActionQueryError) {
+ return { success: false, error: error.code, message: error.message };
+ }
+ return actionStoreError(error);
+ }
+ });
- await kv.set(KV.actionEdges, edge.id, edge);
- await recordAudit(kv, "action_create", "mem::action-edge-create", [edge.id], {
- actor: "unknown",
- edge,
- });
- return { success: true, edge };
+ sdk.registerFunction(
+ "mem::action-graph-snapshot",
+ async (data: { limit?: number }) => {
+ const requestedLimit = data.limit ?? MAX_ACTION_GRAPH_ACTIONS;
+ if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
+ return {
+ success: false,
+ error: "limit must be a positive integer",
+ };
+ }
+
+ try {
+ const limit = Math.min(requestedLimit, MAX_ACTION_GRAPH_ACTIONS);
+ const snapshot = await readActionStoreSnapshot(kv);
+ const rankedActions = [...snapshot.actions].sort(compareGraphActions);
+ const selectedActions = rankedActions.slice(0, limit);
+ const selectedIds = new Set(selectedActions.map((action) => action.id));
+ const selectedEdges = snapshot.edges
+ .filter(
+ (edge) =>
+ selectedIds.has(edge.sourceActionId) &&
+ selectedIds.has(edge.targetActionId),
+ )
+ .sort(compareGraphEdges);
+
+ return {
+ success: true,
+ revision: snapshot.state.revision,
+ actions: selectedActions.map(projectActionForGraph),
+ actionEdges: selectedEdges.map(projectActionEdgeForGraph),
+ totalActions: snapshot.actions.length,
+ totalEdges: snapshot.edges.length,
+ limit,
+ truncatedActions: snapshot.actions.length - selectedActions.length,
+ truncatedEdges: snapshot.edges.length - selectedEdges.length,
+ eventsIncluded: false,
+ };
+ } catch (error) {
+ return actionStoreError(error);
+ }
},
);
- sdk.registerFunction("mem::action-list",
+ sdk.registerFunction("mem::action-get", async (data: { actionId: string }) => {
+ if (!data.actionId) {
+ return { success: false, error: "actionId is required" };
+ }
+ const snapshot = await readActionStoreSnapshot(kv, { includeEvents: true });
+ const action = snapshot.actions.find((candidate) => candidate.id === data.actionId);
+ if (!action) return { success: false, error: "action not found" };
+ const edges = snapshot.edges.filter(
+ (edge) =>
+ edge.sourceActionId === data.actionId ||
+ edge.targetActionId === data.actionId,
+ );
+ const children = snapshot.actions.filter(
+ (candidate) => candidate.parentId === data.actionId,
+ );
+ const events = snapshot.events
+ .filter((event) => event.actionId === data.actionId)
+ .sort(
+ (left, right) =>
+ left.revision - right.revision ||
+ left.timestamp.localeCompare(right.timestamp) ||
+ left.id.localeCompare(right.id),
+ );
+ return {
+ success: true,
+ action,
+ edges,
+ children,
+ events,
+ revision: snapshot.state.revision,
+ };
+ });
+
+ sdk.registerFunction(
+ "mem::action-gc",
async (data: {
- status?: string;
- project?: string;
- parentId?: string;
- tags?: string[];
+ maxAgeDays?: number;
+ dryRun?: boolean;
limit?: number;
+ actor?: string;
}) => {
- let actions = await kv.list(KV.actions);
-
- if (data.status) {
- actions = actions.filter((a) => a.status === data.status);
+ const maxAgeDays = data.maxAgeDays ?? 30;
+ const dryRun = data.dryRun ?? true;
+ const limit = data.limit ?? 500;
+ if (!Number.isFinite(maxAgeDays) || maxAgeDays < 0) {
+ return { success: false, error: "maxAgeDays must be a non-negative number" };
}
- if (data.project) {
- actions = actions.filter((a) => a.project === data.project);
+ if (typeof dryRun !== "boolean") {
+ return { success: false, error: "dryRun must be a boolean" };
}
- if (data.parentId) {
- actions = actions.filter((a) => a.parentId === data.parentId);
+ if (!Number.isInteger(limit) || limit < 1 || limit > 5000) {
+ return { success: false, error: "limit must be an integer between 1 and 5000" };
}
- if (data.tags && data.tags.length > 0) {
- actions = actions.filter((a) =>
- data.tags!.some((t) => a.tags.includes(t)),
+ try {
+ const cutoff = Date.now() - maxAgeDays * 86_400_000;
+ const snapshot = await readActionStoreSnapshot(kv);
+ const edgeEndpoints = new Set(
+ snapshot.edges.flatMap((edge) => [
+ edge.sourceActionId,
+ edge.targetActionId,
+ ]),
);
+ const isCollectable = (action: Action): boolean =>
+ (action.lifecycle === "done" || action.lifecycle === "cancelled") &&
+ Date.parse(action.updatedAt) < cutoff &&
+ !edgeEndpoints.has(action.id);
+ const candidates = snapshot.actions
+ .filter(isCollectable)
+ .sort((left, right) => left.updatedAt.localeCompare(right.updatedAt))
+ .slice(0, limit);
+ const actor = data.actor || "action-gc";
+ const deleted: string[] = [];
+ if (!dryRun) {
+ for (const candidate of candidates) {
+ const current = await kv.get(KV.actions, candidate.id);
+ if (!current || !isCollectable(current)) continue;
+ const result = await deleteAction(kv, candidate.id, {
+ actor,
+ reason: `terminal action older than ${maxAgeDays}d`,
+ });
+ if (result.deleted) deleted.push(candidate.id);
+ }
+ if (deleted.length > 0) {
+ await recordAudit(
+ kv,
+ "action_delete",
+ "mem::action-gc",
+ deleted,
+ { actor, maxAgeDays, dryRun: false, deleted: deleted.length },
+ );
+ }
+ }
+ return {
+ success: true,
+ dryRun,
+ maxAgeDays,
+ cutoff: new Date(cutoff).toISOString(),
+ candidates: candidates.map((action) => action.id),
+ deleted,
+ };
+ } catch (error) {
+ return actionStoreError(error);
}
+ },
+ );
+}
+
+async function propagateCompletionUnlocked(
+ kv: StateKV,
+ completedActionId: string,
+ actor: string,
+): Promise {
+ const allEdges = await kv.list(KV.actionEdges);
+ const candidates = new Set(
+ allEdges
+ .filter(
+ (edge) =>
+ edge.targetActionId === completedActionId &&
+ (edge.type === "requires" || edge.type === "unlocks"),
+ )
+ .map((edge) => edge.sourceActionId),
+ );
+ for (const candidateId of candidates) {
+ const action = await kv.get(KV.actions, candidateId);
+ if (!action || action.lifecycle === "done" || action.lifecycle === "cancelled") {
+ continue;
+ }
+ const lifecycle =
+ action.lifecycle ?? (action.status === "active" ? "active" : "pending");
+ if (lifecycle !== "pending") continue;
+ const stillBlocked = await hasUnsatisfiedDerivedBlockers(
+ kv,
+ action.id,
+ allEdges,
+ );
+ if (stillBlocked || action.blockedReason || action.awaitingHuman) continue;
+ const before = structuredClone(action);
+ action.status = "pending";
+ action.lifecycle = "pending";
+ action.updatedAt = new Date().toISOString();
+ await persistActionUnlocked(kv, action, {
+ actor,
+ before,
+ hasDerivedBlockers: false,
+ reason: `Dependency ${completedActionId} completed`,
+ });
+ }
+}
+
+export async function propagateActionCompletion(
+ kv: StateKV,
+ completedActionId: string,
+ actor: string,
+): Promise {
+ await withActionStoreLock(async () => {
+ await recoverActionStoreUnlocked(kv);
+ await propagateCompletionUnlocked(kv, completedActionId, actor);
+ });
+}
- actions.sort(
- (a, b) =>
- new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
+async function hasUnsatisfiedDerivedBlockers(
+ kv: StateKV,
+ actionId: string,
+ edges: ActionEdge[],
+): Promise {
+ const relevant = edges.filter(
+ (edge) =>
+ edge.sourceActionId === actionId &&
+ (edge.type === "requires" || edge.type === "gated_by"),
+ );
+ for (const edge of relevant) {
+ if (edge.type === "requires") {
+ const dependency = await kv.get(KV.actions, edge.targetActionId);
+ const lifecycle = dependency?.lifecycle ?? dependency?.status;
+ if (lifecycle !== "done") return true;
+ } else {
+ const checkpoint = await kv.get(
+ KV.checkpoints,
+ edge.targetActionId,
+ );
+ if (checkpoint?.status === "passed") continue;
+ const sentinel = await kv.get(
+ KV.sentinels,
+ edge.targetActionId,
);
+ if (sentinel?.status !== "triggered") return true;
+ }
+ }
+ return false;
+}
- const limit = data.limit || 50;
- return { success: true, actions: actions.slice(0, limit) };
- },
+async function actionGateExists(
+ kv: StateKV,
+ targetId: string,
+): Promise {
+ const [checkpoint, sentinel] = await Promise.all([
+ kv.get(KV.checkpoints, targetId),
+ kv.get(KV.sentinels, targetId),
+ ]);
+ return Boolean(checkpoint || sentinel);
+}
+
+/**
+ * True when an action is held blocked by something OTHER than its `requires`
+ * dependency edges: a manual `blockedReason`, `awaitingHuman`, a pending or
+ * rejected `approval`, or an unsatisfied `gated_by` checkpoint/sentinel.
+ *
+ * Used by diagnosis and heal so a "blocked but all dependencies done" finding
+ * is only treated as fixable when the dependencies are the SOLE blocker. An
+ * explicit gate means the block is intentional, and heal must not clear it:
+ * `normalizeActionV2` -> `legacyStatusFor` would immediately re-derive
+ * `status: "blocked"` from the surviving gate, so unblocking would only
+ * produce revision churn and a misleading "newStatus: pending" audit.
+ */
+export async function hasExplicitNonDependencyGate(
+ kv: StateKV,
+ action: Action,
+ edges: ActionEdge[],
+): Promise {
+ if (action.blockedReason) return true;
+ if (action.awaitingHuman) return true;
+ const approvalState = action.approval?.state;
+ if (approvalState === "pending" || approvalState === "rejected") return true;
+ const gates = edges.filter(
+ (edge) => edge.sourceActionId === action.id && edge.type === "gated_by",
);
+ for (const edge of gates) {
+ const checkpoint = await kv.get(
+ KV.checkpoints,
+ edge.targetActionId,
+ );
+ if (checkpoint?.status === "passed") continue;
+ const sentinel = await kv.get(KV.sentinels, edge.targetActionId);
+ if (sentinel?.status !== "triggered") return true;
+ }
+ return false;
+}
- sdk.registerFunction("mem::action-get",
- async (data: { actionId: string }) => {
- if (!data.actionId) {
- return { success: false, error: "actionId is required" };
+function applyActionUpdate(
+ action: Action,
+ data: ActionUpdateInput,
+ hasDerivedBlockers: boolean,
+): Action {
+ const updated = { ...action };
+ if (data.title !== undefined) updated.title = data.title.trim();
+ if (data.description !== undefined) {
+ updated.description = data.description.trim();
+ }
+ if (data.priority !== undefined) updated.priority = normalizePriority(data.priority);
+ if (data.assignedTo !== undefined) updated.assignedTo = data.assignedTo || undefined;
+ if (data.owner !== undefined) updated.owner = data.owner || undefined;
+ if (data.result !== undefined) updated.result = data.result;
+ if (data.tags !== undefined) updated.tags = normalizeActionTags(data.tags);
+ if (data.project !== undefined) {
+ const previousProject = updated.projectId || updated.project;
+ updated.project = data.project;
+ if (data.projectId === undefined) {
+ updated.projectId = undefined;
+ updated.projectAliases = normalizeActionTags([
+ ...(updated.projectAliases ?? []),
+ ...(previousProject ? [previousProject] : []),
+ ]);
+ }
+ }
+ if (data.projectId !== undefined) updated.projectId = data.projectId;
+ if (data.projectAliases !== undefined) {
+ updated.projectAliases = normalizeActionTags(data.projectAliases);
+ }
+ if (data.notBefore !== undefined) updated.notBefore = data.notBefore || undefined;
+ if (data.dueAt !== undefined) updated.dueAt = data.dueAt || undefined;
+ if (data.awaitingHuman !== undefined) updated.awaitingHuman = data.awaitingHuman;
+ if (data.approval !== undefined) updated.approval = data.approval;
+ if (data.blockedReason !== undefined) {
+ updated.blockedReason = data.blockedReason || undefined;
+ }
+ if (data.repoRoot !== undefined) updated.repoRoot = data.repoRoot || undefined;
+ if (data.worktree !== undefined) updated.worktree = data.worktree || undefined;
+ if (data.branch !== undefined) updated.branch = data.branch || undefined;
+ if (data.taskSlug !== undefined) updated.taskSlug = data.taskSlug || undefined;
+
+ if (data.status !== undefined) {
+ updated.status = data.status;
+ if (data.status === "blocked") {
+ updated.lifecycle = "pending";
+ updated.blockedReason =
+ data.blockedReason ||
+ data.result ||
+ updated.blockedReason ||
+ (hasDerivedBlockers ? undefined : "Blocked by legacy status update");
+ } else {
+ updated.lifecycle = data.status;
+ if (data.status === "pending") updated.blockedReason = undefined;
+ }
+ }
+ if (data.lifecycle !== undefined) {
+ updated.lifecycle = data.lifecycle;
+ if (data.lifecycle !== "pending") updated.status = data.lifecycle;
+ }
+ return updated;
+}
+
+function validateCreateInput(data: ActionCreateInput): string | undefined {
+ if (!data?.title || typeof data.title !== "string" || !data.title.trim()) {
+ return "title is required";
+ }
+ if (data.description !== undefined && typeof data.description !== "string") {
+ return "description must be a string";
+ }
+ for (const [field, value] of [
+ ["sourceObservationIds", data.sourceObservationIds],
+ ["sourceMemoryIds", data.sourceMemoryIds],
+ ] as const) {
+ if (
+ value !== undefined &&
+ (!Array.isArray(value) ||
+ value.some((item) => typeof item !== "string"))
+ ) {
+ return `${field} must be an array of strings`;
+ }
+ }
+ if (
+ data.edges !== undefined &&
+ (!Array.isArray(data.edges) ||
+ data.edges.some(
+ (edge) =>
+ !edge ||
+ typeof edge !== "object" ||
+ typeof edge.type !== "string" ||
+ typeof edge.targetActionId !== "string",
+ ))
+ ) {
+ return "edges must contain type and targetActionId strings";
+ }
+ return validateSharedInput(data);
+}
+
+function validateUpdateInput(data: ActionUpdateInput): string | undefined {
+ if (!data?.actionId || typeof data.actionId !== "string") {
+ return "actionId is required";
+ }
+ if (data.status !== undefined && !LEGACY_STATUSES.has(data.status)) {
+ return "status must be pending, active, done, blocked, or cancelled";
+ }
+ if (
+ data.title !== undefined &&
+ (typeof data.title !== "string" || !data.title.trim())
+ ) {
+ return "title must be a non-empty string";
+ }
+ if (data.description !== undefined && typeof data.description !== "string") {
+ return "description must be a string";
+ }
+ return validateSharedInput(data);
+}
+
+function validateSharedInput(
+ data: Partial,
+): string | undefined {
+ if (
+ data.priority !== undefined &&
+ (typeof data.priority !== "number" || !Number.isFinite(data.priority))
+ ) {
+ return "priority must be a finite number";
+ }
+ if (data.lifecycle !== undefined && !isActionLifecycle(data.lifecycle)) {
+ return "lifecycle must be pending, active, done, or cancelled";
+ }
+ if (data.projectId !== undefined && !isCanonicalProjectId(data.projectId)) {
+ return "projectId must be a canonical non-path identifier";
+ }
+ if (
+ data.project !== undefined &&
+ (typeof data.project !== "string" || !data.project.trim())
+ ) {
+ return "project must be a non-empty string";
+ }
+ if (
+ data.projectAliases !== undefined &&
+ (!Array.isArray(data.projectAliases) ||
+ data.projectAliases.some((alias) => typeof alias !== "string"))
+ ) {
+ return "projectAliases must be an array of strings";
+ }
+ if (
+ data.tags !== undefined &&
+ typeof data.tags !== "string" &&
+ (!Array.isArray(data.tags) ||
+ data.tags.some((tag) => typeof tag !== "string"))
+ ) {
+ return "tags must be a string or an array of strings";
+ }
+ if (
+ data.awaitingHuman !== undefined &&
+ typeof data.awaitingHuman !== "boolean"
+ ) {
+ return "awaitingHuman must be boolean";
+ }
+ for (const [field, value] of [
+ ["createdBy", data.createdBy],
+ ["actor", data.actor],
+ ["parentId", data.parentId],
+ ["owner", data.owner],
+ ["assignedTo", data.assignedTo],
+ ["result", data.result],
+ ["blockedReason", data.blockedReason],
+ ["repoRoot", data.repoRoot],
+ ["worktree", data.worktree],
+ ["branch", data.branch],
+ ["taskSlug", data.taskSlug],
+ ["correctionOf", data.correctionOf],
+ ["correctionReason", data.correctionReason],
+ ] as const) {
+ if (value !== undefined && typeof value !== "string") {
+ return `${field} must be a string`;
+ }
+ }
+ if (data.notBefore && !isValidActionTimestamp(data.notBefore)) {
+ return "notBefore must be a valid timestamp";
+ }
+ if (data.dueAt && !isValidActionTimestamp(data.dueAt)) {
+ return "dueAt must be a valid timestamp";
+ }
+ if (
+ data.approval !== undefined &&
+ (!data.approval || !isActionApprovalState(data.approval.state))
+ ) {
+ return "approval.state is invalid";
+ }
+ if (data.approval) {
+ for (const field of ["requestedAt", "decidedAt"] as const) {
+ const timestamp = data.approval[field];
+ if (timestamp !== undefined && !isValidActionTimestamp(timestamp)) {
+ return `approval.${field} must be a valid timestamp`;
}
- const action = await kv.get(KV.actions, data.actionId);
- if (!action) {
- return { success: false, error: "action not found" };
+ }
+ for (const field of ["requestedBy", "decidedBy", "note"] as const) {
+ const value = data.approval[field];
+ if (value !== undefined && typeof value !== "string") {
+ return `approval.${field} must be a string`;
}
+ }
+ }
+ return undefined;
+}
- const allEdges = await kv.list(KV.actionEdges);
- const edges = allEdges.filter(
- (e) =>
- e.sourceActionId === data.actionId ||
- e.targetActionId === data.actionId,
- );
+function normalizePriority(value?: number): number {
+ return Math.max(1, Math.min(10, value || 5));
+}
- const children = (await kv.list(KV.actions)).filter(
- (a) => a.parentId === data.actionId,
- );
+function isValidEdgeType(value: string): value is ActionEdge["type"] {
+ return VALID_EDGE_TYPES.includes(value as ActionEdge["type"]);
+}
- return { success: true, action, edges, children };
- },
+function compareGraphActions(left: Action, right: Action): number {
+ const leftTerminal =
+ left.lifecycle === "done" ||
+ left.lifecycle === "cancelled" ||
+ left.status === "done" ||
+ left.status === "cancelled";
+ const rightTerminal =
+ right.lifecycle === "done" ||
+ right.lifecycle === "cancelled" ||
+ right.status === "done" ||
+ right.status === "cancelled";
+ return (
+ Number(leftTerminal) - Number(rightTerminal) ||
+ (right.priority ?? 0) - (left.priority ?? 0) ||
+ timestampMs(right.updatedAt) - timestampMs(left.updatedAt) ||
+ left.id.localeCompare(right.id)
);
}
-async function propagateCompletion(
- kv: StateKV,
- completedActionId: string,
-): Promise {
- const allEdges = await kv.list(KV.actionEdges);
- const unlockEdges = allEdges.filter(
- (e) =>
- e.targetActionId === completedActionId &&
- (e.type === "requires" || e.type === "unlocks"),
+function compareGraphEdges(left: ActionEdge, right: ActionEdge): number {
+ return (
+ left.sourceActionId.localeCompare(right.sourceActionId) ||
+ left.targetActionId.localeCompare(right.targetActionId) ||
+ left.type.localeCompare(right.type) ||
+ left.id.localeCompare(right.id)
);
+}
- const allActions = await kv.list(KV.actions);
- const actionMap = new Map(allActions.map((a) => [a.id, a]));
+function projectActionForGraph(action: Action) {
+ return {
+ id: action.id,
+ title: action.title,
+ status: action.status,
+ lifecycle: action.lifecycle,
+ project: action.project,
+ projectId: action.projectId,
+ parentId: action.parentId,
+ owner: action.owner,
+ assignedTo: action.assignedTo,
+ priority: action.priority,
+ tags: action.tags,
+ blockedReason: action.blockedReason,
+ repoRoot: action.repoRoot,
+ worktree: action.worktree,
+ branch: action.branch,
+ taskSlug: action.taskSlug,
+ updatedAt: action.updatedAt,
+ };
+}
- for (const edge of unlockEdges) {
- const candidateId = edge.sourceActionId;
- await withKeyedLock(`mem:action:${candidateId}`, async () => {
- const action = await kv.get(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);
- }
- }
- });
+function projectActionEdgeForGraph(edge: ActionEdge) {
+ return {
+ id: edge.id,
+ type: edge.type,
+ sourceActionId: edge.sourceActionId,
+ targetActionId: edge.targetActionId,
+ createdAt: edge.createdAt,
+ };
+}
+
+function timestampMs(value: string | undefined): number {
+ const parsed = Date.parse(value ?? "");
+ return Number.isFinite(parsed) ? parsed : 0;
+}
+
+function actionStoreError(error: unknown) {
+ if (error instanceof ActionRevisionConflictError) {
+ return {
+ success: false,
+ error: "action_revision_conflict",
+ actionId: error.actionId,
+ fields: error.fields,
+ message: error.message,
+ };
}
+ if (error instanceof ActionNormalizationError) {
+ return {
+ success: false,
+ error: "action normalization failed",
+ conflicts: error.conflicts,
+ };
+ }
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
}
+
+export type { ActionListOptions, ActionReadinessView };
diff --git a/src/functions/audit.ts b/src/functions/audit.ts
index 1e75b4b7d2..7a88f46096 100644
--- a/src/functions/audit.ts
+++ b/src/functions/audit.ts
@@ -1,7 +1,12 @@
-import type { AuditEntry } from "../types.js";
+import type { AuditEntry, Lesson } from "../types.js";
import { KV, generateId } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
import { logger } from "../logger.js";
+import {
+ buildLessonAccessIndex,
+ canReadLesson,
+ lessonAccessContextFromPayload,
+} from "./lesson-access.js";
// Audit coverage policy (issue #125).
//
@@ -84,6 +89,7 @@ export async function queryAudit(
dateFrom?: string;
dateTo?: string;
limit?: number;
+ accessContext?: unknown;
},
): Promise {
const all = await kv.list(KV.audit);
@@ -109,5 +115,121 @@ export async function queryAudit(
entries = entries.filter((e) => new Date(e.timestamp).getTime() <= to);
}
+ const accessContext = lessonAccessContextFromPayload(
+ filter?.accessContext,
+ );
+ if (accessContext.mode === "enforce") {
+ const ordinaryEntries = entries.filter(
+ (entry) => !isLessonRelatedAuditEntry(entry),
+ );
+ const lessonEntries = entries.filter(isLessonRelatedAuditEntry);
+ if (lessonEntries.length > 0) {
+ try {
+ const lessons = await kv.list(KV.lessons);
+ const lessonIndex = buildLessonAccessIndex(lessons);
+ const readableLessonEntries = lessonEntries.filter((entry) => {
+ const referencedIds = lessonAuditReferenceIds(entry);
+ if (referencedIds.length === 0) return false;
+ try {
+ return referencedIds.every((id) => {
+ const lesson = lessonIndex.get(id);
+ return lesson !== undefined &&
+ canReadLesson(lesson, accessContext);
+ });
+ } catch {
+ return false;
+ }
+ });
+ const readableEntries = new Set(readableLessonEntries);
+ entries = entries.filter(
+ (entry) =>
+ !isLessonRelatedAuditEntry(entry) ||
+ readableEntries.has(entry),
+ );
+ } catch {
+ // An unavailable or malformed authoritative lesson index cannot prove
+ // any lesson audit row is readable. Preserve unrelated audit rows.
+ entries = ordinaryEntries;
+ }
+ }
+ }
+
return entries.slice(0, filter?.limit || 100);
}
+
+function lessonAuditReferenceIds(entry: AuditEntry): string[] {
+ const ids = new Set();
+ const add = (value: unknown): void => {
+ if (typeof value === "string" && value.length > 0) ids.add(value);
+ };
+ if (Array.isArray(entry.targetIds)) {
+ for (const id of entry.targetIds) add(id);
+ }
+
+ const details =
+ entry.details && typeof entry.details === "object"
+ ? entry.details
+ : undefined;
+ if (!details) return [...ids];
+
+ add(details.lessonId);
+ add(details.replacementLessonId);
+ for (const field of ["lessonIds", "sourceLessonIds"] as const) {
+ const values = details[field];
+ if (Array.isArray(values)) {
+ for (const value of values) add(value);
+ }
+ }
+ for (const field of ["canonicalizedIds", "lifecycleTransitions"] as const) {
+ const values = details[field];
+ if (!Array.isArray(values)) continue;
+ for (const value of values) {
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ add((value as Record).lessonId);
+ }
+ }
+ }
+ return [...ids];
+}
+
+const LESSON_AUDIT_OPERATIONS = new Set([
+ "lesson_save",
+ "lesson_recall",
+ "lesson_strengthen",
+ "lesson_delete",
+ "lesson_supersede",
+]);
+
+function isLessonRelatedAuditEntry(entry: AuditEntry): boolean {
+ if (LESSON_AUDIT_OPERATIONS.has(entry.operation)) return true;
+ if (
+ typeof entry.functionId === "string" &&
+ (entry.functionId.startsWith("mem::lesson-") ||
+ entry.functionId.startsWith("mem::import:lessons"))
+ ) {
+ return true;
+ }
+
+ const details =
+ entry.details && typeof entry.details === "object"
+ ? entry.details
+ : undefined;
+ if (!details) return false;
+ if (
+ "lessonId" in details ||
+ "lessonIds" in details ||
+ "sourceLessonIds" in details ||
+ "canonicalizedIds" in details ||
+ "lifecycleTransitions" in details
+ ) {
+ return true;
+ }
+ const stats = details.stats;
+ return Boolean(
+ stats &&
+ typeof stats === "object" &&
+ "lessons" in stats &&
+ typeof (stats as Record).lessons === "number" &&
+ (stats as Record).lessons > 0,
+ );
+}
diff --git a/src/functions/checkpoints.ts b/src/functions/checkpoints.ts
index efb3957a9c..c25d5ecf98 100644
--- a/src/functions/checkpoints.ts
+++ b/src/functions/checkpoints.ts
@@ -4,6 +4,8 @@ import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, ActionEdge, Checkpoint } from "../types.js";
import { recordAudit } from "./audit.js";
+import { persistAction, persistActionEdge } from "./action-store.js";
+import { refreshLinkedActionReadiness } from "./action-readiness-refresh.js";
export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::checkpoint-create",
@@ -62,14 +64,25 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
targetActionId: checkpoint.id,
createdAt: now.toISOString(),
};
- await kv.set(KV.actionEdges, edge.id, edge);
+ await persistActionEdge(kv, edge, {
+ actor: "checkpoint-create",
+ reason: `Checkpoint ${checkpoint.id} added`,
+ before: null,
+ });
const action = await kv.get(KV.actions, actionId);
if (action && action.status === "pending") {
const previousStatus = action.status;
+ const before = structuredClone(action);
action.status = "blocked";
+ action.lifecycle = "pending";
action.updatedAt = now.toISOString();
- await kv.set(KV.actions, action.id, action);
+ await persistAction(kv, action, {
+ actor: "checkpoint-create",
+ before,
+ hasDerivedBlockers: true,
+ reason: `Waiting for checkpoint ${checkpoint.id}`,
+ });
await recordAudit(kv, "action_update", "mem::checkpoint-create", [action.id], {
action: "status-change",
previousStatus,
@@ -128,49 +141,12 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
newStatus: checkpoint.status,
});
- let unblockedCount = 0;
- if (data.status === "passed" && checkpoint.linkedActionIds.length > 0) {
- const allEdges = await kv.list(KV.actionEdges);
- const allCheckpoints = await kv.list(KV.checkpoints);
- const allActions = await kv.list(KV.actions);
- const cpMap = new Map(allCheckpoints.map((c) => [c.id, c]));
- const actionMap = new Map(allActions.map((a) => [a.id, a]));
-
- for (const actionId of checkpoint.linkedActionIds) {
- await withKeyedLock(`mem:action:${actionId}`, async () => {
- const action = await kv.get(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 allRequiresMet = requires.every((r) => {
- const dep = actionMap.get(r.targetActionId);
- return dep && dep.status === "done";
- });
- if (allGatesPassed && allRequiresMet) {
- const previousStatus = action.status;
- action.status = "pending";
- action.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, action.id, action);
- await recordAudit(kv, "action_update", "mem::checkpoint-resolve", [action.id], {
- action: "unblock",
- checkpointId: checkpoint.id,
- previousStatus,
- newStatus: action.status,
- });
- unblockedCount++;
- }
- }
- });
- }
- }
+ const unblockedCount = await refreshLinkedActionReadiness(
+ kv,
+ checkpoint.linkedActionIds,
+ data.resolvedBy || "checkpoint-resolve",
+ `Checkpoint ${checkpoint.id} resolved ${checkpoint.status}`,
+ );
return { success: true, checkpoint, unblockedCount };
},
diff --git a/src/functions/compress-file.ts b/src/functions/compress-file.ts
index 0a54452b23..d473ffeb32 100644
--- a/src/functions/compress-file.ts
+++ b/src/functions/compress-file.ts
@@ -30,7 +30,10 @@ function stripMarkdownFence(text: string): string {
}
function extractUrls(text: string): string[] {
- return Array.from(new Set(text.match(/https?:\/\/[^\s)]+/g) || []));
+ const urls = text.match(/https?:\/\/[^\s)]+/g) || [];
+ return Array.from(
+ new Set(urls.map((url) => url.replace(/[.,;:!]+$/, ""))),
+ );
}
function extractHeadings(text: string): string[] {
diff --git a/src/functions/compress.ts b/src/functions/compress.ts
index 0569555e06..1350b28d20 100644
--- a/src/functions/compress.ts
+++ b/src/functions/compress.ts
@@ -1,4 +1,4 @@
-import { TriggerAction, type ISdk } from "iii-sdk";
+import type { ISdk } from "iii-sdk";
import { readFileSync } from "node:fs";
import { isManagedImagePath } from "../utils/image-store.js";
import type {
@@ -22,6 +22,7 @@ import { scoreCompression } from "../eval/quality.js";
import { compressWithRetry } from "../eval/self-correct.js";
import type { MetricsStore } from "../eval/metrics-store.js";
import { logger } from "../logger.js";
+import { getLlmExecutionState } from "../config.js";
const VALID_TYPES = new Set([
"file_read",
@@ -77,6 +78,32 @@ export function registerCompressFunction(
raw: RawObservation;
}) => {
const startMs = Date.now();
+ const llmExecutionState = getLlmExecutionState(provider);
+ if (llmExecutionState !== "enabled") {
+ const skipped =
+ llmExecutionState === "disabled"
+ ? "llm_tools_disabled"
+ : "no_llm_provider";
+ if (metricsStore) {
+ await metricsStore.recordSkipped(
+ "mem::compress",
+ Date.now() - startMs,
+ skipped,
+ );
+ }
+ logger.info("Compression skipped", {
+ observationId: data.observationId,
+ skipped,
+ });
+ return {
+ success: true,
+ outcome:
+ llmExecutionState === "disabled"
+ ? "skipped_disabled"
+ : "skipped_unavailable",
+ skipped,
+ };
+ }
let imageDescription: string | undefined;
const hasImage = data.raw.modality === "image" || data.raw.modality === "mixed";
@@ -215,7 +242,6 @@ export function registerCompressFunction(
sessionId: data.sessionId,
},
},
- action: TriggerAction.Void(),
}),
]);
for (const result of streamResults) {
diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.ts
index e51ab97c86..d246af3523 100644
--- a/src/functions/consolidation-pipeline.ts
+++ b/src/functions/consolidation-pipeline.ts
@@ -17,6 +17,10 @@ import {
import { recordAudit } from "./audit.js";
import { getConsolidationDecayDays, isConsolidationEnabled } from "../config.js";
import { logger } from "../logger.js";
+import {
+ lessonAccessContextFromPayload,
+ type LessonAccessContext,
+} from "./lesson-access.js";
function applyDecay(
items: Array<{
@@ -48,11 +52,19 @@ export function registerConsolidationPipelineFunction(
provider: MemoryProvider,
): void {
sdk.registerFunction("mem::consolidate-pipeline",
- async (data?: { tier?: string; force?: boolean; project?: string }) => {
+ async (data?: {
+ tier?: string;
+ force?: boolean;
+ project?: string;
+ accessContext?: LessonAccessContext;
+ }) => {
if (!data?.force && !isConsolidationEnabled()) {
return { success: false, skipped: true, reason: "Consolidation disabled: set CONSOLIDATION_ENABLED=true or configure an LLM provider (ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / GEMINI_API_KEY / GOOGLE_API_KEY / MINIMAX_API_KEY / OPENAI_BASE_URL / AGENTMEMORY_PROVIDER=agent-sdk)" };
}
const tier = data?.tier || "all";
+ const accessContext = lessonAccessContextFromPayload(
+ data?.accessContext,
+ );
const decayDays = getConsolidationDecayDays();
const results: Record = {};
@@ -138,6 +150,7 @@ export function registerConsolidationPipelineFunction(
const reflectResult = await sdk.trigger({ function_id: "mem::reflect", payload: {
maxClusters: 10,
project: data?.project,
+ accessContext,
} });
results.reflect = reflectResult;
} catch (err) {
@@ -249,7 +262,10 @@ export function registerConsolidationPipelineFunction(
if (process.env["OBSIDIAN_AUTO_EXPORT"] === "true") {
try {
- await sdk.trigger({ function_id: "mem::obsidian-export", payload: {} });
+ await sdk.trigger({
+ function_id: "mem::obsidian-export",
+ payload: { accessContext },
+ });
results.obsidianExport = { success: true };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/src/functions/context.ts b/src/functions/context.ts
index 1e6102cf37..aee2c7fd55 100644
--- a/src/functions/context.ts
+++ b/src/functions/context.ts
@@ -17,6 +17,15 @@ import {
listPinnedSlots,
renderPinnedContext,
} from "./slots.js";
+import {
+ isLessonRecallable,
+ toLessonReadModel,
+} from "./lesson-model.js";
+import {
+ canReadLesson,
+ lessonAccessContextFromPayload,
+ type LessonAccessContext,
+} from "./lesson-access.js";
function estimateTokens(text: string): number {
return Math.ceil(text.length / 3);
@@ -36,9 +45,15 @@ export function registerContextFunction(
tokenBudget: number,
): void {
sdk.registerFunction("mem::context",
- async (data: { sessionId: string; project: string; budget?: number }) => {
+ async (data: {
+ sessionId: string;
+ project: string;
+ budget?: number;
+ accessContext?: LessonAccessContext;
+ }) => {
const budget = data.budget || tokenBudget;
const blocks: ContextBlock[] = [];
+ const accessContext = lessonAccessContextFromPayload(data.accessContext);
const [pinnedSlots, profile, lessons] = await Promise.all([
isSlotsEnabled()
@@ -103,7 +118,13 @@ export function registerContextFunction(
// 10 to keep the block bounded since the outer token-budget loop
// below will drop the whole block if it doesn't fit. #457.
const relevantLessons = lessons
- .filter((l) => !l.deleted && (!l.project || l.project === data.project))
+ .filter(
+ (lesson) =>
+ isLessonRecallable(lesson) &&
+ canReadLesson(lesson, accessContext) &&
+ (!lesson.project || lesson.project === data.project),
+ )
+ .map((lesson) => toLessonReadModel(lesson))
.sort((a, b) => {
const scoreA = (a.project === data.project ? 1.5 : 1) * a.confidence;
const scoreB = (b.project === data.project ? 1.5 : 1) * b.confidence;
@@ -113,10 +134,11 @@ export function registerContextFunction(
if (relevantLessons.length > 0) {
const items = relevantLessons
- .map(
- (l) =>
- `- (${l.confidence.toFixed(2)}) ${l.content}${l.context ? ` — ${l.context}` : ""}`,
- )
+ .map((lesson) => {
+ const claim = lesson.claim ? `${lesson.claim} — ` : "";
+ const context = lesson.context ? ` — ${lesson.context}` : "";
+ return `- [verdict:${lesson.evidenceVerdict}] (${lesson.confidence.toFixed(2)}) ${claim}${lesson.content}${context}`;
+ })
.join("\n");
const lessonsContent = `## Lessons Learned\n${items}`;
const mostRecent = relevantLessons.reduce((acc, l) => {
diff --git a/src/functions/crystallize.ts b/src/functions/crystallize.ts
index 1f0b84316d..bcde792870 100644
--- a/src/functions/crystallize.ts
+++ b/src/functions/crystallize.ts
@@ -1,7 +1,20 @@
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";
+import type {
+ Action,
+ ActionEdge,
+ Crystal,
+ Lesson,
+ MemoryProvider,
+} from "../types.js";
+import { persistAction } from "./action-store.js";
+import {
+ buildLessonAccessIndex,
+ canReadCrystal,
+ lessonAccessContextFromPayload,
+ type LessonAccessContext,
+} from "./lesson-access.js";
interface CrystalDigest {
narrative: string;
@@ -25,6 +38,7 @@ export function registerCrystallizeFunction(
actionIds: string[];
sessionId?: string;
project?: string;
+ accessContext?: LessonAccessContext;
}) => {
if (!data.actionIds || data.actionIds.length === 0) {
return { success: false, error: "actionIds is required" };
@@ -52,17 +66,52 @@ export function registerCrystallizeFunction(
);
const prompt = buildChainText(actions, relevantEdges);
+ const accessContext = lessonAccessContextFromPayload(
+ data.accessContext,
+ );
try {
const response = await provider.summarize(CRYSTALLIZE_SYSTEM, prompt);
const digest = parseDigest(response);
+ const crystalId = generateId("crys");
+ const persistedLessons: string[] = [];
+ const sourceLessonIds: string[] = [];
+
+ for (const lesson of digest.lessons) {
+ try {
+ const result = (await sdk.trigger({
+ function_id: "mem::lesson-save",
+ payload: {
+ content: lesson,
+ context: digest.narrative,
+ confidence: 0.6,
+ project: data.project,
+ tags: [],
+ source: "crystal",
+ sourceIds: [crystalId],
+ accessContext,
+ },
+ })) as {
+ success?: boolean;
+ lesson?: { id?: string };
+ };
+ if (result.success && typeof result.lesson?.id === "string") {
+ persistedLessons.push(lesson);
+ sourceLessonIds.push(result.lesson.id);
+ }
+ } catch {}
+ }
const crystal: Crystal = {
- id: generateId("crys"),
+ id: crystalId,
narrative: digest.narrative,
keyOutcomes: digest.keyOutcomes,
filesAffected: digest.filesAffected,
- lessons: digest.lessons,
+ lessons:
+ accessContext.mode === "classify"
+ ? digest.lessons
+ : persistedLessons,
+ sourceLessonIds,
sourceActionIds: data.actionIds,
sessionId: data.sessionId,
project: data.project,
@@ -71,28 +120,13 @@ export function registerCrystallizeFunction(
await kv.set(KV.crystals, crystal.id, crystal);
- await Promise.all(
- digest.lessons.map((lesson) =>
- sdk
- .trigger({
- function_id: "mem::lesson-save",
- payload: {
- content: lesson,
- context: crystal.narrative,
- confidence: 0.6,
- project: data.project,
- tags: [],
- source: "crystal",
- sourceIds: [crystal.id],
- },
- })
- .catch(() => {}),
- ),
- );
-
for (const action of actions) {
const updated = { ...action, crystallizedInto: crystal.id };
- await kv.set(KV.actions, action.id, updated);
+ await persistAction(kv, updated, {
+ actor: "crystallize",
+ before: action,
+ reason: `Crystallized into ${crystal.id}`,
+ });
}
return { success: true, crystal };
@@ -110,9 +144,30 @@ export function registerCrystallizeFunction(
project?: string;
sessionId?: string;
limit?: number;
+ accessContext?: LessonAccessContext;
}) => {
const limit = data.limit ?? 20;
+ const accessContext = lessonAccessContextFromPayload(
+ data.accessContext,
+ );
let crystals = await kv.list(KV.crystals);
+ if (accessContext.mode === "enforce") {
+ try {
+ const lessonIndex = buildLessonAccessIndex(
+ await kv.list(KV.lessons),
+ );
+ crystals = crystals.filter((crystal) =>
+ canReadCrystal(crystal, lessonIndex, accessContext),
+ );
+ } catch {
+ return {
+ success: false,
+ code: "lesson_state_unavailable",
+ error: "crystal access is unavailable",
+ crystals: [],
+ };
+ }
+ }
if (data.project) {
crystals = crystals.filter((c) => c.project === data.project);
@@ -131,7 +186,10 @@ export function registerCrystallizeFunction(
);
sdk.registerFunction("mem::crystal-get",
- async (data: { crystalId: string }) => {
+ async (data: {
+ crystalId: string;
+ accessContext?: LessonAccessContext;
+ }) => {
if (!data.crystalId) {
return { success: false, error: "crystalId is required" };
}
@@ -140,6 +198,25 @@ export function registerCrystallizeFunction(
if (!crystal) {
return { success: false, error: "crystal not found" };
}
+ const accessContext = lessonAccessContextFromPayload(
+ data.accessContext,
+ );
+ if (accessContext.mode === "enforce") {
+ try {
+ const lessonIndex = buildLessonAccessIndex(
+ await kv.list(KV.lessons),
+ );
+ if (!canReadCrystal(crystal, lessonIndex, accessContext)) {
+ return { success: false, error: "crystal not found" };
+ }
+ } catch {
+ return {
+ success: false,
+ code: "lesson_state_unavailable",
+ error: "crystal access is unavailable",
+ };
+ }
+ }
return { success: true, crystal };
},
@@ -150,6 +227,7 @@ export function registerCrystallizeFunction(
olderThanDays?: number;
project?: string;
dryRun?: boolean;
+ accessContext?: LessonAccessContext;
}) => {
const olderThanDays = data.olderThanDays ?? 7;
const dryRun = data.dryRun ?? false;
@@ -209,6 +287,7 @@ export function registerCrystallizeFunction(
const result = (await sdk.trigger({ function_id: "mem::crystallize", payload: {
actionIds,
project,
+ accessContext: data.accessContext,
} })) as { success: boolean; crystal?: Crystal };
if (result.success && result.crystal) {
diff --git a/src/functions/diagnostics.ts b/src/functions/diagnostics.ts
index cc982883f6..a707c76504 100644
--- a/src/functions/diagnostics.ts
+++ b/src/functions/diagnostics.ts
@@ -3,6 +3,18 @@ import type { StateKV } from "../state/kv.js";
import { KV } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import { recordAudit } from "./audit.js";
+import {
+ deleteAction,
+ deleteActionEdge,
+ persistAction,
+} from "./action-store.js";
+import { hasExplicitNonDependencyGate } from "./actions.js";
+import { stripMemoryReferences } from "../state/memory-utils.js";
+import { isLessonListable } from "./lesson-model.js";
+import {
+ canReadLesson,
+ lessonAccessContextFromPayload,
+} from "./lesson-access.js";
import type {
Action,
ActionEdge,
@@ -45,7 +57,7 @@ const ONE_HOUR_MS = 60 * 60 * 1000;
export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::diagnose",
- async (data: { categories?: string[] }) => {
+ async (data: { categories?: string[]; accessContext?: unknown }) => {
const categories = data.categories && data.categories.length > 0
? data.categories.filter((c) => ALL_CATEGORIES.includes(c))
: ALL_CATEGORIES;
@@ -88,13 +100,26 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
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,
- });
+ // Only a dependency-only block is a fixable defect. An explicit
+ // non-dependency gate (blockedReason / awaitingHuman /
+ // pending-or-rejected approval / unsatisfied gated_by) means the
+ // block is intentional — flagging it as "deps done, should
+ // unblock" is a false positive (heal cannot clear the gate;
+ // legacyStatusFor would revert the unblock).
+ const hasExplicitGate = await hasExplicitNonDependencyGate(
+ kv,
+ action,
+ allEdges,
+ );
+ if (!hasExplicitGate) {
+ 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,
+ });
+ }
}
}
}
@@ -333,13 +358,44 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
category: "memories",
status: "warn",
message: `Memory "${memory.title}" supersedes non-existent memory ${sid}`,
- fixable: false,
+ // Fixable via mem::heal {categories:["memories"]}, which now
+ // prunes dangling supersedes/parentId/relatedIds references.
+ fixable: true,
});
memoryIssues++;
}
supersededBy.set(sid, memory.id);
}
}
+
+ // parentId / relatedIds dangling-reference detection. Same root
+ // cause as missing-supersedes (a delete that did not clear
+ // back-references), so they are heal-fixable too.
+ if (memory.parentId && !memoryIds.has(memory.parentId)) {
+ checks.push({
+ name: `memory-missing-parent:${memory.id}:${memory.parentId}`,
+ category: "memories",
+ status: "warn",
+ message: `Memory "${memory.title}" has parentId ${memory.parentId} which does not exist`,
+ fixable: true,
+ });
+ memoryIssues++;
+ }
+
+ if (memory.relatedIds && memory.relatedIds.length > 0) {
+ for (const rid of memory.relatedIds) {
+ if (!memoryIds.has(rid)) {
+ checks.push({
+ name: `memory-missing-related:${memory.id}:${rid}`,
+ category: "memories",
+ status: "warn",
+ message: `Memory "${memory.title}" references non-existent related memory ${rid}`,
+ fixable: true,
+ });
+ memoryIssues++;
+ }
+ }
+ }
}
for (const memory of memories) {
@@ -356,11 +412,35 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
// Project-coverage check: unscoped memories (no project field) will
- // appear in every project's context and search results until the
- // infer-memory-projects migration runs. Surface a count so operators
- // know the backfill is still pending and can trigger it explicitly.
+ // appear in every project's context and search results until they are
+ // assigned a project. The message must be honest about what the
+ // infer-memory-projects migration can actually do: it only attributes
+ // memories that have sessionIds resolving to a strict-majority project.
+ // Unscoped memories with empty sessionIds (common for pre-session-link
+ // legacy rows) are returned as `ambiguous` and left unchanged, so
+ // prescribing that migration for them is a no-op. Split the count so
+ // an operator knows how many are inferable vs need manual assignment.
const latestMemories = memories.filter((m) => m.isLatest);
- const unscopedCount = latestMemories.filter((m) => !m.project).length;
+ const unscoped = latestMemories.filter((m) => !m.project);
+ const unscopedCount = unscoped.length;
+ const inferableCount = unscoped.filter(
+ (m) => (m.sessionIds?.length ?? 0) > 0,
+ ).length;
+ const ambiguousCount = unscopedCount - inferableCount;
+ const inferHint =
+ inferableCount > 0
+ ? `run POST /agentmemory/migrate {"step":"infer-memory-projects"} to attempt backfill of the ${inferableCount} session-linked`
+ : `no session-linked unscoped memories remain; infer-memory-projects is a no-op here`;
+ const ambiguousHint =
+ ambiguousCount > 0
+ ? `; the remaining ${ambiguousCount} have no sessionIds and need manual project assignment (or a session linkage pass) — the migration cannot attribute them`
+ : "";
+ // Fixability is honest: the engine can only auto-backfill the
+ // session-linked (inferable) subset via infer-memory-projects. When
+ // every unscoped memory lacks sessionIds the migration is a no-op, so
+ // the finding is not fixable by an automated heal/migrate step (it
+ // needs manual project assignment or a session-linkage pass).
+ const coverageFixable = inferableCount > 0;
if (unscopedCount === 0) {
checks.push({
name: "memory-project-coverage",
@@ -374,16 +454,16 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
name: "memory-project-coverage",
category: "memories",
status: "warn",
- message: `${unscopedCount} of ${latestMemories.length} latest memories have no project scope — run POST /agentmemory/migrate {"step":"infer-memory-projects"} to backfill`,
- fixable: true,
+ message: `${unscopedCount} of ${latestMemories.length} latest memories have no project scope — ${inferHint}${ambiguousHint}`,
+ fixable: coverageFixable,
});
} else {
checks.push({
name: "memory-project-coverage",
category: "memories",
status: "fail",
- message: `${unscopedCount} of ${latestMemories.length} latest memories have no project scope — run POST /agentmemory/migrate {"step":"infer-memory-projects"} to backfill`,
- fixable: true,
+ message: `${unscopedCount} of ${latestMemories.length} latest memories have no project scope — ${inferHint}${ambiguousHint}`,
+ fixable: coverageFixable,
});
}
@@ -399,12 +479,75 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
if (categories.includes("lessons")) {
+ const lessonAccessContext = lessonAccessContextFromPayload(
+ data.accessContext,
+ );
// Counts only live lessons (deleted=true rows are tombstoned).
// Catches bad confidence values that would silently break recall
// scoring (memory_lesson_recall multiplies by confidence).
- const lessons = await kv.list(KV.lessons);
- const live = lessons.filter((l) => !l.deleted);
- let lessonIssues = 0;
+ let lessons: Lesson[];
+ let lessonStateUnavailable = false;
+ if (lessonAccessContext.mode === "classify") {
+ lessons = await kv.list(KV.lessons);
+ } else {
+ try {
+ lessons = await kv.list(KV.lessons);
+ } catch {
+ lessonStateUnavailable = true;
+ checks.push({
+ name: "lesson-projection-unavailable",
+ category: "lessons",
+ status: "fail",
+ message:
+ "Lesson diagnostics are unavailable because authoritative lesson state could not be read",
+ fixable: false,
+ });
+ lessons = [];
+ }
+ }
+ const live: Lesson[] = [];
+ let readableLessonCount = 0;
+ let lessonIssues = lessonStateUnavailable ? 1 : 0;
+ let projectionIncomplete = false;
+ for (const lesson of lessons) {
+ try {
+ if (
+ lessonAccessContext.mode === "enforce" &&
+ !canReadLesson(lesson, lessonAccessContext)
+ ) {
+ continue;
+ }
+ const listable = isLessonListable(lesson);
+ readableLessonCount++;
+ if (listable) live.push(lesson);
+ } catch (error) {
+ if (lessonAccessContext.mode === "enforce") {
+ projectionIncomplete = true;
+ continue;
+ }
+ checks.push({
+ name: `lesson-invalid-structured:${lesson.id}`,
+ category: "lessons",
+ status: "fail",
+ message: `Lesson ${lesson.id} has invalid structured data: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ fixable: false,
+ });
+ lessonIssues++;
+ }
+ }
+ if (projectionIncomplete) {
+ checks.push({
+ name: "lesson-projection-incomplete",
+ category: "lessons",
+ status: "fail",
+ message:
+ "Lesson diagnostics are incomplete because one or more authoritative rows were unreadable or invalid",
+ fixable: false,
+ });
+ lessonIssues++;
+ }
for (const l of live) {
// Number.isFinite rejects NaN / Infinity / non-numbers; a
// corrupted row passing those would silently survive the < / >
@@ -431,7 +574,7 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
name: "lessons-ok",
category: "lessons",
status: "pass",
- message: `All ${live.length} lessons are healthy (${lessons.length - live.length} tombstoned)`,
+ message: `All ${live.length} lessons are healthy (${readableLessonCount - live.length} tombstoned)`,
fixable: false,
});
}
@@ -685,9 +828,24 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
return target && target.status === "done";
});
if (!stillAllDone) return false;
+ // Skip actions held by an explicit non-dependency gate:
+ // unblocking them is a no-op (legacyStatusFor reverts it)
+ // that only churns revisions and writes a misleading audit.
+ if (
+ await hasExplicitNonDependencyGate(kv, fresh, freshEdges)
+ ) {
+ return false;
+ }
+ const before = structuredClone(fresh);
fresh.status = "pending";
+ fresh.lifecycle = "pending";
fresh.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, fresh.id, fresh);
+ await persistAction(kv, fresh, {
+ actor: "heal",
+ before,
+ hasDerivedBlockers: false,
+ reason: "blocked dependencies completed",
+ });
await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
reason: "blocked-deps-done",
previousStatus: "blocked",
@@ -744,9 +902,16 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
return !target || target.status !== "done";
});
if (!stillUnsatisfied) return false;
+ const before = structuredClone(fresh);
fresh.status = "blocked";
+ fresh.lifecycle = "pending";
fresh.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, fresh.id, fresh);
+ await persistAction(kv, fresh, {
+ actor: "heal",
+ before,
+ hasDerivedBlockers: true,
+ reason: "pending action has unsatisfied dependencies",
+ });
await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
reason: "pending-unsatisfied-deps",
previousStatus: "pending",
@@ -811,15 +976,33 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
action.status === "active" &&
action.assignedTo === fresh.agentId
) {
+ const before = structuredClone(action);
action.status = "pending";
+ action.lifecycle = "pending";
action.assignedTo = undefined;
action.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, action.id, action);
+ await persistAction(kv, action, {
+ actor: "heal",
+ before,
+ reason: "released expired lease",
+ });
await recordAudit(kv, "heal", "mem::heal", [action.id], {
entityType: "action",
reason: "release-expired-lease",
newStatus: "pending",
});
+ } else if (
+ action &&
+ action.status !== "done" &&
+ action.status !== "cancelled"
+ ) {
+ const before = structuredClone(action);
+ action.updatedAt = new Date().toISOString();
+ await persistAction(kv, action, {
+ actor: "heal",
+ before,
+ reason: "expired lease; readiness revision refreshed",
+ });
}
return true;
},
@@ -941,7 +1124,10 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
actionIdSet.has(edge.sourceActionId) ||
actionIdSet.has(edge.targetActionId)
) {
- await kv.delete(KV.actionEdges, edge.id);
+ await deleteActionEdge(kv, edge.id, {
+ actor: "heal",
+ reason: `Garbage-collected discarded sketch ${fresh.id}`,
+ });
await recordAudit(kv, "heal", "mem::heal", [edge.id], {
entityType: "actionEdge",
reason: "sketch-gc-discard",
@@ -950,7 +1136,10 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
}
for (const actionId of fresh.actionIds) {
- await kv.delete(KV.actions, actionId);
+ await deleteAction(kv, actionId, {
+ actor: "heal",
+ reason: `Garbage-collected discarded sketch ${fresh.id}`,
+ });
await recordAudit(kv, "heal", "mem::heal", [actionId], {
entityType: "action",
reason: "sketch-gc-discard",
@@ -1055,6 +1244,63 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
}
}
+
+ // Prune dangling inter-memory references (supersedes/parentId/
+ // relatedIds pointing at non-existent memories). These accumulate when
+ // memories are removed outside governance-delete (legacy deletes,
+ // manual KV edits) and are exactly what the memory-missing-* warns
+ // above flag. Code-only: no live data is touched until an operator
+ // invokes mem::heal after deploy.
+ const currentMemories = await kv.list(KV.memories);
+ const existingIds = new Set(currentMemories.map((m) => m.id));
+ for (const memory of currentMemories) {
+ const dangling = new Set();
+ for (const id of memory.supersedes ?? []) {
+ if (!existingIds.has(id)) dangling.add(id);
+ }
+ if (memory.parentId && !existingIds.has(memory.parentId)) {
+ dangling.add(memory.parentId);
+ }
+ for (const id of memory.relatedIds ?? []) {
+ if (!existingIds.has(id)) dangling.add(id);
+ }
+ if (dangling.size === 0) continue;
+
+ if (dryRun) {
+ details.push(
+ `[dry-run] Would prune ${dangling.size} dangling reference(s) from memory "${memory.title}" (${memory.id})`,
+ );
+ fixed++;
+ continue;
+ }
+ const didFix = await withKeyedLock(
+ `mem:memory:${memory.id}`,
+ async () => {
+ const fresh = await kv.get(KV.memories, memory.id);
+ if (!fresh) return false;
+ const { memory: next, changed } =
+ stripMemoryReferences(fresh, dangling);
+ if (!changed) return false;
+ next.updatedAt = new Date().toISOString();
+ await kv.set(KV.memories, next.id, next);
+ await recordAudit(kv, "heal", "mem::heal", [next.id], {
+ entityType: "memory",
+ reason: "dangling-memory-reference-prune",
+ action: "update",
+ removed: [...dangling],
+ });
+ return true;
+ },
+ );
+ if (didFix) {
+ details.push(
+ `Pruned ${dangling.size} dangling reference(s) from memory "${memory.title}" (${memory.id})`,
+ );
+ fixed++;
+ } else {
+ skipped++;
+ }
+ }
}
return { success: true, fixed, skipped, details };
diff --git a/src/functions/disk-size-manager.ts b/src/functions/disk-size-manager.ts
index 0905e83c3e..682f129e96 100644
--- a/src/functions/disk-size-manager.ts
+++ b/src/functions/disk-size-manager.ts
@@ -1,10 +1,11 @@
-import { TriggerAction, type ISdk } from "iii-sdk";
+import type { ISdk } from "iii-sdk";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { getMaxBytes } from "../utils/image-store.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import { logger } from "../logger.js";
import type { StateScope, StateScopeKey } from "../types.js";
+import { triggerDetached } from "../utils/trigger-detached.js";
const DISK_SIZE_KEY: StateScopeKey = "system:currentDiskSize";
@@ -26,10 +27,9 @@ export function registerDiskSizeManager(sdk: ISdk, kv: StateKV): void {
await kv.set(KV.state, DISK_SIZE_KEY, newTotal);
if (data.deltaBytes > 0 && newTotal > getMaxBytes()) {
- sdk.trigger({
+ triggerDetached(sdk, {
function_id: "mem::image-quota-cleanup",
payload: {},
- action: TriggerAction.Void(),
});
logger.info("Disk quota exceeded, cleanup triggered", {
currentBytes: newTotal,
diff --git a/src/functions/evict.ts b/src/functions/evict.ts
index 626f4ff1df..ba5c57ad0d 100644
--- a/src/functions/evict.ts
+++ b/src/functions/evict.ts
@@ -11,6 +11,7 @@ import { StateKV } from "../state/kv.js";
import { recordAudit } from "./audit.js";
import { deleteAccessLog } from "./access-tracker.js";
import { logger } from "../logger.js";
+import type { LessonAccessContext } from "./lesson-access.js";
interface EvictionConfig {
staleSessionDays: number;
@@ -79,11 +80,14 @@ async function recoverStaleSession(
}
}
-async function runRecoveredSessionConsolidation(sdk: ISdk): Promise {
+async function runRecoveredSessionConsolidation(
+ sdk: ISdk,
+ accessContext?: LessonAccessContext,
+): Promise {
try {
await sdk.trigger({
function_id: "mem::consolidate-pipeline",
- payload: { tier: "all" },
+ payload: { tier: "all", accessContext },
});
} catch (err) {
logger.warn("Recovered session consolidation failed", {
@@ -94,7 +98,10 @@ async function runRecoveredSessionConsolidation(sdk: ISdk): Promise {
export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::evict",
- async (data: { dryRun?: boolean }): Promise => {
+ async (data: {
+ dryRun?: boolean;
+ accessContext?: LessonAccessContext;
+ }): Promise => {
const dryRun = data?.dryRun ?? false;
const { decrementImageRef } = await import("./image-refs.js");
@@ -179,7 +186,10 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
}
if (!dryRun && recoveredStaleSessions > 0) {
- await runRecoveredSessionConsolidation(sdk);
+ await runRecoveredSessionConsolidation(
+ sdk,
+ data.accessContext,
+ );
}
const projectObs = new Map();
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 327117b265..7ee0031f87 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -1,4 +1,5 @@
import type { ISdk } from "iii-sdk";
+import { isDeepStrictEqual } from "node:util";
import type {
Session,
CompressedObservation,
@@ -12,6 +13,8 @@ import type {
ProceduralMemory,
Action,
ActionEdge,
+ ActionCollectionState,
+ ActionEvent,
Routine,
Signal,
Checkpoint,
@@ -30,10 +33,84 @@ import { StateKV } from "../state/kv.js";
import { VERSION } from "../version.js";
import { recordAudit } from "./audit.js";
import { logger } from "../logger.js";
+import {
+ ACTION_SCHEMA_VERSION,
+ normalizeActionV2,
+} from "./action-model.js";
+import {
+ readActionStoreSnapshot,
+ withActionStoreLock,
+} from "./action-store.js";
+import {
+ isLessonRecallable,
+ normalizeLesson,
+ parseImportedLesson,
+ sameLessonContradictionScope,
+ sameLessonScope,
+} from "./lesson-model.js";
+import { withLessonMutationLock } from "./lesson-locks.js";
+import {
+ bindResolvedLessonWriteIdentity,
+ buildCrystalAccessIndex,
+ buildLessonAccessIndex,
+ canReadCrystal,
+ canReadInsight,
+ canReadLesson,
+ canUseLessonOperatorCapability,
+ canWriteLessonScope,
+ lessonAccessContextFromPayload,
+ type LessonAccessContext,
+} from "./lesson-access.js";
+
+interface ImportedLessonCandidate {
+ lesson: Lesson;
+ sourceId: string;
+ canonicalized: boolean;
+}
+
+interface LessonLifecycleTransition {
+ lessonId: string;
+ before?: string;
+ after?: string;
+}
+
+const MAX_LESSON_STATE_DIAGNOSTIC_DETAIL_LENGTH = 256;
+
+function isRecordWithNonEmptyString(
+ value: unknown,
+ field: string,
+): boolean {
+ return (
+ value !== null &&
+ typeof value === "object" &&
+ !Array.isArray(value) &&
+ typeof (value as Record)[field] === "string" &&
+ ((value as Record)[field] as string).length > 0
+ );
+}
export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::export",
- async (data?: { maxSessions?: number; offset?: number }) => {
+ async (data?: {
+ maxSessions?: number;
+ offset?: number;
+ accessContext?: LessonAccessContext;
+ }) => {
+ const accessContext = lessonAccessContextFromPayload(
+ data?.accessContext,
+ );
+ if (
+ !canUseLessonOperatorCapability(
+ accessContext,
+ "lesson:export",
+ )
+ ) {
+ return {
+ success: false,
+ code: "access_denied",
+ error: "lesson access denied for export",
+ };
+ }
const rawMax = Number(data?.maxSessions);
const maxSessions = Number.isFinite(rawMax) && rawMax > 0 ? Math.min(Math.floor(rawMax), 1000) : undefined;
const rawOffset = Number(data?.offset);
@@ -77,8 +154,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
graphEdges,
semanticMemories,
proceduralMemories,
- actions,
- actionEdges,
+ actionStore,
sentinels,
sketches,
crystals,
@@ -94,19 +170,38 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
kv.list(KV.graphEdges).catch(() => []),
kv.list(KV.semantic).catch(() => []),
kv.list(KV.procedural).catch(() => []),
- kv.list(KV.actions).catch(() => []),
- kv.list(KV.actionEdges).catch(() => []),
+ readActionStoreSnapshot(kv, { includeEvents: true }),
kv.list(KV.sentinels).catch(() => []),
kv.list(KV.sketches).catch(() => []),
kv.list(KV.crystals).catch(() => []),
kv.list(KV.facets).catch(() => []),
- kv.list(KV.lessons).catch(() => []),
+ kv.list(KV.lessons).catch((error) => {
+ throw new Error(
+ `Lesson export failed closed: authoritative lesson state read failed (${boundedLessonStateDiagnosticDetail(error)})`,
+ );
+ }),
kv.list(KV.insights).catch(() => []),
kv.list(KV.routines).catch(() => []),
kv.list(KV.signals).catch(() => []),
kv.list(KV.checkpoints).catch(() => []),
kv.list(KV.accessLog).catch(() => []),
]);
+ const lessonIndex = buildLessonAccessIndex(lessons);
+ const crystalIndex = buildCrystalAccessIndex(crystals);
+ const authorizedLessons = lessons
+ .filter((lesson) => canReadLesson(lesson, accessContext))
+ .map((lesson) => normalizeLesson(lesson));
+ const authorizedCrystals = crystals.filter((crystal) =>
+ canReadCrystal(crystal, lessonIndex, accessContext),
+ );
+ const authorizedInsights = insights.filter((insight) =>
+ canReadInsight(
+ insight,
+ lessonIndex,
+ crystalIndex,
+ accessContext,
+ ),
+ );
const exportData: ExportData = {
version: VERSION,
@@ -122,14 +217,34 @@ 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,
+ actions:
+ actionStore.actions.length > 0 ? actionStore.actions : undefined,
+ actionEdges:
+ actionStore.edges.length > 0 ? actionStore.edges : undefined,
+ actionEvents:
+ actionStore.events.length > 0 ? actionStore.events : undefined,
+ actionSnapshot: {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision: actionStore.state.revision,
+ actionCount: actionStore.actions.length,
+ edgeCount: actionStore.edges.length,
+ eventCount: actionStore.events.length,
+ },
sentinels: sentinels.length > 0 ? sentinels : undefined,
sketches: sketches.length > 0 ? sketches : undefined,
- crystals: crystals.length > 0 ? crystals : undefined,
+ crystals:
+ authorizedCrystals.length > 0
+ ? authorizedCrystals
+ : undefined,
facets: facets.length > 0 ? facets : undefined,
- lessons: lessons.length > 0 ? lessons : undefined,
- insights: insights.length > 0 ? insights : undefined,
+ lessons:
+ authorizedLessons.length > 0
+ ? authorizedLessons
+ : undefined,
+ insights:
+ authorizedInsights.length > 0
+ ? authorizedInsights
+ : undefined,
routines: routines.length > 0 ? routines : undefined,
signals: signals.length > 0 ? signals : undefined,
checkpoints: checkpoints.length > 0 ? checkpoints : undefined,
@@ -150,6 +265,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
0,
);
logger.info("Export complete", {
+ actor: accessContext.principalId,
sessions: paginatedSessions.length,
totalSessions: allSessions.length,
observations: totalObs,
@@ -165,7 +281,23 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
async (data: {
exportData: ExportData;
strategy?: "merge" | "replace" | "skip";
+ accessContext?: LessonAccessContext;
}) => {
+ const accessContext = lessonAccessContextFromPayload(
+ data?.accessContext,
+ );
+ if (
+ !canUseLessonOperatorCapability(
+ accessContext,
+ "lesson:import",
+ )
+ ) {
+ return {
+ success: false,
+ code: "access_denied",
+ error: "lesson access denied for import",
+ };
+ }
if (
!data?.exportData ||
typeof data.exportData !== "object" ||
@@ -173,7 +305,19 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
) {
return { success: false, error: "exportData with string version is required" };
}
- const strategy = data.strategy || "merge";
+ const requestedStrategy = (data as { strategy?: unknown }).strategy;
+ if (
+ requestedStrategy !== undefined &&
+ requestedStrategy !== "merge" &&
+ requestedStrategy !== "replace" &&
+ requestedStrategy !== "skip"
+ ) {
+ return {
+ success: false,
+ error: "strategy must be merge, replace, or skip",
+ };
+ }
+ const strategy = requestedStrategy ?? "merge";
const importData = data.exportData;
const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8", "0.8.9", "0.8.10", "0.8.11", "0.8.12", "0.8.13", "0.9.0", "0.9.1", "0.9.2", "0.9.3", "0.9.4", "0.9.5", "0.9.6", "0.9.7", "0.9.8", "0.9.9", "0.9.10", "0.9.11", "0.9.12", "0.9.13", "0.9.14", "0.9.15", "0.9.16", "0.9.17", "0.9.18", "0.9.19", "0.9.20", "0.9.21", "0.9.22", "0.9.23", "0.9.24", "0.9.25", "0.9.26", "0.9.27"]);
@@ -190,6 +334,10 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
const MAX_OBS_PER_SESSION = 5_000;
const MAX_TOTAL_OBSERVATIONS = 500_000;
const MAX_ACCESS_LOGS = 50_000;
+ const MAX_ACTIONS = 100_000;
+ const MAX_ACTION_EDGES = 250_000;
+ const MAX_ACTION_EVENTS = 500_000;
+ const MAX_LESSONS = 100_000;
if (!Array.isArray(importData.sessions)) {
return { success: false, error: "sessions must be an array" };
@@ -207,6 +355,60 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
) {
return { success: false, error: "observations must be an object" };
}
+ const importRecord = importData as unknown as Record<
+ string,
+ unknown
+ >;
+ const keyedCollections: Array<{
+ field: string;
+ key: string;
+ required?: boolean;
+ }> = [
+ { field: "sessions", key: "id", required: true },
+ { field: "memories", key: "id", required: true },
+ {
+ field: "summaries",
+ key: "sessionId",
+ required: true,
+ },
+ { field: "profiles", key: "project" },
+ { field: "graphNodes", key: "id" },
+ { field: "graphEdges", key: "id" },
+ { field: "semanticMemories", key: "id" },
+ { field: "proceduralMemories", key: "id" },
+ { field: "actions", key: "id" },
+ { field: "actionEdges", key: "id" },
+ { field: "actionEvents", key: "id" },
+ { field: "routines", key: "id" },
+ { field: "signals", key: "id" },
+ { field: "checkpoints", key: "id" },
+ { field: "sentinels", key: "id" },
+ { field: "sketches", key: "id" },
+ { field: "crystals", key: "id" },
+ { field: "facets", key: "id" },
+ { field: "insights", key: "id" },
+ { field: "accessLogs", key: "memoryId" },
+ ];
+ for (const collection of keyedCollections) {
+ const value = importRecord[collection.field];
+ if (value === undefined && !collection.required) continue;
+ if (!Array.isArray(value)) {
+ return {
+ success: false,
+ error: `${collection.field} must be an array`,
+ };
+ }
+ if (
+ !value.every((item) =>
+ isRecordWithNonEmptyString(item, collection.key),
+ )
+ ) {
+ return {
+ success: false,
+ error: `${collection.field} contains an invalid record`,
+ };
+ }
+ }
if (importData.sessions.length > MAX_SESSIONS) {
return {
@@ -240,6 +442,16 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
if (!Array.isArray(obs)) {
return { success: false, error: "observation values must be arrays" };
}
+ if (
+ !obs.every((item) =>
+ isRecordWithNonEmptyString(item, "id"),
+ )
+ ) {
+ return {
+ success: false,
+ error: "observations contain an invalid record",
+ };
+ }
if (obs.length > MAX_OBS_PER_SESSION) {
return {
success: false,
@@ -255,14 +467,242 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
};
}
+ const importedLessons = importData.lessons ?? [];
+ if (!Array.isArray(importedLessons)) {
+ return { success: false, error: "lessons must be an array" };
+ }
+ if (importedLessons.length > MAX_LESSONS) {
+ return {
+ success: false,
+ error: `Too many lessons (max ${MAX_LESSONS})`,
+ };
+ }
+ const normalizedImportedLessons: ImportedLessonCandidate[] = [];
+ const importedLessonIds = new Set();
+ const importedLessonAliases = new Map();
+ for (const lesson of importedLessons) {
+ const parsed = parseImportedLesson(lesson);
+ if (!parsed.success) {
+ return {
+ success: false,
+ error: `Invalid lesson: ${parsed.error}`,
+ };
+ }
+ if (importedLessonIds.has(parsed.lesson.id)) {
+ return {
+ success: false,
+ error: `Duplicate lesson: ${parsed.lesson.id}`,
+ };
+ }
+ importedLessonIds.add(parsed.lesson.id);
+ for (const alias of [
+ parsed.sourceId,
+ ...(parsed.lesson.idAliases ?? []),
+ parsed.lesson.id,
+ ]) {
+ const claimedBy = importedLessonAliases.get(alias);
+ if (claimedBy && claimedBy !== parsed.lesson.id) {
+ return {
+ success: false,
+ error: `Duplicate lesson identity alias ${alias}: ${claimedBy}, ${parsed.lesson.id}`,
+ };
+ }
+ importedLessonAliases.set(alias, parsed.lesson.id);
+ }
+ normalizedImportedLessons.push(parsed);
+ }
+
+ const importedActions = Array.isArray(importData.actions)
+ ? importData.actions
+ : [];
+ if (importedActions.length > MAX_ACTIONS) {
+ return {
+ success: false,
+ error: `Too many actions (max ${MAX_ACTIONS})`,
+ };
+ }
+ const normalizedImportedActions: Action[] = [];
+ const actionIds = new Set();
+ for (const action of importedActions) {
+ if (!isImportableAction(action)) {
+ return { success: false, error: "Invalid action" };
+ }
+ if (actionIds.has(action.id)) {
+ return { success: false, error: `Duplicate action: ${action.id}` };
+ }
+ actionIds.add(action.id);
+ }
+ const importedActionEdges = importData.actionEdges ?? [];
+ if (!Array.isArray(importedActionEdges)) {
+ return { success: false, error: "actionEdges must be an array" };
+ }
+ if (importedActionEdges.length > MAX_ACTION_EDGES) {
+ return {
+ success: false,
+ error: `Too many action edges (max ${MAX_ACTION_EDGES})`,
+ };
+ }
+ const edgeIds = new Set();
+ for (const edge of importedActionEdges) {
+ if (!isImportableActionEdge(edge)) {
+ return { success: false, error: "Invalid action edge" };
+ }
+ if (edgeIds.has(edge.id)) {
+ return { success: false, error: `Duplicate action edge: ${edge.id}` };
+ }
+ edgeIds.add(edge.id);
+ }
+ const importedActionsWithDerivedBlockers =
+ collectImportedActionsWithDerivedBlockers(
+ importedActions,
+ importedActionEdges,
+ Array.isArray(importData.checkpoints) ? importData.checkpoints : [],
+ Array.isArray(importData.sentinels) ? importData.sentinels : [],
+ );
+ for (const action of importedActions) {
+ const normalized = normalizeActionV2(action, {
+ hasDerivedBlockers: importedActionsWithDerivedBlockers.has(action.id),
+ });
+ if (normalized.conflicts.length > 0) {
+ return {
+ success: false,
+ error: `Invalid action ${action.id}: ${normalized.conflicts.join(", ")}`,
+ };
+ }
+ normalizedImportedActions.push(normalized.action);
+ }
+ const importedActionEvents = importData.actionEvents ?? [];
+ if (!Array.isArray(importedActionEvents)) {
+ return { success: false, error: "actionEvents must be an array" };
+ }
+ if (importedActionEvents.length > MAX_ACTION_EVENTS) {
+ return {
+ success: false,
+ error: `Too many action events (max ${MAX_ACTION_EVENTS})`,
+ };
+ }
+ const eventIds = new Set();
+ const validActionEventTypes = new Set([
+ "created",
+ "fields_changed",
+ "lifecycle_changed",
+ "result_recorded",
+ "corrected",
+ "migrated",
+ "deleted",
+ "edge_created",
+ "edge_deleted",
+ ]);
+ for (const event of importedActionEvents) {
+ if (
+ !event ||
+ event.schemaVersion !== ACTION_SCHEMA_VERSION ||
+ typeof event.id !== "string" ||
+ !event.id ||
+ typeof event.actionId !== "string" ||
+ !event.actionId ||
+ (event.entityType !== "action" && event.entityType !== "edge") ||
+ !validActionEventTypes.has(event.type) ||
+ typeof event.actor !== "string" ||
+ !event.actor ||
+ typeof event.timestamp !== "string" ||
+ Number.isNaN(Date.parse(event.timestamp)) ||
+ !Number.isInteger(event.revision) ||
+ event.revision < 1
+ ) {
+ return { success: false, error: "Invalid action event" };
+ }
+ if (eventIds.has(event.id)) {
+ return { success: false, error: `Duplicate action event: ${event.id}` };
+ }
+ eventIds.add(event.id);
+ if (!isValidActionEventImage(event)) {
+ return { success: false, error: `Invalid action event image: ${event.id}` };
+ }
+ }
+ const importedActionSnapshot = importData.actionSnapshot;
+ if (importedActionSnapshot) {
+ if (
+ importedActionSnapshot.schemaVersion !== ACTION_SCHEMA_VERSION ||
+ importedActionSnapshot.actionCount !== normalizedImportedActions.length ||
+ importedActionSnapshot.edgeCount !== importedActionEdges.length ||
+ importedActionSnapshot.eventCount !== importedActionEvents.length ||
+ !Number.isInteger(importedActionSnapshot.revision) ||
+ importedActionSnapshot.revision < 0 ||
+ importedActionSnapshot.revision <
+ Math.max(
+ 0,
+ ...normalizedImportedActions.map(
+ (action) => action.revision ?? 0,
+ ),
+ ...importedActionEvents.map((event) => event.revision),
+ )
+ ) {
+ return { success: false, error: "Action snapshot counts or revision are invalid" };
+ }
+ }
+ if (strategy === "merge" || strategy === "skip") {
+ for (const event of importedActionEvents) {
+ const existing = await kv
+ .get(KV.actionEvents, event.id)
+ .catch(() => null);
+ if (
+ existing &&
+ JSON.stringify(existing) !== JSON.stringify(event)
+ ) {
+ return {
+ success: false,
+ error: `Action event ID conflict: ${event.id}`,
+ };
+ }
+ }
+ }
+ if (
+ importData.accessLogs !== undefined &&
+ !Array.isArray(importData.accessLogs)
+ ) {
+ return { success: false, error: "accessLogs must be an array" };
+ }
+ if (
+ Array.isArray(importData.accessLogs) &&
+ importData.accessLogs.length > MAX_ACCESS_LOGS
+ ) {
+ return {
+ success: false,
+ error: `Too many access logs (max ${MAX_ACCESS_LOGS})`,
+ };
+ }
+
const stats = {
sessions: 0,
observations: 0,
memories: 0,
summaries: 0,
+ actions: 0,
+ actionEdges: 0,
+ actionEvents: 0,
+ lessons: 0,
skipped: 0,
};
+ const lessonImport = await withLessonMutationLock(() =>
+ applyImportedLessonBatch(
+ kv,
+ normalizedImportedLessons,
+ strategy,
+ accessContext,
+ ),
+ );
+ if (!lessonImport.success) {
+ return {
+ success: false,
+ error: lessonImport.error,
+ ...(lessonImport.code ? { code: lessonImport.code } : {}),
+ };
+ }
+ stats.lessons = lessonImport.written;
+ stats.skipped += lessonImport.skipped;
+
if (strategy === "replace") {
const existing = await kv.list(KV.sessions);
for (const session of existing) {
@@ -282,12 +722,6 @@ 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(KV.actions).catch(() => [])) {
- await kv.delete(KV.actions, a.id);
- }
- for (const e of await kv.list(KV.actionEdges).catch(() => [])) {
- await kv.delete(KV.actionEdges, e.id);
- }
for (const r of await kv.list(KV.routines).catch(() => [])) {
await kv.delete(KV.routines, r.id);
}
@@ -309,9 +743,6 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
for (const f of await kv.list(KV.facets).catch(() => [])) {
await kv.delete(KV.facets, f.id);
}
- for (const l of await kv.list(KV.lessons).catch(() => [])) {
- await kv.delete(KV.lessons, l.id);
- }
for (const i of await kv.list(KV.insights).catch(() => [])) {
await kv.delete(KV.insights, i.id);
}
@@ -448,24 +879,110 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
}
}
- if (importData.actions) {
- for (const action of importData.actions) {
+ await withActionStoreLock(async () => {
+ const priorActionState = await kv
+ .get(KV.actionState, "current")
+ .catch(() => null);
+ let replacedExistingActionData = false;
+ if (strategy === "replace") {
+ const existingActions = await kv.list(KV.actions).catch(() => []);
+ const existingEdges = await kv
+ .list(KV.actionEdges)
+ .catch(() => []);
+ const existingEvents = await kv
+ .list(KV.actionEvents)
+ .catch(() => []);
+ replacedExistingActionData = Boolean(
+ priorActionState ||
+ existingActions.length ||
+ existingEdges.length ||
+ existingEvents.length,
+ );
+ for (const action of existingActions) {
+ await kv.delete(KV.actions, action.id);
+ }
+ for (const edge of existingEdges) {
+ await kv.delete(KV.actionEdges, edge.id);
+ }
+ for (const event of existingEvents) {
+ await kv.delete(KV.actionEvents, event.id);
+ }
+ await kv.delete(KV.actionState, "current").catch(() => {});
+ }
+
+ for (const action of normalizedImportedActions) {
if (strategy === "skip") {
- const existing = await kv.get(KV.actions, action.id).catch(() => null);
- if (existing) { stats.skipped++; continue; }
+ const existing = await kv
+ .get(KV.actions, action.id)
+ .catch(() => null);
+ if (existing) {
+ stats.skipped++;
+ continue;
+ }
}
await kv.set(KV.actions, action.id, action);
+ stats.actions++;
}
- }
- if (importData.actionEdges) {
- for (const edge of importData.actionEdges) {
+ for (const edge of importedActionEdges) {
if (strategy === "skip") {
- const existing = await kv.get(KV.actionEdges, edge.id).catch(() => null);
- if (existing) { stats.skipped++; continue; }
+ const existing = await kv
+ .get(KV.actionEdges, edge.id)
+ .catch(() => null);
+ if (existing) {
+ stats.skipped++;
+ continue;
+ }
}
await kv.set(KV.actionEdges, edge.id, edge);
+ stats.actionEdges++;
}
- }
+ for (const event of importedActionEvents) {
+ if (strategy === "skip" || strategy === "merge") {
+ const existing = await kv
+ .get(KV.actionEvents, event.id)
+ .catch(() => null);
+ if (existing) {
+ stats.skipped++;
+ continue;
+ }
+ }
+ await kv.set(KV.actionEvents, event.id, event);
+ stats.actionEvents++;
+ }
+
+ const actionDataChanged =
+ stats.actions > 0 ||
+ stats.actionEdges > 0 ||
+ stats.actionEvents > 0 ||
+ replacedExistingActionData ||
+ (strategy === "replace" &&
+ (normalizedImportedActions.length > 0 ||
+ importedActionEdges.length > 0 ||
+ importedActionEvents.length > 0));
+ if (actionDataChanged || importedActionSnapshot) {
+ const currentActionState = await kv
+ .get(KV.actionState, "current")
+ .catch(() => null);
+ const importedRevision = Math.max(
+ importedActionSnapshot?.revision ?? 0,
+ ...normalizedImportedActions.map((action) => action.revision ?? 0),
+ ...importedActionEvents.map((event) => event.revision),
+ );
+ const revision =
+ strategy === "replace"
+ ? replacedExistingActionData
+ ? Math.max(priorActionState?.revision ?? 0, importedRevision) +
+ 1
+ : importedRevision
+ : Math.max(currentActionState?.revision ?? 0, importedRevision) + 1;
+ const nextActionState: ActionCollectionState = {
+ schemaVersion: ACTION_SCHEMA_VERSION,
+ revision,
+ updatedAt: new Date().toISOString(),
+ };
+ await kv.set(KV.actionState, "current", nextActionState);
+ }
+ });
if (importData.routines) {
for (const routine of importData.routines) {
if (strategy === "skip") {
@@ -529,15 +1046,6 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
await kv.set(KV.facets, facet.id, facet);
}
}
- if (importData.lessons) {
- for (const lesson of importData.lessons) {
- if (strategy === "skip") {
- const existing = await kv.get(KV.lessons, lesson.id).catch(() => null);
- if (existing) { stats.skipped++; continue; }
- }
- await kv.set(KV.lessons, lesson.id, lesson);
- }
- }
if (importData.insights) {
for (const insight of importData.insights) {
if (strategy === "skip") {
@@ -548,15 +1056,6 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
}
}
if (importData.accessLogs) {
- if (!Array.isArray(importData.accessLogs)) {
- return { success: false, error: "accessLogs must be an array" };
- }
- if (importData.accessLogs.length > MAX_ACCESS_LOGS) {
- return {
- success: false,
- error: `Too many access logs (max ${MAX_ACCESS_LOGS})`,
- };
- }
const memoryIds = new Set(
importData.memories.map((m) => m.id),
);
@@ -578,6 +1077,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
logger.info("Import complete", { strategy, ...stats });
await recordAudit(kv, "import", "mem::import", [], {
+ actor: accessContext.principalId,
strategy,
stats,
});
@@ -585,3 +1085,518 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
},
);
}
+
+async function applyImportedLessonBatch(
+ kv: StateKV,
+ imported: ImportedLessonCandidate[],
+ strategy: "merge" | "replace" | "skip",
+ accessContext: LessonAccessContext,
+): Promise<
+ | { success: true; written: number; skipped: number }
+ | { success: false; error: string; code?: "access_denied" }
+> {
+ let existingRows: Lesson[];
+ try {
+ existingRows = await kv.list(KV.lessons);
+ } catch (error) {
+ return {
+ success: false,
+ error: `Lesson import failed closed: authoritative lesson state read failed (${boundedLessonStateDiagnosticDetail(error)})`,
+ };
+ }
+ const preimage = new Map(
+ existingRows.map((lesson) => [lesson.id, lesson] as const),
+ );
+ const authorizedImported: ImportedLessonCandidate[] = [];
+ for (const candidate of imported) {
+ const prepared = bindResolvedLessonWriteIdentity(
+ candidate.lesson,
+ accessContext,
+ );
+ if (!prepared.success) {
+ return {
+ success: false,
+ ...(prepared.code === "access_denied"
+ ? { code: "access_denied" as const }
+ : {}),
+ error: prepared.error,
+ };
+ }
+ try {
+ authorizedImported.push({
+ ...candidate,
+ lesson: normalizeLesson(prepared.value as Lesson),
+ });
+ } catch {
+ return {
+ success: false,
+ error: "Invalid imported lesson after server identity binding",
+ };
+ }
+ }
+ imported = authorizedImported;
+ const existing = new Map();
+ const existingAliases = new Map();
+ for (const row of existingRows) {
+ let normalized: Lesson;
+ try {
+ normalized = normalizeLesson(row);
+ } catch (error) {
+ return {
+ success: false,
+ error: `Invalid existing structured lesson ${row.id}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ };
+ }
+ existing.set(normalized.id, normalized);
+ for (const alias of [
+ normalized.id,
+ ...(normalized.idAliases ?? []),
+ ]) {
+ const claimedBy = existingAliases.get(alias);
+ if (claimedBy && claimedBy !== normalized.id) {
+ return {
+ success: false,
+ error: `Existing lesson identity alias conflict ${alias}: ${claimedBy}, ${normalized.id}`,
+ };
+ }
+ existingAliases.set(alias, normalized.id);
+ }
+ }
+
+ for (const candidate of imported) {
+ const normalized = normalizeLesson(candidate.lesson);
+ if (
+ !canWriteLessonScope(
+ normalized.scope,
+ normalized.sensitivity,
+ accessContext,
+ )
+ ) {
+ return {
+ success: false,
+ code: "access_denied",
+ error: "Lesson import access denied for incoming durable scope",
+ };
+ }
+ const current = existing.get(normalized.id);
+ if (
+ current &&
+ (!canReadLesson(current, accessContext) ||
+ !canWriteLessonScope(
+ current.scope!,
+ current.sensitivity!,
+ accessContext,
+ ))
+ ) {
+ return {
+ success: false,
+ code: "access_denied",
+ error: "Lesson import access denied for existing durable scope",
+ };
+ }
+ }
+ if (strategy === "replace") {
+ for (const current of existing.values()) {
+ if (
+ !canReadLesson(current, accessContext) ||
+ !canWriteLessonScope(
+ current.scope!,
+ current.sensitivity!,
+ accessContext,
+ )
+ ) {
+ return {
+ success: false,
+ code: "access_denied",
+ error: "Lesson import access denied for replace deletion",
+ };
+ }
+ }
+ }
+
+ const incomingAliases = new Map();
+ for (const candidate of imported) {
+ for (const alias of [
+ candidate.sourceId,
+ candidate.lesson.id,
+ ...(candidate.lesson.idAliases ?? []),
+ ]) {
+ const claimedBy = incomingAliases.get(alias);
+ if (claimedBy && claimedBy !== candidate.lesson.id) {
+ return {
+ success: false,
+ error: `Imported lesson identity alias conflict ${alias}: ${claimedBy}, ${candidate.lesson.id}`,
+ };
+ }
+ const existingOwner = existingAliases.get(alias);
+ if (
+ strategy !== "replace" &&
+ existingOwner &&
+ existingOwner !== candidate.lesson.id
+ ) {
+ return {
+ success: false,
+ error: `Imported lesson identity ${alias} conflicts with existing lesson ${existingOwner}`,
+ };
+ }
+ incomingAliases.set(alias, candidate.lesson.id);
+ }
+ }
+
+ const resolveRelationId = (id: string): string =>
+ incomingAliases.get(id) ?? existingAliases.get(id) ?? id;
+ const incoming = new Map();
+ for (const candidate of imported) {
+ const rewritten = normalizeLesson({
+ ...candidate.lesson,
+ supersededByLessonId: candidate.lesson.supersededByLessonId
+ ? resolveRelationId(candidate.lesson.supersededByLessonId)
+ : undefined,
+ contradictedByLessonIds: (
+ candidate.lesson.contradictedByLessonIds ?? []
+ )
+ .map(resolveRelationId)
+ .filter((id, index, ids) => ids.indexOf(id) === index)
+ .sort(),
+ });
+ incoming.set(rewritten.id, rewritten);
+ }
+ for (const lesson of incoming.values()) {
+ const relationIds = [
+ ...(lesson.supersededByLessonId
+ ? [lesson.supersededByLessonId]
+ : []),
+ ...lesson.contradictedByLessonIds!,
+ ];
+ for (const relationId of relationIds) {
+ const target = incoming.get(relationId) ?? existing.get(relationId);
+ if (target && !canReadLesson(target, accessContext)) {
+ return {
+ success: false,
+ code: "access_denied",
+ error: "Lesson import access denied for relation target",
+ };
+ }
+ }
+ }
+
+ const finalLessons =
+ strategy === "replace"
+ ? new Map(incoming)
+ : new Map(existing);
+ let skipped = 0;
+ for (const [id, lesson] of incoming) {
+ const current = existing.get(id);
+ if (strategy === "skip" && current) {
+ skipped++;
+ continue;
+ }
+ if (
+ strategy === "merge" &&
+ current &&
+ (current.lifecycle === "retracted" ||
+ current.lifecycle === "superseded") &&
+ lesson.lifecycle !== current.lifecycle
+ ) {
+ return {
+ success: false,
+ error: `Merge import cannot replace terminal ${current.lifecycle} lesson ${id} with ${lesson.lifecycle}; use replace import for an explicit audited restore`,
+ };
+ }
+ finalLessons.set(id, lesson);
+ }
+
+ const graphError = validateLessonGraph(finalLessons);
+ if (graphError) return { success: false, error: graphError };
+
+ const writes = [...incoming.values()].filter(
+ (lesson) => strategy !== "skip" || !existing.has(lesson.id),
+ );
+ const deletes =
+ strategy === "replace"
+ ? [...existing.keys()].filter((id) => !incoming.has(id))
+ : [];
+ const transitions: LessonLifecycleTransition[] = [];
+ for (const lesson of writes) {
+ transitions.push({
+ lessonId: lesson.id,
+ before: existing.get(lesson.id)?.lifecycle,
+ after: normalizeLesson(lesson).lifecycle,
+ });
+ }
+ for (const id of deletes) {
+ transitions.push({
+ lessonId: id,
+ before: existing.get(id)?.lifecycle,
+ after: undefined,
+ });
+ }
+
+ const affectedIds = transitions.map((transition) => transition.lessonId);
+ const auditDetails = {
+ strategy,
+ canonicalizedIds: imported
+ .filter((candidate) => candidate.canonicalized)
+ .map((candidate) => ({
+ sourceId: candidate.sourceId,
+ lessonId: candidate.lesson.id,
+ })),
+ lifecycleTransitions: transitions,
+ };
+ try {
+ for (const id of deletes) {
+ await kv.delete(KV.lessons, id);
+ }
+ for (const lesson of writes) {
+ await kv.set(KV.lessons, lesson.id, lesson);
+ }
+ if (affectedIds.length > 0) {
+ await recordAudit(
+ kv,
+ "import",
+ "mem::import:lessons",
+ affectedIds,
+ { ...auditDetails, actor: accessContext.principalId },
+ );
+ }
+ } catch (error) {
+ const rollback = await restoreLessonPreimage(
+ kv,
+ affectedIds,
+ preimage,
+ );
+ let auditError: string | undefined;
+ try {
+ await recordAudit(
+ kv,
+ "import",
+ "mem::import:lessons-rollback",
+ affectedIds,
+ {
+ ...auditDetails,
+ actor: accessContext.principalId,
+ applyError: error instanceof Error ? error.message : String(error),
+ rollback,
+ },
+ );
+ } catch (rollbackAuditError) {
+ auditError =
+ rollbackAuditError instanceof Error
+ ? rollbackAuditError.message
+ : String(rollbackAuditError);
+ }
+ const applyError = error instanceof Error ? error.message : String(error);
+ if (!rollback.success) {
+ return {
+ success: false,
+ error: `Lesson import failed (${applyError}); rollback failed: ${rollback.errors.join("; ")}${auditError ? `; rollback audit failed: ${auditError}` : ""}`,
+ };
+ }
+ return {
+ success: false,
+ error: `Lesson import failed (${applyError}); exact preimage restored${auditError ? `; rollback audit failed: ${auditError}` : ""}`,
+ };
+ }
+ return { success: true, written: writes.length, skipped };
+}
+
+function boundedLessonStateDiagnosticDetail(error: unknown): string {
+ const raw = error instanceof Error ? error.message : String(error);
+ const normalized = raw.replace(/\s+/g, " ").trim() || "unknown error";
+ if (normalized.length <= MAX_LESSON_STATE_DIAGNOSTIC_DETAIL_LENGTH) {
+ return normalized;
+ }
+ return `${normalized.slice(0, MAX_LESSON_STATE_DIAGNOSTIC_DETAIL_LENGTH - 3)}...`;
+}
+
+async function restoreLessonPreimage(
+ kv: StateKV,
+ affectedIds: string[],
+ preimage: Map,
+): Promise<{ success: boolean; errors: string[] }> {
+ const errors: string[] = [];
+ for (const id of [...new Set(affectedIds)].reverse()) {
+ try {
+ const before = preimage.get(id);
+ if (before) {
+ await kv.set(KV.lessons, id, before);
+ } else {
+ await kv.delete(KV.lessons, id);
+ }
+ } catch (error) {
+ errors.push(
+ `${id}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+ for (const id of new Set(affectedIds)) {
+ try {
+ const actual = await kv.get(KV.lessons, id);
+ const expected = preimage.get(id) ?? null;
+ if (!isDeepStrictEqual(actual, expected)) {
+ errors.push(`${id}: preimage verification mismatch`);
+ }
+ } catch (error) {
+ errors.push(
+ `${id}: verification failed: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+ }
+ return { success: errors.length === 0, errors };
+}
+
+function validateLessonGraph(lessons: Map): string | null {
+ for (const lesson of lessons.values()) {
+ const normalized = normalizeLesson(lesson);
+ const supersededBy = normalized.supersededByLessonId;
+ if (supersededBy) {
+ if (supersededBy === normalized.id) {
+ return `Lesson ${normalized.id} cannot supersede itself`;
+ }
+ const target = lessons.get(supersededBy);
+ if (!target) {
+ return `Lesson ${normalized.id} has dangling supersession target ${supersededBy}`;
+ }
+ if (!isLessonRecallable(target)) {
+ return `Lesson ${normalized.id} supersession target ${supersededBy} must be active`;
+ }
+ if (!sameLessonScope(normalized, target)) {
+ return `Lesson ${normalized.id} supersession target ${supersededBy} crosses durable scope`;
+ }
+ }
+ for (const contradictionId of normalized.contradictedByLessonIds) {
+ if (contradictionId === normalized.id) {
+ return `Lesson ${normalized.id} cannot contradict itself`;
+ }
+ const target = lessons.get(contradictionId);
+ if (!target) {
+ return `Lesson ${normalized.id} has dangling contradiction target ${contradictionId}`;
+ }
+ if (!isLessonRecallable(target)) {
+ return `Lesson ${normalized.id} contradiction target ${contradictionId} must be active`;
+ }
+ if (!sameLessonContradictionScope(normalized, target)) {
+ return `Lesson ${normalized.id} contradiction target ${contradictionId} crosses durable scope or project`;
+ }
+ }
+ }
+ return null;
+}
+
+function collectImportedActionsWithDerivedBlockers(
+ actions: Action[],
+ edges: ActionEdge[],
+ checkpoints: Checkpoint[],
+ sentinels: Sentinel[],
+): Set {
+ const actionMap = new Map(actions.map((action) => [action.id, action]));
+ const checkpointMap = new Map(
+ checkpoints.map((checkpoint) => [checkpoint.id, checkpoint]),
+ );
+ const sentinelMap = new Map(
+ sentinels.map((sentinel) => [sentinel.id, sentinel]),
+ );
+ const unresolved = new Set();
+ for (const edge of edges) {
+ if (edge.type === "requires") {
+ const dependency = actionMap.get(edge.targetActionId);
+ if ((dependency?.lifecycle ?? dependency?.status) !== "done") {
+ unresolved.add(edge.sourceActionId);
+ }
+ continue;
+ }
+ if (edge.type === "gated_by") {
+ if (
+ checkpointMap.get(edge.targetActionId)?.status !== "passed" &&
+ sentinelMap.get(edge.targetActionId)?.status !== "triggered"
+ ) {
+ unresolved.add(edge.sourceActionId);
+ }
+ }
+ }
+ return unresolved;
+}
+
+function isValidActionEventImage(event: ActionEvent): boolean {
+ const isDeletion = event.type === "deleted" || event.type === "edge_deleted";
+ if (isDeletion ? !event.before || event.after : !event.after) return false;
+ if (
+ event.entityType === "action" &&
+ (event.type === "edge_created" || event.type === "edge_deleted")
+ ) {
+ return false;
+ }
+ if (
+ event.entityType === "edge" &&
+ event.type !== "edge_created" &&
+ event.type !== "edge_deleted" &&
+ event.type !== "fields_changed"
+ ) {
+ return false;
+ }
+ for (const image of [event.before, event.after]) {
+ if (!image || typeof image !== "object") continue;
+ if (event.entityType === "action") {
+ if ((image as Action).id !== event.actionId) return false;
+ continue;
+ }
+ const edge = image as ActionEdge;
+ if (
+ typeof edge.id !== "string" ||
+ !edge.id ||
+ edge.sourceActionId !== event.actionId ||
+ typeof edge.targetActionId !== "string" ||
+ !edge.targetActionId
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function isImportableAction(value: unknown): value is Action {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ const action = value as Partial;
+ return (
+ typeof action.id === "string" &&
+ Boolean(action.id) &&
+ typeof action.title === "string" &&
+ typeof action.description === "string" &&
+ ["pending", "active", "done", "blocked", "cancelled"].includes(
+ String(action.status),
+ ) &&
+ typeof action.priority === "number" &&
+ Number.isFinite(action.priority) &&
+ typeof action.createdAt === "string" &&
+ !Number.isNaN(Date.parse(action.createdAt)) &&
+ typeof action.updatedAt === "string" &&
+ !Number.isNaN(Date.parse(action.updatedAt)) &&
+ typeof action.createdBy === "string"
+ );
+}
+
+function isImportableActionEdge(value: unknown): value is ActionEdge {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ const edge = value as Partial;
+ return (
+ typeof edge.id === "string" &&
+ Boolean(edge.id) &&
+ [
+ "requires",
+ "unlocks",
+ "spawned_by",
+ "gated_by",
+ "conflicts_with",
+ ].includes(String(edge.type)) &&
+ typeof edge.sourceActionId === "string" &&
+ Boolean(edge.sourceActionId) &&
+ typeof edge.targetActionId === "string" &&
+ Boolean(edge.targetActionId) &&
+ typeof edge.createdAt === "string" &&
+ !Number.isNaN(Date.parse(edge.createdAt))
+ );
+}
diff --git a/src/functions/frontier.ts b/src/functions/frontier.ts
index 30f43fec60..1b39bf7e82 100644
--- a/src/functions/frontier.ts
+++ b/src/functions/frontier.ts
@@ -1,122 +1,96 @@
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";
+import type {
+ ActionBlocker,
+ ActionReadinessView,
+ Checkpoint,
+ Lease,
+ Sentinel,
+} from "../types.js";
+import {
+ buildActionViewIndex,
+ classifyAction,
+ computeActionScore,
+} from "./action-model.js";
+import { matchesActionProject } from "./action-query.js";
+import { readActionStoreSnapshot } from "./action-store.js";
export interface FrontierItem {
- action: Action;
+ action: import("../types.js").Action;
score: number;
- blockers: string[];
+ blockers: ActionBlocker[];
leased: boolean;
+ view: ActionReadinessView;
}
export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction("mem::frontier",
+ sdk.registerFunction(
+ "mem::frontier",
async (data: {
project?: string;
agentId?: string;
limit?: number;
includeLeasedByOthers?: boolean;
}) => {
- const actions = await kv.list(KV.actions);
- const edges = await kv.list(KV.actionEdges);
- const leases = await kv.list(KV.leases);
- const checkpoints = await kv.list(KV.checkpoints);
+ const [snapshot, leases, checkpoints, sentinels] = await Promise.all([
+ readActionStoreSnapshot(kv),
+ kv.list(KV.leases).catch(() => []),
+ kv.list(KV.checkpoints).catch(() => []),
+ kv.list(KV.sentinels).catch(() => []),
+ ]);
const now = Date.now();
-
- const activeLeaseMap = new Map();
- for (const lease of leases) {
- if (
- lease.status === "active" &&
- new Date(lease.expiresAt).getTime() > now
- ) {
- activeLeaseMap.set(lease.actionId, lease);
- }
- }
-
- const checkpointMap = new Map();
- for (const cp of checkpoints) {
- checkpointMap.set(cp.id, cp);
- }
-
- const actionMap = new Map();
- 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",
+ const viewContext = {
+ actions: snapshot.actions,
+ edges: snapshot.edges,
+ checkpoints,
+ sentinels,
+ leases,
+ agentId: data.includeLeasedByOthers ? undefined : data.agentId,
+ now,
+ };
+ const index = buildActionViewIndex(viewContext);
+ const frontier = snapshot.actions
+ .filter(
+ (action) =>
+ !data.project || matchesActionProject(action, data.project),
+ )
+ .map((action) =>
+ classifyAction(action, {
+ ...viewContext,
+ index,
+ }),
+ )
+ .filter((item) => item.view === "actionable")
+ .map((item) => ({
+ ...item,
+ score: computeActionScore(
+ item.action,
+ index.edgesByActionId.get(item.action.id) ?? [],
+ now,
+ ),
+ }))
+ .sort(
+ (left, right) =>
+ right.score - left.score ||
+ left.action.id.localeCompare(right.action.id),
);
- 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;
-
+ const limit =
+ Number.isInteger(data.limit) && (data.limit ?? 0) > 0
+ ? Math.min(data.limit!, 500)
+ : 20;
return {
success: true,
frontier: frontier.slice(0, limit),
- totalActions: actions.length,
+ totalActions: snapshot.actions.length,
totalUnblocked: frontier.length,
+ revision: snapshot.state.revision,
};
},
);
- sdk.registerFunction("mem::next",
+ sdk.registerFunction(
+ "mem::next",
async (data: { project?: string; agentId?: string }) => {
const result = await sdk.trigger<
{ project?: string; agentId?: string; limit?: number },
@@ -125,12 +99,12 @@ export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
frontier: FrontierItem[];
totalActions: number;
totalUnblocked: number;
+ revision: number;
}
- >({ function_id: "mem::frontier", payload: {
- project: data.project,
- agentId: data.agentId,
- limit: 1,
- } });
+ >({
+ function_id: "mem::frontier",
+ payload: { project: data.project, agentId: data.agentId, limit: 1 },
+ });
if (!result.success) {
return {
@@ -146,6 +120,8 @@ export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
suggestion: null,
message: "No actionable work found",
totalActions: result.totalActions || 0,
+ totalUnblocked: 0,
+ revision: result.revision,
};
}
@@ -159,36 +135,15 @@ export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
priority: top.action.priority,
score: top.score,
tags: top.action.tags,
+ view: top.view,
+ dueAt: top.action.dueAt,
+ owner: top.action.owner,
},
message: `Suggested: ${top.action.title} (priority ${top.action.priority}, score ${top.score.toFixed(2)})`,
totalActions: result.totalActions,
totalUnblocked: result.totalUnblocked,
+ revision: result.revision,
};
},
);
}
-
-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/governance.ts b/src/functions/governance.ts
index 16d0d1c427..97b899e4d8 100644
--- a/src/functions/governance.ts
+++ b/src/functions/governance.ts
@@ -2,11 +2,61 @@ import type { ISdk } from "iii-sdk";
import type { Memory, GovernanceFilter, AuditEntry } from "../types.js";
import { KV } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
+import { withKeyedLock } from "../state/keyed-mutex.js";
import { recordAudit, safeAudit, queryAudit } from "./audit.js";
import { deleteAccessLog } from "./access-tracker.js";
import { getSearchIndex, vectorIndexRemove, flushIndexSave } from "./search.js";
+import { stripMemoryReferences } from "../state/memory-utils.js";
import { logger } from "../logger.js";
+/**
+ * After memories are deleted, clear now-dangling `supersedes`/`parentId`/
+ * `relatedIds` back-references in the *surviving* memories. Returns the IDs of
+ * memories that were repaired and how many references were dropped, for audit
+ * and result reporting. Indexes are not touched: reference fields are not part
+ * of the search/vector observation shape.
+ *
+ * Each survivor is repaired under its per-memory keyed lock
+ * (`mem:memory:`, the same key diagnostics heal uses) with a fresh read
+ * immediately before stripping/writing, so a concurrent update to a survivor
+ * (e.g. a new `supersedes` added between the list and the write) is preserved
+ * rather than clobbered by a stale snapshot.
+ */
+async function clearDanglingMemoryReferences(
+ kv: StateKV,
+ deletedIds: string[],
+): Promise<{ repairedReferrers: string[]; removedCount: number }> {
+ if (deletedIds.length === 0) {
+ return { repairedReferrers: [], removedCount: 0 };
+ }
+ const removed = new Set(deletedIds);
+ // List once to pick candidate survivors; the authoritative read happens per
+ // memory inside the lock below.
+ const snapshot = await kv.list