` -> `taskSlug`;
+- `requires-confirmation`, `awaiting-human`, or `approval-required` ->
+ `awaitingHuman=true` and a pending approval.
+
+Invalid timestamps are preserved in tags and reported; they are not copied to
+typed fields. If a legacy blocked action has unresolved `requires` or
+`gated_by` edges, its block remains derived. If it is waiting for approval, it
+becomes `waiting`. Otherwise it receives `blockedReason="Legacy blocked state"`
+so no manual block disappears.
+
+## Append-only Events and Collection Revision
+
+`mem:action-events` stores immutable `ActionEvent` rows:
+
+```ts
+type ActionEventType =
+ | "created"
+ | "fields_changed"
+ | "lifecycle_changed"
+ | "result_recorded"
+ | "corrected"
+ | "migrated"
+ | "deleted"
+ | "edge_created"
+ | "edge_deleted";
+
+interface ActionEvent {
+ schemaVersion: 2;
+ id: string;
+ actionId: string;
+ revision: number;
+ type: ActionEventType;
+ actor: string;
+ timestamp: string;
+ reason?: string;
+ correctionOf?: string;
+ before?: Action | ActionEdge;
+ after?: Action | ActionEdge;
+}
+```
+
+There is no event update/delete API. Corrections append a `corrected` event and
+identify the corrected event when known. The action projection changes to the
+correct value; the original event remains.
+
+`mem:action-state/current` stores:
+
+```ts
+interface ActionCollectionState {
+ schemaVersion: 2;
+ revision: number;
+ updatedAt: string;
+ pending?: { revision: number; eventId: string };
+}
+```
+
+All action/edge projection writes use one keyed action-store lock and this
+recoverable sequence:
+
+1. write `pending` with the next revision and event ID;
+2. append the event containing the post-image;
+3. write or delete the projection;
+4. commit the collection revision and clear `pending`.
+
+If the worker stops mid-write, the next action-store operation reconciles the
+pending marker. An existing event is replayed into the projection; a marker
+without an event is cleared without advancing the revision. Normal reads never
+observe intermediate writes because they use the same in-process lock.
+
+Secondary action writers supply the projection they read as an optimistic base.
+The store rebases non-overlapping field changes onto the current projection and
+rejects same-field races with `action_revision_conflict`. This keeps checkpoint,
+lease, sketch, routine, mesh, crystallization, and healing updates from silently
+overwriting a concurrent action change even when their larger workflows use
+different entity locks.
+
+The existing audit log remains. Action events are the domain history; audit
+entries remain the system-wide operational record.
+
+## Readiness Views
+
+Readiness is derived at read time in this precedence order:
+
+1. lifecycle `done` -> `completed`;
+2. lifecycle `cancelled` -> `cancelled`;
+3. explicit `blockedReason`, rejected approval, unsatisfied `requires`, failed
+ or pending checkpoint/sentinel `gated_by`, an active conflict, or an unavailable lease ->
+ `blocked`;
+4. `awaitingHuman` or pending approval -> `waiting`;
+5. future `notBefore` -> `scheduled`;
+6. otherwise -> `actionable`.
+
+Each computed item includes structured blockers rather than only display
+strings. `memory_frontier` remains the actionable view and excludes leases held
+by other agents unless requested. `memory_next` remains the highest-ranked
+actionable item.
+
+`dueAt` does not block readiness. It adds a bounded urgency component to the
+existing priority/age score. Invalid or past `notBefore` values never crash a
+read; invalid persisted values are reported as blockers until corrected.
+
+## API and MCP Compatibility
+
+Existing names, required arguments, response fields, and status values remain
+valid.
+
+Additive changes:
+
+- action create accepts `projectId`, `projectAliases`, `owner`, `notBefore`,
+ `dueAt`, `awaitingHuman`, `approval`, `blockedReason`, `repoRoot`, `worktree`,
+ `branch`, `taskSlug`, and `actor`;
+- action update accepts the same mutable fields plus `lifecycle`, `actor`,
+ `correctionOf`, and `correctionReason`;
+- action list accepts `view`, `owner`, `cursor`, and `revision` and returns
+ `revision`, `nextCursor`, and computed view entries while retaining
+ `actions`, `total`, `limit`, `offset`, and `hasMore`;
+- a new `memory_action_list` MCP tool exposes the same bounded views;
+- frontier items gain additive `view` and structured blocker data;
+- REST handlers explicitly whitelist every forwarded field.
+
+Legacy `status="blocked"` updates create or retain a manual block. A later
+legacy `status="pending"` clears only that manual block; it does not approve a
+pending human decision or bypass dependencies/checkpoints.
+
+## Revision-bound Pagination
+
+Action pages are sorted deterministically by `updatedAt DESC, id ASC`.
+
+The first page returns the collection `revision` and an opaque cursor encoding
+the revision, offset, and a fingerprint of the filters. Subsequent requests
+must either pass that cursor or the same explicit revision. A changed
+collection, modified filter, malformed cursor, or mismatched revision returns
+a typed `revision_conflict`/`invalid_cursor` failure instead of a partial page.
+
+Offset-only calls remain supported for old clients but are not advertised as a
+complete snapshot mechanism.
+
+Checkpoint and sentinel transitions re-project their linked actions and append
+an action event. This advances the same collection revision used by cursors, so
+a gate changing between pages fails closed instead of silently changing the
+derived readiness set.
+
+## Export and Import
+
+`ExportData` gains optional `actionEvents` and `actionSnapshot` fields. Action,
+edge, event, and state reads occur under the action-store lock, so one export
+contains a self-consistent action revision.
+
+Old exports without v2 fields still import. Imported actions are normalized
+before persistence. Imported event IDs are deduplicated. A replace import also
+replaces action events/state; a merge import appends non-conflicting events and
+advances the local collection revision. Existing import safety limits gain
+bounded action/event limits.
+
+An export reports action count, edge count, event count, schema version, and
+revision. Import validates those counts when snapshot metadata is present and
+fails before mutation on mismatch.
+
+## Migration
+
+`POST /agentmemory/migrate` gains `step="actions-v2"` with whitelisted fields:
+
+- `dryRun` (default true);
+- `projectAliases` mapping legacy values to canonical IDs;
+- `defaultProjectId` (default `workstation`);
+- `limit` and opaque `cursor` for bounded batches.
+
+The migration:
+
+1. reads a deterministic page of actions;
+2. normalizes tags and typed context;
+3. resolves project identity and reports conflicts/inferences;
+4. derives lifecycle without removing the legacy status;
+5. appends one `migrated` event per changed action;
+6. writes the v2 projection and collection revision;
+7. returns counts, warnings, unresolved rows, revision, and next cursor.
+
+It skips already-normalized actions, making retries idempotent. Dry-run performs
+no KV writes, events, audit writes, or revision changes. A non-dry batch stops
+before mutation if any row has an invalid explicit canonical project ID or
+conflicting explicit identities. Inferred/defaulted mappings are warnings and
+remain reviewable in the result and event.
+
+## Failure Handling
+
+- Boundary validation rejects invalid lifecycle/status values, priorities,
+ approval combinations, project IDs, and timestamps.
+- No raw REST request body is forwarded to an internal function.
+- Migration errors identify action IDs but do not include secrets or full
+ descriptions/results.
+- Event/state recovery is idempotent and runs before action-store mutations or
+ revision-bound reads.
+- Existing v1 rows are normalized on read for classification, but only the
+ explicit migration or a mutation persists v2 fields.
+- No live migration is implicit at process startup.
+
+## Rollout Plan
+
+1. Merge code and documentation with all tests passing.
+2. Build a package from the exact merge commit; do not install it yet.
+3. Export and stop-backup the live store.
+4. Run `actions-v2` dry-run with aliases sourced by deployment tooling from the
+ external workspace project registry.
+5. Review conflicts, inferred mappings, counts, and projected revision.
+6. Install the package and restart only with explicit deployment approval.
+7. Run bounded migration batches, verifying counts and revision after each.
+8. Exercise old REST/MCP/CLI calls and new views against the migrated store.
+9. Keep v1 fields for at least one release before considering deprecation.
+
+## Acceptance Criteria
+
+- Existing action, frontier, next, lease, export/import, checkpoint, sentinel,
+ routine, sketch, crystallize, mesh, diagnostics, and MCP tests still pass.
+- New creates persist a complete v2 projection while old create inputs work.
+- String/list tags normalize without losing tokens.
+- Path aliases, tag project IDs, and unscoped rows migrate deterministically and
+ are reported by category.
+- Dry-run is byte-for-byte non-mutating and repeated migration is idempotent.
+- Every lifecycle, result, correction, and migration change appends an event
+ with actor and timestamp.
+- Manual blocks, dependencies, approvals, schedules, leases, and terminal
+ lifecycle states land in the correct readiness view.
+- A collection change between pages produces a revision conflict rather than
+ an incomplete export.
+- Export action counts/events/revision are internally consistent; old exports
+ remain importable.
+- No test or migration path touches the workstation live data store.
diff --git a/iii-config.docker.yaml b/iii-config.docker.yaml
index 682236ec37..f8d46dcfde 100644
--- a/iii-config.docker.yaml
+++ b/iii-config.docker.yaml
@@ -16,8 +16,18 @@ workers:
file_path: /data/state_store.db
- name: iii-queue
config:
+ queue_configs:
+ agentmemory-observations:
+ max_retries: 5
+ concurrency: 4
+ type: standard
+ backoff_ms: 250
+ poll_interval_ms: 50
adapter:
name: builtin
+ config:
+ store_method: file_based
+ file_path: /data/queue_store
- name: iii-pubsub
config:
adapter:
diff --git a/iii-config.yaml b/iii-config.yaml
index 62892f5143..25770e26b4 100644
--- a/iii-config.yaml
+++ b/iii-config.yaml
@@ -16,8 +16,18 @@ workers:
file_path: ./data/state_store.db
- name: iii-queue
config:
+ queue_configs:
+ agentmemory-observations:
+ max_retries: 5
+ concurrency: 4
+ type: standard
+ backoff_ms: 250
+ poll_interval_ms: 50
adapter:
name: builtin
+ config:
+ store_method: file_based
+ file_path: ./data/queue_store
- name: iii-pubsub
config:
adapter:
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..f351b2c8bc 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, 54 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..f135276f48 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, 54 MCP tools, 8 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
"url": "https://github.com/rohitg00"
diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md
index 60f5e5bb94..6bcc4b321e 100644
--- a/plugin/opencode/README.md
+++ b/plugin/opencode/README.md
@@ -9,7 +9,7 @@
-
+
diff --git a/plugin/plugin.json b/plugin/plugin.json
index 9d0751a7ab..e6e34d7da6 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, 54 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..c3be22d835 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) {
@@ -74,7 +153,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..5875c3c576 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) {
@@ -50,16 +126,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 +155,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..fded47a1ef 100644
--- a/plugin/skills/agentmemory-config/REFERENCE.md
+++ b/plugin/skills/agentmemory-config/REFERENCE.md
@@ -3,36 +3,53 @@
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). 51 recognized variables:
- `AGENTMEMORY_AGENT_SCOPE`
- `AGENTMEMORY_ALLOW_AGENT_SDK`
- `AGENTMEMORY_AUTO_COMPRESS`
+- `AGENTMEMORY_BUILD_ID`
+- `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_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_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`
diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
index 0c556fc77f..00f1b85345 100644
--- a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
+++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
@@ -3,19 +3,20 @@
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 54 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. |
@@ -28,7 +29,7 @@ agentmemory exposes 53 MCP tools. 8 are in the lean core set (`--tools core` or
| `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_recall` | yes | `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_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. |
@@ -36,13 +37,13 @@ agentmemory exposes 53 MCP tools. 8 are in the lean core set (`--tools core` or
| `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..598a3332ee 100644
--- a/plugin/skills/agentmemory-rest-api/REFERENCE.md
+++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md
@@ -5,7 +5,7 @@ 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:
+119 registered endpoints:
| Method | Path |
| --- | --- |
@@ -77,6 +77,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 +99,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..bf8b6b4261 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,8 @@ 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
+ Tool visibility (default: all = ${ALL_TOOLS_COUNT}; core = ${CORE_TOOLS_COUNT}; workstation = curated coordination set)
--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 +204,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 +221,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 +230,14 @@ 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"].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, 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 +1205,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 +1426,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 +1440,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";
@@ -2649,6 +2678,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));
@@ -2982,6 +3016,7 @@ const commands: Record Promise> = {
stop: runStop,
remove: runRemove,
mcp: runMcp,
+ "mcp-http": runMcpHttp,
"import-jsonl": runImportJsonl,
};
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..c97fc16a5f 100644
--- a/src/functions/actions.ts
+++ b/src/functions/actions.ts
@@ -1,46 +1,119 @@
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",
+]);
- 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 +121,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,
+ };
});
- },
- );
-
- 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" };
- }
+ } catch (error) {
+ return actionStoreError(error);
+ }
+ });
- 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 };
+ sdk.registerFunction("mem::action-update", async (data: ActionUpdateInput) => {
+ const validationError = validateUpdateInput(data);
+ if (validationError) return { success: false, error: validationError };
- 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 +292,555 @@ 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-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-list",
+ 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);
}
-
- actions.sort(
- (a, b) =>
- new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
- );
-
- const limit = data.limit || 50;
- return { success: true, actions: actions.slice(0, limit) };
},
);
+}
- sdk.registerFunction("mem::action-get",
- async (data: { actionId: string }) => {
- if (!data.actionId) {
- return { success: false, error: "actionId is required" };
- }
- const action = await kv.get(KV.actions, data.actionId);
- if (!action) {
- return { success: false, error: "action not found" };
- }
-
- const allEdges = await kv.list(KV.actionEdges);
- const edges = allEdges.filter(
- (e) =>
- e.sourceActionId === data.actionId ||
- e.targetActionId === data.actionId,
- );
-
- const children = (await kv.list(KV.actions)).filter(
- (a) => a.parentId === data.actionId,
- );
-
- return { success: true, action, edges, children };
- },
+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`,
+ });
+ }
}
-async function propagateCompletion(
+export async function propagateActionCompletion(
kv: StateKV,
completedActionId: string,
+ actor: string,
): Promise {
- const allEdges = await kv.list(KV.actionEdges);
- const unlockEdges = allEdges.filter(
- (e) =>
- e.targetActionId === completedActionId &&
- (e.type === "requires" || e.type === "unlocks"),
+ await withActionStoreLock(async () => {
+ await recoverActionStoreUnlocked(kv);
+ await propagateCompletionUnlocked(kv, completedActionId, actor);
+ });
+}
+
+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 allActions = await kv.list(KV.actions);
- const actionMap = new Map(allActions.map((a) => [a.id, a]));
+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);
+}
- 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 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`;
}
- });
+ }
+ 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;
}
+
+function normalizePriority(value?: number): number {
+ return Math.max(1, Math.min(10, value || 5));
+}
+
+function isValidEdgeType(value: string): value is ActionEdge["type"] {
+ return VALID_EDGE_TYPES.includes(value as ActionEdge["type"]);
+}
+
+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/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.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/crystallize.ts b/src/functions/crystallize.ts
index 1f0b84316d..98598c13fc 100644
--- a/src/functions/crystallize.ts
+++ b/src/functions/crystallize.ts
@@ -2,6 +2,7 @@ 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 { persistAction } from "./action-store.js";
interface CrystalDigest {
narrative: string;
@@ -92,7 +93,11 @@ export function registerCrystallizeFunction(
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 };
diff --git a/src/functions/diagnostics.ts b/src/functions/diagnostics.ts
index cc982883f6..18526a8632 100644
--- a/src/functions/diagnostics.ts
+++ b/src/functions/diagnostics.ts
@@ -3,6 +3,11 @@ 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 type {
Action,
ActionEdge,
@@ -685,9 +690,16 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
return target && target.status === "done";
});
if (!stillAllDone) 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 +756,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 +830,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 +978,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 +990,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",
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/export-import.ts b/src/functions/export-import.ts
index 327117b265..aafb04c65d 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -12,6 +12,8 @@ import type {
ProceduralMemory,
Action,
ActionEdge,
+ ActionCollectionState,
+ ActionEvent,
Routine,
Signal,
Checkpoint,
@@ -30,6 +32,14 @@ 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";
export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::export",
@@ -77,8 +87,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
graphEdges,
semanticMemories,
proceduralMemories,
- actions,
- actionEdges,
+ actionStore,
sentinels,
sketches,
crystals,
@@ -94,8 +103,7 @@ 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(() => []),
@@ -122,8 +130,19 @@ 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,
@@ -190,6 +209,9 @@ 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;
if (!Array.isArray(importData.sessions)) {
return { success: false, error: "sessions must be an array" };
@@ -255,11 +277,160 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
};
}
+ 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}`,
+ };
+ }
+ }
+ }
+
const stats = {
sessions: 0,
observations: 0,
memories: 0,
summaries: 0,
+ actions: 0,
+ actionEdges: 0,
+ actionEvents: 0,
skipped: 0,
};
@@ -282,12 +453,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);
}
@@ -448,24 +613,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") {
@@ -585,3 +836,117 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
},
);
}
+
+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/image-quota-cleanup.ts b/src/functions/image-quota-cleanup.ts
index d07dfa9698..92028a3f85 100644
--- a/src/functions/image-quota-cleanup.ts
+++ b/src/functions/image-quota-cleanup.ts
@@ -1,4 +1,4 @@
-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 { readdir, stat } from "node:fs/promises";
@@ -6,6 +6,7 @@ import { join } from "node:path";
import { IMAGES_DIR, getMaxBytes, deleteImage } from "../utils/image-store.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import { logger } from "../logger.js";
+import { triggerDetached } from "../utils/trigger-detached.js";
const GRACE_PERIOD_MS = 30_000;
@@ -75,10 +76,9 @@ export function registerImageQuotaCleanup(sdk: ISdk, kv: StateKV): void {
const { deletedBytes } = await deleteImage(f.filePath);
if (deletedBytes > 0) {
- sdk.trigger({
+ triggerDetached(sdk, {
function_id: "mem::disk-size-delta",
payload: { deltaBytes: -deletedBytes },
- action: TriggerAction.Void(),
});
totalToFree -= deletedBytes;
freedBytes += deletedBytes;
diff --git a/src/functions/image-refs.ts b/src/functions/image-refs.ts
index ce1661df42..60d91adf84 100644
--- a/src/functions/image-refs.ts
+++ b/src/functions/image-refs.ts
@@ -1,8 +1,9 @@
-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 { deleteImage, touchImage } from "../utils/image-store.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
+import { triggerDetached } from "../utils/trigger-detached.js";
export async function getImageRefCount(kv: StateKV, filePath: string): Promise {
const count = await kv.get(KV.imageRefs, filePath);
@@ -25,10 +26,9 @@ export async function decrementImageRef(kv: StateKV, sdk: ISdk, filePath: string
await kv.delete(KV.imageRefs, filePath);
const { deletedBytes } = await deleteImage(filePath);
if (deletedBytes > 0) {
- sdk.trigger({
+ triggerDetached(sdk, {
function_id: "mem::disk-size-delta",
payload: { deltaBytes: -deletedBytes },
- action: TriggerAction.Void(),
});
}
} else {
diff --git a/src/functions/leases.ts b/src/functions/leases.ts
index 1a2de33bfc..de1ca03049 100644
--- a/src/functions/leases.ts
+++ b/src/functions/leases.ts
@@ -2,8 +2,15 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
-import type { Action, Lease } from "../types.js";
+import type { Action, Checkpoint, Lease, Sentinel } from "../types.js";
import { recordAudit } from "./audit.js";
+import {
+ ActionRevisionConflictError,
+ persistAction,
+ readActionStoreSnapshot,
+} from "./action-store.js";
+import { propagateActionCompletion } from "./actions.js";
+import { classifyAction } from "./action-model.js";
const DEFAULT_LEASE_TTL_MS = 10 * 60 * 1000;
const MAX_LEASE_TTL_MS = 60 * 60 * 1000;
@@ -28,18 +35,19 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
if (action.status === "done" || action.status === "cancelled") {
return { success: false, error: "action already completed" };
}
- if (action.status === "blocked") {
- return { success: false, error: "action is blocked" };
- }
-
- const existingLeases = await kv.list(KV.leases);
+ const [snapshot, existingLeases, checkpoints, sentinels] =
+ await Promise.all([
+ readActionStoreSnapshot(kv),
+ kv.list(KV.leases),
+ kv.list(KV.checkpoints).catch(() => []),
+ kv.list(KV.sentinels).catch(() => []),
+ ]);
const activeLease = existingLeases.find(
- (l) =>
- l.actionId === data.actionId &&
- l.status === "active" &&
- new Date(l.expiresAt).getTime() > Date.now(),
+ (lease) =>
+ lease.actionId === data.actionId &&
+ lease.status === "active" &&
+ new Date(lease.expiresAt).getTime() > Date.now(),
);
-
if (activeLease) {
if (activeLease.agentId === data.agentId) {
return {
@@ -56,6 +64,21 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
expiresAt: activeLease.expiresAt,
};
}
+ const readiness = classifyAction(action, {
+ actions: snapshot.actions,
+ edges: snapshot.edges,
+ checkpoints,
+ sentinels,
+ leases: existingLeases,
+ agentId: data.agentId,
+ });
+ if (readiness.view !== "actionable") {
+ return {
+ success: false,
+ error: `action is ${readiness.view}`,
+ blockers: readiness.blockers,
+ };
+ }
const now = new Date();
const lease: Lease = {
@@ -68,20 +91,37 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.leases, lease.id, lease);
+ const before = { ...action };
+ action.status = "active";
+ action.lifecycle = "active";
+ action.assignedTo = data.agentId;
+ action.updatedAt = now.toISOString();
+ let persisted: Awaited>;
+ try {
+ persisted = await persistAction(kv, action, {
+ actor: data.agentId,
+ before,
+ reason: "lease acquired",
+ });
+ } catch (error) {
+ await kv.delete(KV.leases, lease.id).catch(() => {});
+ if (error instanceof ActionRevisionConflictError) {
+ return {
+ success: false,
+ error: "action_revision_conflict",
+ fields: error.fields,
+ };
+ }
+ throw error;
+ }
await recordAudit(kv, "lease_acquire", "mem::lease-acquire", [lease.id], {
actionId: data.actionId,
agentId: data.agentId,
expiresAt: lease.expiresAt,
});
-
- const before = { ...action };
- action.status = "active";
- action.assignedTo = data.agentId;
- action.updatedAt = now.toISOString();
- await kv.set(KV.actions, action.id, action);
await recordAudit(kv, "action_update", "mem::lease-acquire", [action.id], {
before,
- after: action,
+ after: persisted.action,
});
return { success: true, lease, renewed: false };
@@ -122,18 +162,39 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
const before = { ...action };
if (data.result) {
action.status = "done";
+ action.lifecycle = "done";
action.result = data.result;
} else {
action.status = "pending";
+ action.lifecycle = "pending";
}
action.assignedTo = undefined;
action.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, action.id, action);
+ const persisted = await persistAction(kv, action, {
+ actor: data.agentId,
+ before,
+ reason: data.result ? "lease released with result" : "lease released",
+ });
await recordAudit(kv, "action_update", "mem::lease-release", [action.id], {
before,
- after: action,
+ after: persisted.action,
agentId: data.agentId,
});
+ if (data.result) {
+ await propagateActionCompletion(kv, action.id, data.agentId);
+ }
+ } else if (
+ action &&
+ action.status !== "done" &&
+ action.status !== "cancelled"
+ ) {
+ const before = structuredClone(action);
+ action.updatedAt = new Date().toISOString();
+ await persistAction(kv, action, {
+ actor: data.agentId,
+ before,
+ reason: "lease released; readiness revision refreshed",
+ });
}
return { success: true, released: true };
@@ -228,15 +289,34 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
action.status === "active" &&
action.assignedTo === currentLease.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: "lease-cleanup",
+ before,
+ reason: "expired lease cleanup",
+ });
await recordAudit(kv, "action_update", "mem::lease-cleanup", [action.id], {
action: "status-change",
newStatus: action.status,
actionId: action.id,
});
+ } else if (
+ action &&
+ !otherActiveLease &&
+ action.status !== "done" &&
+ action.status !== "cancelled"
+ ) {
+ const before = structuredClone(action);
+ action.updatedAt = new Date().toISOString();
+ await persistAction(kv, action, {
+ actor: "lease-cleanup",
+ before,
+ reason: "expired lease; readiness revision refreshed",
+ });
}
return true;
},
diff --git a/src/functions/mesh.ts b/src/functions/mesh.ts
index ad52e5ea73..446d2faf0c 100644
--- a/src/functions/mesh.ts
+++ b/src/functions/mesh.ts
@@ -15,6 +15,7 @@ import type {
} from "../types.js";
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
+import { persistAction } from "./action-store.js";
function isPrivateIP(ip: string): boolean {
if (ip === "127.0.0.1" || ip === "::1" || ip === "0.0.0.0") return true;
@@ -105,6 +106,42 @@ async function lwwMergeList(
return count;
}
+async function lwwMergeActions(
+ kv: StateKV,
+ items: Action[] | undefined,
+): Promise {
+ if (!items || !Array.isArray(items)) return 0;
+ let count = 0;
+ for (const item of items) {
+ if (
+ !item?.id ||
+ typeof item.id !== "string" ||
+ typeof item.updatedAt !== "string" ||
+ Number.isNaN(Date.parse(item.updatedAt))
+ ) {
+ continue;
+ }
+ const wrote = await withKeyedLock(`mem:action:${item.id}`, async () => {
+ const existing = await kv.get(KV.actions, item.id);
+ if (
+ existing &&
+ Date.parse(existing.updatedAt) >= Date.parse(item.updatedAt)
+ ) {
+ return false;
+ }
+ await persistAction(kv, item, {
+ actor: "mesh-sync",
+ before: existing,
+ type: existing ? "fields_changed" : "created",
+ reason: "Last-write-wins mesh synchronization",
+ });
+ return true;
+ });
+ if (wrote) count++;
+ }
+ return count;
+}
+
function graphNodeTs(node: GraphNode): string {
return node.updatedAt || node.createdAt;
}
@@ -340,7 +377,7 @@ export function registerMeshFunction(
let accepted = 0;
accepted += await lwwMergeList(kv, KV.memories, data.memories, "mem:memory", "updatedAt");
- accepted += await lwwMergeList(kv, KV.actions, data.actions, "mem:action", "updatedAt");
+ accepted += await lwwMergeActions(kv, data.actions);
accepted += await lwwMergeList(kv, KV.semantic, data.semantic, "mem:semantic", "updatedAt");
accepted += await lwwMergeList(kv, KV.procedural, data.procedural, "mem:procedural", "updatedAt");
if (data.relations && Array.isArray(data.relations)) {
@@ -461,7 +498,7 @@ async function applySyncData(
applied += await lwwMergeList(kv, KV.memories, data.memories, "mem:memory", "updatedAt");
}
if (scopes.includes("actions")) {
- applied += await lwwMergeList(kv, KV.actions, data.actions, "mem:action", "updatedAt");
+ applied += await lwwMergeActions(kv, data.actions);
}
if (scopes.includes("semantic")) {
applied += await lwwMergeList(kv, KV.semantic, data.semantic, "mem:semantic", "updatedAt");
diff --git a/src/functions/migrate.ts b/src/functions/migrate.ts
index c2039ea1c3..5963f279ed 100644
--- a/src/functions/migrate.ts
+++ b/src/functions/migrate.ts
@@ -10,6 +10,10 @@ import type {
SessionSummary,
} from "../types.js";
import { logger } from "../logger.js";
+import {
+ migrateActionsV2,
+ type ActionsV2MigrationInput,
+} from "./actions-v2-migration.js";
const ALLOWED_DIRS = [resolve(homedir(), ".agentmemory")];
@@ -87,8 +91,42 @@ export async function inferMemoryProjects(
export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::migrate",
- async (data: { dbPath?: string; step?: string; dryRun?: boolean }) => {
+ async (data: {
+ dbPath?: string;
+ step?: string;
+ dryRun?: boolean;
+ projectAliases?: Record;
+ defaultProjectId?: string;
+ limit?: number;
+ cursor?: string;
+ actor?: string;
+ }) => {
// In-place KV migration steps (no SQLite dependency).
+ if (data.step === "actions-v2") {
+ const migrationInput: ActionsV2MigrationInput = {
+ dryRun: data.dryRun ?? true,
+ projectAliases: data.projectAliases,
+ defaultProjectId: data.defaultProjectId,
+ limit: data.limit,
+ cursor: data.cursor,
+ actor: data.actor,
+ };
+ logger.info("Migration step: actions-v2", {
+ dryRun: migrationInput.dryRun,
+ limit: migrationInput.limit,
+ hasCursor: Boolean(migrationInput.cursor),
+ aliasCount: Object.keys(migrationInput.projectAliases ?? {}).length,
+ });
+ try {
+ return await migrateActionsV2(kv, migrationInput);
+ } catch (error) {
+ return {
+ success: false,
+ step: "actions-v2",
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
if (data.step === "infer-memory-projects") {
const dryRun = data.dryRun ?? false;
logger.info("Migration step: infer-memory-projects", { dryRun });
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index 8ad4ba0ff5..2ec4bde99f 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -1,5 +1,5 @@
-import { TriggerAction, type ISdk } from "iii-sdk";
-import type { RawObservation, HookPayload } from "../types.js";
+import type { ISdk } from "iii-sdk";
+import type { RawObservation, HookPayload, Session } from "../types.js";
import { KV, STREAM, generateId } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { stripPrivateData } from "./privacy.js";
@@ -11,6 +11,18 @@ import { getSearchIndex, vectorIndexAddGuarded } from "./search.js";
import { getAgentId } from "../config.js";
import { logger } from "../logger.js";
import { saveImageToDisk } from "../utils/image-store.js";
+import { safeAudit } from "./audit.js";
+import { triggerDetached } from "../utils/trigger-detached.js";
+
+const SESSION_CONTEXT_FIELDS = [
+ "project",
+ "cwd",
+ "repoRoot",
+ "scopeType",
+ "worktree",
+ "branch",
+ "taskSlug",
+] as const;
export function extractImage(d: unknown): string | undefined {
if (!d) return undefined;
@@ -59,7 +71,12 @@ export function registerObserveFunction(
};
}
- const obsId = generateId("obs");
+ const requestedObservationId =
+ typeof payload.observationId === "string" &&
+ /^obs_[a-z0-9_]{1,96}$/i.test(payload.observationId.trim())
+ ? payload.observationId.trim()
+ : undefined;
+ const obsId = requestedObservationId ?? generateId("obs");
let dedupHash: string | undefined;
if (dedupMap) {
@@ -73,9 +90,6 @@ export function registerObserveFunction(
toolName,
d["tool_input"],
);
- if (dedupMap.isDuplicate(dedupHash)) {
- return { deduplicated: true, sessionId: payload.sessionId };
- }
}
let sanitizedRaw: unknown = payload.data;
@@ -125,9 +139,38 @@ export function registerObserveFunction(
const pendingImageData = extractedImage;
return withKeyedLock(`obs:${payload.sessionId}`, async () => {
+ const observationScope = KV.observations(payload.sessionId);
+ const existingObservation = requestedObservationId
+ ? await kv.get(
+ observationScope,
+ obsId,
+ )
+ : null;
+ if (existingObservation && "title" in existingObservation) {
+ return {
+ observationId: obsId,
+ deduplicated: true,
+ durableRetry: true,
+ };
+ }
+ if (existingObservation) {
+ Object.assign(raw, existingObservation);
+ }
+ if (
+ !existingObservation &&
+ dedupMap &&
+ dedupHash &&
+ dedupMap.isDuplicate(dedupHash)
+ ) {
+ return { deduplicated: true, sessionId: payload.sessionId };
+ }
+
if (maxObservationsPerSession && maxObservationsPerSession > 0) {
- const existing = await kv.list(KV.observations(payload.sessionId));
- if (existing.length >= maxObservationsPerSession) {
+ const existing = await kv.list(observationScope);
+ if (
+ !existingObservation &&
+ existing.length >= maxObservationsPerSession
+ ) {
return {
success: false,
error: `Session observation limit reached (${maxObservationsPerSession})`,
@@ -139,11 +182,10 @@ export function registerObserveFunction(
// undefined). Env AGENT_ID only fires when no session row
// exists yet — otherwise an unscoped session would get
// retroactively scoped by a later AGENT_ID export.
- const existingSession = await kv.get<{
- agentId?: string;
- observationCount?: number;
- firstPrompt?: string;
- }>(KV.sessions, payload.sessionId);
+ const existingSession = await kv.get(
+ KV.sessions,
+ payload.sessionId,
+ );
const inheritedAgentId = existingSession
? existingSession.agentId
: getAgentId();
@@ -151,33 +193,37 @@ export function registerObserveFunction(
raw.agentId = inheritedAgentId;
}
- if (pendingImageData && (pendingImageData.startsWith("data:image/") || pendingImageData.startsWith("iVBORw0KGgo") || pendingImageData.startsWith("/9j/"))) {
+ if (
+ !existingObservation &&
+ pendingImageData &&
+ (pendingImageData.startsWith("data:image/") ||
+ pendingImageData.startsWith("iVBORw0KGgo") ||
+ pendingImageData.startsWith("/9j/"))
+ ) {
const { filePath, bytesWritten } = await saveImageToDisk(pendingImageData);
raw.imageData = filePath;
const { incrementImageRef } = await import("./image-refs.js");
await incrementImageRef(kv, filePath);
- sdk.trigger({
+ triggerDetached(sdk, {
function_id: "mem::disk-size-delta",
payload: { deltaBytes: bytesWritten },
- action: TriggerAction.Void(),
});
if (process.env["AGENTMEMORY_IMAGE_EMBEDDINGS"] === "true") {
- sdk.trigger({
+ triggerDetached(sdk, {
function_id: "mem::vision-embed",
payload: {
imageRef: filePath,
sessionId: payload.sessionId,
observationId: obsId,
},
- action: TriggerAction.Void(),
});
}
}
try {
-
- await kv.set(KV.observations(payload.sessionId), obsId, raw);
-
+ if (!existingObservation) {
+ await kv.set(observationScope, obsId, raw);
+ }
} catch (error) {
if (raw.imageData) {
// Roll back the ref taken above. decrementImageRef deletes the file
@@ -199,42 +245,65 @@ export function registerObserveFunction(
throw error;
}
- if (dedupMap && dedupHash) {
+ if (!existingObservation && dedupMap && dedupHash) {
dedupMap.record(dedupHash);
}
- await sdk.trigger({
- function_id: "stream::set",
- payload: {
- stream_name: STREAM.name,
- group_id: STREAM.group(payload.sessionId),
- item_id: obsId,
- data: { type: "raw", observation: raw },
- },
- });
+ if (!existingObservation) {
+ await sdk.trigger({
+ function_id: "stream::set",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.group(payload.sessionId),
+ item_id: obsId,
+ data: { type: "raw", observation: raw },
+ },
+ });
- await sdk.trigger({
- function_id: "stream::send",
- payload: {
- stream_name: STREAM.name,
- group_id: STREAM.viewerGroup,
- id: `raw-${obsId}`,
- type: "raw_observation",
- data: { type: "raw", observation: raw, sessionId: payload.sessionId },
- },
- action: TriggerAction.Void(),
- });
+ triggerDetached(sdk, {
+ function_id: "stream::send",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.viewerGroup,
+ id: `raw-${obsId}`,
+ type: "raw_observation",
+ data: { type: "raw", observation: raw, sessionId: payload.sessionId },
+ },
+ });
+ }
const session = existingSession;
if (session) {
+ const updatedAt = new Date().toISOString();
+ const changedContext: string[] = [];
const updates: Array<{ type: "set"; path: string; value: unknown }> = [
- { type: "set", path: "updatedAt", value: new Date().toISOString() },
+ { type: "set", path: "updatedAt", value: updatedAt },
{
type: "set",
path: "observationCount",
- value: (session.observationCount || 0) + 1,
+ value: requestedObservationId
+ ? (await kv.list(observationScope)).length
+ : (session.observationCount || 0) + 1,
},
];
+ for (const field of SESSION_CONTEXT_FIELDS) {
+ const value = payload[field];
+ if (typeof value !== "string" || !value.trim()) continue;
+ const normalized = value.trim();
+ if (session[field] === normalized) continue;
+ updates.push({ type: "set", path: field, value: normalized });
+ changedContext.push(field);
+ }
+ if (changedContext.includes("project") && session.project) {
+ const aliases = new Set(session.projectAliases ?? []);
+ aliases.add(session.project);
+ aliases.delete(payload.project.trim());
+ updates.push({
+ type: "set",
+ path: "projectAliases",
+ value: [...aliases].sort(),
+ });
+ }
if (!session.firstPrompt && typeof raw.userPrompt === "string") {
const trimmed = raw.userPrompt.replace(/\s+/g, " ").trim();
if (trimmed.length > 0) {
@@ -246,6 +315,15 @@ export function registerObserveFunction(
}
}
await kv.update(KV.sessions, payload.sessionId, updates);
+ if (changedContext.length > 0) {
+ await safeAudit(
+ kv,
+ "session_context_update",
+ "mem::observe",
+ [payload.sessionId],
+ { changed: changedContext },
+ );
+ }
} else if (
typeof payload.project === "string" &&
payload.project.trim().length > 0 &&
@@ -269,6 +347,11 @@ export function registerObserveFunction(
id: payload.sessionId,
project: payload.project,
cwd: payload.cwd,
+ ...(payload.repoRoot ? { repoRoot: payload.repoRoot } : {}),
+ ...(payload.scopeType ? { scopeType: payload.scopeType } : {}),
+ ...(payload.worktree ? { worktree: payload.worktree } : {}),
+ ...(payload.branch ? { branch: payload.branch } : {}),
+ ...(payload.taskSlug ? { taskSlug: payload.taskSlug } : {}),
startedAt: payload.timestamp ?? ts,
updatedAt: ts,
status: "active",
@@ -285,15 +368,18 @@ export function registerObserveFunction(
// and BM25 search still work without burning the user's Claude
// token allocation on every tool invocation.
if (isAutoCompressEnabled()) {
- await sdk.trigger({
- function_id: "mem::compress",
- payload: {
- observationId: obsId,
- sessionId: payload.sessionId,
- raw,
+ triggerDetached(
+ sdk,
+ {
+ function_id: "mem::compress",
+ payload: {
+ observationId: obsId,
+ sessionId: payload.sessionId,
+ raw,
+ },
},
- action: TriggerAction.Void(),
- });
+ { sessionId: payload.sessionId, observationId: obsId },
+ );
} else {
const synthetic = buildSyntheticCompression(raw);
await kv.set(
@@ -317,12 +403,13 @@ export function registerObserveFunction(
data: { type: "compressed", observation: synthetic },
},
});
- await sdk.trigger({
- function_id: "stream::set",
+ triggerDetached(sdk, {
+ function_id: "stream::send",
payload: {
stream_name: STREAM.name,
group_id: STREAM.viewerGroup,
- item_id: obsId,
+ id: `compressed-${obsId}`,
+ type: "compressed_observation",
data: {
type: "compressed",
observation: synthetic,
diff --git a/src/functions/remember.ts b/src/functions/remember.ts
index 5735b4f238..0621989486 100644
--- a/src/functions/remember.ts
+++ b/src/functions/remember.ts
@@ -1,4 +1,4 @@
-import { TriggerAction, type ISdk } from "iii-sdk";
+import type { ISdk } from "iii-sdk";
import type { Memory } from "../types.js";
import { KV, generateId, jaccardSimilarity } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
@@ -153,7 +153,6 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
payload: {
supersededMemoryId: supersededId,
},
- action: TriggerAction.Void(),
});
}
diff --git a/src/functions/routines.ts b/src/functions/routines.ts
index d1a9135a9e..75f7d5543c 100644
--- a/src/functions/routines.ts
+++ b/src/functions/routines.ts
@@ -4,6 +4,7 @@ import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, Routine, RoutineStep, RoutineRun } from "../types.js";
import { recordAudit } from "./audit.js";
+import { persistAction, persistActionEdge } from "./action-store.js";
export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::routine-create",
@@ -138,7 +139,13 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
metadata: { routineId: routine.id, stepOrder: step.order },
};
- await kv.set(KV.actions, action.id, action);
+ await persistAction(kv, action, {
+ actor: data.initiatedBy || "routine",
+ type: "created",
+ before: null,
+ hasDerivedBlockers: hasDeps,
+ reason: `Routine ${routine.id} instantiated`,
+ });
stepOrderToActionId.set(step.order, action.id);
actionIds.push(action.id);
stepStatus[step.order] = "pending";
@@ -158,7 +165,11 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
targetActionId: depActionId,
createdAt: now,
};
- await kv.set(KV.actionEdges, edge.id, edge);
+ await persistActionEdge(kv, edge, {
+ actor: data.initiatedBy || "routine",
+ before: null,
+ reason: `Routine ${routine.id} dependency`,
+ });
}
}
diff --git a/src/functions/sentinels.ts b/src/functions/sentinels.ts
index ed29aee940..f70175033b 100644
--- a/src/functions/sentinels.ts
+++ b/src/functions/sentinels.ts
@@ -2,8 +2,10 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
-import type { Action, ActionEdge, Checkpoint, CompressedObservation, FunctionMetrics, Sentinel, Session } from "../types.js";
+import type { Action, ActionEdge, CompressedObservation, FunctionMetrics, Sentinel, Session } from "../types.js";
import { recordAudit } from "./audit.js";
+import { persistActionEdge } from "./action-store.js";
+import { refreshLinkedActionReadiness } from "./action-readiness-refresh.js";
const VALID_TYPES: Sentinel["type"][] = [
"webhook",
@@ -123,13 +125,23 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
targetActionId: sentinel.id,
createdAt: now.toISOString(),
};
- await kv.set(KV.actionEdges, edge.id, edge);
+ await persistActionEdge(kv, edge, {
+ actor: "sentinel-create",
+ before: null,
+ reason: `Sentinel ${sentinel.id} gate added`,
+ });
await recordAudit(kv, "sentinel_create", "mem::sentinel-create", [edge.id], {
action: "sentinel.create.edge",
sentinelId: sentinel.id,
sourceActionId: actionId,
});
}
+ await refreshLinkedActionReadiness(
+ kv,
+ data.linkedActionIds,
+ "sentinel-create",
+ `Sentinel ${sentinel.id} gate added`,
+ );
}
if (data.type === "timer") {
@@ -148,7 +160,12 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
reason: "timer_elapsed",
durationMs,
});
- await unblockLinkedActions(kv, fresh);
+ await refreshLinkedActionReadiness(
+ kv,
+ fresh.linkedActionIds,
+ "sentinel-timer",
+ `Sentinel ${fresh.id} triggered`,
+ );
});
} catch (err) {
console.error("sentinel timer callback failed", sentinel.id, err);
@@ -193,10 +210,12 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
result: data.result,
});
- let unblockedCount = 0;
- if (sentinel.linkedActionIds.length > 0) {
- unblockedCount = await unblockLinkedActions(kv, sentinel);
- }
+ const unblockedCount = await refreshLinkedActionReadiness(
+ kv,
+ sentinel.linkedActionIds,
+ "sentinel-trigger",
+ `Sentinel ${sentinel.id} triggered`,
+ );
return { success: true, sentinel, unblockedCount };
},
@@ -252,7 +271,12 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
action: "sentinel.threshold_trigger",
result: fresh.result,
});
- await unblockLinkedActions(kv, fresh);
+ await refreshLinkedActionReadiness(
+ kv,
+ fresh.linkedActionIds,
+ "sentinel-check",
+ `Sentinel ${fresh.id} threshold triggered`,
+ );
},
);
triggered.push(sentinel.id);
@@ -304,7 +328,12 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
action: "sentinel.pattern_trigger",
result: fresh.result,
});
- await unblockLinkedActions(kv, fresh);
+ await refreshLinkedActionReadiness(
+ kv,
+ fresh.linkedActionIds,
+ "sentinel-check",
+ `Sentinel ${fresh.id} pattern triggered`,
+ );
},
);
triggered.push(sentinel.id);
@@ -345,6 +374,12 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
action: "sentinel.cancel",
status: "cancelled",
});
+ await refreshLinkedActionReadiness(
+ kv,
+ sentinel.linkedActionIds,
+ "sentinel-cancel",
+ `Sentinel ${sentinel.id} cancelled`,
+ );
return { success: true, sentinel };
},
@@ -399,6 +434,12 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
action: "sentinel.expire",
status: "expired",
});
+ await refreshLinkedActionReadiness(
+ kv,
+ fresh.linkedActionIds,
+ "sentinel-expire",
+ `Sentinel ${fresh.id} expired`,
+ );
return true;
},
);
@@ -410,46 +451,3 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
},
);
}
-
-async function unblockLinkedActions(
- kv: StateKV,
- sentinel: Sentinel,
-): Promise {
- if (sentinel.linkedActionIds.length === 0) return 0;
-
- const allEdges = await kv.list(KV.actionEdges);
- const allSentinels = await kv.list(KV.sentinels);
- const allCheckpoints = await kv.list(KV.checkpoints);
- const gateMap = new Map();
- for (const s of allSentinels) gateMap.set(s.id, { status: s.status === "triggered" ? "passed" : s.status });
- for (const c of allCheckpoints) gateMap.set(c.id, { status: c.status });
-
- let unblockedCount = 0;
-
- for (const actionId of sentinel.linkedActionIds) {
- await withKeyedLock(`mem:action:${actionId}`, async () => {
- const action = await kv.get(KV.actions, actionId);
- if (action && action.status === "blocked") {
- const gates = allEdges.filter(
- (e) => e.sourceActionId === actionId && e.type === "gated_by",
- );
- const allPassed = gates.every((g) => {
- const gate = gateMap.get(g.targetActionId);
- return gate && gate.status === "passed";
- });
- if (allPassed) {
- action.status = "pending";
- action.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, action.id, action);
- await recordAudit(kv, "action_update", "mem::sentinel-unblock", [action.id], {
- action: "action.unblocked",
- sentinelId: sentinel.id,
- });
- unblockedCount++;
- }
- }
- });
- }
-
- return unblockedCount;
-}
diff --git a/src/functions/session-context.ts b/src/functions/session-context.ts
new file mode 100644
index 0000000000..cf7ff979a0
--- /dev/null
+++ b/src/functions/session-context.ts
@@ -0,0 +1,98 @@
+import type { ISdk } from "iii-sdk";
+import type { Session } 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 } from "./audit.js";
+
+export interface SessionContextInput {
+ sessionId: string;
+ project?: string;
+ cwd?: string;
+ repoRoot?: string;
+ scopeType?: string;
+ worktree?: string;
+ branch?: string;
+ taskSlug?: string;
+}
+
+const CONTEXT_FIELDS = [
+ "project",
+ "cwd",
+ "repoRoot",
+ "scopeType",
+ "worktree",
+ "branch",
+ "taskSlug",
+] as const;
+
+function contextView(session: Session) {
+ return {
+ id: session.id,
+ project: session.project,
+ cwd: session.cwd,
+ repoRoot: session.repoRoot,
+ scopeType: session.scopeType,
+ worktree: session.worktree,
+ branch: session.branch,
+ taskSlug: session.taskSlug,
+ projectAliases: session.projectAliases,
+ updatedAt: session.updatedAt,
+ contextUpdatedAt: session.contextUpdatedAt,
+ };
+}
+
+export function registerSessionContextFunction(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction("mem::session-context-update", async (data: SessionContextInput) => {
+ if (!data?.sessionId || typeof data.sessionId !== "string") {
+ return { success: false, error: "sessionId is required" };
+ }
+ return withKeyedLock(`session-context:${data.sessionId}`, async () => {
+ const session = await kv.get(KV.sessions, data.sessionId);
+ if (!session) {
+ return { success: false, error: "session not found", sessionId: data.sessionId };
+ }
+
+ const updates: Array<{ type: "set"; path: string; value: unknown }> = [];
+ const changed: string[] = [];
+ for (const field of CONTEXT_FIELDS) {
+ const value = data[field];
+ if (typeof value !== "string" || !value.trim()) continue;
+ const normalized = value.trim();
+ if (session[field] === normalized) continue;
+ updates.push({ type: "set", path: field, value: normalized });
+ changed.push(field);
+ }
+
+ if (changed.includes("project") && session.project) {
+ const aliases = new Set(session.projectAliases ?? []);
+ aliases.add(session.project);
+ aliases.delete(data.project?.trim() ?? "");
+ updates.push({ type: "set", path: "projectAliases", value: [...aliases].sort() });
+ }
+ if (updates.length === 0) {
+ return { success: true, changed: [], context: contextView(session) };
+ }
+
+ updates.push({
+ type: "set",
+ path: "contextUpdatedAt",
+ value: new Date().toISOString(),
+ });
+ await kv.update(KV.sessions, data.sessionId, updates);
+ await recordAudit(
+ kv,
+ "session_context_update",
+ "mem::session-context-update",
+ [data.sessionId],
+ { changed },
+ );
+ const updated = await kv.get(KV.sessions, data.sessionId);
+ return {
+ success: true,
+ changed,
+ context: updated ? contextView(updated) : null,
+ };
+ });
+ });
+}
diff --git a/src/functions/session-list.ts b/src/functions/session-list.ts
new file mode 100644
index 0000000000..c45ba594f3
--- /dev/null
+++ b/src/functions/session-list.ts
@@ -0,0 +1,149 @@
+import type { Session } from "../types.js";
+
+export interface SessionListOptions {
+ limit?: number;
+ cursor?: string;
+ project?: string;
+ status?: Session["status"];
+ since?: string;
+ format?: "compact" | "full";
+ includePrompt?: boolean;
+ includeMalformed?: boolean;
+}
+
+export interface SessionPage {
+ sessions: Array & Pick & { issues?: string[] }>;
+ pagination: {
+ total: number;
+ limit: number;
+ nextCursor: string | null;
+ hasMore: boolean;
+ malformedExcluded: number;
+ };
+}
+
+const DEFAULT_LIMIT = 50;
+const MAX_LIMIT = 500;
+
+function encodeCursor(offset: number): string {
+ return Buffer.from(String(offset), "utf8").toString("base64url");
+}
+
+function decodeCursor(cursor?: string): number {
+ if (!cursor) return 0;
+ try {
+ const raw = Buffer.from(cursor, "base64url").toString("utf8");
+ const offset = Number(raw);
+ if (!Number.isInteger(offset) || offset < 0) throw new Error("invalid offset");
+ return offset;
+ } catch {
+ throw new Error("cursor must be a valid session-page cursor");
+ }
+}
+
+function normalizedLimit(value?: number): number {
+ if (!Number.isFinite(value) || !value || value < 1) return DEFAULT_LIMIT;
+ return Math.min(Math.floor(value), MAX_LIMIT);
+}
+
+function sessionTimestamp(session: Session): string {
+ return session.updatedAt || session.startedAt || "";
+}
+
+export function sessionIssues(session: Session): string[] {
+ const issues: string[] = [];
+ if (typeof session?.id !== "string" || !session.id.trim()) issues.push("missing_id");
+ if (typeof session?.project !== "string" || !session.project.trim()) issues.push("missing_project");
+ if (typeof session?.cwd !== "string" || !session.cwd.trim()) issues.push("missing_cwd");
+ if (typeof session?.startedAt !== "string" || Number.isNaN(Date.parse(session.startedAt))) {
+ issues.push("invalid_started_at");
+ }
+ if (!["active", "completed", "abandoned"].includes(session?.status)) issues.push("invalid_status");
+ return issues;
+}
+
+function compactSession(session: Session): SessionPage["sessions"][number] {
+ const issues = sessionIssues(session);
+ return {
+ id: typeof session.id === "string" ? session.id : "",
+ project: typeof session.project === "string" ? session.project : "",
+ status: ["active", "completed", "abandoned"].includes(session.status)
+ ? session.status
+ : "abandoned",
+ observationCount: session.observationCount,
+ startedAt: session.startedAt,
+ updatedAt: session.updatedAt,
+ contextUpdatedAt: session.contextUpdatedAt,
+ endedAt: session.endedAt,
+ agentId: session.agentId,
+ repoRoot: session.repoRoot,
+ scopeType: session.scopeType,
+ worktree: session.worktree,
+ branch: session.branch,
+ taskSlug: session.taskSlug,
+ ...(issues.length > 0 ? { issues } : {}),
+ };
+}
+
+function fullSession(session: Session, includePrompt: boolean): Session {
+ if (includePrompt) return { ...session };
+ const { firstPrompt: _firstPrompt, ...safe } = session;
+ return safe as Session;
+}
+
+export function selectSessionPage(
+ input: Session[],
+ options: SessionListOptions = {},
+): SessionPage {
+ const limit = normalizedLimit(options.limit);
+ const offset = decodeCursor(options.cursor);
+ const format = options.format ?? "compact";
+ if (format !== "compact" && format !== "full") {
+ throw new Error("format must be compact or full");
+ }
+ if (options.status && !["active", "completed", "abandoned"].includes(options.status)) {
+ throw new Error("status must be active, completed, or abandoned");
+ }
+ const sinceMs = options.since ? Date.parse(options.since) : null;
+ if (options.since && Number.isNaN(sinceMs)) {
+ throw new Error("since must be a valid ISO timestamp");
+ }
+
+ const malformed = input.filter((session) => sessionIssues(session).length > 0);
+ const candidates = options.includeMalformed
+ ? input
+ : input.filter((session) => sessionIssues(session).length === 0);
+ const filtered = candidates
+ .filter((session) => {
+ if (
+ options.project &&
+ session.project !== options.project &&
+ !(Array.isArray(session.projectAliases) && session.projectAliases.includes(options.project))
+ ) {
+ return false;
+ }
+ if (options.status && session.status !== options.status) return false;
+ if (sinceMs !== null && Date.parse(sessionTimestamp(session)) < sinceMs) return false;
+ return true;
+ })
+ .sort((left, right) => {
+ const byTime = sessionTimestamp(right).localeCompare(sessionTimestamp(left));
+ return byTime || String(right.id || "").localeCompare(String(left.id || ""));
+ });
+
+ const page = filtered.slice(offset, offset + limit);
+ const nextOffset = offset + page.length;
+ const hasMore = nextOffset < filtered.length;
+ return {
+ sessions: page.map((session) =>
+ format === "full" ? fullSession(session, options.includePrompt === true) : compactSession(session),
+ ),
+ pagination: {
+ total: filtered.length,
+ limit,
+ nextCursor: hasMore ? encodeCursor(nextOffset) : null,
+ hasMore,
+ malformedExcluded: options.includeMalformed ? 0 : malformed.length,
+ },
+ };
+}
diff --git a/src/functions/sketches.ts b/src/functions/sketches.ts
index c617a29817..e1575a3ab6 100644
--- a/src/functions/sketches.ts
+++ b/src/functions/sketches.ts
@@ -4,6 +4,12 @@ import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, ActionEdge, Sketch } from "../types.js";
import { safeAudit } from "./audit.js";
+import {
+ deleteAction,
+ deleteActionEdge,
+ persistAction,
+ persistActionEdge,
+} from "./action-store.js";
export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("mem::sketch-create",
@@ -68,7 +74,10 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
id: generateId("act"),
title: data.title.trim(),
description: (data.description || "").trim(),
- status: "pending",
+ status:
+ data.dependsOn && data.dependsOn.length > 0
+ ? "blocked"
+ : "pending",
priority: Math.max(1, Math.min(10, data.priority || 5)),
createdAt: now,
updatedAt: now,
@@ -92,7 +101,13 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
}
}
- await kv.set(KV.actions, action.id, action);
+ const persistedAction = await persistAction(kv, action, {
+ actor: "sketch",
+ type: "created",
+ before: null,
+ hasDerivedBlockers: Boolean(data.dependsOn?.length),
+ reason: `Added to sketch ${sketch.id}`,
+ });
await safeAudit(kv, "sketch_create", "mem::sketch-add", [action.id], {
action: "add.action",
sketchId: sketch.id,
@@ -108,7 +123,11 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
targetActionId: depId,
createdAt: now,
};
- await kv.set(KV.actionEdges, edge.id, edge);
+ await persistActionEdge(kv, edge, {
+ actor: "sketch",
+ before: null,
+ reason: `Sketch ${sketch.id} dependency`,
+ });
await safeAudit(kv, "sketch_create", "mem::sketch-add", [edge.id], {
action: "add.edge",
sketchId: sketch.id,
@@ -124,7 +143,7 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
addedActionId: action.id,
});
- return { success: true, action, edges: createdEdges };
+ return { success: true, action: persistedAction.action, edges: createdEdges };
});
},
);
@@ -148,12 +167,25 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
for (const actionId of sketch.actionIds) {
const action = await kv.get(KV.actions, actionId);
if (action) {
+ const before = structuredClone(action);
delete action.sketchId;
if (data.project) {
+ const previousProject = action.projectId || action.project;
action.project = data.project;
+ action.projectId = undefined;
+ action.projectAliases = [
+ ...new Set([
+ ...(action.projectAliases ?? []),
+ ...(previousProject ? [previousProject] : []),
+ ]),
+ ];
}
action.updatedAt = new Date().toISOString();
- await kv.set(KV.actions, action.id, action);
+ await persistAction(kv, action, {
+ actor: "sketch-promote",
+ before,
+ reason: `Promoted from sketch ${sketch.id}`,
+ });
await safeAudit(kv, "sketch_promote", "mem::sketch-promote", [action.id], {
action: "promote.action",
sketchId: sketch.id,
@@ -198,7 +230,10 @@ export function registerSketchesFunction(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: "sketch-discard",
+ reason: `Discarded sketch ${sketch.id}`,
+ });
await safeAudit(kv, "sketch_discard", "mem::sketch-discard", [edge.id], {
action: "discard.edge",
sketchId: sketch.id,
@@ -207,7 +242,10 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
}
for (const actionId of sketch.actionIds) {
- await kv.delete(KV.actions, actionId);
+ await deleteAction(kv, actionId, {
+ actor: "sketch-discard",
+ reason: `Discarded sketch ${sketch.id}`,
+ });
await safeAudit(kv, "sketch_discard", "mem::sketch-discard", [actionId], {
action: "discard.action",
sketchId: sketch.id,
@@ -283,7 +321,10 @@ export function registerSketchesFunction(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: "sketch-gc",
+ reason: `Expired sketch ${current.id}`,
+ });
await safeAudit(kv, "sketch_discard", "mem::sketch-gc", [edge.id], {
action: "gc.edge",
sketchId: current.id,
@@ -292,7 +333,10 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
}
for (const actionId of current.actionIds) {
- await kv.delete(KV.actions, actionId);
+ await deleteAction(kv, actionId, {
+ actor: "sketch-gc",
+ reason: `Expired sketch ${current.id}`,
+ });
await safeAudit(kv, "sketch_discard", "mem::sketch-gc", [actionId], {
action: "gc.action",
sketchId: current.id,
diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts
index 4c501ca8cf..d51b3f273b 100644
--- a/src/functions/summarize.ts
+++ b/src/functions/summarize.ts
@@ -20,6 +20,7 @@ import { scoreSummary } from "../eval/quality.js";
import type { MetricsStore } from "../eval/metrics-store.js";
import { safeAudit } from "./audit.js";
import { logger } from "../logger.js";
+import { getLlmExecutionState } from "../config.js";
// Per-chunk observation budget when a session is too large to fit in one
// LLM call. Default ≈ 50k input tokens per chunk at ~110 tok/obs — fits
@@ -240,6 +241,30 @@ export function registerSummarizeFunction(
}
const sessionId = data.sessionId.trim();
+ const llmExecutionState = getLlmExecutionState(provider);
+ if (llmExecutionState !== "enabled") {
+ const skipped =
+ llmExecutionState === "disabled"
+ ? "llm_tools_disabled"
+ : "no_llm_provider";
+ if (metricsStore) {
+ await metricsStore.recordSkipped(
+ "mem::summarize",
+ Date.now() - startMs,
+ skipped,
+ );
+ }
+ logger.info("Summarize skipped", { sessionId, skipped });
+ return {
+ success: true,
+ outcome:
+ llmExecutionState === "disabled"
+ ? "skipped_disabled"
+ : "skipped_unavailable",
+ skipped,
+ };
+ }
+
const session = await kv.get(KV.sessions, sessionId);
if (!session) {
logger.warn("Session not found for summarize", {
@@ -260,18 +285,6 @@ export function registerSummarizeFunction(
return { success: false, error: "no_observations" };
}
- if (provider.name === "noop") {
- logger.info("Summarize skipped — no LLM provider configured", {
- sessionId,
- });
- return {
- success: false,
- error: "no_provider",
- reason:
- "No LLM provider key set; Summarize is a no-op. Set ANTHROPIC_API_KEY (or GEMINI/OPENROUTER/MINIMAX) in ~/.agentmemory/.env to enable.",
- };
- }
-
try {
// #783: chunk-level produceSummaryXml retries internally, but
// the final merge used to parse once and bail. Wrap the
diff --git a/src/hooks/_observe.ts b/src/hooks/_observe.ts
new file mode 100644
index 0000000000..0adf1597fb
--- /dev/null
+++ b/src/hooks/_observe.ts
@@ -0,0 +1,38 @@
+const DEFAULT_ACK_TIMEOUT_MS = 500;
+const MAX_ACK_TIMEOUT_MS = 5_000;
+
+function ackTimeoutMs(): number {
+ 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(): Record {
+ const headers: Record = {
+ "Content-Type": "application/json",
+ };
+ const secret = process.env["AGENTMEMORY_SECRET"] || "";
+ if (secret) headers["Authorization"] = `Bearer ${secret}`;
+ return headers;
+}
+
+export async function submitObservation(
+ payload: Record,
+): Promise {
+ const restUrl = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
+ try {
+ const response = await fetch(`${restUrl}/agentmemory/observe/async`, {
+ method: "POST",
+ headers: authHeaders(),
+ body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(ackTimeoutMs()),
+ });
+ await response.arrayBuffer();
+ } catch {
+ // Hook capture is best-effort and must never fail the host agent session.
+ }
+}
diff --git a/src/hooks/_project.ts b/src/hooks/_project.ts
index 35364ea3bb..d161177168 100644
--- a/src/hooks/_project.ts
+++ b/src/hooks/_project.ts
@@ -1,20 +1,138 @@
-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";
-// Resolution order: AGENTMEMORY_PROJECT_NAME env → git toplevel basename → cwd basename.
-export function resolveProject(cwd?: string): string {
- const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
- if (explicit && explicit.trim()) return explicit.trim();
- const dir = cwd && cwd.trim() ? cwd : process.cwd();
+export interface ProjectContext {
+ project: string;
+ cwd: string;
+ repoRoot: string;
+ scopeType: string;
+ worktree?: string;
+ branch?: string;
+ taskSlug?: string;
+}
+
+interface ProjectFile {
+ project_id?: unknown;
+ projectId?: unknown;
+ repo_root?: unknown;
+ repoRoot?: unknown;
+ scope_type?: unknown;
+ scopeType?: unknown;
+}
+
+function git(cwd: string, args: string[]): string {
try {
- const top = execSync("git rev-parse --show-toplevel", {
- cwd: dir,
+ return execFileSync("git", args, {
+ cwd,
stdio: ["ignore", "pipe", "ignore"],
timeout: 500,
})
.toString()
.trim();
- if (top) return basename(top);
- } catch {}
- return basename(dir);
+ } catch {
+ return "";
+ }
+}
+
+function canonicalExistingPath(path: string): string {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+
+function nearestProjectFile(cwd: string, boundary?: string): string | undefined {
+ 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 undefined;
+ const parent = dirname(current);
+ if (parent === current) return undefined;
+ current = parent;
+ }
+}
+
+function readProjectFile(cwd: string, boundary?: string): { file: string; data: ProjectFile } | undefined {
+ const file = nearestProjectFile(cwd, boundary);
+ if (!file) return undefined;
+ try {
+ const data = JSON.parse(readFileSync(file, "utf8")) as ProjectFile;
+ return { file, data };
+ } catch {
+ return undefined;
+ }
+}
+
+function remoteProjectName(remote: string): string {
+ const normalized = remote.trim().replace(/\/$/, "").replace(/\.git$/, "");
+ if (!normalized) return "";
+ const tail = normalized.split(/[/:]/).filter(Boolean).at(-1);
+ return tail || "";
+}
+
+function nonEmpty(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+export function resolveProjectContext(cwd?: string): ProjectContext {
+ const rawDir = cwd && cwd.trim() ? cwd.trim() : process.cwd();
+ // Copilot can forward a Windows cwd to a hook running under WSL or a
+ // POSIX test harness. node:path would otherwise turn `C:\\repo` into a
+ // child of the current POSIX directory and inherit an unrelated manifest.
+ 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 || undefined);
+ const remoteName = remoteProjectName(git(dir, ["config", "--get", "remote.origin.url"]));
+ const fileProject = projectFile
+ ? nonEmpty(projectFile.data.project_id) ?? nonEmpty(projectFile.data.projectId)
+ : undefined;
+ const explicitProject = nonEmpty(process.env["AGENTMEMORY_PROJECT_NAME"]);
+ const rawRepoRoot = projectFile
+ ? nonEmpty(projectFile.data.repo_root) ?? nonEmpty(projectFile.data.repoRoot)
+ : undefined;
+ const configuredRepoRoot = nonEmpty(process.env["AGENTMEMORY_REPO_ROOT"]);
+ const projectFileRoot = projectFile ? dirname(dirname(projectFile.file)) : undefined;
+ 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)
+ : undefined) ??
+ (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 } : {}),
+ };
+}
+
+export function resolveProject(cwd?: string): string {
+ return resolveProjectContext(cwd).project;
}
diff --git a/src/hooks/notification.ts b/src/hooks/notification.ts
index 9ad7704239..23d0153e97 100644
--- a/src/hooks/notification.ts
+++ b/src/hooks/notification.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -7,15 +8,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -38,25 +30,19 @@ async function main() {
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 as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: new Date().toISOString(),
- data: {
- notification_type: notificationType,
- title: data.title,
- message: data.message,
- },
- }),
- signal: AbortSignal.timeout(2000),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ const context = resolveProjectContext(data.cwd as string | undefined);
+
+ await submitObservation({
+ hookType: "notification",
+ sessionId,
+ ...context,
+ timestamp: new Date().toISOString(),
+ data: {
+ notification_type: notificationType,
+ title: data.title,
+ message: data.message,
+ },
+ });
}
main();
diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.ts
index f0295b3e62..b50bc15ee7 100644
--- a/src/hooks/post-tool-failure.ts
+++ b/src/hooks/post-tool-failure.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -7,15 +8,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -34,33 +26,31 @@ async function main() {
const sessionId = ((data.session_id || data.sessionId) as string) || "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 as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: new Date().toISOString(),
- data: {
- tool_name: toolName,
- tool_input:
- typeof toolInput === "string"
- ? toolInput.slice(0, 4000)
- : JSON.stringify(toolInput ?? "").slice(0, 4000),
- error:
- typeof error === "string"
- ? error.slice(0, 4000)
- : JSON.stringify(error ?? "").slice(0, 4000),
- },
- }),
- signal: AbortSignal.timeout(3000),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ const context = resolveProjectContext(data.cwd as string | undefined);
+
+ await submitObservation({
+ hookType: "post_tool_failure",
+ sessionId,
+ ...context,
+ timestamp: new Date().toISOString(),
+ data: {
+ tool_name: toolName,
+ tool_input:
+ typeof toolInput === "string"
+ ? toolInput.slice(0, 4000)
+ : JSON.stringify(toolInput ?? "").slice(0, 4000),
+ error:
+ typeof error === "string"
+ ? error.slice(0, 4000)
+ : JSON.stringify(error ?? "").slice(0, 4000),
+ },
+ });
}
main();
diff --git a/src/hooks/post-tool-use.ts b/src/hooks/post-tool-use.ts
index c68a7731d3..d561f689f2 100644
--- a/src/hooks/post-tool-use.ts
+++ b/src/hooks/post-tool-use.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -7,15 +8,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -34,28 +26,45 @@ async function main() {
const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";
const toolName = data.tool_name ?? data.toolName;
const toolInput = data.tool_input ?? data.toolArgs;
+ if (shouldSkipTool(toolName)) return;
+ const context = resolveProjectContext(data.cwd as string | undefined);
+ 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 as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: new Date().toISOString(),
- data: {
- tool_name: toolName,
- tool_input: toolInput,
- tool_output: truncate(cleanOutput, 8000),
- ...(imageData ? { image_data: imageData } : {}),
- },
- }),
- signal: AbortSignal.timeout(3000),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ await submitObservation({
+ hookType: "post_tool_use",
+ sessionId,
+ ...context,
+ timestamp: new Date().toISOString(),
+ data: {
+ tool_name: toolName,
+ tool_input: truncate(toolInput, maxChars),
+ tool_output: truncate(cleanOutput, maxChars),
+ ...(imageData ? { image_data: imageData } : {}),
+ },
+ });
+}
+
+function shouldSkipTool(value: unknown): boolean {
+ const name = typeof value === "string" ? value.trim().toLowerCase() : "";
+ if (!name) return false;
+ if (name.startsWith("mcp__agentmemory__") || name.startsWith("memory_")) {
+ return true;
+ }
+ const configured = (process.env["AGENTMEMORY_SKIP_TOOLS"] || "")
+ .split(",")
+ .map((item) => item.trim().toLowerCase())
+ .filter(Boolean);
+ return configured.some((pattern) =>
+ pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern,
+ );
+}
+
+function maxCaptureChars(): number {
+ const value = Number(process.env["AGENTMEMORY_MAX_TOOL_CAPTURE_CHARS"] || "8000");
+ if (!Number.isFinite(value) || value < 0) return 8000;
+ return Math.min(Math.floor(value), 32_000);
}
function toolOutput(data: Record): unknown {
diff --git a/src/hooks/prompt-submit.ts b/src/hooks/prompt-submit.ts
index 2da8ea6a41..5e3946cba0 100644
--- a/src/hooks/prompt-submit.ts
+++ b/src/hooks/prompt-submit.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -7,15 +8,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -32,21 +24,28 @@ async function main() {
if (isSdkChildContext(data)) return;
const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";
+ const context = resolveProjectContext(data.cwd as string | undefined);
+ const prompt = data.prompt ?? data.userPrompt;
+ const promptData = promptCapture(prompt);
+
+ await submitObservation({
+ hookType: "prompt_submit",
+ sessionId,
+ ...context,
+ timestamp: new Date().toISOString(),
+ data: promptData,
+ });
+}
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "prompt_submit",
- sessionId,
- project: resolveProject(data.cwd as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: new Date().toISOString(),
- data: { prompt: data.prompt ?? data.userPrompt },
- }),
- signal: AbortSignal.timeout(3000),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+function promptCapture(value: unknown): Record {
+ 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), 16_000) : 4000;
+ return { prompt: text.slice(0, limit) };
}
main();
diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.ts
index 573c092b14..80505a6ef8 100644
--- a/src/hooks/session-start.ts
+++ b/src/hooks/session-start.ts
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
// Inlined from ./sdk-guard so each hook bundles to a single self-contained
// .mjs (matches the pattern used by every other hook entry in tsdown.config).
@@ -52,14 +52,13 @@ async function main() {
const sessionId =
((data.session_id || data.sessionId) as string) ||
`ses_${Date.now().toString(36)}`;
- const cwd = (data.cwd as string) || process.cwd();
- const project = resolveProject(data.cwd as string | undefined);
+ const context = resolveProjectContext(data.cwd as string | undefined);
const url = `${REST_URL}/agentmemory/session/start`;
const init: RequestInit = {
method: "POST",
headers: authHeaders(),
- body: JSON.stringify({ sessionId, project, cwd }),
+ body: JSON.stringify({ sessionId, ...context }),
};
if (!INJECT_CONTEXT) {
diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.ts
index 44c87c85e9..bf7c66f29c 100644
--- a/src/hooks/subagent-start.ts
+++ b/src/hooks/subagent-start.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
// Inlined from ./sdk-guard so each hook bundles to a single self-contained
// .mjs (matches the pattern used by every other hook entry in tsdown.config).
@@ -9,21 +10,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-// Passive telemetry only — nothing reads the response, so the previous
-// `await` was pure latency. Tightened from 2000ms to a defensive cap so a
-// slow/unreachable server can't stack onto every concurrent subagent
-// startup (#221).
-const TIMEOUT_MS = 800;
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -42,24 +28,18 @@ async function main() {
const sessionId = ((data.session_id || data.sessionId) as string) || "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 as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: new Date().toISOString(),
- data: {
- agent_id: agentId,
- agent_type: agentType,
- },
- }),
- signal: AbortSignal.timeout(TIMEOUT_MS),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ const context = resolveProjectContext(data.cwd as string | undefined);
+
+ await submitObservation({
+ hookType: "subagent_start",
+ sessionId,
+ ...context,
+ timestamp: new Date().toISOString(),
+ data: {
+ agent_id: agentId,
+ agent_type: agentType,
+ },
+ });
}
main();
diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.ts
index 5a437c9fd4..73562da847 100644
--- a/src/hooks/subagent-stop.ts
+++ b/src/hooks/subagent-stop.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -7,15 +8,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -38,25 +30,19 @@ async function main() {
typeof data.last_assistant_message === "string"
? data.last_assistant_message.slice(0, 4000)
: "";
-
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "subagent_stop",
- sessionId,
- project: resolveProject(data.cwd as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: new Date().toISOString(),
- data: {
- agent_id: agentId,
- agent_type: agentType,
- last_message: lastMsg,
- },
- }),
- signal: AbortSignal.timeout(2000),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ const context = resolveProjectContext(data.cwd as string | undefined);
+
+ await submitObservation({
+ hookType: "subagent_stop",
+ sessionId,
+ ...context,
+ timestamp: new Date().toISOString(),
+ data: {
+ agent_id: agentId,
+ agent_type: agentType,
+ last_message: lastMsg,
+ },
+ });
}
main();
diff --git a/src/hooks/task-completed.ts b/src/hooks/task-completed.ts
index dbdf815ac8..c937f757e8 100644
--- a/src/hooks/task-completed.ts
+++ b/src/hooks/task-completed.ts
@@ -1,5 +1,6 @@
#!/usr/bin/env node
-import { resolveProject } from "./_project.js";
+import { resolveProjectContext } from "./_project.js";
+import { submitObservation } from "./_observe.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -7,15 +8,6 @@ function isSdkChildContext(payload: unknown): boolean {
return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";
}
-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
-const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
-
-function authHeaders(): Record {
- const h: Record = { "Content-Type": "application/json" };
- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
- return h;
-}
-
async function main() {
let input = "";
for await (const chunk of process.stdin) {
@@ -32,29 +24,23 @@ async function main() {
if (isSdkChildContext(data)) return;
const sessionId = (data.session_id as string) || "unknown";
-
- fetch(`${REST_URL}/agentmemory/observe`, {
- method: "POST",
- headers: authHeaders(),
- body: JSON.stringify({
- hookType: "task_completed",
- sessionId,
- project: resolveProject(data.cwd as string | undefined),
- cwd: (data.cwd as string | undefined) || process.cwd(),
- timestamp: 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, 2000)
- : "",
- teammate_name: data.teammate_name,
- team_name: data.team_name,
- },
- }),
- signal: AbortSignal.timeout(2000),
- }).catch(() => {});
- setTimeout(() => process.exit(0), 500).unref();
+ const context = resolveProjectContext(data.cwd as string | undefined);
+
+ await submitObservation({
+ hookType: "task_completed",
+ sessionId,
+ ...context,
+ timestamp: 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, 2000)
+ : "",
+ teammate_name: data.teammate_name,
+ team_name: data.team_name,
+ },
+ });
}
main();
diff --git a/src/index.ts b/src/index.ts
index 1e623eae81..d082430d86 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -88,6 +88,7 @@ import { registerTemporalGraphFunctions } from "./functions/temporal-graph.js";
import { registerRetentionFunctions } from "./functions/retention.js";
import { registerCompressFileFunction } from "./functions/compress-file.js";
import { registerReplayFunctions } from "./functions/replay.js";
+import { registerSessionContextFunction } from "./functions/session-context.js";
import { registerApiTriggers } from "./triggers/api.js";
import { registerEventTriggers } from "./triggers/events.js";
import { registerMcpEndpoints } from "./mcp/server.js";
@@ -99,32 +100,34 @@ import { registerHealthMonitor } from "./health/monitor.js";
import { initMetrics, OTEL_CONFIG } from "./telemetry/setup.js";
import { VERSION } from "./version.js";
import { bootLog } from "./logger.js";
-import { mkdirSync, writeFileSync, unlinkSync } from "node:fs";
-import { dirname, join } from "node:path";
+import {
+ acquireWorkerPidfile,
+ releaseWorkerPidfile,
+ type WorkerPidfileLease,
+} from "./worker-pidfile.js";
+import { join } from "node:path";
import { homedir } from "node:os";
// #640 + #474: the worker process (this file) is spawned by iii-exec
// inside the engine. When `agentmemory stop` kills only the engine pid,
// this worker can survive (detached spawn, signal not propagated, or a
// wrapper script keeps it running) and reconnects to the next engine as
-// a duplicate worker. Write the worker pid alongside iii.pid so
-// `agentmemory stop` can reap us too.
+// a duplicate worker. The exclusive pidfile is acquired before the SDK
+// registers anything, so a second worker cannot later unregister the live
+// worker's shared function and REST trigger IDs when it exits.
function workerPidfilePath(): string {
return join(homedir(), ".agentmemory", "worker.pid");
}
-function writeWorkerPidfile(): void {
- try {
- const p = workerPidfilePath();
- mkdirSync(dirname(p), { recursive: true });
- writeFileSync(p, `${process.pid}\n`, { encoding: "utf-8" });
- } catch {
- // best-effort; stop still has the engine pidfile + port scan fallback
- }
+let workerPidfileLease: WorkerPidfileLease | null = null;
+function acquireWorkerPidfileLease(): void {
+ workerPidfileLease = acquireWorkerPidfile(workerPidfilePath());
}
function clearWorkerPidfile(): void {
+ if (!workerPidfileLease) return;
try {
- unlinkSync(workerPidfilePath());
+ releaseWorkerPidfile(workerPidfileLease);
} catch {}
+ workerPidfileLease = null;
}
function hasGetMeter(
@@ -158,6 +161,7 @@ process.on("unhandledRejection", (reason) => {
});
async function main() {
+ acquireWorkerPidfileLease();
const config = loadConfig();
const embeddingConfig = loadEmbeddingConfig();
const fallbackConfig = loadFallbackConfig();
@@ -214,8 +218,6 @@ async function main() {
},
});
- writeWorkerPidfile();
-
const kv = new StateKV(sdk);
const secret = getEnvVar("AGENTMEMORY_SECRET");
const metricsStore = new MetricsStore(kv);
@@ -332,6 +334,7 @@ async function main() {
registerRetentionFunctions(sdk, kv);
registerCompressFileFunction(sdk, kv, provider);
registerReplayFunctions(sdk, kv);
+ registerSessionContextFunction(sdk, kv);
bootLog(
`v0.6 advanced retrieval: sliding-window, query-expansion, temporal-graph, retention-scoring`,
);
@@ -518,7 +521,7 @@ async function main() {
`Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`,
);
bootLog(
- `REST API: 128 endpoints at http://localhost:${config.restPort}/agentmemory/*`,
+ `REST API: 131 endpoints at http://localhost:${config.restPort}/agentmemory/*`,
);
bootLog(
`MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`,
@@ -607,6 +610,7 @@ async function main() {
}
main().catch((err) => {
+ clearWorkerPidfile();
console.error(`[agentmemory] Fatal:`, err);
process.exit(1);
});
diff --git a/src/mcp/http.ts b/src/mcp/http.ts
new file mode 100644
index 0000000000..a0ee592530
--- /dev/null
+++ b/src/mcp/http.ts
@@ -0,0 +1,410 @@
+#!/usr/bin/env node
+
+import {
+ createServer as createNodeServer,
+ type IncomingMessage,
+ type Server as NodeServer,
+ type ServerResponse,
+} from "node:http";
+import { pathToFileURL } from "node:url";
+import { resolve } from "node:path";
+import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
+import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
+import {
+ CallToolRequestSchema,
+ ListToolsRequestSchema,
+ type CallToolResult,
+ type Tool,
+} from "@modelcontextprotocol/sdk/types.js";
+import { timingSafeCompare } from "../auth.js";
+import { VERSION } from "../version.js";
+import { resolveEnvOrEmpty } from "./rest-proxy.js";
+
+const DEFAULT_ENGINE_URL = "http://127.0.0.1:3111";
+const DEFAULT_HOST = "127.0.0.1";
+const DEFAULT_PORT = 3114;
+const BACKEND_TIMEOUT_MS = 15_000;
+
+export interface McpHttpBackend {
+ health: () => Promise;
+ listTools: () => Promise<{ tools: Tool[] }>;
+ callTool: (
+ name: string,
+ args: Record,
+ ) => Promise;
+}
+
+export interface McpHttpOptions {
+ host?: string;
+ port?: number;
+ path?: string;
+ token?: string;
+ allowedOrigins?: string[];
+ allowRemote?: boolean;
+ backend?: McpHttpBackend;
+}
+
+function positivePort(value: string | undefined, fallback: number): number {
+ const parsed = Number(value);
+ return Number.isInteger(parsed) && parsed > 0 && parsed <= 65_535
+ ? parsed
+ : fallback;
+}
+
+function isLoopbackHost(host: string): boolean {
+ const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
+ return (
+ normalized === "localhost" ||
+ normalized === "127.0.0.1" ||
+ normalized === "::1"
+ );
+}
+
+function isWildcardHost(host: string): boolean {
+ const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
+ return normalized === "0.0.0.0" || normalized === "::";
+}
+
+function parseAllowedOrigins(raw: string): string[] {
+ return raw
+ .split(",")
+ .map((value) => value.trim().replace(/\/$/, ""))
+ .filter(Boolean);
+}
+
+function normalizeOptions(options: McpHttpOptions = {}): Required<
+ Omit
+> & { backend: McpHttpBackend } {
+ const host = options.host ?? (
+ resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_HOST") || DEFAULT_HOST
+ );
+ const port = options.port ?? positivePort(
+ resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_PORT"),
+ DEFAULT_PORT,
+ );
+ const token = options.token ?? resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_TOKEN");
+ const allowedOrigins = options.allowedOrigins ?? parseAllowedOrigins(
+ resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_ALLOWED_ORIGINS"),
+ );
+ const allowRemote = options.allowRemote ?? ["1", "true"].includes(
+ resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_ALLOW_REMOTE").toLowerCase(),
+ );
+
+ if (!isLoopbackHost(host) && (!allowRemote || !token)) {
+ throw new Error(
+ "Non-loopback MCP HTTP binds require AGENTMEMORY_MCP_HTTP_ALLOW_REMOTE=1 and a bearer token",
+ );
+ }
+
+ return {
+ host,
+ port,
+ path: options.path ?? "/mcp",
+ token,
+ allowedOrigins,
+ allowRemote,
+ backend: options.backend ?? createProxyBackend(),
+ };
+}
+
+function engineHeaders(): Record {
+ const secret = resolveEnvOrEmpty("AGENTMEMORY_SECRET");
+ return {
+ "content-type": "application/json",
+ ...(secret ? { authorization: `Bearer ${secret}` } : {}),
+ };
+}
+
+export function createProxyBackend(options: {
+ baseUrl?: string;
+ fetchImpl?: typeof fetch;
+} = {}): McpHttpBackend {
+ const baseUrl = (
+ options.baseUrl ?? (
+ resolveEnvOrEmpty("AGENTMEMORY_URL") || DEFAULT_ENGINE_URL
+ )
+ ).replace(/\/+$/, "");
+ const fetchImpl = options.fetchImpl ?? fetch;
+
+ async function request(path: string, init: RequestInit): Promise {
+ const response = await fetchImpl(`${baseUrl}${path}`, {
+ ...init,
+ headers: { ...engineHeaders(), ...(init.headers ?? {}) },
+ signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
+ });
+ if (!response.ok) {
+ throw new Error(
+ `${init.method ?? "GET"} ${path} -> ${response.status} ${response.statusText}`,
+ );
+ }
+ const text = await response.text();
+ return text ? JSON.parse(text) : null;
+ }
+
+ return {
+ async health() {
+ try {
+ const response = await fetchImpl(`${baseUrl}/agentmemory/livez`, {
+ method: "GET",
+ headers: engineHeaders(),
+ signal: AbortSignal.timeout(2_000),
+ });
+ return response.ok;
+ } catch {
+ return false;
+ }
+ },
+ async listTools() {
+ const result = await request("/agentmemory/mcp/tools", { method: "GET" });
+ if (
+ !result ||
+ typeof result !== "object" ||
+ !Array.isArray((result as { tools?: unknown }).tools)
+ ) {
+ throw new Error("AgentMemory returned an invalid tools/list payload");
+ }
+ return { tools: (result as { tools: Tool[] }).tools };
+ },
+ async callTool(name, args) {
+ const result = await request("/agentmemory/mcp/call", {
+ method: "POST",
+ body: JSON.stringify({ name, arguments: args }),
+ });
+ if (
+ !result ||
+ typeof result !== "object" ||
+ !Array.isArray((result as { content?: unknown }).content)
+ ) {
+ throw new Error("AgentMemory returned an invalid tools/call payload");
+ }
+ return result as CallToolResult;
+ },
+ };
+}
+
+export function createProtocolServer(backend: McpHttpBackend): McpServer {
+ const server = new McpServer(
+ { name: "agentmemory", version: VERSION },
+ { capabilities: { tools: { listChanged: false } } },
+ );
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => backend.listTools());
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ try {
+ return await backend.callTool(
+ request.params.name,
+ request.params.arguments ?? {},
+ );
+ } catch (error) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`,
+ },
+ ],
+ isError: true,
+ };
+ }
+ });
+
+ return server;
+}
+
+function hostHeaderAllowed(hostHeader: string | undefined, host: string): boolean {
+ if (!hostHeader) return false;
+ try {
+ const requested = new URL(`http://${hostHeader}`).hostname;
+ if (isLoopbackHost(host)) return isLoopbackHost(requested);
+ if (isWildcardHost(host)) return true;
+ return requested.toLowerCase() === host.toLowerCase();
+ } catch {
+ return false;
+ }
+}
+
+function originAllowed(
+ origin: string | undefined,
+ host: string,
+ allowedOrigins: string[],
+): boolean {
+ if (!origin) return true;
+ const normalized = origin.replace(/\/$/, "");
+ if (allowedOrigins.includes(normalized)) return true;
+ try {
+ return isLoopbackHost(host) && isLoopbackHost(new URL(normalized).hostname);
+ } catch {
+ return false;
+ }
+}
+
+function sendJson(
+ response: ServerResponse,
+ statusCode: number,
+ body: unknown,
+ headers: Record = {},
+): void {
+ response.writeHead(statusCode, {
+ "content-type": "application/json",
+ "cache-control": "no-store",
+ ...headers,
+ });
+ response.end(JSON.stringify(body));
+}
+
+function sendProtocolError(
+ response: ServerResponse,
+ statusCode: number,
+ message: string,
+ headers: Record = {},
+): void {
+ sendJson(
+ response,
+ statusCode,
+ {
+ jsonrpc: "2.0",
+ error: { code: -32000, message },
+ id: null,
+ },
+ headers,
+ );
+}
+
+export function createMcpHttpHandler(
+ rawOptions: McpHttpOptions = {},
+): (request: IncomingMessage, response: ServerResponse) => Promise {
+ const options = normalizeOptions(rawOptions);
+
+ return async (request, response) => {
+ const url = new URL(request.url ?? "/", "http://localhost");
+
+ if (url.pathname === "/healthz") {
+ const upstream = await options.backend.health();
+ sendJson(response, upstream ? 200 : 503, {
+ status: upstream ? "ok" : "degraded",
+ transport: "streamable-http",
+ upstream,
+ });
+ return;
+ }
+
+ if (url.pathname !== options.path) {
+ sendProtocolError(response, 404, "Not found");
+ return;
+ }
+
+ if (!hostHeaderAllowed(request.headers.host, options.host)) {
+ sendProtocolError(response, 403, "Forbidden host");
+ return;
+ }
+
+ const origin = Array.isArray(request.headers.origin)
+ ? request.headers.origin[0]
+ : request.headers.origin;
+ if (!originAllowed(origin, options.host, options.allowedOrigins)) {
+ sendProtocolError(response, 403, "Forbidden origin");
+ return;
+ }
+
+ if (options.token) {
+ const authorization = request.headers.authorization ?? "";
+ if (!timingSafeCompare(authorization, `Bearer ${options.token}`)) {
+ sendProtocolError(response, 401, "Unauthorized", {
+ "www-authenticate": "Bearer",
+ });
+ return;
+ }
+ }
+
+ if (request.method !== "POST") {
+ sendProtocolError(response, 405, "Method not allowed", { allow: "POST" });
+ return;
+ }
+
+ const protocol = createProtocolServer(options.backend);
+ const transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ });
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ void protocol.close().catch(() => {});
+ };
+ response.once("close", close);
+
+ try {
+ await protocol.connect(transport);
+ await transport.handleRequest(request, response);
+ } catch (error) {
+ close();
+ if (!response.headersSent) {
+ sendProtocolError(
+ response,
+ 500,
+ error instanceof Error ? error.message : "Internal server error",
+ );
+ }
+ }
+ };
+}
+
+export async function startMcpHttpServer(
+ rawOptions: McpHttpOptions = {},
+): Promise {
+ const options = normalizeOptions(rawOptions);
+ const handler = createMcpHttpHandler(options);
+ const server = createNodeServer((request, response) => {
+ void handler(request, response).catch((error) => {
+ if (!response.headersSent) {
+ sendProtocolError(
+ response,
+ 500,
+ error instanceof Error ? error.message : "Internal server error",
+ );
+ } else {
+ response.destroy(error instanceof Error ? error : undefined);
+ }
+ });
+ });
+
+ await new Promise((resolveListen, rejectListen) => {
+ server.once("error", rejectListen);
+ server.listen(options.port, options.host, () => {
+ server.off("error", rejectListen);
+ resolveListen();
+ });
+ });
+
+ return server;
+}
+
+export async function runMcpHttpServer(): Promise {
+ const host = resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_HOST") || DEFAULT_HOST;
+ const port = positivePort(
+ resolveEnvOrEmpty("AGENTMEMORY_MCP_HTTP_PORT"),
+ DEFAULT_PORT,
+ );
+ const server = await startMcpHttpServer({ host, port });
+ process.stderr.write(
+ `[@agentmemory/mcp] Streamable HTTP server v${VERSION} listening on http://${host}:${port}/mcp\n`,
+ );
+
+ const shutdown = () => {
+ server.close(() => process.exit(0));
+ };
+ process.once("SIGINT", shutdown);
+ process.once("SIGTERM", shutdown);
+}
+
+const entrypoint = process.argv[1]
+ ? pathToFileURL(resolve(process.argv[1])).href
+ : "";
+if (entrypoint === import.meta.url) {
+ void runMcpHttpServer().catch((error) => {
+ process.stderr.write(
+ `[@agentmemory/mcp] HTTP server failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`,
+ );
+ process.exit(1);
+ });
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index dbca07d9b8..11b76b63eb 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -11,6 +11,7 @@ import type {
import { getVisibleTools } from "./tools-registry.js";
import { timingSafeCompare } from "../auth.js";
import { getAgentId, isAgentScopeIsolated } from "../config.js";
+import { selectSessionPage } from "../functions/session-list.js";
type McpResponse = {
status_code: number;
@@ -253,12 +254,22 @@ export function registerMcpEndpoints(
}
case "memory_sessions": {
- const sessions = await kv.list(KV.sessions);
+ const sessions = await kv.list(KV.sessions);
+ const page = selectSessionPage(sessions, {
+ limit: asNumber(args.limit, 20),
+ cursor: asNonEmptyString(args.cursor),
+ project: asNonEmptyString(args.project),
+ status: asNonEmptyString(args.status) as Session["status"] | undefined,
+ since: asNonEmptyString(args.since),
+ format: (asNonEmptyString(args.format) ?? "compact") as "compact" | "full",
+ includePrompt: args.includePrompt === true,
+ includeMalformed: args.includeMalformed === true,
+ });
return {
status_code: 200,
body: {
content: [
- { type: "text", text: JSON.stringify({ sessions }, null, 2) },
+ { type: "text", text: JSON.stringify(page, null, 2) },
],
},
};
@@ -674,14 +685,39 @@ export function registerMcpEndpoints(
const tags = typeof args.tags === "string" && args.tags.trim()
? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean)
: [];
+ const projectAliases =
+ typeof args.projectAliases === "string" &&
+ args.projectAliases.trim()
+ ? args.projectAliases
+ .split(",")
+ .map((alias: string) => alias.trim())
+ .filter(Boolean)
+ : undefined;
const actionResult = await sdk.trigger({ function_id: "mem::action-create", payload: {
title: args.title,
description: args.description,
priority: args.priority,
project: args.project,
+ projectId: args.projectId,
+ projectAliases,
tags,
parentId: args.parentId,
edges: edges.length > 0 ? edges : undefined,
+ lifecycle: args.lifecycle,
+ owner: args.owner,
+ notBefore: args.notBefore,
+ dueAt: args.dueAt,
+ awaitingHuman: args.awaitingHuman,
+ approval:
+ typeof args.approvalState === "string"
+ ? { state: args.approvalState }
+ : undefined,
+ blockedReason: args.blockedReason,
+ repoRoot: args.repoRoot,
+ worktree: args.worktree,
+ branch: args.branch,
+ taskSlug: args.taskSlug,
+ actor: args.actor,
} });
return {
status_code: 200,
@@ -700,11 +736,49 @@ export function registerMcpEndpoints(
body: { error: "actionId is required" },
};
}
+ const tags =
+ typeof args.tags === "string"
+ ? args.tags
+ .split(",")
+ .map((tag: string) => tag.trim())
+ .filter(Boolean)
+ : undefined;
+ const projectAliases =
+ typeof args.projectAliases === "string"
+ ? args.projectAliases
+ .split(",")
+ .map((alias: string) => alias.trim())
+ .filter(Boolean)
+ : undefined;
const updateResult = await sdk.trigger({ function_id: "mem::action-update", payload: {
actionId: args.actionId,
status: args.status,
+ lifecycle: args.lifecycle,
+ title: args.title,
+ description: args.description,
result: args.result,
priority: args.priority,
+ assignedTo: args.assignedTo,
+ owner: args.owner,
+ tags,
+ project: args.project,
+ projectId: args.projectId,
+ projectAliases,
+ notBefore: args.notBefore,
+ dueAt: args.dueAt,
+ awaitingHuman: args.awaitingHuman,
+ approval:
+ typeof args.approvalState === "string"
+ ? { state: args.approvalState }
+ : undefined,
+ blockedReason: args.blockedReason,
+ repoRoot: args.repoRoot,
+ worktree: args.worktree,
+ branch: args.branch,
+ taskSlug: args.taskSlug,
+ actor: args.actor,
+ correctionOf: args.correctionOf,
+ correctionReason: args.correctionReason,
} });
return {
status_code: 200,
@@ -716,6 +790,35 @@ export function registerMcpEndpoints(
};
}
+ case "memory_action_list": {
+ const tags =
+ typeof args.tags === "string" && args.tags.trim()
+ ? args.tags
+ .split(",")
+ .map((tag: string) => tag.trim())
+ .filter(Boolean)
+ : undefined;
+ const listResult = await sdk.trigger({ function_id: "mem::action-list", payload: {
+ project: args.project,
+ status: args.status,
+ view: args.view,
+ owner: args.owner,
+ tags,
+ agentId: args.agentId,
+ limit: args.limit,
+ cursor: args.cursor,
+ revision: args.revision,
+ } });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(listResult, null, 2) },
+ ],
+ },
+ };
+ }
+
case "memory_frontier": {
const frontierResult = await sdk.trigger({ function_id: "mem::frontier", payload: {
project: args.project,
diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts
index dd66ecb1dd..f3aa81712d 100644
--- a/src/mcp/standalone.ts
+++ b/src/mcp/standalone.ts
@@ -6,6 +6,8 @@ import { getAllTools } from "./tools-registry.js";
import { getStandalonePersistPath } from "../config.js";
import { VERSION } from "../version.js";
import { generateId } from "../state/schema.js";
+import { selectSessionPage } from "../functions/session-list.js";
+import type { Session } from "../types.js";
import {
resolveHandle,
invalidateHandle,
@@ -105,6 +107,12 @@ interface Validated {
tokenBudget?: number;
memoryIds?: string[];
reason?: string;
+ cursor?: string;
+ project?: string;
+ status?: string;
+ since?: string;
+ includePrompt?: boolean;
+ includeMalformed?: boolean;
}
function validate(toolName: string, args: Record): Validated {
@@ -147,6 +155,13 @@ function validate(toolName: string, args: Record): Validated {
}
case "memory_sessions": {
v.limit = parseLimit(args["limit"], 20);
+ if (typeof args["cursor"] === "string") v.cursor = args["cursor"].trim();
+ if (typeof args["project"] === "string") v.project = args["project"].trim();
+ if (typeof args["status"] === "string") v.status = args["status"].trim();
+ if (typeof args["since"] === "string") v.since = args["since"].trim();
+ if (typeof args["format"] === "string") v.format = args["format"].trim().toLowerCase();
+ v.includePrompt = args["includePrompt"] === true;
+ v.includeMalformed = args["includeMalformed"] === true;
return v;
}
case "memory_governance_delete": {
@@ -208,8 +223,18 @@ async function handleProxy(
return textResponse(result, true);
}
case "memory_sessions": {
+ const params = new URLSearchParams({
+ limit: String(v.limit),
+ format: v.format ?? "compact",
+ });
+ if (v.cursor) params.set("cursor", v.cursor);
+ if (v.project) params.set("project", v.project);
+ if (v.status) params.set("status", v.status);
+ if (v.since) params.set("since", v.since);
+ if (v.includePrompt) params.set("includePrompt", "true");
+ if (v.includeMalformed) params.set("includeMalformed", "true");
const result = await handle.call(
- `/agentmemory/sessions?limit=${v.limit}`,
+ `/agentmemory/sessions?${params.toString()}`,
{ method: "GET" },
);
return textResponse(result, true);
@@ -289,9 +314,18 @@ async function handleLocal(
case "memory_sessions": {
const sessions =
- await kvInstance.list>("mem:sessions");
- const limit = v.limit ?? 20;
- return textResponse({ sessions: sessions.slice(0, limit) }, true);
+ await kvInstance.list("mem:sessions");
+ const page = selectSessionPage(sessions, {
+ limit: v.limit,
+ cursor: v.cursor,
+ project: v.project,
+ status: v.status as Session["status"] | undefined,
+ since: v.since,
+ format: (v.format ?? "compact") as "compact" | "full",
+ includePrompt: v.includePrompt,
+ includeMalformed: v.includeMalformed,
+ });
+ return textResponse(page, true);
}
case "memory_governance_delete": {
@@ -339,7 +373,7 @@ async function handleProxyGeneric(
handle: ProxyHandle,
): Promise<{ content: Array<{ type: string; text: string }> }> {
// Forward to the server's full MCP surface so non-Claude clients can
- // reach all 53 tools (lessons, sentinels, slots, signals, graph, …)
+ // reach all 54 tools (lessons, sentinels, slots, signals, graph, …)
// instead of being capped at the 7 IMPLEMENTED_TOOLS set baked into
// this shim. The server validates arguments per tool.
const result = (await handle.call("/agentmemory/mcp/call", {
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index c4df3499c7..6f36c1aebb 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -115,8 +115,20 @@ export const CORE_TOOLS: McpToolDef[] = [
{
name: "memory_sessions",
description:
- "List recent sessions with their status and observation counts.",
- inputSchema: { type: "object", properties: {} },
+ "List recent sessions with bounded pagination. Compact output omits prompts by default.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ limit: { type: "number", description: "Page size (default 20, maximum 500)" },
+ cursor: { type: "string", description: "Opaque nextCursor from the previous page" },
+ project: { type: "string", description: "Canonical project id or a recorded alias" },
+ status: { type: "string", description: "active, completed, or abandoned" },
+ since: { type: "string", description: "Only sessions updated at or after this ISO timestamp" },
+ format: { type: "string", description: "compact (default) or full" },
+ includePrompt: { type: "boolean", description: "Include firstPrompt in full output (default false)" },
+ includeMalformed: { type: "boolean", description: "Include malformed legacy session rows with issue labels (default false)" },
+ },
+ },
},
{
name: "memory_smart_search",
@@ -374,7 +386,18 @@ export const V050_TOOLS: McpToolDef[] = [
type: "number",
description: "Priority 1-10 (10 highest)",
},
- project: { type: "string", description: "Project path" },
+ project: {
+ type: "string",
+ description: "Legacy project identifier or alias",
+ },
+ projectId: {
+ type: "string",
+ description: "Canonical non-path project identifier",
+ },
+ projectAliases: {
+ type: "string",
+ description: "Comma-separated legacy project aliases",
+ },
tags: {
type: "string",
description: "Comma-separated tags",
@@ -388,6 +411,33 @@ export const V050_TOOLS: McpToolDef[] = [
description:
"Comma-separated action IDs that must complete before this",
},
+ lifecycle: {
+ type: "string",
+ description: "Canonical lifecycle: pending, active, done, or cancelled",
+ },
+ owner: { type: "string", description: "Durable action owner" },
+ notBefore: {
+ type: "string",
+ description: "ISO timestamp before which the action is scheduled",
+ },
+ dueAt: { type: "string", description: "ISO due timestamp" },
+ awaitingHuman: {
+ type: "boolean",
+ description: "Whether progress waits for human input",
+ },
+ approvalState: {
+ type: "string",
+ description: "not_required, pending, approved, or rejected",
+ },
+ blockedReason: {
+ type: "string",
+ description: "Explicit manual blocking reason",
+ },
+ repoRoot: { type: "string", description: "Repository root context" },
+ worktree: { type: "string", description: "Worktree path or label" },
+ branch: { type: "string", description: "Git branch context" },
+ taskSlug: { type: "string", description: "Stable task slug" },
+ actor: { type: "string", description: "Agent or human making the change" },
},
required: ["title"],
},
@@ -404,15 +454,91 @@ export const V050_TOOLS: McpToolDef[] = [
type: "string",
description: "New status: pending, active, done, blocked, cancelled",
},
+ lifecycle: {
+ type: "string",
+ description: "Canonical lifecycle: pending, active, done, or cancelled",
+ },
+ title: { type: "string", description: "Replacement action title" },
+ description: {
+ type: "string",
+ description: "Replacement action description",
+ },
result: {
type: "string",
description: "Outcome description (when completing)",
},
priority: { type: "number", description: "New priority 1-10" },
+ assignedTo: {
+ type: "string",
+ description: "Current worker assignment",
+ },
+ owner: { type: "string", description: "Durable action owner" },
+ tags: { type: "string", description: "Comma-separated replacement tags" },
+ project: {
+ type: "string",
+ description: "Legacy project identifier or alias",
+ },
+ projectId: {
+ type: "string",
+ description: "Canonical non-path project identifier",
+ },
+ projectAliases: {
+ type: "string",
+ description: "Comma-separated legacy project aliases",
+ },
+ notBefore: { type: "string", description: "ISO scheduling timestamp" },
+ dueAt: { type: "string", description: "ISO due timestamp" },
+ awaitingHuman: {
+ type: "boolean",
+ description: "Whether progress waits for human input",
+ },
+ approvalState: {
+ type: "string",
+ description: "not_required, pending, approved, or rejected",
+ },
+ blockedReason: {
+ type: "string",
+ description: "Explicit manual blocking reason",
+ },
+ repoRoot: { type: "string", description: "Repository root context" },
+ worktree: { type: "string", description: "Worktree path or label" },
+ branch: { type: "string", description: "Git branch context" },
+ taskSlug: { type: "string", description: "Stable task slug" },
+ actor: { type: "string", description: "Agent or human making the change" },
+ correctionOf: {
+ type: "string",
+ description: "Event ID corrected by this append-only change",
+ },
+ correctionReason: {
+ type: "string",
+ description: "Reason for the correction",
+ },
},
required: ["actionId"],
},
},
+ {
+ name: "memory_action_list",
+ description:
+ "List actions through revision-bound actionable, scheduled, waiting, blocked, completed, or cancelled views.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ project: { type: "string", description: "Canonical project ID or alias" },
+ status: { type: "string", description: "Legacy status filter" },
+ view: {
+ type: "string",
+ description: "actionable, scheduled, waiting, blocked, completed, or cancelled",
+ },
+ owner: { type: "string", description: "Durable owner filter" },
+ tags: { type: "string", description: "Comma-separated tag filter" },
+ agentId: { type: "string", description: "Agent ID for lease readiness" },
+ limit: { type: "number", description: "Page size (default 50, maximum 500)" },
+ cursor: { type: "string", description: "Opaque nextCursor from the prior page" },
+ revision: { type: "number", description: "Expected collection revision" },
+ },
+ },
+ },
{
name: "memory_frontier",
description:
@@ -928,11 +1054,30 @@ export const V010_SLOTS_TOOLS: McpToolDef[] = [
export const ESSENTIAL_TOOLS = new Set([
"memory_save",
"memory_recall",
- "memory_consolidate",
"memory_smart_search",
"memory_sessions",
"memory_diagnose",
"memory_lesson_save",
+ "memory_lesson_recall",
+]);
+
+export const WORKSTATION_TOOLS = new Set([
+ ...ESSENTIAL_TOOLS,
+ "memory_file_history",
+ "memory_action_create",
+ "memory_action_update",
+ "memory_action_list",
+ "memory_frontier",
+ "memory_next",
+ "memory_lease",
+ "memory_signal_send",
+ "memory_signal_read",
+]);
+
+export const LLM_BACKED_TOOLS = new Set([
+ "memory_compress_file",
+ "memory_consolidate",
+ "memory_crystallize",
"memory_reflect",
]);
@@ -949,13 +1094,36 @@ export function getAllTools(): McpToolDef[] {
];
}
-// default switched from "core" (8 essential tools) to "all"
-// (full 53-tool surface). README and plugin manifests have always
-// advertised 53 tools "in proxy mode"; the old default left OpenCode /
-// Claude Code users seeing 8 with no indication the other tools existed.
-// Users who want the lean essentials can still set AGENTMEMORY_TOOLS=core.
export function getVisibleTools(): McpToolDef[] {
const mode = process.env["AGENTMEMORY_TOOLS"] || "all";
- if (mode === "core") return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));
- return getAllTools();
+ const all = getAllTools();
+ let selected: McpToolDef[];
+ if (mode === "all") {
+ selected = all;
+ } else if (mode === "core") {
+ selected = all.filter((tool) => ESSENTIAL_TOOLS.has(tool.name));
+ } else if (mode === "workstation") {
+ selected = all.filter((tool) => WORKSTATION_TOOLS.has(tool.name));
+ } else {
+ const allow = new Set(
+ mode
+ .split(",")
+ .map((name) => name.trim())
+ .filter(Boolean),
+ );
+ selected = all.filter((tool) => allow.has(tool.name));
+ if (selected.length === 0) {
+ selected = all.filter((tool) => ESSENTIAL_TOOLS.has(tool.name));
+ }
+ }
+ const disabled = new Set(
+ (process.env["AGENTMEMORY_DISABLED_TOOLS"] || "")
+ .split(",")
+ .map((name) => name.trim())
+ .filter(Boolean),
+ );
+ const noLlm = process.env["AGENTMEMORY_DISABLE_LLM_TOOLS"] === "true";
+ return selected.filter(
+ (tool) => !disabled.has(tool.name) && !(noLlm && LLM_BACKED_TOOLS.has(tool.name)),
+ );
}
diff --git a/src/providers/noop.ts b/src/providers/noop.ts
index 6e74f9aa75..326610c4a5 100644
--- a/src/providers/noop.ts
+++ b/src/providers/noop.ts
@@ -9,6 +9,7 @@ import type { MemoryProvider } from "../types.js";
*/
export class NoopProvider implements MemoryProvider {
name = "noop";
+ kind = "noop" as const;
async compress(): Promise {
return "";
diff --git a/src/providers/resilient.ts b/src/providers/resilient.ts
index 95ece40c96..10d6718eb6 100644
--- a/src/providers/resilient.ts
+++ b/src/providers/resilient.ts
@@ -4,9 +4,11 @@ import { CircuitBreaker } from "./circuit-breaker.js";
export class ResilientProvider implements MemoryProvider {
private breaker = new CircuitBreaker();
name: string;
+ kind: "llm" | "noop";
constructor(private inner: MemoryProvider) {
this.name = `resilient(${inner.name})`;
+ this.kind = inner.kind ?? (inner.name === "noop" ? "noop" : "llm");
}
private async call(fn: () => Promise): Promise {
diff --git a/src/state/kv.ts b/src/state/kv.ts
index 0c0e6ccc12..f455bbaa87 100644
--- a/src/state/kv.ts
+++ b/src/state/kv.ts
@@ -4,10 +4,15 @@ export class StateKV {
constructor(private sdk: ISdk) {}
async get(scope: string, key: string): Promise {
- return this.sdk.trigger<{ scope: string; key: string }, T | null>({
+ // The iii-engine resolves `state::get` with `undefined` (an absent
+ // result field) for missing keys, not `null`. Normalize here so the
+ // declared `T | null` contract holds — callers compare against `null`
+ // with strict equality (e.g. rebaseActionMutation's create path).
+ const value = await this.sdk.trigger<{ scope: string; key: string }, T | null>({
function_id: 'state::get',
payload: { scope, key },
})
+ return value ?? null
}
async set(scope: string, key: string, value: T): Promise