From d006520dfb03b4f05a7e8f7defa52283b53165c0 Mon Sep 17 00:00:00 2001 From: neal Date: Mon, 21 Sep 2026 15:54:44 -0400 Subject: [PATCH 01/10] fix(providers): honor the configured LLM timeout instead of clamping it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fetchWithTimeout clamped every budget to a 170s HARD_BUDGET_CAP_MS while openai.ts still reported the unclamped value in its timeout error, so an AGENTMEMORY_LLM_TIMEOUT_MS of 480000 aborted at 170s and claimed 480000ms. Broker-side records confirm it: 86 client-disconnect 499s on the general route, p50 duration 169,996ms, p90 170,004ms, none past 400s. The cap existed to stay under iii's 180s invocation timeout. ADR 0001 deleted that runtime — the in-process Engine has no invocation timeout, so the ceiling bounded against a limit that no longer exists and turned slow local models into provider failures, which then tripped the circuit breaker and failed unrelated calls. The caller's timeout is now the total budget for all attempts plus sleeps, honored exactly. test/fetch-timeout.test.ts asserted the clamp; it now asserts the opposite. Generated-By: Claude Opus 5 (1M context) --- CLAUDE.md | 5 ++++ .../0001-single-in-process-sqlite-engine.md | 5 ++++ src/providers/_fetch.ts | 24 ++++++++----------- test/fetch-timeout.test.ts | 24 ++++++++++--------- 4 files changed, 33 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 55ccc14360..ffe90bf10e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -125,6 +125,11 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no Engine import). - REST endpoints must whitelist fields — never pass raw request body to `sdk.trigger()` - Use `recordAudit()` for state-changing operations - Timestamps: capture once with `new Date().toISOString()` and reuse +- Outbound LLM/embedding calls go through `fetchWithTimeout`, which honors the configured + bound (`OPENAI_TIMEOUT_MS` → `AGENTMEMORY_LLM_TIMEOUT_MS` → 60s) exactly. The in-process + Engine has no invocation timeout, so never reintroduce a ceiling that clamps that bound — + the old 170s `HARD_BUDGET_CAP_MS` cited iii's 180s limit, silently cut every longer + timeout, and still reported the configured value in the error. ## Testing diff --git a/docs/adrs/0001-single-in-process-sqlite-engine.md b/docs/adrs/0001-single-in-process-sqlite-engine.md index 0f9b2f73a7..2a8a435dad 100644 --- a/docs/adrs/0001-single-in-process-sqlite-engine.md +++ b/docs/adrs/0001-single-in-process-sqlite-engine.md @@ -66,3 +66,8 @@ this fork does not execute. Rejected on cost against zero realised benefit. registration and `trigger()` become direct in-process calls. - Documentation describing agentmemory as built on iii-engine's three primitives becomes false for this fork and must be rewritten, not annotated. +- Code that budgeted time against iii's 180s invocation timeout is now bounding itself + against a limit that no longer exists. `fetchWithTimeout`'s 170s `HARD_BUDGET_CAP_MS` was + one such residual: it clamped every configured LLM timeout above it while the error still + reported the unclamped value, so a slow local model looked like a provider failure. Treat + any remaining iii-derived ceiling as a defect, not a safety margin. diff --git a/src/providers/_fetch.ts b/src/providers/_fetch.ts index 3b02d9352d..b90f55c747 100644 --- a/src/providers/_fetch.ts +++ b/src/providers/_fetch.ts @@ -3,13 +3,10 @@ import { getEnvVar } from "../config.js"; // Bounded retry for transient rate-limit / unavailable responses. Attempts is // total tries (initial + retries). Retries are bounded by a TOTAL elapsed // deadline — not per-attempt — so the worst case never blows past the caller's -// timeout budget or the iii invocation timeout. A single retry delay is capped -// low so a hostile Retry-After header can't dominate the budget. +// timeout budget. A single retry delay is capped low so a hostile Retry-After +// header can't dominate the budget. const MAX_ATTEMPTS = 3; const MAX_RETRY_DELAY_MS = 5000; -// Absolute ceiling on the total budget, kept well under the iii 180s invocation -// timeout so retries + sleeps + per-attempt timeouts can never overrun it. -const HARD_BUDGET_CAP_MS = 170000; // A retry only makes sense if there's room for at least a token attempt after // the sleep; without this floor we'd sleep, fire, and get instantly cut off. const MIN_ATTEMPT_FLOOR_MS = 100; @@ -65,15 +62,14 @@ export async function fetchWithTimeout( Number.parseInt(getEnvVar("AGENTMEMORY_LLM_TIMEOUT_MS") ?? "60000", 10); const ms = Number.isFinite(parsed) && parsed > 0 ? parsed : 60000; - // The caller's timeout is the TOTAL budget for all attempts + sleeps, hard - // capped so we never approach the iii invocation timeout. - const budgetMs = Math.min(ms, HARD_BUDGET_CAP_MS); + // The caller's timeout is the TOTAL budget for all attempts + sleeps, and it + // is honored exactly. This fork runs only the in-process Engine (ADR 0001), + // which imposes no invocation timeout to stay under, so a configured bound + // must not be silently shortened — a slow local model legitimately needs the + // minutes it was given. const start = Date.now(); - // The first attempt must honor the capped budget too — passing raw `ms` - // here would let a large caller timeout hang past HARD_BUDGET_CAP_MS (and - // the iii 180s invocation timeout) before any retry logic runs. - let response: Response = await fetchOnce(url, init, budgetMs); + let response: Response = await fetchOnce(url, init, ms); for (let attempt = 1; attempt < MAX_ATTEMPTS; attempt++) { if (!RETRY_STATUS.has(response.status)) return response; @@ -86,7 +82,7 @@ export async function fetchWithTimeout( // budget — a hostile Retry-After that alone exceeds the remaining budget // returns the last response instead of stalling the caller. const elapsed = Date.now() - start; - const remaining = budgetMs - elapsed; + const remaining = ms - elapsed; if (delay + MIN_ATTEMPT_FLOOR_MS > remaining) return response; // This response is being discarded for a retry; release its body so the @@ -98,7 +94,7 @@ export async function fetchWithTimeout( // can't push total elapsed past the deadline. const attemptMs = Math.max( MIN_ATTEMPT_FLOOR_MS, - Math.min(ms, budgetMs - (Date.now() - start)), + ms - (Date.now() - start), ); response = await fetchOnce(url, init, attemptMs); } diff --git a/test/fetch-timeout.test.ts b/test/fetch-timeout.test.ts index f4a4286780..11ea970261 100644 --- a/test/fetch-timeout.test.ts +++ b/test/fetch-timeout.test.ts @@ -79,7 +79,7 @@ describe("fetchWithTimeout", () => { // // The retry wrapper must bound TOTAL elapsed time across every // attempt + sleep — not per-attempt — so worst case never blows -// past the caller's budget or the iii 180s invocation timeout. +// past the caller's configured budget. // ───────────────────────────────────────────────────────────── describe("fetchWithTimeout bounded retry (total deadline)", () => { // Builds a fetch mock that replays a queue of {status, headers} in order, @@ -106,12 +106,12 @@ describe("fetchWithTimeout bounded retry (total deadline)", () => { delete process.env["AGENTMEMORY_LLM_TIMEOUT_MS"]; }); - // 0. The FIRST attempt must honor the hard budget cap, not the raw caller - // timeout. Regression: fetchOnce was called with `ms` instead of the - // capped `budgetMs`, so a large caller timeout (e.g. 300s) could hang the - // initial request past HARD_BUDGET_CAP_MS (170s) and the iii 180s - // invocation timeout before any retry logic ran. - it("caps the first attempt at the hard budget, not the raw caller timeout", async () => { + // 0. The FIRST attempt must honor the caller's configured timeout in full. + // Regression: a 170s HARD_BUDGET_CAP_MS silently shortened every budget + // above it, so AGENTMEMORY_LLM_TIMEOUT_MS=480000 aborted at 170s while the + // error message still reported 480000ms. Slow local models legitimately + // run past 170s; the configured bound is the only bound. + it("honors the full caller timeout on the first attempt", async () => { const signals: AbortSignal[] = []; const capturing = ((_url: string, init?: RequestInit) => { const signal = init!.signal as AbortSignal; @@ -125,15 +125,17 @@ describe("fetchWithTimeout bounded retry (total deadline)", () => { vi.spyOn(globalThis, "fetch").mockImplementation(capturing); vi.useFakeTimers(); - // 300s caller timeout — far above the 170s HARD_BUDGET_CAP_MS. + // 300s caller timeout — well past the 170s cap this used to be clamped to. const p = fetchWithTimeout("https://example.com", {}, 300000); p.catch(() => {}); // observe rejection so it isn't flagged unhandled expect(signals).toHaveLength(1); - // Just before the cap the first attempt is still alive. - await vi.advanceTimersByTimeAsync(169999); + // Past the old 170s cap the attempt must still be alive. + await vi.advanceTimersByTimeAsync(200000); + expect(signals[0].aborted).toBe(false); + // It aborts only at the configured 300s bound. + await vi.advanceTimersByTimeAsync(99999); expect(signals[0].aborted).toBe(false); - // At the cap it must abort. Pre-fix (raw 300s) it would still be alive. await vi.advanceTimersByTimeAsync(2); expect(signals[0].aborted).toBe(true); From e6c0cbde7ebbb0cf476ac7f76517aaf92912837b Mon Sep 17 00:00:00 2001 From: neal Date: Mon, 21 Sep 2026 15:54:49 -0400 Subject: [PATCH 02/10] fix(engine): stop a literal NUL making sdk.ts unsearchable groupKey joined its two parts with a raw NUL byte. One NUL is enough for git and grep to classify the whole file as binary, so every search over src/engine/inproc/sdk.ts silently returned nothing and `file` reported it as data rather than source. U+001F separates just as well. The key is only ever a streamItems Map key and is never persisted, so nothing migrates. Generated-By: Claude Opus 5 (1M context) --- src/engine/inproc/sdk.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/engine/inproc/sdk.ts b/src/engine/inproc/sdk.ts index 70d6b434fc..057817838d 100644 --- a/src/engine/inproc/sdk.ts +++ b/src/engine/inproc/sdk.ts @@ -251,8 +251,10 @@ export function createInprocSdk(opts: InprocSdkOptions): InprocSdk { let streamBytes = 0; const subscriptions = new Set(); + // Separator is U+001F, not NUL: a literal NUL in the source makes git and + // grep classify this whole file as binary and silently skip it in searches. const groupKey = (streamName: string, groupId: string) => - `${streamName}${groupId}`; + `${streamName}${groupId}`; function broadcast(message: Record): void { const streamName = message.streamName as string; From 04a9213796f33702b7438b620a3b5a9d9f1e298d Mon Sep 17 00:00:00 2001 From: neal Date: Mon, 21 Sep 2026 15:59:02 -0400 Subject: [PATCH 03/10] docs: state what the memory system is for at the top of CLAUDE.md CLAUDE.md opened straight into architecture, so every feature argument started from mechanism. Lead with the goal instead: right Memory, right moment, right scope, least record that restates it. Generated-By: Claude Opus 5 (1M context) --- CLAUDE.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index ffe90bf10e..46d6a7b6c8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1,30 @@ # agentmemory — Agent Instructions +## Goal + +Put the right Memory in front of an Agent at the moment it needs it, and pay as little as +possible to be able to do that. Every feature here is judged against that sentence. + +- **Right content** — Recall returns what bears on the work in hand, not everything that + matched the query. A near-miss that costs the Agent a read is worse than one fewer result. +- **Right moment** — context arrives at hook boundaries (session start, pre-tool-use, + pre-compact) without the Agent having to know to ask. Memory the Agent must remember to + query is memory that goes unused. +- **Right scope** — results are bounded by project, branch, and Session + (`scope: "project" | "global"`, `src/types.ts:277`). One repo's work never surfaces in + another's. +- **Least record that restates** — store the smallest durable claim that reconstructs a + decision later: the conclusion and why, not the transcript that produced it. Observations + are raw and cheap; a Memory earns its place by being worth re-reading. +- **Durable beats recent** — a correction that changes future behaviour outranks a log of + what happened. Volume is a cost, not a measure of success; Eviction is expected, not a + failure mode. +- **Never on the critical path** — memory accelerates a Session and is never a dependency of + one. A dead daemon, a missed hook, or a slow Recall degrades the work; it does not block + it. +- **The Operator's attention is the scarce resource** — disk growth, restarts, and noisy + recall are the real costs, and they land on one person. + ## Architecture agentmemory is a persistent memory system for AI coding agents. It runs as a single process on one in-process Engine ([ADR 0001](./docs/adrs/0001-single-in-process-sqlite-engine.md)) — importing `src/index.ts` *is* starting the daemon. There is no separate runtime to install, spawn, adopt or stop. From 304c40ab28f490969564dd0be6ab94404727281e Mon Sep 17 00:00:00 2001 From: neal Date: Mon, 21 Sep 2026 18:07:28 -0400 Subject: [PATCH 04/10] docs: triage upstream's open issues and orphan PRs against this tree Score every open upstream issue on severity x difficulty, cross-link the PRs that claim to fix each one, and score the 168 PRs that reference no open issue by how much of their diff lands in files this fork tracks. Every row carries a disposition: wont-fix for what is out of scope here (no iii engine, no npm publish, no Windows CI, no deploy tree, no adapter for the host), already-fixed for what this tree already carries, candidate for the working set. The 17 high-severity/low-difficulty issues and the 35 high-relevance candidate PRs were then opened against this tree and read. Rows checked that way carry a status whose leading token says what the read found; 15 claims turned out to be already fixed here and moved out of the candidate set. A row with no status is still upstream's claim, not a verified defect. Generated-By: Claude Opus 5 (1M context) --- CLAUDE.md | 17 + docs/upstream-issue-triage.yaml | 2734 +++++++++++++++++++++++++++++++ docs/upstream-pr-triage.yaml | 2388 +++++++++++++++++++++++++++ 3 files changed, 5139 insertions(+) create mode 100644 docs/upstream-issue-triage.yaml create mode 100644 docs/upstream-pr-triage.yaml diff --git a/CLAUDE.md b/CLAUDE.md index 46d6a7b6c8..d703fa631b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -196,6 +196,23 @@ the `@agentmemory/mcp` shim wherever it is invoked as a proxy — `plugin/.mcp.j running server, not from the shim. The translated `READMEs/` were deleted rather than kept stale — do not re-add translations without a way to keep them current. +`docs/upstream-issue-triage.yaml` scores every open upstream issue by severity and fix +difficulty. It is a survey of defects in the shared code lineage, used to pick what is worth +fixing *here* — it is not a backlog to merge from, and it is a dated snapshot, not a live +mirror. Re-generate it from `gh issue list` rather than editing rows by hand. Its rows +cross-link the open upstream PRs that claim to fix them; `docs/upstream-pr-triage.yaml` +covers the remaining PRs — the ones that reference no open issue — scored by whether they +land in code this fork carries. Both are read for the defect and the diagnosis, never for +the patch. + +Every row in both files carries a `disposition`: `already-fixed` (verified against this tree; +`fixed_by`/`status` names the evidence), `wont-fix` (out of scope here — no iii engine, no npm +publish, no Windows CI, no deploy tree, or a host with no adapter in `src/cli/connect/`; +`wont_fix_reason` says which), or `candidate` — the working set. A row that was opened against +this tree also carries `status`, whose leading token says what the read found +(`fixed-here`, `present-here`, `partly-present-here`, `unresolved`). No `status` means +unchecked: the note is still upstream's claim, not a verified defect. + ## Current Stats (v0.9.29) - 55 MCP tools (all visible by default, `AGENTMEMORY_TOOLS=core` for the 8 essentials) diff --git a/docs/upstream-issue-triage.yaml b/docs/upstream-issue-triage.yaml new file mode 100644 index 0000000000..0603df299f --- /dev/null +++ b/docs/upstream-issue-triage.yaml @@ -0,0 +1,2734 @@ +# Upstream open-issue triage — rohitg00/agentmemory +# +# Scope: every open issue (not PR) on the upstream repository, scored on two axes. +# This fork does not merge from upstream (see CLAUDE.md); this is a survey of known +# defects in the shared code lineage, used to decide what is worth fixing here. +# +# severity — user impact if unfixed: +# high data loss, daemon/worker crash or unavailability, cross-agent or cross-user +# leakage, silent corruption, or a headline feature that never works at all +# med broken in a specific configuration, wrong or incomplete results, avoidable +# LLM spend, install/connect failure with a workaround +# low cosmetic, documentation, small UX, or a nice-to-have request +# +# difficulty — cost to fix in this codebase: +# low one or a few call sites, parameter plumbing, config or guard +# med several modules plus tests, a new endpoint, or a migration +# high architectural change, engine/dependency-level work, or a new subsystem +# +# kind — bug | feature | docs | chore | question | report | promo +# +# disposition — what this fork intends to do: +# already-fixed verified fixed in this tree; `fixed_by` names the evidence +# wont-fix out of scope here; `wont_fix_reason` says why +# candidate applies here and is unclaimed — the working set +# +# status — present only where the claim was checked against this tree by reading the +# code. "present-here" means the defect reproduces here as reported; +# "partly-present-here" means part of it was already fixed; "unresolved" means this +# tree cannot settle it. Absent means unchecked: the note is still upstream's claim. +# +# fix_prs — open upstream PRs whose title or body claims to close this issue +# (closing keyword). Read the PR before writing the fix here; several +# issues have competing PRs, and none of them are merged. +# mentioned_by_prs — open PRs that reference the issue without claiming to close it. +# Absent fields mean no open PR references the issue. 168 of the 291 open PRs reference +# no open issue at all and are NOT represented here. +# Snapshot: 308 open issues, cross-linked against 291 open PRs, as of +# 2026-09-21 (gh issue list / gh pr list --repo rohitg00/agentmemory). + +issues: + - number: 195 + title: "Architecture: Prevent Event Loop Freezes Caused by Heavy CPU-bound Tasks." + severity: high + difficulty: high + kind: bug + note: "Vector search blocks the single Node thread; fixing it means moving CPU work off the event loop." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/195 + - number: 259 + title: "Support custom metadata fields per session" + severity: low + difficulty: med + kind: feature + note: "Free-form session metadata plus a filterable surface in search_sessions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/259 + mentioned_by_prs: [306, 318] + - number: 262 + title: "Plugin doesn't work on OpenClaw 2026.5.7 — hook signatures and message_sent don't match" + severity: med + difficulty: med + kind: bug + note: "OpenClaw plugin hook signatures do not match the SDK, so chat capture is a no-op." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/262 + - number: 263 + title: "Consider implementing regex safety for Sentinels pattern matching" + severity: med + difficulty: low + kind: bug + note: "Sentinel patterns compile user regex directly; ReDoS on the observation path." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/263 + fix_prs: [297] + - number: 274 + title: "Lessons not created in flow-compress, consolidate, and consolidation-pipeline" + severity: med + difficulty: med + kind: bug + note: "flow-compress/consolidate extract lessons but never persist them via mem::lesson-save." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/274 + fix_prs: [279] + - number: 276 + title: "CRITICAL: Session summary and firstPrompt set to identical value" + severity: med + difficulty: low + kind: bug + note: "summary and firstPrompt written to the same truncated title (api.ts:542)." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/276 + - number: 299 + title: "Viewer UI shows empty state when fronted by a reverse proxy on standard ports (80/443) — JS hardcodes :3113" + severity: med + difficulty: low + kind: bug + note: "Viewer JS hardcodes :3113, so every panel is empty behind a reverse proxy." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/299 + mentioned_by_prs: [1083] + - number: 301 + title: "0.9.7 persistence fix is incomplete — distroless iii-engine (UID 65532) can't write to root-owned docker volume" + severity: high + difficulty: med + kind: bug + note: "Distroless UID 65532 cannot write the root-owned volume; state still non-persistent." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/301 + - number: 334 + title: "Antigravity (VS-code)" + severity: low + difficulty: med + kind: question + note: "Asks for an Antigravity plugin." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/334 + mentioned_by_prs: [1083] + - number: 336 + title: "Proposal: refactor viewer into a typed Vue/Vite frontend" + severity: low + difficulty: high + kind: feature + note: "Rewrite the single-file viewer as typed Vue 3 + Vite." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/336 + - number: 338 + title: "mem::graph-stats returns 'Function not found' — graph extraction broken in v0.9.11 / iii 0.11.2" + severity: high + difficulty: med + kind: bug + note: "mem::graph-stats returns Function not found; graph extraction dead in 0.9.11." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/338 + mentioned_by_prs: [341] + - number: 345 + title: "concept_edges table + BFS-depth-2 recall mode" + severity: med + difficulty: high + kind: feature + note: "concept_edges table plus a BFS-depth-2 recall mode." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/345 + fix_prs: [349] + - number: 392 + title: "Feature Request: Support time range filtering for memory_recall and memory_sessions" + severity: low + difficulty: med + kind: feature + note: "Time-range filters for memory_recall and memory_sessions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/392 + fix_prs: [414] + - number: 395 + title: "Bug: Local embedding stuck at \"none\" (BM25-only) in v0.9.13 despite correct xenova config" + severity: med + difficulty: med + kind: bug + note: "Local embedding stays at none despite a correct xenova config." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/395 + fix_prs: [412, 1283] + - number: 399 + title: "Feature request: Kubernetes Helm chart" + severity: low + difficulty: med + kind: feature + note: "Kubernetes Helm chart under deploy/helm." + disposition: wont-fix + wont_fix_reason: "Docker / PaaS / Kubernetes deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/issues/399 + - number: 400 + title: "Codex plugin install does not expose advertised full MCP tool surface" + severity: med + difficulty: low + kind: bug + note: "Codex plugin starts the shim without env, so only core tools are exposed." + disposition: wont-fix + wont_fix_reason: "unsupported host — Codex and Cursor are not supported here" + url: https://github.com/rohitg00/agentmemory/issues/400 + - number: 420 + title: "Feature: memory_signal_peek tool (read-only signal listing, no readAt mark)" + severity: low + difficulty: low + kind: feature + note: "Read-only memory_signal_peek that does not set readAt." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/420 + - number: 422 + title: "Viewer tab bar collapses/clips on Windows/Chromium layout" + severity: low + difficulty: low + kind: bug + note: "Viewer .tab-bar collapses vertically on Windows/Chromium." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/422 + - number: 429 + title: "How to move Agentmemory storage to another disk(e.g D or E)?" + severity: low + difficulty: low + kind: question + note: "How to relocate storage to another drive." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/429 + - number: 430 + title: "npm installs anthropic dependencies" + severity: low + difficulty: low + kind: bug + note: "Anthropic SDK pulled in for users who do not run Claude Code." + disposition: wont-fix + wont_fix_reason: "npm distribution — nothing is published from this fork" + url: https://github.com/rohitg00/agentmemory/issues/430 + - number: 431 + title: "Feature Request: Native Hooks / Auto-Context Injection for OpenCode" + severity: med + difficulty: med + kind: feature + note: "Native hooks / auto context injection for OpenCode." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/431 + - number: 433 + title: "Expose agent_id / session_id in /agentmemory/audit so external rate-limiters can scope per-agent" + severity: med + difficulty: low + kind: feature + note: "Expose agent_id/session_id in /agentmemory/audit for per-agent rate limiting." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/433 + - number: 436 + title: "[Question] Desktop Apps Auto-detect?" + severity: low + difficulty: med + kind: question + note: "Whether desktop apps are auto-detected." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/436 + - number: 437 + title: "[BUG] Proxy Detected, Cannot Install" + severity: low + difficulty: low + kind: bug + note: "npm ECONNRESET behind a proxy on Windows 11; environment, not code." + disposition: wont-fix + wont_fix_reason: "npm distribution — nothing is published from this fork" + url: https://github.com/rohitg00/agentmemory/issues/437 + - number: 439 + title: "support Volcengine embedding model URL" + severity: low + difficulty: low + kind: feature + note: "Support the Volcengine embedding base URL shape." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/439 + - number: 440 + title: "MCP `memory_recall` is aliased to smart-search and drops `format` param - full content unreachable via MCP" + severity: high + difficulty: low + kind: bug + note: "memory_recall aliased to smart-search and drops format, so full content is unreachable over MCP." + disposition: already-fixed + fixed_by: "memory_recall routes to mem::search, not smart-search (src/mcp/server.ts:145)." + url: https://github.com/rohitg00/agentmemory/issues/440 + - number: 455 + title: "Worker refuses to start after embedding provider change: stale index dimension mismatch (2048D vs 384D)" + severity: high + difficulty: med + kind: bug + note: "Stale index dimension mismatch makes the worker refuse to start; REST unreachable." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/455 + fix_prs: [575] + mentioned_by_prs: [525] + - number: 469 + title: "Vector Index Dimension Mismatch Crashes Server on Startup (2048 vs 384)" + severity: high + difficulty: med + kind: bug + note: "Same 2048-vs-384 dimension mismatch crashing startup on macOS." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/469 + fix_prs: [575] + mentioned_by_prs: [525] + - number: 480 + title: "Feature Request: Add eviction timer + env toggle for `mem::evict` (parity with `mem::auto-forget`)" + severity: med + difficulty: low + kind: feature + note: "Eviction timer plus env toggle for mem::evict, matching mem::auto-forget." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/480 + fix_prs: [490] + - number: 483 + title: "Feature request: i18n / Chinese localization for viewer UI" + severity: low + difficulty: high + kind: feature + note: "i18n for the viewer, starting with Chinese." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/483 + fix_prs: [541, 673] + - number: 496 + title: "Feature Request: Add DELETE endpoints for Actions and Crystals" + severity: med + difficulty: med + kind: feature + note: "DELETE endpoints for Actions and Crystals." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/496 + - number: 499 + title: "AgentMemory server becomes unresponsive with multiple concurrent Claude Code sessions" + severity: high + difficulty: high + kind: bug + note: "Server becomes unresponsive under three concurrent Claude Code sessions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/499 + - number: 505 + title: "Viewer Rebuild Graph button calls missing /agentmemory/graph/build endpoint" + severity: med + difficulty: low + kind: bug + note: "Viewer Rebuild Graph calls a nonexistent POST /agentmemory/graph/build." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/505 + fix_prs: [533, 538] + - number: 510 + title: "Bug: MCP tools not loaded by Claude Code despite healthy server and working plugin" + severity: med + difficulty: med + kind: bug + note: "MCP tools not loaded by Claude Code despite a healthy server." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/510 + - number: 511 + title: "npm install shows peer dependency conflict with @anthropic-ai/sdk (0.39.0 vs >=0.93.0)" + severity: low + difficulty: low + kind: bug + note: "Peer dependency conflict on @anthropic-ai/sdk during global install." + disposition: wont-fix + wont_fix_reason: "npm distribution — nothing is published from this fork" + url: https://github.com/rohitg00/agentmemory/issues/511 + - number: 512 + title: "Chinese/Japanese i18n: improve viewer Memories search" + severity: med + difficulty: med + kind: feature + note: "CJK tokenization for viewer Memories search." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/512 + fix_prs: [536] + - number: 515 + title: "Codex worktrees are treated as separate projects, fragmenting context and project-scoped memory" + severity: med + difficulty: med + kind: bug + note: "Codex worktrees keyed by worktree cwd, fragmenting project-scoped memory." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/515 + fix_prs: [717] + - number: 518 + title: "AGENTMEMORY_SECRET enables api-auth middleware that also rejects internal worker callbacks, silently halting consolidation pipeline (v0.9.20)" + severity: high + difficulty: med + kind: bug + note: "AGENTMEMORY_SECRET auth rejects internal worker callbacks, silently halting consolidation." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/518 + fix_prs: [577] + mentioned_by_prs: [531, 535] + - number: 523 + title: "Suggestion: LAN Multi-Machine Support and Scheduled Database Backup" + severity: med + difficulty: high + kind: feature + note: "LAN multi-machine client/server mode plus scheduled database backup." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/523 + - number: 524 + title: "Feature request: built-in service install for daemon-mode autostart (macOS / Linux / Windows)" + severity: med + difficulty: med + kind: feature + note: "Ship LaunchAgent/systemd/Windows service units for daemon autostart." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/524 + - number: 527 + title: "Support OpenAI/Codex subscription-auth fallback without requiring OPENAI_API_KEY" + severity: low + difficulty: high + kind: feature + note: "OpenAI/Codex subscription-auth fallback without OPENAI_API_KEY." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/527 + - number: 552 + title: "docs: memory_lesson_save MCP tool exists but is completely undocumented (confidence, decay, reinforcement lifecycle)" + severity: low + difficulty: low + kind: docs + note: "memory_lesson_save exists but is absent from every doc surface." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/552 + - number: 557 + title: "error: unsupported OS when installing on Windows 11" + severity: med + difficulty: low + kind: bug + note: "iii console installer rejects MINGW64 on Windows 11." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/557 + - number: 559 + title: "agentmemory Graph empty" + severity: med + difficulty: med + kind: bug + note: "Graph stays empty on macOS with GRAPH_EXTRACTION_ENABLED=true." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/559 + - number: 586 + title: "Feature request: signal detector hook (on_turn_start) for entity extraction" + severity: low + difficulty: med + kind: feature + note: "Regex signal detector on on_turn_start for zero-LLM entity extraction." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/586 + - number: 589 + title: "How to use it with github copilot" + severity: low + difficulty: low + kind: question + note: "How to use agentmemory with GitHub Copilot in VS Code." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/589 + fix_prs: [622] + - number: 590 + title: "`mem::context` and `smart-search` skip `KV.insights` and `KV.semantic`" + severity: med + difficulty: med + kind: bug + note: "mem::context and smart-search never read KV.insights or KV.semantic." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/590 + - number: 595 + title: "Expose privacy-safe memory governance/delete receipts" + severity: low + difficulty: med + kind: feature + note: "Privacy-safe governance/delete receipts as an observability boundary." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/595 + - number: 596 + title: "OpenClaw plugin should scope recall/capture by session/user to avoid cross-user memory leakage" + severity: high + difficulty: med + kind: bug + note: "OpenClaw integration has no session/user scoping; cross-user memory leakage." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/596 + mentioned_by_prs: [598] + - number: 600 + title: "Bug: Knowledge graph extraction never fires automatically" + severity: high + difficulty: low + kind: bug + note: "event::session::stopped listens on a topic nothing publishes, so graph extraction never fires." + disposition: already-fixed + fixed_by: "Graph extraction fires from the observe pipeline (src/triggers/events.ts:123)." + url: https://github.com/rohitg00/agentmemory/issues/600 + - number: 603 + title: "cline --tui not recording sessions" + severity: med + difficulty: med + kind: bug + note: "cline --tui triggers no hooks, so no sessions are recorded." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/603 + - number: 605 + title: "memory_verify + Citation provenance: does a hybrid raw-anchor schema fit the audit lane?" + severity: low + difficulty: high + kind: feature + note: "Raw-anchor citation provenance schema for the verify/audit lane." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/605 + - number: 608 + title: "Doc - Link to an auto-generated architecture overview for agentmemory" + severity: low + difficulty: low + kind: promo + note: "Vendor offering to link auto-generated architecture docs." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/608 + - number: 609 + title: "Viewer dashboard can freeze Chrome by processing large mem-live sync backlogs" + severity: high + difficulty: med + kind: bug + note: "Large mem-live WebSocket sync backlog grows Chrome by GBs and freezes it." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/609 + fix_prs: [623, 1302] + - number: 620 + title: "Reduce MCP tool surface area" + severity: med + difficulty: med + kind: feature + note: "Cut the MCP tool surface so models stop picking wrong entry points." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/620 + - number: 621 + title: "Standardize MCP tool dispatch test mocks" + severity: low + difficulty: low + kind: chore + note: "Standardize MCP dispatch test mocks on the repo pattern." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/621 + - number: 637 + title: "Windows: mem::summarize fails with Unicode characters (em dash) — ByteString conversion error" + severity: high + difficulty: low + kind: bug + note: "mem::summarize 500s on any character above U+00FF on Windows (ByteString conversion)." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/637 + - number: 645 + title: "安装时有一些警告,虽然不影响使用,但我觉得对新用户体验很差" + severity: low + difficulty: low + kind: bug + note: "Install-time npm peer dependency warnings; duplicate of 511." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/645 + - number: 655 + title: "memory_consolidate (semantic) and memory_reflect timeout due to sequential KV operations" + severity: high + difficulty: med + kind: bug + note: "Semantic consolidate and reflect time out from sequential KV operations." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/655 + mentioned_by_prs: [867] + - number: 658 + title: "Hermes saved plugin config does not affect runtime" + severity: med + difficulty: low + kind: bug + note: "Hermes saved plugin config is written but never read at runtime." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/658 + fix_prs: [663] + - number: 668 + title: "@agentmemory/mcp does not pin the matching core version, allowing fixed MCP behavior to regress" + severity: med + difficulty: low + kind: bug + note: "@agentmemory/mcp does not pin a matching core version, so fixed behavior regresses." + disposition: wont-fix + wont_fix_reason: "npm distribution — nothing is published from this fork" + url: https://github.com/rohitg00/agentmemory/issues/668 + fix_prs: [1231] + - number: 691 + title: "[viewer] Graph nodes jumping/flickering on every poll refresh due to missing position preservation and no velocity cap" + severity: low + difficulty: med + kind: bug + note: "Graph nodes jump on every poll; no position preservation or velocity cap." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/691 + - number: 695 + title: "Feature request: Transparent fallback mode — indicate local storage in tool response & add strict/no-fallback option" + severity: med + difficulty: med + kind: feature + note: "Signal local-fallback writes in the tool response and add a strict no-fallback mode." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/695 + - number: 700 + title: "iii-engine state_store.db pollutes user's data/ directory — should use hidden path" + severity: med + difficulty: low + kind: bug + note: "Engine state_store.db lands in the user project's data/ directory." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/700 + - number: 706 + title: "Native audit: Zed auto-loads via Cline / AGENTS.md fallback" + severity: low + difficulty: med + kind: feature + note: "Use Zed's richer auto-load surface instead of MCP-only wiring." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/706 + - number: 708 + title: "Tracking: native-surface audit for the 5 agents added in PR #677 (skills/prompts/rules, not just MCP)" + severity: low + difficulty: med + kind: chore + note: "Tracking issue for native-surface audits of the five agents from PR 677." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/708 + - number: 712 + title: "iii-console install - Illegal option -o pipefail" + severity: med + difficulty: low + kind: bug + note: "iii-console installer uses set -o pipefail under dash on Ubuntu." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/712 + - number: 713 + title: "Bug: Local embedding fails with \"fetch failed\" despite model already downloaded" + severity: med + difficulty: med + kind: bug + note: "Local embedding fails with fetch failed although the model is already downloaded." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/713 + - number: 714 + title: "Any plans for OpenClaw plugin with hook-based auto-capture?" + severity: med + difficulty: med + kind: feature + note: "OpenClaw plugin with hook-based auto-capture, not just MCP tools." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/714 + - number: 715 + title: "Bug: `crypto.randomUUID()` breaks on Node.js < 19" + severity: low + difficulty: low + kind: bug + note: "crypto.randomUUID unavailable on Node 16; below the supported floor." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/715 + - number: 716 + title: "Resolve project identity from canonical repo URL, not directory basename" + severity: med + difficulty: med + kind: feature + note: "Resolve project identity from the canonical repo URL rather than the directory basename." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/716 + fix_prs: [717] + - number: 720 + title: "Token input cache rate dropped ~10pp due to per-turn system prompt mutation" + severity: med + difficulty: med + kind: bug + note: "Per-turn system prompt mutation drops the prompt cache hit rate ~10pp." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/720 + fix_prs: [1281] + mentioned_by_prs: [1325] + - number: 723 + title: "web端显示问题" + severity: low + difficulty: high + kind: feature + note: "Chinese localization request for the web viewer." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/723 + - number: 724 + title: "Reranker is a no-op: text-classification softmax over single-logit cross-encoder always returns 1.0" + severity: med + difficulty: med + kind: bug + note: "Reranker is a silent no-op: softmax over a single logit always scores 1.0." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/724 + - number: 725 + title: "local embedding provider hardcodes English-only model — make it configurable (multilingual default)" + severity: med + difficulty: low + kind: bug + note: "Local embedding provider hardcodes an English-only model, crippling non-English recall." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/725 + mentioned_by_prs: [943] + - number: 728 + title: "Hook resolveProject() is not worktree-aware: each git worktree becomes a separate memory silo" + severity: med + difficulty: low + kind: bug + note: "Hook resolveProject is not worktree-aware, so each worktree is its own memory silo." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/728 + - number: 730 + title: "feat: add Nix flake support for one-command installation" + severity: low + difficulty: med + kind: feature + note: "Nix flake for one-command installation." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/730 + fix_prs: [740] + - number: 732 + title: "feat(context): inject semantic + procedural + crystals + insights into mem::context (dark memory gap)" + severity: med + difficulty: med + kind: feature + note: "Inject semantic, procedural, crystals and insights into mem::context." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/732 + - number: 733 + title: "Project identity uses git-toplevel basename — collides across same-named repos, no remote-based identity" + severity: med + difficulty: med + kind: bug + note: "git-toplevel basename project identity collides across same-named repos." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/733 + fix_prs: [738] + - number: 736 + title: "feat(import): support Hermes Agent JSONL format in import-jsonl" + severity: low + difficulty: med + kind: feature + note: "Support the Hermes Agent JSONL schema in import-jsonl." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/736 + - number: 737 + title: "feat(recovery): abandoned session detection and backfill for abruptly terminated sessions" + severity: med + difficulty: med + kind: feature + note: "Detect and backfill sessions that terminated without a SessionEnd hook." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/737 + - number: 739 + title: "The memories endpoint `GET /agentmemory/memories` returns entries with an `id` field, so the data model already supports individual records." + severity: med + difficulty: low + kind: feature + note: "DELETE endpoint for individual memories by id." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/739 + - number: 745 + title: "`stop` hook prematurely calls `/agentmemory/session/end`, causing sessions to be marked as ended before user actually exits" + severity: med + difficulty: low + kind: bug + note: "stop hook ends the session on every assistant pause, marking live sessions completed." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/745 + fix_prs: [1288] + - number: 747 + title: "Same title consolidation produces duplicate and orphaned memories" + severity: med + difficulty: low + kind: bug + note: "Consolidation ignores memories created in the same run, producing duplicates and orphans." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/747 + - number: 751 + title: "memory_save accepts `project` parameter but iii engine serialization drops it — `memory-project-coverage` diagnose perpetually fails" + severity: high + difficulty: med + kind: bug + note: "Engine serialization drops Memory.project, so project coverage can never pass." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/751 + mentioned_by_prs: [1195] + - number: 754 + title: "Viewer: surface per-tier gate reasons when consolidation tabs are empty" + severity: low + difficulty: med + kind: feature + note: "Surface per-tier consolidation gate reasons instead of empty viewer tabs." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/754 + - number: 765 + title: "feat(consolidation): deterministic LLM extraction cache with prompt-SHA + model-snapshot keying" + severity: med + difficulty: high + kind: feature + note: "Deterministic LLM extraction cache keyed by prompt SHA and model snapshot." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/765 + - number: 766 + title: "feat(audit): consolidation/extract failures as first-class audit events with retry-with-backoff" + severity: med + difficulty: med + kind: feature + note: "Consolidation/extract failures as first-class audit events with backoff retry." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/766 + - number: 767 + title: "feat(budget): per-session token cap with soft warn + hard block" + severity: med + difficulty: med + kind: feature + note: "Per-session token cap with soft warn and hard block." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/767 + fix_prs: [934] + - number: 768 + title: "feat(graph): state trigger auto-stales targets on supersedes/contradicts/extends edges" + severity: low + difficulty: med + kind: feature + note: "State trigger that stales supersede/contradict targets automatically." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/768 + - number: 769 + title: "feat(bench): LongMemEval-S harness with statistical rigor + CI gate" + severity: med + difficulty: high + kind: feature + note: "LongMemEval-S retrieval benchmark harness with a CI gate." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/769 + - number: 770 + title: "feat(smart-search): index semantic facts, procedural skills, crystals, insights, facets" + severity: med + difficulty: med + kind: feature + note: "Index semantic, procedural, crystals, insights and facets in smart-search." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/770 + fix_prs: [784] + - number: 787 + title: "Project scoping not honored by MCP search tools (memory_smart_search / memory_recall) or /smart-search" + severity: high + difficulty: low + kind: bug + note: "MCP search tools and /smart-search ignore project, so reads are unscoped." + disposition: candidate + status: "present-here — mem::search accepts project (src/functions/search.ts:514) and mem::smart-search accepts it too (src/functions/smart-search.ts:88), but neither MCP handler forwards args.project — memory_recall sends only query/limit/format/token_budget/agentId (src/mcp/server.ts:145) and memory_smart_search only query/expandIds/limit (src/mcp/server.ts:346). Every MCP read is cross-project." + url: https://github.com/rohitg00/agentmemory/issues/787 + fix_prs: [869] + mentioned_by_prs: [1195] + - number: 790 + title: "Rebuild agent-memory.dev as a technical showcase" + severity: low + difficulty: high + kind: feature + note: "Rebuild agent-memory.dev as a technical showcase." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/790 + - number: 808 + title: "OpenRouter reasoning models need provider-specific reasoning request/response support" + severity: med + difficulty: med + kind: feature + note: "OpenRouter reasoning models need provider-specific request and response handling." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/808 + fix_prs: [810] + - number: 809 + title: "OpenRouterEmbeddingProvider hardcodes 1536 dimensions, breaking non-1536 embedding models" + severity: med + difficulty: low + kind: bug + note: "OpenRouterEmbeddingProvider hardcodes 1536 dimensions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/809 + fix_prs: [811, 856] + - number: 817 + title: "AGENT_ID isolated scope not enforced on mem::search (REST /search, memory_recall, recall_context) → cross-agent memory leak" + severity: high + difficulty: low + kind: bug + note: "mem::search applies no agent-scope filter, leaking memory across isolated agents." + disposition: already-fixed + fixed_by: "mem::search enforces agent scope; the code cites this issue (src/mcp/server.ts:137)." + url: https://github.com/rohitg00/agentmemory/issues/817 + fix_prs: [821] + mentioned_by_prs: [1201] + - number: 819 + title: "memory_smart_search returns results from all layers flat — no way to search only memory_save entries (L2)" + severity: med + difficulty: med + kind: feature + note: "No way to search only memory_save entries; observation noise buries L2." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/819 + - number: 820 + title: "memory_governance_delete returns deleted:0 for memory_save entries" + severity: med + difficulty: med + kind: bug + note: "memory_governance_delete returns deleted:0 for valid memory_save ids." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/820 + - number: 825 + title: "Bug: no path to rebuild or reset a >25K legacy graph — snapshot-rebuild + graph-reset both heartbeat-crash on state::list (follow-up to #816)" + severity: high + difficulty: high + kind: bug + note: "No path to rebuild or reset a >25K legacy graph; both paths heartbeat-crash." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/825 + - number: 826 + title: "feat: Expose post-tool-use and TaskCompleted hooks to Python plugin (Hermes integration)" + severity: med + difficulty: med + kind: feature + note: "Expose post-tool-use and TaskCompleted hooks to the Python/Hermes plugin." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/826 + - number: 828 + title: "Bug: entity-graph query/traversal (graph-query query + startNodeId) heartbeat-crashes past ~25K nodes on FRESH corpora — needs the per-node edge index #816 references" + severity: high + difficulty: high + kind: bug + note: "graph-query traversal enumerates the full graph and crashes past ~25K nodes." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/828 + fix_prs: [893] + - number: 833 + title: "/agentmemory:forget deletes nothing — memory_governance_delete only targets the memories store, not observations (reports success: true)" + severity: high + difficulty: med + kind: bug + note: "forget reports success while deleting nothing; governance delete never targets observations." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/833 + - number: 834 + title: "on_memory_write hook: smarter sync — skip add/update, archive on remove" + severity: low + difficulty: low + kind: feature + note: "Smarter on_memory_write sync: skip add/update, archive on remove." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/834 + fix_prs: [864] + - number: 843 + title: "All data lost on restart — stop order kills iii engine before worker can flush" + severity: high + difficulty: med + kind: bug + note: "Stop order kills the engine before the worker flushes; all data lost on restart." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/843 + mentioned_by_prs: [1268] + - number: 850 + title: "[Feature] Memory validation layer to detect poisoned/injected memories" + severity: med + difficulty: high + kind: feature + note: "Validation layer to detect poisoned or injected memories." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/850 + - number: 863 + title: "OPENAI_EMBEDDING_API_KEY" + severity: med + difficulty: low + kind: bug + note: "OPENAI_EMBEDDING_API_KEY ignored when OPENAI_API_KEY is also set." + disposition: already-fixed + fixed_by: "OPENAI_EMBEDDING_API_KEY takes precedence (src/providers/embedding/openai.ts:61)." + url: https://github.com/rohitg00/agentmemory/issues/863 + mentioned_by_prs: [943] + - number: 866 + title: "fix: MCP proxy CALL_TIMEOUT_MS hardcoded at 15 s causes memory_consolidate / memory_reflect to abort on large stores" + severity: med + difficulty: low + kind: bug + note: "MCP proxy CALL_TIMEOUT_MS hardcoded at 15s aborts consolidate and reflect." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/866 + fix_prs: [867] + - number: 871 + title: "Use ~/.local/bin per XDG Base Directory Specification instead of ~/.agentmemory/bin" + severity: low + difficulty: low + kind: chore + note: "Install iii to ~/.local/bin per XDG instead of ~/.agentmemory/bin." + disposition: wont-fix + wont_fix_reason: "npm distribution — nothing is published from this fork" + url: https://github.com/rohitg00/agentmemory/issues/871 + - number: 873 + title: "Agent picker: selected `OpenCode` becomes `Claude Code`" + severity: med + difficulty: low + kind: bug + note: "Agent picker selection of OpenCode resolves to Claude Code." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/873 + - number: 874 + title: "doctor: \"iii-on-path-not-local-bin\" and fixes is a no-op -- install succeeds but check still finds other binary first" + severity: med + difficulty: low + kind: bug + note: "doctor fix for iii-on-path-not-local-bin never satisfies its own check." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/874 + fix_prs: [895] + - number: 875 + title: "engine-version-mismatch fix doesn't update PATH — iii-on-path-not-local-bin still fails after install" + severity: med + difficulty: low + kind: bug + note: "engine-version-mismatch fix does not update PATH, so doctor loops." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/875 + fix_prs: [895] + - number: 876 + title: "Lost all data after restart" + severity: high + difficulty: med + kind: bug + note: "All memories lost after a laptop restart; same class as 843." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/876 + - number: 880 + title: "Add Log Time" + severity: low + difficulty: low + kind: feature + note: "Show timestamps in the viewer log panel." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/880 + - number: 881 + title: "LocalEmbeddingProvider should respect EMBEDDING_MODEL env var for non-English embeddings" + severity: med + difficulty: low + kind: bug + note: "LocalEmbeddingProvider ignores EMBEDDING_MODEL, blocking multilingual embeddings." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/881 + fix_prs: [943] + - number: 884 + title: "MCP tool descriptions lack 'when to use' guidance — LLM struggles to choose the right tool among 53" + severity: med + difficulty: med + kind: feature + note: "Tool descriptions say what, not when, so the model picks wrong among 53." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/884 + fix_prs: [904] + - number: 888 + title: "MCP call path for slot tools returns opaque \"Internal error\" when AGENTMEMORY_SLOTS is not enabled (v0.9.27)" + severity: low + difficulty: low + kind: bug + note: "Slot tools return opaque Internal error when AGENTMEMORY_SLOTS is off." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/888 + fix_prs: [894] + - number: 889 + title: "memory_smart_search `expandIds` is a silent no-op: standalone MCP shim drops the param, and the engine cannot expand the `mem_…` IDs smart-search returns" + severity: med + difficulty: med + kind: bug + note: "expandIds is a no-op end to end: shim drops it and the engine cannot expand mem_ ids." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/889 + fix_prs: [1230] + - number: 890 + title: "mesh/export has no pagination — backlogs past the worker WS message limit fail forever with \"Invocation stopped\", making mesh sync unrecoverable after an outage" + severity: high + difficulty: med + kind: bug + note: "mesh/export has no pagination, so sync can never catch up after a long outage." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/890 + mentioned_by_prs: [1143] + - number: 899 + title: "feat: allow a cheaper model for compression than for summarization" + severity: med + difficulty: low + kind: feature + note: "Allow a cheaper model for compression than for summarization." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/899 + fix_prs: [900] + - number: 902 + title: "Compressed output shouldn't be locked to English: add language option to eliminate the semantic gap between query and memory" + severity: med + difficulty: low + kind: bug + note: "Compression prompt is hardcoded English, creating a query/memory semantic gap." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/902 + - number: 905 + title: "Example request: AIML API with OpenAI-compatible agent memory workflows" + severity: low + difficulty: low + kind: promo + note: "Vendor asking for an AIML API docs example." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/905 + - number: 906 + title: "Viewer stuck on \"Loading actions...\" when any action has tags as a string instead of an array" + severity: med + difficulty: low + kind: bug + note: "Viewer Actions tab hangs forever if any action has tags as a string." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/906 + - number: 907 + title: "Request to add available APIs for batch session deletion and graph cleanup" + severity: med + difficulty: med + kind: feature + note: "Batch session deletion and graph cleanup APIs." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/907 + - number: 908 + title: "Claude Code can't connect to agentmemory's mcp server anymore" + severity: med + difficulty: med + kind: bug + note: "Claude Code can no longer connect to the MCP server on 0.9.27." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/908 + - number: 909 + title: "agentmemory hangs ~90s on shutdown (systemd black screen) — iii-sdk telemetry shutdown never resolves" + severity: med + difficulty: med + kind: bug + note: "SIGTERM handler never resolves, hanging OS shutdown ~90s under systemd." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/909 + fix_prs: [910] + - number: 911 + title: "remember skill stores user secrets verbatim — W007 insecure credential handling" + severity: high + difficulty: med + kind: bug + note: "remember skill preserves exact phrasing, storing user secrets verbatim (Snyk W007)." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/911 + mentioned_by_prs: [941] + - number: 912 + title: "OpenCode not listed as supported agent in `connect` command" + severity: med + difficulty: low + kind: bug + note: "connect opencode fails with Unknown agent despite appearing in the picker." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/912 + - number: 913 + title: "Windows: engine state store silently falls back to in-memory (total data loss on restart) — relative `./data/` path + detached spawn without `cwd`" + severity: high + difficulty: med + kind: bug + note: "Windows scheduled-task CWD makes the engine run in-memory; total data loss per restart." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/913 + - number: 915 + title: "\"/recall\" slash command fails: HTTP 404 on memory_lesson_recall endpoint" + severity: med + difficulty: low + kind: bug + note: "/recall calls memory_lesson_recall, which has no server endpoint (404)." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/915 + - number: 918 + title: "GET /agentmemory/memories ignores the `project` query param — returns all projects" + severity: med + difficulty: low + kind: bug + note: "GET /agentmemory/memories ignores the project query param." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/918 + fix_prs: [988] + - number: 919 + title: "feat: add LLM_PROVIDER env var to explicitly select primary provider (bypass hardcoded detection order)" + severity: med + difficulty: low + kind: feature + note: "LLM_PROVIDER env var to bypass hardcoded provider detection order." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/919 + - number: 921 + title: "Viewer dashboard flickers under active sessions - per-event full reload blanks the panel" + severity: low + difficulty: med + kind: bug + note: "Per-event full reload blanks the dashboard, causing flicker under active sessions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/921 + - number: 924 + title: "[BUG] `import-jsonl` utility fails silently on historical data due to Claude Code cleanupPeriodDays conflict" + severity: low + difficulty: low + kind: docs + note: "import-jsonl finds nothing because Claude Code purges transcripts after cleanupPeriodDays." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/924 + - number: 925 + title: "graph search silently drops all results due to hardcoded `sessionId: \"\"`" + severity: high + difficulty: low + kind: bug + note: "Graph retrieval hardcodes sessionId:\"\", discarding every traversal result." + disposition: already-fixed + fixed_by: "GraphRetrieval.resolveSessionIds verifies each hit's owning session and falls back to a scan on a miss (src/functions/graph-retrieval.ts:72-126). No hardcoded sessionId; the only \"\" in the tree is src/replay/timeline.ts:107." + url: https://github.com/rohitg00/agentmemory/issues/925 + fix_prs: [937] + - number: 926 + title: "memory_save & memory_recall silently drop the `project` parameter (MCP server)" + severity: high + difficulty: low + kind: bug + note: "MCP memory_save and memory_recall silently drop project; memories saved unscoped forever." + disposition: already-fixed + fixed_by: "memory_save exposes project and agentId (src/mcp/tools-registry.ts:78-86)." + url: https://github.com/rohitg00/agentmemory/issues/926 + fix_prs: [1195] + - number: 931 + title: "Local embedding provider (@xenova/transformers) not detected in v0.9.27 — smart-search returns 0 semantic hits" + severity: med + difficulty: med + kind: bug + note: "Local embedding provider never activates in 0.9.27; smart-search silently BM25-only." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/931 + fix_prs: [1284] + mentioned_by_prs: [1283] + - number: 938 + title: "import \"replace\" wipes KV but leaves search indices stale" + severity: high + difficulty: med + kind: bug + note: "Replace-import wipes KV but leaves the search indices stale until restart." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/938 + - number: 944 + title: "[viewer] Agentmemory Token Savings always 0% — estInjected counts all sessions, not just active" + severity: low + difficulty: low + kind: bug + note: "Token Savings always 0% because estInjected counts all sessions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/944 + - number: 945 + title: "Missing lesson_delete tool — no way to delete/cleanup lessons via MCP or REST API" + severity: med + difficulty: med + kind: feature + note: "No lesson_delete tool or REST endpoint anywhere." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/945 + - number: 948 + title: "Add option to include low-score results in semantic search" + severity: low + difficulty: low + kind: feature + note: "Option to include low-score semantic results rather than returning nothing." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/948 + - number: 950 + title: "[BUG] Docker: iii-engine uses in_memory despite file_based config in /app/config.yaml" + severity: high + difficulty: med + kind: bug + note: "Docker engine uses in_memory despite a mounted file_based config." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/950 + - number: 951 + title: "Dashboard MEMORIES tile counts only memory_save facts, not the semantic/summary corpus (reads \"1\" on a healthy install)" + severity: low + difficulty: low + kind: bug + note: "Dashboard MEMORIES tile counts only memory_save facts, reading 1 on a healthy install." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/951 + fix_prs: [973] + - number: 952 + title: "agentmemory connect zed overwrites existing Zed settings.json instead of merging context_servers" + severity: high + difficulty: low + kind: bug + note: "connect zed overwrites the user's entire settings.json instead of merging." + disposition: already-fixed + fixed_by: "connect zed merges into context_servers (src/cli/connect/zed.ts:18)." + url: https://github.com/rohitg00/agentmemory/issues/952 + fix_prs: [966] + - number: 964 + title: "Local iii engine grows to ~3.7GB RSS with file_based storage and contributes to desktop OOMs" + severity: high + difficulty: high + kind: bug + note: "Engine grows to ~3.7GB RSS with file_based storage and contributes to desktop OOMs." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/964 + - number: 965 + title: "CEM Tree Memory: Branch-classified retrieval on BEAM (78%) and MABench (77.4% F1)" + severity: low + difficulty: high + kind: promo + note: "Vendor benchmark pitch for a tree-memory architecture." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/965 + - number: 969 + title: "import-jsonl (and live capture) hangs indefinitely on observations containing multibyte/CJK text" + severity: high + difficulty: med + kind: bug + note: "Observations containing CJK text hang import and live ingestion indefinitely." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/969 + - number: 972 + title: "Add an optional HVTracker trust badge to the README" + severity: low + difficulty: low + kind: promo + note: "Request to add a third-party trust badge to the README." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/972 + - number: 977 + title: "Feature Request: Publish Official Docker Images to Docker Hub" + severity: med + difficulty: med + kind: feature + note: "Publish official prebuilt Docker images." + disposition: wont-fix + wont_fix_reason: "Docker / PaaS / Kubernetes deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/issues/977 + fix_prs: [1354] + - number: 978 + title: "Batch/throttle graph extraction instead of triggering an LLM call on every Stop hook" + severity: med + difficulty: med + kind: bug + note: "Graph extraction fires an LLM call on every Stop hook rather than at real session end." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/978 + fix_prs: [1280] + - number: 979 + title: "Feature Request: Separate API configuration for LLM and embedding providers" + severity: med + difficulty: low + kind: feature + note: "Separate API key and base URL for LLM versus embedding providers." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/979 + - number: 981 + title: "Add first-class workspace namespace isolation" + severity: med + difficulty: high + kind: feature + note: "First-class workspace namespace isolation above project scope." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/981 + fix_prs: [982] + - number: 985 + title: "Feature Request: batch mode for background LLM routines via Anthropic Message Batches API" + severity: low + difficulty: high + kind: feature + note: "Use the Anthropic Message Batches API for background routines." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/985 + - number: 986 + title: "Feature Request: plain self-hosted Docker deploy template (no PaaS control plane)" + severity: low + difficulty: med + kind: feature + note: "Plain self-hosted Docker deploy template with no PaaS control plane." + disposition: wont-fix + wont_fix_reason: "Docker / PaaS / Kubernetes deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/issues/986 + fix_prs: [976] + - number: 987 + title: "fix: opencode plugin projectPath falls back to hash ID instead of filesystem path" + severity: med + difficulty: low + kind: bug + note: "opencode plugin falls back to a hash project id when ctx.worktree is null." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/987 + - number: 990 + title: "GET /agentmemory/memories?latest=true returns oldest memories first — viewer shows stale data when corpus > limit" + severity: med + difficulty: low + kind: bug + note: "memories?latest=true returns the oldest rows, so the viewer shows stale data." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/990 + - number: 991 + title: "SessionEnd hook reports \"Hook cancelled\" on exit (1.5s deferred exit outlives shutdown grace)" + severity: low + difficulty: low + kind: bug + note: "SessionEnd's 1.5s deferred exit outlives the shutdown grace, reporting Hook cancelled." + disposition: already-fixed + fixed_by: "Telemetry hooks use the documented fetch-and-unref'd-setTimeout exit pattern." + url: https://github.com/rohitg00/agentmemory/issues/991 + - number: 993 + title: "post-tool-use captures agentmemory MCP calls as observations, polluting recall results" + severity: med + difficulty: low + kind: bug + note: "post-tool-use records agentmemory's own MCP calls, polluting recall." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/993 + fix_prs: [994, 1044] + - number: 996 + title: "Zero-LLM mode: mem::summarize no-op skip (no_provider) inflates failureCount with false failures" + severity: low + difficulty: low + kind: bug + note: "Zero-LLM summarize no-op skips are recorded as failures, inflating failureCount." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/996 + - number: 998 + title: "Codex-visible hook skill should distinguish Codex hooks from Claude Code hooks" + severity: low + difficulty: low + kind: docs + note: "Hook skill wording misleads Codex users about which hooks exist." + disposition: wont-fix + wont_fix_reason: "unsupported host — Codex and Cursor are not supported here" + url: https://github.com/rohitg00/agentmemory/issues/998 + - number: 1003 + title: "Graph extraction always 404s: requests retired model `claude-3-haiku-20240307`, ignores ANTHROPIC_MODEL" + severity: high + difficulty: low + kind: bug + note: "Graph extraction requests the retired claude-3-haiku-20240307 and 404s, ignoring ANTHROPIC_MODEL." + disposition: already-fixed + fixed_by: "claude-3-haiku-20240307 appears nowhere in src/." + url: https://github.com/rohitg00/agentmemory/issues/1003 + - number: 1007 + title: "Feature request: auto-restore from latest snapshot on daemon startup" + severity: med + difficulty: med + kind: feature + note: "Auto-restore from the latest snapshot on daemon startup." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1007 + - number: 1008 + title: "POST /agentmemory/consolidate returns 500 with unhandled \"[object Object]\" error" + severity: med + difficulty: low + kind: bug + note: "POST /agentmemory/consolidate 500s with an unhandled [object Object] error." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1008 + fix_prs: [1041] + - number: 1009 + title: "Feature request: asymmetric embedding support (query_param / document_param for OpenAI-compatible endpoints)" + severity: med + difficulty: med + kind: feature + note: "Asymmetric query/document embedding parameters for OpenAI-compatible endpoints." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1009 + - number: 1013 + title: "All HTTP REST endpoints return 404 after iii-engine WebSocket reconnection (iii-engine #1796) — v0.19.2 only a partial fix, holds in v0.22.x" + severity: high + difficulty: high + kind: bug + note: "All REST endpoints 404 after an engine WebSocket reconnect; the process stays alive." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1013 + - number: 1015 + title: "Post-restart diagnostic: search can't find 646 backfill obs; vector/graph/rerank unverified" + severity: med + difficulty: high + kind: report + note: "Post-restart diagnostic: 646 backfill observations unfindable, vector/graph/rerank unverified." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1015 + - number: 1018 + title: "Feature request: Add memory_update Tool for Memory Versioning" + severity: med + difficulty: med + kind: feature + note: "memory_update tool for versioning instead of duplicate v1 memories." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1018 + fix_prs: [1038] + - number: 1020 + title: "Zero-LLM noop provider never matches the `mem::summarize` short-circuit because `ResilientProvider` renames it to `resilient(noop)` — summaries fail as `empty_provider_response` / `too_many_chunks_skipped` instead of a clean skip" + severity: med + difficulty: low + kind: bug + note: "ResilientProvider renames noop, so the summarize short-circuit can never fire." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1020 + fix_prs: [1040] + - number: 1022 + title: "GET /agentmemory/sessions ignores the limit query param, always returns full history" + severity: high + difficulty: low + kind: bug + note: "GET /agentmemory/sessions ignores limit and returned 5.38M characters into the caller's context." + disposition: candidate + status: "present-here — api::sessions reads no limit query param (src/triggers/api.ts:849-887): it lists every session, fetches every summary in batches of 10, and returns the lot. The standalone MCP client does send ?limit= (src/mcp/standalone.ts:230) — the server ignores it." + url: https://github.com/rohitg00/agentmemory/issues/1022 + mentioned_by_prs: [1034, 1352] + - number: 1024 + title: "Backfill corpus quality: 6c727be fix landed but LLM drain stalled, 33% LLM-compressed after 11h" + severity: med + difficulty: high + kind: report + note: "Backfill corpus quality fix landed but the LLM drain stalled at 33% coverage." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1024 + - number: 1025 + title: "[Cat B] Follow-up: 1867 obs stuck synthetic, drain throughput dropped 16x" + severity: med + difficulty: high + kind: report + note: "Follow-up: 1867 observations stuck synthetic, drain throughput down 16x." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1025 + - number: 1026 + title: "[Cat A] Defer: b61469b dead code + stale inline eval scripts" + severity: low + difficulty: low + kind: chore + note: "Dead code and stale inline eval scripts from a failed experiment." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1026 + mentioned_by_prs: [1083] + - number: 1027 + title: "[Cat C] Closed: corpus-quality goal achieved (R@10=100% on best queries)" + severity: low + difficulty: low + kind: report + note: "Informational: corpus-quality goal met, R@10 ~100% on best queries." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1027 + - number: 1029 + title: "2026-07-08: agentmemory restart left LLM drain stalled (6 unresolved problems)" + severity: med + difficulty: high + kind: report + note: "Six unresolved problems observed while restarting the daemon and resuming the drain." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1029 + - number: 1030 + title: "upgrade-backfill-compression.py progress.json drift: 207 obs marked done but missing compressionKind" + severity: low + difficulty: med + kind: bug + note: "Backfill progress.json says 1588 done but 207 have no compressionKind." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1030 + - number: 1031 + title: "\"agentmemory connect antigravity\" cannot detect Antigravity CLI (agy) v1.1.0" + severity: med + difficulty: low + kind: bug + note: "connect antigravity cannot detect the agy CLI v1.1.0 on PATH." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1031 + - number: 1035 + title: "pi: extension throws stale ctx after await getHealth() in refreshStatus" + severity: med + difficulty: low + kind: bug + note: "pi extension throws on stale ctx after awaiting getHealth in refreshStatus." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1035 + fix_prs: [1036] + - number: 1047 + title: "PostToolUse (and other) hooks crash with exit code 1 when payload JSON is null (unguarded data.xxx access)" + severity: med + difficulty: low + kind: bug + note: "Hooks crash with exit 1 when the payload JSON is literal null (unguarded data access)." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1047 + - number: 1048 + title: "feat: add support for gemini-embedding-2 and make Gemini embedding model configurable" + severity: low + difficulty: low + kind: feature + note: "Support gemini-embedding-2 and make the Gemini embedding model configurable." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1048 + - number: 1054 + title: "Agentmemory dashboard doesn't reflect renamed Codex sessions (Windows)" + severity: low + difficulty: med + kind: bug + note: "Dashboard does not reflect sessions renamed in Codex on Windows." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/1054 + - number: 1058 + title: "OpenClaw plugin: agent_end observe broken (missing project/cwd, raw-path project, zombie active sessions)" + severity: high + difficulty: med + kind: bug + note: "OpenClaw agent_end omits project/cwd, so turns are never persisted and sessions stay active." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1058 + mentioned_by_prs: [1252] + - number: 1059 + title: "backfill observation.concepts during graph-extract to unblock legacy consolidate under AUTO_COMPRESS=false" + severity: med + difficulty: med + kind: bug + note: "Synthetic compression hardcodes empty concepts, so legacy consolidate never groups." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1059 + - number: 1060 + title: "AGENTMEMORY_TOOLS=core in ~/.agentmemory/.env is ignored (getVisibleTools reads process.env directly)" + severity: med + difficulty: low + kind: bug + note: "getVisibleTools reads process.env directly, ignoring ~/.agentmemory/.env." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1060 + - number: 1062 + title: "Session stop triggers mem::summarize twice; unchanged sessions are fully re-summarized on every stop" + severity: high + difficulty: low + kind: bug + note: "Session stop dispatches mem::summarize twice, each re-summarizing from scratch." + disposition: candidate + status: "partly-present-here — The double dispatch is fixed: the Stop hook posts only /session/end and cites this class of bug (src/hooks/stop.ts:43). The re-summarize half is live — mem::summarize never reads KV.summaries before running (src/functions/summarize.ts:235-360), so every stop is a full LLM pass over every compressed observation." + url: https://github.com/rohitg00/agentmemory/issues/1062 + fix_prs: [1061] + - number: 1063 + title: "Session stop re-runs graph extraction over the full observation set even when nothing changed" + severity: med + difficulty: low + kind: bug + note: "Session stop re-extracts the full observation set with no change detection." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1063 + fix_prs: [1061, 1280] + - number: 1064 + title: "Phantom sessions: hooks + import-jsonl ingest Claude Code's machine-generated summarizer/Warmup transcripts as real sessions" + severity: med + difficulty: low + kind: bug + note: "Claude Code summarizer and Warmup transcripts ingested as real phantom sessions." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1064 + - number: 1065 + title: "lesson-recall default minConfidence (0.1) + decay + auto-prune make most auto-consolidated lessons invisible, with no config override" + severity: high + difficulty: low + kind: bug + note: "Default minConfidence plus decay hides 438 of 439 lessons from recall, with no override." + disposition: candidate + status: "present-here — mem::lesson-recall defaults minConfidence to 0.1 and drops anything below it (src/functions/lessons.ts:159,173). The decay sweep floors confidence at 0.05 (src/functions/lessons.ts:320), so a decayed lesson lands in 0.05-0.1 and is invisible at the default. Upstream's \"no override\" is wrong — the param is exposed." + url: https://github.com/rohitg00/agentmemory/issues/1065 + - number: 1066 + title: "memory_heal claims \"fixable\": true for project-scope backfill but the heal step does nothing ({\"fixed\":0,\"skipped\":0})" + severity: med + difficulty: med + kind: bug + note: "memory_heal reports project backfill fixable but fixes nothing." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1066 + - number: 1067 + title: "connect claude-code hardcodes ~/.claude.json / ~/.claude/settings.json, ignoring CLAUDE_CONFIG_DIR" + severity: med + difficulty: low + kind: bug + note: "connect claude-code hardcodes ~/.claude, ignoring CLAUDE_CONFIG_DIR; reports success but is inert." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1067 + - number: 1069 + title: "bug: session-end hook causes 'Hook cancelled' due to .unref() making setTimeout passive while fetch keeps event loop alive" + severity: low + difficulty: low + kind: bug + note: "unref'd timer does not force exit while fetch holds the loop; Hook cancelled on close." + disposition: already-fixed + fixed_by: "Same as #991." + url: https://github.com/rohitg00/agentmemory/issues/1069 + fix_prs: [1070] + - number: 1073 + title: "standalone.mjs: memory_save ignores title/tags, uses content as title — breaks keyword search" + severity: med + difficulty: low + kind: bug + note: "standalone memory_save drops title and tags and stores content as the title." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1073 + - number: 1077 + title: "import-jsonl in server-hosted mode is fundamentally confusing" + severity: low + difficulty: med + kind: docs + note: "import-jsonl path semantics are undocumented and confusing in server-hosted mode." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1077 + - number: 1080 + title: "Smart search cannot expand or consistently scope durable memories" + severity: med + difficulty: med + kind: bug + note: "expandIds only searches observations and project is inconsistently applied to durable memories." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1080 + fix_prs: [1091] + - number: 1081 + title: "Allow configurable external rerank endpoints" + severity: low + difficulty: med + kind: feature + note: "Configurable external Cohere-compatible rerank endpoint." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1081 + fix_prs: [1090] + - number: 1086 + title: "oh-my-pi (omp) support" + severity: low + difficulty: med + kind: feature + note: "Support for the oh-my-pi agent." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1086 + fix_prs: [1099] + - number: 1092 + title: "Memory dashboard truncates long content and entries cannot be opened" + severity: low + difficulty: low + kind: bug + note: "Dashboard truncates long memory content with no way to expand the entry." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1092 + - number: 1093 + title: "Idle CPU leak: `iii` worker threads busy-wait, growing to a full core over ~40h uptime" + severity: high + difficulty: high + kind: bug + note: "Worker threads busy-wait to a full core over ~40h uptime." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1093 + - number: 1094 + title: "`infer-memory-projects` permanently unfixable after a project directory move — path-keyed project identity marks every memory ambiguous" + severity: med + difficulty: med + kind: bug + note: "Path-keyed project identity makes infer-memory-projects permanently ambiguous after a directory move." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1094 + - number: 1097 + title: "Droid: MCP tools force approval at every autonomy level — no risk annotations" + severity: med + difficulty: low + kind: feature + note: "Droid MCP tools lack risk annotations, forcing approval at every autonomy level." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1097 + fix_prs: [1098] + - number: 1103 + title: "import-jsonl (and claude-bridge MEMORY.md path) also hardcode ~/.claude, ignoring CLAUDE_CONFIG_DIR" + severity: med + difficulty: low + kind: bug + note: "import-jsonl and the claude-bridge MEMORY.md path also ignore CLAUDE_CONFIG_DIR." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1103 + - number: 1104 + title: "Community Windows + Codex Desktop plugin (auto-start, MCP, hooks, self-healing troubleshooting skill)" + severity: med + difficulty: high + kind: feature + note: "Community Windows + Codex Desktop plugin with autostart, MCP, hooks and a troubleshooting skill." + disposition: wont-fix + wont_fix_reason: "unsupported host — Codex and Cursor are not supported here" + url: https://github.com/rohitg00/agentmemory/issues/1104 + - number: 1105 + title: "memory_action_create MCP tool drops createdBy, unlike lease/frontier tools which correctly pass agentId" + severity: low + difficulty: low + kind: bug + note: "memory_action_create never forwards createdBy, so every action is created by unknown." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1105 + fix_prs: [1107] + - number: 1106 + title: "AGENTMEMORY_TOOLS env var in ~/.agentmemory/.env is ignored — MCP server always exposes all tools" + severity: med + difficulty: low + kind: bug + note: "AGENTMEMORY_TOOLS in ~/.agentmemory/.env ignored; duplicate of 1060." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1106 + - number: 1108 + title: "\"project\"-scoped memory slots (project_context, pending_items, self_notes, session_patterns) are actually global, not per-project" + severity: high + difficulty: med + kind: bug + note: "project-scoped memory slots share one flat namespace, so they are global in practice." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1108 + fix_prs: [1337] + - number: 1114 + title: "Session summary chunk merge: `concepts` duplicated across chunks, and silently emitted empty when chunks fail" + severity: med + difficulty: low + kind: bug + note: "Summary concepts are concatenated without dedupe and silently emitted empty when chunks fail." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1114 + - number: 1115 + title: "Orphaned index generations accumulate when the previous manifest read fails — store grows until the server pegs a core while idle" + severity: high + difficulty: med + kind: bug + note: "Orphaned index generations accumulate when the manifest read fails; the store grows until a core pegs." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1115 + fix_prs: [1256, 1282] + - number: 1116 + title: "Viewer stores bearer token in sessionStorage — users must re-enter on every new tab" + severity: low + difficulty: low + kind: bug + note: "Viewer keeps the bearer token in sessionStorage, so it must be re-entered per tab." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1116 + - number: 1117 + title: "Viewer stores bearer token in sessionStorage — users must re-enter on every new tab" + severity: low + difficulty: low + kind: bug + note: "Duplicate of 1116." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1117 + - number: 1119 + title: "createEmbeddingProvider's \"openai\" case hardcodes OPENAI_API_KEY, defeating OPENAI_EMBEDDING_API_KEY fallback" + severity: med + difficulty: low + kind: bug + note: "Embedding factory passes OPENAI_API_KEY explicitly, defeating the OPENAI_EMBEDDING_API_KEY fallback." + disposition: already-fixed + fixed_by: "Same as #863." + url: https://github.com/rohitg00/agentmemory/issues/1119 + - number: 1124 + title: "mem::smart-search crashes the whole iii worker — one request unregisters all 271 functions for ~5s" + severity: high + difficulty: high + kind: bug + note: "One smart-search request unregisters all 271 functions for ~5s, taking the whole REST surface down." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1124 + - number: 1127 + title: "mem::graph-extract hangs to its own 180s invocation timeout on every batch, eventually stalling state::get and crashing the worker" + severity: high + difficulty: high + kind: bug + note: "graph-extract hangs to its 180s invocation timeout each batch, stalling state::get and crashing the worker." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1127 + fix_prs: [1128] + mentioned_by_prs: [1384] + - number: 1131 + title: "Session summarization is quadratic: the Stop hook re-summarizes the entire session every assistant turn" + severity: high + difficulty: med + kind: bug + note: "The Stop hook re-summarizes the whole session every assistant turn; cost is quadratic." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1131 + fix_prs: [1269] + - number: 1133 + title: "buildGraphClusters breaks out of the seed loop on an already-visited seed, collapsing insights into a few mega-clusters" + severity: med + difficulty: low + kind: bug + note: "buildGraphClusters breaks instead of continuing on a visited seed, collapsing insights into mega-clusters." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1133 + fix_prs: [1243, 1343] + - number: 1140 + title: "CLI `consolidate` run against a live daemon boots a second instance, then breaks the daemon REST routing (every /agentmemory/* route 404s)" + severity: high + difficulty: med + kind: bug + note: "CLI consolidate against a live daemon boots a second instance and 404s every REST route." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1140 + - number: 1142 + title: "GET /agentmemory/export drops the iii worker once the response passes 16 MiB, 404ing every endpoint" + severity: high + difficulty: med + kind: bug + note: "GET /agentmemory/export past 16 MiB drops the worker and 404s every endpoint." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1142 + mentioned_by_prs: [1143, 1233] + - number: 1148 + title: "Fix disabled slot MCP errors and Windows test portability" + severity: med + difficulty: med + kind: bug + note: "Disabled slot tools 500, diagnostics misclassify global memories, tests are not Windows-portable." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/1148 + fix_prs: [1149] + mentioned_by_prs: [1352] + - number: 1151 + title: "agentmemory stop in Docker mode signals the wrong PID — can kill Docker Desktop's backend entirely, and separately tears down unrelated compose services" + severity: high + difficulty: med + kind: bug + note: "agentmemory stop in Docker mode signals the wrong PID and can kill Docker Desktop's backend." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1151 + - number: 1153 + title: "iii-engine OOM-killed every ~61s: allocation spike scales with the container limit (0.11.2 and 0.11.5)" + severity: high + difficulty: high + kind: bug + note: "iii-engine OOM-killed on a ~61s cycle; the allocation spike scales with the container limit." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1153 + - number: 1157 + title: "Observation eviction leaves session counters and graph provenance stale" + severity: med + difficulty: med + kind: bug + note: "Eviction leaves session observationCount and graph provenance stale." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1157 + - number: 1158 + title: "Scheduled Git snapshots grow without a retention policy" + severity: med + difficulty: low + kind: feature + note: "Git snapshot repository has no age, count or size retention policy." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1158 + - number: 1159 + title: "REST shims silently drop agentId on /agentmemory/remember and /agentmemory/observe — per-request multi-agent scoping impossible over REST" + severity: high + difficulty: low + kind: bug + note: "REST shims drop agentId on remember and observe, making per-request multi-agent scoping impossible." + disposition: candidate + status: "partly-present-here — /agentmemory/remember does forward agentId (src/triggers/api.ts:1046-1048). /observe does not, but by design: mem::observe treats the session row as the source of truth and falls back to env AGENT_ID only when no row exists (src/functions/observe.ts:157-170)." + url: https://github.com/rohitg00/agentmemory/issues/1159 + fix_prs: [1202, 1272] + mentioned_by_prs: [1198, 1199, 1201] + - number: 1160 + title: "memoryToObservation() drops agentId — memories invisible to every agent-scoped search (residual hole in the #817 fix)" + severity: high + difficulty: low + kind: bug + note: "memoryToObservation drops agentId, hiding every memory from agent-scoped search." + disposition: already-fixed + fixed_by: "memoryToObservation carries agentId through, with a comment naming this exact bug (src/state/memory-utils.ts:85-88)." + url: https://github.com/rohitg00/agentmemory/issues/1160 + fix_prs: [1198] + mentioned_by_prs: [1187, 1272] + - number: 1161 + title: "integrations/openclaw: recall hook never fires on current OpenClaw (before_agent_start is not a typed plugin hook) + no agent identity threading" + severity: med + difficulty: med + kind: bug + note: "OpenClaw recall hook never fires: before_agent_start is not a typed plugin hook." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1161 + - number: 1162 + title: "Engine SDK port 49134 is inside the Linux ephemeral range — silent bind failure, infinite worker retry loop" + severity: high + difficulty: med + kind: bug + note: "Engine SDK port 49134 sits in the Linux ephemeral range; a stolen port means an infinite silent retry loop." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1162 + - number: 1163 + title: "import: observations persist but are never added to the BM25 index (invisible to smart-search)" + severity: high + difficulty: med + kind: bug + note: "Imported observations are never added to the BM25 index and have no reindex path." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1163 + mentioned_by_prs: [1187] + - number: 1165 + title: "Issues connecting to antigravity agy cli" + severity: med + difficulty: low + kind: bug + note: "connect cannot reach the antigravity agy CLI." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1165 + - number: 1166 + title: "memory_diagnose reports all checks PASS on a completely empty store — data loss is indistinguishable from a healthy store" + severity: med + difficulty: low + kind: bug + note: "memory_diagnose reports 15/15 PASS on an empty store, so data loss looks healthy." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1166 + - number: 1167 + title: "The \"backups\" feature never backs up memory — ~/.agentmemory/backups/ holds only connect config snapshots; no memory backup/restore command exists" + severity: med + difficulty: med + kind: bug + note: "~/.agentmemory/backups holds only connect config snapshots; no memory backup command exists." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1167 + - number: 1168 + title: "Unbounded sourceObservationIds / sourceMemoryIds are what push collections past the worker limit in #1142 / #1124" + severity: high + difficulty: med + kind: bug + note: "Unbounded provenance arrays are ~97% of collection bytes and are what push collections past the worker limit." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1168 + fix_prs: [1295, 1349] + mentioned_by_prs: [1233, 1353] + - number: 1169 + title: "agentmemory, analyzed by Claude and compared with other memory systems" + severity: low + difficulty: low + kind: promo + note: "Third-party analysis link and Discord invite." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1169 + - number: 1171 + title: "graph nodes: sourceObservationIds capped at creation but unbounded on merge" + severity: high + difficulty: low + kind: bug + note: "mergeNode re-unions sourceObservationIds with no cap, so provenance grows monotonically." + disposition: already-fixed + fixed_by: "mergeNode runs the union through capSourceIds (src/functions/graph.ts:432); src/functions/graph-provenance.ts caps from the tail so merges keep the newest ids." + url: https://github.com/rohitg00/agentmemory/issues/1171 + fix_prs: [1294, 1349] + mentioned_by_prs: [1353] + - number: 1173 + title: "prompt_submit observations silently dropped: dedup hash ignores prompt content (all prompts share one hash)" + severity: high + difficulty: low + kind: bug + note: "prompt_submit dedup hash reads a nonexistent field, so all prompts share a hash and only the first in 300s survives." + disposition: already-fixed + fixed_by: "The dedup hash falls back to the whole payload when tool_input is absent (src/functions/observe.ts:76-81), so prompt_submit events hash on their own prompt." + url: https://github.com/rohitg00/agentmemory/issues/1173 + - number: 1178 + title: "Test suite reads the developer's real ~/.agentmemory/.env — 14 tests fail on any machine with an install" + severity: med + difficulty: low + kind: bug + note: "Tests read the developer's real ~/.agentmemory/.env; 14 fail on any machine with an install." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1178 + - number: 1179 + title: "No way to rebuild the search index without restarting: rebuildIndex only runs when the index is empty" + severity: med + difficulty: med + kind: feature + note: "rebuildIndex only runs at boot on an empty index; no supported rebuild path." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1179 + - number: 1180 + title: "Index persistence is never scheduled after boot: everything indexed at runtime is lost unless the process exits cleanly" + severity: high + difficulty: med + kind: bug + note: "Nothing schedules an index save after boot, so runtime indexing is lost unless the process exits cleanly." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1180 + - number: 1181 + title: "mem:audit is 71% index_persist rows the audit policy does not cover" + severity: med + difficulty: low + kind: bug + note: "index_persist rows are 71% of the audit store, slowing memory_audit and every startup read." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1181 + fix_prs: [1182] + - number: 1183 + title: "[FEAT][08-12-2026] add support on these `features` that I've notice so far using `agentmemory`, if not integrated yet." + severity: med + difficulty: high + kind: feature + note: "Grab bag: Windows connect support, Antigravity variants, doctor checks." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1183 + - number: 1184 + title: "opencode plugin: auto-title generation consumes the once-per-session memory injection — main conversation never gets context" + severity: high + difficulty: low + kind: bug + note: "OpenCode auto-title generation consumes the once-per-session injection, so the real conversation gets no context." + disposition: candidate + status: "unresolved — contextInjectedSessions is keyed by session id and set on the first experimental.chat.system.transform call (plugin/opencode/agentmemory-capture.ts:665-684). No guard distinguishes a title-generation pass from the real conversation. Whether the title pass shares the session id is an OpenCode runtime question this tree cannot answer." + url: https://github.com/rohitg00/agentmemory/issues/1184 + fix_prs: [1281] + - number: 1188 + title: "OpenCode sessions inherit project/cwd from shared module state across directories" + severity: high + difficulty: low + kind: bug + note: "OpenCode plugin keeps project and cwd in module state, recording sessions under another repository." + disposition: already-fixed + fixed_by: "Attribution is per-session via sessionProjects, resolved from each session's own directory; module-level defaults are only a fallback, and the comment names this bug (plugin/opencode/agentmemory-capture.ts:66-81)." + url: https://github.com/rohitg00/agentmemory/issues/1188 + fix_prs: [1281] + - number: 1189 + title: "Bug: graph-reset leaves pre-reset rows queryable and races graph-extract" + severity: med + difficulty: med + kind: bug + note: "graph-reset leaves pre-reset rows queryable and races a concurrent graph-extract." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1189 + - number: 1190 + title: "Bug: snapshot restore is additive and omits durable stores" + severity: high + difficulty: med + kind: bug + note: "Snapshot restore is additive and omits durable stores, so it is not a recovery point." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1190 + - number: 1191 + title: "Semantic and Procedural Memory need a bounded retention path" + severity: med + difficulty: med + kind: feature + note: "Semantic and procedural memory have no bounded retention path." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1191 + - number: 1192 + title: "Audit storage needs retention and bounded queries" + severity: med + difficulty: med + kind: feature + note: "Audit storage needs retention and bounded queries." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1192 + - number: 1193 + title: "Lesson and Insight tombstones need bounded physical reclamation" + severity: med + difficulty: med + kind: feature + note: "Lesson and insight tombstones need physical reclamation." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1193 + - number: 1196 + title: "Replay loses raw prompt/tool/response content under default synthetic compression" + severity: med + difficulty: med + kind: bug + note: "Default synthetic compression caps the narrative at 400 chars, so replay loses raw content." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1196 + - number: 1197 + title: "memory_save MCP path drops agentId at three more points — schema never exposes it, and two forwarding hops drop it independently of #1159/#1160" + severity: high + difficulty: low + kind: bug + note: "memory_save drops agentId at three more MCP-path points beyond 1159 and 1160." + disposition: already-fixed + fixed_by: "Same as #926." + url: https://github.com/rohitg00/agentmemory/issues/1197 + mentioned_by_prs: [1198, 1199, 1200, 1201, 1202, 1272] + - number: 1203 + title: "mem::summarize is dispatched twice per Stop hook" + severity: high + difficulty: low + kind: bug + note: "Two concurrent mem::summarize runs per Stop hook with no lease; duplicate of 1062." + disposition: already-fixed + fixed_by: "The Stop hook makes one call — /session/end — and session/end fans the summary out server-side (src/hooks/stop.ts:43, src/triggers/events.ts:99)." + url: https://github.com/rohitg00/agentmemory/issues/1203 + mentioned_by_prs: [1269] + - number: 1204 + title: "logger writes info and warn to stderr, so log platforms tag every line as an error" + severity: low + difficulty: low + kind: bug + note: "logger sends info and warn to stderr, so log platforms tag every line an error." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1204 + - number: 1208 + title: "feat: DeepSeek Harness (dsh) integration — connect adapter + cordis plugin" + severity: low + difficulty: med + kind: feature + note: "DeepSeek Harness connect adapter plus a cordis capture plugin." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1208 + fix_prs: [1209] + - number: 1218 + title: "Cannot update" + severity: med + difficulty: low + kind: bug + note: "npx upgrade does not move to the latest version." + disposition: wont-fix + wont_fix_reason: "npm distribution — nothing is published from this fork" + url: https://github.com/rohitg00/agentmemory/issues/1218 + - number: 1219 + title: "Bug: v0.9.29 default OpenAI model (`gpt-5.6-luna`) is a reasoning model, but `OpenAIProvider` sends `max_tokens` → every `mem::compress` / `mem::summarize` 400s" + severity: high + difficulty: low + kind: bug + note: "0.9.29's default OpenAI model is a reasoning model but the provider still sends max_tokens; every compress and summarize 400s." + disposition: candidate + status: "present-here — Default model is gpt-5.6-luna (src/providers/openai.ts:12, src/config.ts:95) and the chat body always sends max_tokens (src/providers/openai.ts:82) while also sending reasoning_effort (src/providers/openai.ts:95) — the two are mutually exclusive on OpenAI's chat-completions API. Nothing maps to max_completion_tokens." + url: https://github.com/rohitg00/agentmemory/issues/1219 + fix_prs: [1275] + - number: 1221 + title: "Graph node identity is the absolute path, so git worktrees and agent scratch dirs create duplicate nodes for the same file" + severity: med + difficulty: med + kind: bug + note: "Graph file-node identity is the absolute path, duplicating nodes across worktrees." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1221 + - number: 1223 + title: "Health reports critical from heapUsed/heapTotal, so /agentmemory/health returns 503 on a healthy process" + severity: med + difficulty: low + kind: bug + note: "Health grades memory against heapTotal, so a healthy process returns 503." + disposition: already-fixed + fixed_by: "Saturation is measured against the heap ceiling (src/health/thresholds.ts:88)." + url: https://github.com/rohitg00/agentmemory/issues/1223 + fix_prs: [1285] + mentioned_by_prs: [1236, 1237] + - number: 1225 + title: "MCP tools ask the model for a project id it has no way to know" + severity: high + difficulty: med + kind: bug + note: "Every project-scoped MCP tool asks the model for a project id nothing tells it." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1225 + - number: 1226 + title: "mem::patterns walks every observation in the store — memory_patterns 500s \"Invocation stopped\" and drops the worker" + severity: high + difficulty: med + kind: bug + note: "mem::patterns loads every observation, 500s, and takes the worker with it." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1226 + - number: 1228 + title: "Unable to recompress raw observations; compression failures leave observations uncompressed with no recovery path" + severity: med + difficulty: med + kind: feature + note: "No way to recompress an observation whose LLM compression failed." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1228 + - number: 1229 + title: "Viewer renders session summary as '[object Object]' (array fields not serialized)" + severity: low + difficulty: low + kind: bug + note: "Viewer renders array-valued session summaries as [object Object]." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1229 + fix_prs: [1332] + - number: 1232 + title: "memory_recall: token_budget silently drops the highest-value records first, making explicit memories look absent" + severity: high + difficulty: low + kind: bug + note: "token_budget fills with short high-scoring observations, excluding saved memories entirely." + disposition: candidate + status: "present-here — applyTokenBudget returns at the first item that overflows instead of skipping it (src/functions/search.ts:756-773), so one oversized record truncates everything ranked below it." + url: https://github.com/rohitg00/agentmemory/issues/1232 + fix_prs: [1242] + - number: 1235 + title: "Health reports cpu_critical on multi-core hosts: CPU percent is single-core scale but thresholds assume total capacity" + severity: med + difficulty: low + kind: bug + note: "CPU percent is single-core scale but thresholds assume total capacity, so multi-core hosts report critical." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1235 + fix_prs: [1236, 1286] + mentioned_by_prs: [1237] + - number: 1238 + title: "`GRAPH_EXTRACTION_ENABLED=false` does not stop graph writes - structural extraction runs unconditionally on session stop" + severity: med + difficulty: low + kind: bug + note: "GRAPH_EXTRACTION_ENABLED=false still runs structural extraction and writes graph rows." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1238 + - number: 1239 + title: "`POST /agentmemory/graph/reset` reports success while leaving nodes and edges untouched" + severity: high + difficulty: low + kind: bug + note: "POST /agentmemory/graph/reset reports success while leaving every node and edge in place." + disposition: already-fixed + fixed_by: "mem::graph-reset stamps resetAt on an empty snapshot, clears the name shards and flips retrieval onto the resetAt-filtering index path (src/functions/graph.ts:1308-1335); persistGraphDelta drops pre-reset rows from the merge (src/functions/graph.ts:784-791)." + url: https://github.com/rohitg00/agentmemory/issues/1239 + - number: 1240 + title: "`mem::summarize` asks for freehand XML and never sends `response_format` - 19% first-attempt parse failure, plus an unreported `narrative: Too small` validation failure" + severity: med + difficulty: med + kind: bug + note: "summarize asks for freehand XML with no response_format; 19% first-attempt parse failure." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1240 + - number: 1244 + title: "Session summarisation re-runs on already-summarised sessions (954x on one session; 150x more calls than material)" + severity: high + difficulty: med + kind: bug + note: "Summarisation re-runs on already-summarised sessions, 954x on one session, each a paid call." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1244 + - number: 1245 + title: "--instance / --port never reach the generated engine config, so a second daemon always binds instance-0 ports" + severity: high + difficulty: med + kind: bug + note: "--instance and --port never reach the generated engine config, so a second daemon always collides." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1245 + - number: 1249 + title: "vision-search queryText always fails: CLIP text branch uses feature-extraction, which demands pixel_values" + severity: med + difficulty: med + kind: bug + note: "vision-search queryText always fails: the CLIP text branch demands pixel_values." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1249 + fix_prs: [1250] + mentioned_by_prs: [1253] + - number: 1251 + title: "session/end creates malformed row when session does not exist" + severity: high + difficulty: low + kind: bug + note: "session/end upserts a malformed row for unknown sessions, later breaking GET /sessions." + disposition: candidate + status: "present-here — api::session::end calls kv.update on the session id with no existence check (src/triggers/api.ts:667-670), and update on a missing key auto-creates it as {} (src/engine/inproc/state.ts:11). An unknown id yields a row with only endedAt and status — which api::sessions then returns." + url: https://github.com/rohitg00/agentmemory/issues/1251 + fix_prs: [1252] + - number: 1254 + title: "vision-search silently ignores `limit` while every other search function uses it" + severity: low + difficulty: low + kind: bug + note: "vision-search silently ignores limit while every sibling honors it." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1254 + fix_prs: [1255] + - number: 1264 + title: "Test suite: 30 failures on Windows, all test-side platform assumptions" + severity: med + difficulty: med + kind: bug + note: "30 Windows test failures, all test-side platform assumptions." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/1264 + mentioned_by_prs: [1265, 1266, 1267] + - number: 1270 + title: "Hooks with no tool payload produce empty compression prompts, burning LLM calls on content-free observations" + severity: med + difficulty: low + kind: bug + note: "Payload-free hooks build empty compression prompts, burning LLM calls on nothing." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1270 + - number: 1271 + title: "`getXmlTag` is a first-match unanchored regex, so any text before the payload can be parsed as the payload -- and `compressWithRetry` commits a response its own validator rejected" + severity: high + difficulty: med + kind: bug + note: "Unanchored getXmlTag takes the first match anywhere and compressWithRetry commits a response its validator rejected." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1271 + - number: 1273 + title: "Governance delete finds a captured observation but deletes nothing (deleted:0)" + severity: high + difficulty: med + kind: bug + note: "Governance delete finds a captured observation and deletes nothing." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1273 + - number: 1274 + title: "Feature: deprecate / supersede observations (invalidate bad captures) with audit trail" + severity: med + difficulty: med + kind: feature + note: "No way to deprecate or supersede a bad capture with an audit trail." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1274 + - number: 1276 + title: "Bug: Azure content filter rejections open the circuit breaker, failing unrelated compressions" + severity: med + difficulty: low + kind: bug + note: "Content-filter rejections count as provider failures and open the circuit breaker for unrelated work." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1276 + fix_prs: [1277] + - number: 1278 + title: "PreToolUse context injection cannot reach the model: raw stdout instead of the hook envelope, plus a 2s fetch budget against a 6-29s /agentmemory/enrich" + severity: high + difficulty: med + kind: bug + note: "PreToolUse injection uses raw stdout instead of the hook envelope, against a 2s budget on a 6-29s endpoint." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1278 + - number: 1279 + title: "[viewer] Dashboard \"Memories\" stat card caps at 500 — uses .length of a limited fetch instead of the total field" + severity: low + difficulty: low + kind: bug + note: "Dashboard Memories card uses the length of a limited fetch, capping at 500." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1279 + fix_prs: [1347] + - number: 1292 + title: "deriveCrystalAndLessons slices lessons mid-sentence: 775/981 (79%) unusable, and they cannot decay out" + severity: high + difficulty: med + kind: bug + note: "deriveCrystalAndLessons slices lessons mid-sentence; 775 of 981 unusable and some invert meaning." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1292 + - number: 1297 + title: "Feature request: signal deletion / TTL for signals" + severity: low + difficulty: med + kind: feature + note: "Signals have no delete or TTL, so the store grows without bound." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1297 + - number: 1312 + title: "[deps] Please bump iii-sdk / iii-engine past 0.11.2 — unbounded RSS growth + hung graceful shutdown in long-running deployments" + severity: med + difficulty: high + kind: chore + note: "Bump iii-sdk/engine past the 0.11.2 pin for RSS growth and shutdown hangs." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1312 + - number: 1313 + title: "benchmark/COMPARISON.md documents four npm scripts that are not defined" + severity: low + difficulty: low + kind: docs + note: "benchmark/COMPARISON.md documents four npm scripts that do not exist." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1313 + - number: 1314 + title: "COMPARISON.md states all datasets are committed; benchmark/data/.gitignore excludes the LongMemEval-S dataset" + severity: low + difficulty: low + kind: docs + note: "COMPARISON.md claims all datasets are committed; the LongMemEval-S dataset is gitignored." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1314 + - number: 1315 + title: "Question: where is the DCO sign-off requirement enforced?" + severity: low + difficulty: low + kind: question + note: "Where the CONTRIBUTING DCO sign-off requirement is actually enforced." + disposition: wont-fix + wont_fix_reason: "upstream housekeeping, marketing or repo diary" + url: https://github.com/rohitg00/agentmemory/issues/1315 + - number: 1316 + title: "Feature request: target-scoped graph provenance correction after agent mistakes" + severity: med + difficulty: high + kind: feature + note: "Target-scoped graph provenance correction without a full graph reset." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1316 + - number: 1321 + title: "Codex prompt_submit observation can be returned by same-turn recall (self-recall)" + severity: med + difficulty: low + kind: bug + note: "Same-turn recall can return the prompt the hook just persisted." + disposition: wont-fix + wont_fix_reason: "unsupported host — Codex and Cursor are not supported here" + url: https://github.com/rohitg00/agentmemory/issues/1321 + - number: 1326 + title: "/sessions endpoint still hangs indefinitely in v0.9.29 (fix #1136 installed) — kv.list(KV.sessions) never resolves, breaks viewer dashboard + MCP memory_sessions" + severity: high + difficulty: high + kind: bug + note: "GET /agentmemory/sessions still hangs indefinitely on 0.9.29; kv.list(KV.sessions) never resolves." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1326 + - number: 1328 + title: "feat: Allow custom HTTP headers on LLM provider requests (needed for x-opencode-session)" + severity: med + difficulty: low + kind: feature + note: "Custom HTTP headers on LLM provider requests, needed for x-opencode-session." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1328 + - number: 1330 + title: "Docker deployment: real-time viewer on :3113 is unreachable (engine-only image never launches the npm viewer process)" + severity: med + difficulty: med + kind: bug + note: "The Docker engine-only image never launches the viewer, so :3113 is unreachable." + disposition: wont-fix + wont_fix_reason: "Docker / PaaS / Kubernetes deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/issues/1330 + - number: 1331 + title: "Windows: ~/.agentmemory/.env never loaded (HOME unset), so AGENTMEMORY_SECRET is empty and every integration fails silently while reporting healthy" + severity: high + difficulty: med + kind: bug + note: "Windows never loads ~/.agentmemory/.env, so every authenticated request 401s while reporting healthy." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/1331 + - number: 1333 + title: "Pinned slot block is silently dropped whole when it exceeds TOKEN_BUDGET (continue, not truncate)" + severity: med + difficulty: low + kind: bug + note: "The pinned-slot block is dropped whole and silently when it exceeds the token budget." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1333 + - number: 1334 + title: "/agentmemory/export returns the oversized refusal under HTTP 200, and materialises the payload before refusing it (18.5 GB RSS)" + severity: high + difficulty: med + kind: bug + note: "The oversized export refusal ships under HTTP 200 after materialising 18.5GB of RSS." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1334 + - number: 1335 + title: "Shutdown index save is lost to a container teardown race, and boot only reconciles a completely empty index" + severity: high + difficulty: med + kind: bug + note: "The shutdown index save is lost to a teardown race and boot only reconciles a fully empty index." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1335 + - number: 1338 + title: "fix(providers): createFallbackProvider drops baseURL — custom-endpoint fallbacks (DeepSeek/Kimi/etc.) hit the wrong API host" + severity: med + difficulty: low + kind: bug + note: "createFallbackProvider drops baseURL, so custom-endpoint fallbacks hit the vendor's host." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1338 + fix_prs: [1345] + - number: 1339 + title: "graph/build: server-side batch loop outlives its \"Invocation stopped\" HTTP response; bulk backfill impossible on large graph stores (Win32 + remote LLM, corroborates #1127)" + severity: high + difficulty: high + kind: bug + note: "graph/build's server-side batch loop outlives its response and burns LLM calls for hours." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1339 + mentioned_by_prs: [1384] + - number: 1340 + title: "Viewer SPA: dashboard flips between stats and 'new install' hero under live capture traffic (reload storm + failure!=empty conflation)" + severity: med + difficulty: med + kind: bug + note: "Viewer conflates fetch failure with empty, flipping between stats and the new-install hero." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1340 + fix_prs: [1342] + - number: 1341 + title: "mem::summarize: dead noop gate causes failure storm when no LLM key is set" + severity: med + difficulty: low + kind: bug + note: "Dead noop gate causes a summarize failure storm when no LLM key is set." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1341 + mentioned_by_prs: [1342] + - number: 1360 + title: "Oversized store fields and unpaginated full-list endpoints: sourceSessionIds/sourceMemoryIds bloat + 16 MiB WS frame limit" + severity: high + difficulty: high + kind: bug + note: "Unbounded sourceSessionIds/sourceMemoryIds plus unpaginated list endpoints hit the 16 MiB frame limit." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1360 + - number: 1361 + title: "Windows hardening: cross-platform build script, test normalization, and audit split" + severity: med + difficulty: med + kind: chore + note: "Windows build script portability, test normalization and audit split." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/issues/1361 + fix_prs: [1362] + - number: 1364 + title: "Bug: /insights 500 Invocation stopped — trailing garbage bytes appended to mem:insights.bin" + severity: high + difficulty: high + kind: bug + note: "Trailing garbage bytes appended to mem:insights.bin make GET /insights fail with Invocation stopped." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1364 + - number: 1365 + title: "session-end transcript back-fill extracts no prompts from a Claude Code transcript" + severity: med + difficulty: low + kind: bug + note: "extractTranscriptPrompts matches no Claude Code transcript shape, so prompt backfill posts nothing." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1365 + fix_prs: [1366] + - number: 1370 + title: "[viewer] WebUI randomly disconnects, backend remains healthy, only page refresh fixes it" + severity: med + difficulty: med + kind: bug + note: "Viewer randomly loses its connection while the backend stays healthy; only a refresh recovers." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1370 + - number: 1372 + title: "Semantic search silently stops saving new memories once the store passes a size set by the embedding width, and a restart does not rebuild them" + severity: high + difficulty: high + kind: bug + note: "Semantic search silently stops saving once the serialized index passes the string-length ceiling." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1372 + - number: 1373 + title: "Semantic search never stores anything with most non-OpenAI embedding models unless the operator sets the dimension variable by hand" + severity: high + difficulty: low + kind: bug + note: "Non-OpenAI embedding models never store vectors unless the operator sets the dimension variable by hand." + disposition: already-fixed + fixed_by: "Dimensions resolve through resolveDimensions() (src/providers/embedding/openai.ts:82)." + url: https://github.com/rohitg00/agentmemory/issues/1373 + - number: 1374 + title: "Unbounded sourceObservationIds inflate a 4062-node graph to 192MB; every traversal drops the worker and takes /search down with it" + severity: high + difficulty: med + kind: bug + note: "Unbounded provenance inflates a 4062-node graph to 192MB; every traversal drops the worker." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1374 + - number: 1377 + title: "[mcp] Some MCP host bridges receive empty inputSchema from tools/list — parameterized tool calls fail" + severity: high + difficulty: med + kind: bug + note: "Some MCP host bridges receive an empty inputSchema from tools/list, so parameterized calls fail." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1377 + - number: 1378 + title: "Worker heartbeat death loop on large legacy graph corpus: any vector result triggers blocking expandFromChunks (plus DROP_STALE_INDEX full-rebuild variant)" + severity: high + difficulty: high + kind: bug + note: "Any vector result triggers a blocking expandFromChunks, putting the worker in a heartbeat death loop." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1378 + - number: 1379 + title: "Bug: iii Console install prompt repeats after accepting installation in v0.9.29" + severity: low + difficulty: low + kind: bug + note: "iii Console install prompt repeats because the installer and detection logic disagree." + disposition: wont-fix + wont_fix_reason: "no iii engine — this fork runs one in-process SQLite Engine (ADR 0001)" + url: https://github.com/rohitg00/agentmemory/issues/1379 + - number: 1381 + title: "persistGraphDelta can zero the graph snapshot on a transient read failure (readSnapshot fail-open)" + severity: high + difficulty: low + kind: bug + note: "persistGraphDelta treats a failed snapshot read as empty and writes the zeroed snapshot back." + disposition: already-fixed + fixed_by: "persistGraphDelta wraps loadSnapshot in try/catch and abandons the batch rather than writing an empty view (src/functions/graph.ts:751-759)." + url: https://github.com/rohitg00/agentmemory/issues/1381 + fix_prs: [1384] + - number: 1382 + title: "paginateFromSnapshot can report a total below the nodes it returns; truncated banner never fires" + severity: low + difficulty: low + kind: bug + note: "paginateFromSnapshot can report a total below the node count it returns; the truncated banner never fires." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1382 + fix_prs: [1385] + - number: 1383 + title: "viewer: \"Rebuild Graph\" fires a full corpus replay with no confirmation, in-flight guard, or result handling" + severity: med + difficulty: low + kind: bug + note: "Viewer Rebuild Graph fires a full corpus replay with no confirmation, in-flight guard or result handling." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/issues/1383 + fix_prs: [1386] diff --git a/docs/upstream-pr-triage.yaml b/docs/upstream-pr-triage.yaml new file mode 100644 index 0000000000..392b58b199 --- /dev/null +++ b/docs/upstream-pr-triage.yaml @@ -0,0 +1,2388 @@ +# Upstream orphan-PR triage — rohitg00/agentmemory +# +# Scope: the 168 open upstream PRs that reference no open upstream issue, and are +# therefore absent from docs/upstream-issue-triage.yaml. The other 123 open PRs are +# cross-linked from the issues they claim to fix in that file. +# +# This fork does not merge, rebase or cherry-pick from upstream (see CLAUDE.md). These +# rows are read for the defect and the diagnosis, not for the patch. +# +# kind — fix | feature | provider | host | deps | docs | test | ci | deploy +# +# relevance — worth acting on in THIS fork: +# high a real defect or a recall-quality gain in code this fork carries and runs +# med applies here, but narrower: one host, one provider path, or a smaller win +# low another host/provider/deploy target, dependency bumps, or code absent here +# +# in_fork — /. A low ratio usually means +# the PR lands in files this fork deleted (deploy/, README translations, iii engine +# config, dropped hosts) — read it before assuming it does not apply. +# paths lists only the tracked ones, capped at 10. +# +# disposition — what this fork intends to do: +# already-fixed verified fixed in this tree; see status +# wont-fix out of scope here; wont_fix_reason says why +# candidate applies here and is unclaimed — the working set +# +# status — present only where the claim was checked against this tree by reading the +# code. "fixed-here" means this fork already carries the fix; "present-here" means the +# defect reproduces here as reported; "partly-present-here" means part of it was already +# fixed. Absent means unchecked: the note is still upstream's claim. +# +# Snapshot: 168 orphan PRs as of 2026-09-21 (gh pr list --repo rohitg00/agentmemory, +# changed files from repos/rohitg00/agentmemory/pulls/N/files). + +prs: + - number: 228 + title: "feat(vector): auto-index observations into vector store | 向量索引自动集成" + kind: feature + relevance: high + in_fork: 2/2 + churn: 19 + paths: + - src/functions/observe.ts + - src/index.ts + note: "Auto-index compressed observations into the vector store during observe; without it hybrid search needs a manual build." + disposition: already-fixed + status: "fixed-here — observe already indexes into the vector store via vectorIndexAddGuarded (src/functions/observe.ts:12,327)." + url: https://github.com/rohitg00/agentmemory/pull/228 + - number: 264 + title: "Implement surgical security and robustness improvements" + kind: fix + relevance: high + in_fork: 9/9 + churn: 110 + paths: + - src/auth.ts + - src/functions/claude-bridge.ts + - src/functions/snapshot.ts + - src/index.ts + - src/mcp/server.ts + - src/triggers/api.ts + - src/viewer/server.ts + - test/claude-bridge.test.ts + - test/snapshot.test.ts + note: "Viewer-proxy auth, snapshot write integrity and several hardening fixes across 9 files this fork carries." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/264 + - number: 300 + title: "feat: add sqlite-vec vector backend with Strategy pattern" + kind: feature + relevance: high + in_fork: 9/16 + churn: 805 + paths: + - benchmark/longmemeval-bench.ts + - benchmark/quality-eval.ts + - benchmark/real-embeddings-eval.ts + - benchmark/scale-eval.ts + - package.json + - src/index.ts + - src/state/hybrid-search.ts + - src/state/vector-index.ts + - test/vector-index.test.ts + note: "sqlite-vec vector backend behind a Strategy interface — the closest upstream work to this fork's own storage model." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/300 + - number: 470 + title: "Add consistency guards for MCP tools and REST endpoint drift" + kind: test + relevance: high + in_fork: 1/1 + churn: 20 + paths: + - test/consistency.test.ts + note: "Guards that every getAllTools() entry has a server switch case and that the endpoint count matches — directly automates this fork's Consistency Rules." + disposition: already-fixed + status: "fixed-here — test/consistency.test.ts and test/tool-count-consistency.test.ts already guard tool and endpoint drift." + url: https://github.com/rohitg00/agentmemory/pull/470 + - number: 532 + title: "fix(mcp): route memory_recall through full search" + kind: fix + relevance: high + in_fork: 3/3 + churn: 389 + paths: + - src/mcp/standalone.ts + - test/mcp-standalone-proxy.test.ts + - test/mcp-standalone.test.ts + note: "Standalone memory_recall proxies to smart-search, so format and token_budget are ignored and advertised recall modes do not work." + disposition: already-fixed + status: "fixed-here — Standalone memory_recall calls /agentmemory/search and forwards format and token_budget (src/mcp/standalone.ts:205-217); only memory_smart_search goes to /smart-search." + url: https://github.com/rohitg00/agentmemory/pull/532 + - number: 571 + title: "feat(smart-search): boost title/narrative matches on 'who/what is X' queries" + kind: feature + relevance: high + in_fork: 3/3 + churn: 262 + paths: + - src/functions/smart-search.ts + - src/types.ts + - test/smart-search.test.ts + note: "Boosts title/narrative matches on 'who/what is X' queries, where BM25 currently ranks busy observations over the record that names the concept." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/571 + - number: 572 + title: "perf(summarize): skip mem::summarize when a fresh summary exists" + kind: fix + relevance: high + in_fork: 1/1 + churn: 38 + paths: + - src/functions/summarize.ts + note: "Stop hooks fire mem::summarize every turn and stack full LLM passes; skips when a fresh summary exists." + disposition: candidate + status: "present-here — Same evidence as issue #1062: mem::summarize never checks for an existing fresh summary (src/functions/summarize.ts:235-360)." + url: https://github.com/rohitg00/agentmemory/pull/572 + - number: 615 + title: "feat(context,smart-search): inject insights into session context and smart search results (#457)" + kind: feature + relevance: high + in_fork: 2/2 + churn: 79 + paths: + - src/functions/context.ts + - src/functions/smart-search.ts + note: "mem::context and smart-search load lessons but skip insights, so mem::reflect output is reachable only by explicit tool call." + disposition: candidate + status: "present-here — KV.insights (src/state/schema.ts:88) is written by reflect.ts and read only by diagnostics.ts and export-import.ts. mem::context loads slots, profile and lessons and never insights (src/functions/context.ts:73-161); smart-search has no reference either." + url: https://github.com/rohitg00/agentmemory/pull/615 + - number: 667 + title: "fix(cli): status uses /memories?count=true instead of /export" + kind: fix + relevance: high + in_fork: 1/3 + churn: 83 + paths: + - src/cli.ts + note: "agentmemory status calls unbounded /export to get two counts and times out on any grown install." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/667 + - number: 757 + title: "fix(compression): fallback to synthetic compression when memory provider is noop" + kind: fix + relevance: high + in_fork: 2/2 + churn: 146 + paths: + - src/functions/compress.ts + - test/auto-compress.test.ts + note: "Compression against the noop provider produces nothing; falls back to local synthetic compression so keyless installs still store something." + disposition: already-fixed + status: "fixed-here — compress.ts already degrades to buildSyntheticCompression on provider failure (src/functions/compress.ts:113-130)." + url: https://github.com/rohitg00/agentmemory/pull/757 + - number: 829 + title: "Add project isolation for agentmemory" + kind: feature + relevance: high + in_fork: 50/56 + churn: 1605 + paths: + - .env.example + - plugin/.mcp.copilot.json + - plugin/.mcp.json + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/pre-tool-use.mjs + - plugin/scripts/prompt-submit.mjs + # +40 more + note: "AGENTMEMORY_PROJECT_ISOLATION enforced across MCP, REST and search, including a cross-project leak in hybrid smart-search." + disposition: candidate + status: "present-here — no AGENTMEMORY_PROJECT_ISOLATION." + url: https://github.com/rohitg00/agentmemory/pull/829 + - number: 878 + title: "Security: escape stored memory content in injected context (H1)" + kind: fix + relevance: high + in_fork: 5/6 + churn: 316 + paths: + - src/functions/context.ts + - src/functions/enrich.ts + - src/functions/slots.ts + - src/prompts/xml.ts + - test/context-lessons.test.ts + note: "Stored memory content is interpolated raw into , so a memory can close the wrapper and inject instructions." + disposition: candidate + status: "present-here — src/functions/context.ts escapes only the project attribute (line 26); stored fields are still interpolated raw." + url: https://github.com/rohitg00/agentmemory/pull/878 + - number: 898 + title: "fix(viewer): prevent path-traversal SSRF in proxy (CWE-918)" + kind: fix + relevance: high + in_fork: 1/2 + churn: 221 + paths: + - src/viewer/server.ts + note: "Path-traversal SSRF (CWE-918) in the viewer proxy: local callers escape the /agentmemory/ prefix with the auth header attached." + disposition: candidate + status: "present-here — pathname is a raw slice of req.url with no normalization (src/viewer/server.ts:253) and the proxy concatenates it straight into the upstream URL (src/viewer/server.ts:399-403) while attaching Authorization: Bearer . A ../ segment resolves during fetch, so the secret rides a request outside the /agentmemory/ prefix. Local-only reach." + url: https://github.com/rohitg00/agentmemory/pull/898 + - number: 922 + title: "fix(security): close secret-scrubbing bypass paths in all MCP write routes" + kind: fix + relevance: high + in_fork: 8/11 + churn: 1599 + paths: + - src/functions/compress.ts + - src/functions/export-import.ts + - src/functions/lessons.ts + - src/functions/privacy.ts + - src/functions/remember.ts + - src/functions/sketches.ts + - src/functions/slots.ts + - src/functions/team.ts + note: "stripPrivateData runs only in the observe pipeline; seven MCP write tools store secrets in plaintext." + disposition: candidate + status: "present-here — stripPrivateData is called only from src/functions/observe.ts." + url: https://github.com/rohitg00/agentmemory/pull/922 + - number: 928 + title: "feat(search): add temporal decay to recall ranking" + kind: feature + relevance: high + in_fork: 4/8 + churn: 1676 + paths: + - .env.example + - src/config.ts + - src/index.ts + - src/state/hybrid-search.ts + note: "Opt-in exponential temporal decay in RRF fusion; today a note from this morning ranks identically to one from a year ago." + disposition: candidate + status: "present-here — no temporal decay in src/state/hybrid-search.ts." + url: https://github.com/rohitg00/agentmemory/pull/928 + - number: 975 + title: "Fix: unified environment behavior" + kind: fix + relevance: high + in_fork: 18/19 + churn: 210 + paths: + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/pre-tool-use.mjs + - plugin/scripts/prompt-submit.mjs + - plugin/scripts/session-end.mjs + - plugin/scripts/session-start.mjs + - plugin/scripts/stop.mjs + # +8 more + note: "Every hook script reads AGENTMEMORY_* at module level, so config living only in ~/.agentmemory/.env is silently ignored; touches 18 hook scripts this fork carries." + disposition: candidate + status: "present-here — No hook imports ../config.js; pre-tool-use.ts has no imports at all and reads process.env at module load (src/hooks/pre-tool-use.ts:23-26) while its own comment tells you to set the value in ~/.agentmemory/.env (line 20). Only the daemon hydrates that file (src/config.ts:75-83), so hook-only config set there is silently ignored." + url: https://github.com/rohitg00/agentmemory/pull/975 + - number: 1005 + title: "fix: evicted observations leave ghost entries in search indexes" + kind: fix + relevance: high + in_fork: 1/1 + churn: 13 + paths: + - src/functions/evict.ts + note: "Evicted observations are never removed from the BM25 or vector index, so search returns ids whose KV lookup is null and silently under-fills pages." + disposition: candidate + status: "present-here — src/functions/evict.ts deletes from KV without touching the BM25 or vector index." + url: https://github.com/rohitg00/agentmemory/pull/1005 + - number: 1039 + title: "fix: schedule periodic snapshot timer (#1006)" + kind: fix + relevance: high + in_fork: 1/2 + churn: 93 + paths: + - src/index.ts + note: "SNAPSHOT_ENABLED is loaded and logged but no timer ever calls mem::snapshot-create — the feature never runs." + disposition: already-fixed + status: "fixed-here — the periodic snapshot timer exists (src/index.ts:357)." + url: https://github.com/rohitg00/agentmemory/pull/1039 + - number: 1174 + title: "fix: evict lowest-value observations at the session cap instead of refusing writes" + kind: fix + relevance: high + in_fork: 1/2 + churn: 211 + paths: + - src/functions/observe.ts + note: "At MAX_OBS_PER_SESSION every further observation is discarded; evicts the lowest-value one instead of dropping the newest." + disposition: candidate + status: "present-here — At MAX_OBS_PER_SESSION mem::observe refuses every further observation outright (src/functions/observe.ts:147-154). The newest work is dropped rather than the least valuable one evicted." + url: https://github.com/rohitg00/agentmemory/pull/1174 + - number: 1175 + title: "feat(slots): reject stale slot overwrites, keep an undo copy, report headroom" + kind: fix + relevance: high + in_fork: 4/5 + churn: 389 + paths: + - src/functions/slots.ts + - src/mcp/server.ts + - src/mcp/tools-registry.ts + - src/types.ts + note: "mem::slot-replace is an unguarded whole-object write, so two sessions silently clobber each other." + disposition: candidate + status: "partly-present-here — mem::slot-replace is serialized by withKeyedLock (src/functions/slots.ts:319), so it is not the unguarded write described. It still has no version precondition and no undo copy, so a read-modify-write across two sessions silently loses the first write." + url: https://github.com/rohitg00/agentmemory/pull/1175 + - number: 1176 + title: "fix: bound the audit log with AGENTMEMORY_AUDIT_MAX" + kind: fix + relevance: high + in_fork: 1/2 + churn: 143 + paths: + - src/functions/audit.ts + note: "recordAudit has no retention and the KV adapter rewrites the whole scope per write, so audit cost compounds on long-lived installs." + disposition: candidate + status: "present-here — recordAudit has no retention bound." + url: https://github.com/rohitg00/agentmemory/pull/1176 + - number: 1210 + title: "fix(providers): replace retired Anthropic default model identifiers" + kind: fix + relevance: high + in_fork: 3/3 + churn: 16 + paths: + - .env.example + - src/config.ts + - src/providers/index.ts + note: "claude-sonnet-4-20250514 was retired on 15 June 2026 and is still the fallback default in six places." + disposition: already-fixed + status: "fixed-here — claude-sonnet-4-20250514 appears nowhere in src/." + url: https://github.com/rohitg00/agentmemory/pull/1210 + - number: 1220 + title: "fix(hooks): scope pre-tool-use enrichment to the current project" + kind: fix + relevance: high + in_fork: 2/3 + churn: 199 + paths: + - plugin/scripts/pre-tool-use.mjs + - src/hooks/pre-tool-use.ts + note: "PreToolUse carries no project field, so hook enrichment is always unscoped and pulls context across projects." + disposition: already-fixed + status: "fixed-here — pre-tool-use resolves project and forwards it on the enrich call (src/hooks/pre-tool-use.ts:97-111)." + url: https://github.com/rohitg00/agentmemory/pull/1220 + - number: 1247 + title: "feat(api): add /agentmemory/memories/search" + kind: feature + relevance: high + in_fork: 1/1 + churn: 179 + paths: + - src/triggers/api.ts + note: "No search endpoint covers memories written by remember — /memories only lists." + disposition: candidate + status: "present-here — no /agentmemory/memories/search route in src/triggers/api.ts." + url: https://github.com/rohitg00/agentmemory/pull/1247 + - number: 1259 + title: "fix(providers): bound LLM provider concurrency and stop counting 429s as breaker failures" + kind: fix + relevance: high + in_fork: 1/3 + churn: 341 + paths: + - src/providers/resilient.ts + note: "No concurrency bound on the provider path and 429s count as circuit-breaker failures, so load trips the breaker." + disposition: candidate + status: "partly-present-here — 429 and 503 are already retried with Retry-After before reaching the breaker (src/providers/_fetch.ts:13,76-82). A concurrency cap exists, but only on the agent-sdk provider (src/providers/agent-sdk.ts:99) — the HTTP providers have none." + url: https://github.com/rohitg00/agentmemory/pull/1259 + - number: 1260 + title: "fix(mcp): read graph stats from the snapshot instead of enumerating the graph" + kind: fix + relevance: high + in_fork: 2/2 + churn: 56 + paths: + - src/mcp/server.ts + - test/mcp-resources.test.ts + note: "agentmemory://graph/stats enumerates every node and edge over the transport to compute four aggregates." + disposition: already-fixed + status: "fixed-here — mem::graph-stats reads the snapshot and never enumerates (src/functions/graph.ts:1105)." + url: https://github.com/rohitg00/agentmemory/pull/1260 + - number: 1287 + title: "fix(evict): schedule the eviction sweep at boot" + kind: fix + relevance: high + in_fork: 5/6 + churn: 204 + paths: + - .env.example + - src/config.ts + - src/functions/evict.ts + - src/index.ts + - test/evict.test.ts + note: "mem::evict is fully implemented but nothing schedules it — Eviction never runs." + disposition: candidate + status: "present-here — mem::evict is registered (src/functions/evict.ts:109) but src/index.ts schedules only auto-forget and consolidate-pipeline." + url: https://github.com/rohitg00/agentmemory/pull/1287 + - number: 1307 + title: "fix(sessions): close idle sessions no client ever ended" + kind: fix + relevance: high + in_fork: 5/11 + churn: 862 + paths: + - src/config.ts + - src/index.ts + - src/triggers/api.ts + - src/triggers/events.ts + - src/types.ts + note: "Sessions only reach completed when a client POSTs /session/end; clients that never do leave sessions active forever." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1307 + - number: 1309 + title: "feat(graph): delta graph extraction" + kind: fix + relevance: high + in_fork: 5/5 + churn: 250 + paths: + - src/functions/graph.ts + - src/state/schema.ts + - test/graph-heuristic-extract.test.ts + - test/graph.test.ts + - test/schema.test.ts + note: "Graph extraction re-runs over all observations every trigger, duplicating nodes and burning LLM calls." + disposition: candidate + status: "present-here — no graphExtracted scope in src/state/schema.ts." + url: https://github.com/rohitg00/agentmemory/pull/1309 + - number: 1310 + title: "fix(compression): guard empty compression prompts and watermark summarization" + kind: fix + relevance: high + in_fork: 10/11 + churn: 575 + paths: + - src/functions/compress-synthetic.ts + - src/functions/compress.ts + - src/functions/summarize.ts + - src/prompts/compression.ts + - src/state/schema.ts + - src/triggers/api.ts + - src/triggers/events.ts + - src/types.ts + - test/schema.test.ts + - test/summarize.test.ts + note: "Empty observations produce empty compression prompts, and summarization re-runs on an unchanged observation count." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1310 + - number: 1317 + title: "fix(health): measure heap saturation against the heap ceiling, not heapTotal" + kind: fix + relevance: high + in_fork: 4/4 + churn: 62 + paths: + - src/health/monitor.ts + - src/health/thresholds.ts + - src/types.ts + - test/health-thresholds.test.ts + note: "Health measured heapUsed/heapTotal, which reads 80-95% in any healthy process; measures against the real ceiling instead." + disposition: already-fixed + status: "fixed-here — saturation is measured against the heap ceiling (src/health/thresholds.ts:88)." + url: https://github.com/rohitg00/agentmemory/pull/1317 + - number: 1319 + title: "fix(consolidation): dedupe double-fired consolidation LLM runs + crash-safe audit" + kind: fix + relevance: high + in_fork: 3/3 + churn: 383 + paths: + - src/functions/audit.ts + - src/functions/consolidation-pipeline.ts + - test/consolidation-pipeline.test.ts + note: "The consolidation pipeline fires the same full-corpus LLM run twice for one corpus state." + disposition: already-fixed + status: "fixed-here — The consolidation pipeline already holds a lock that joins a second run over the same corpus state (src/functions/consolidation-pipeline.ts:52-56)." + url: https://github.com/rohitg00/agentmemory/pull/1319 + - number: 1324 + title: "fix(viewer): dashboard shows 0 sessions when unbounded KV scopes overflow iii invocation" + kind: fix + relevance: high + in_fork: 2/2 + churn: 58 + paths: + - src/triggers/api.ts + - src/viewer/index.html + note: "api::semantic-list and siblings run unbounded kv.list over a ~17MB scope, overflowing the invocation and blanking the dashboard." + disposition: candidate + status: "present-here — api::semantic-list and api::procedural-list run unbounded kv.list with no limit and return the whole scope (src/triggers/api.ts:2235, 2249)." + url: https://github.com/rohitg00/agentmemory/pull/1324 + - number: 1344 + title: "feat(reflect): project-level namespace isolation for reflection and consolidation" + kind: fix + relevance: high + in_fork: 6/6 + churn: 191 + paths: + - src/functions/consolidation-pipeline.ts + - src/functions/reflect.ts + - src/mcp/server.ts + - src/mcp/tools-registry.ts + - test/consolidation-pipeline.test.ts + - test/reflect.test.ts + note: "Reflection and consolidation are not project-scoped, so concept clusters and insights cross-contaminate between repos." + disposition: candidate + status: "partly-present-here — mem::reflect accepts and filters on project (src/functions/reflect.ts:187,354,385), so the capability is present; it is opt-in, and the scheduled run passes no project." + url: https://github.com/rohitg00/agentmemory/pull/1344 + - number: 1350 + title: "fix(providers): clear the circuit breaker failure count on success" + kind: fix + relevance: high + in_fork: 4/4 + churn: 138 + paths: + - src/config.ts + - src/providers/circuit-breaker.ts + - src/providers/resilient.ts + - test/circuit-breaker.test.ts + note: "recordSuccess() does not reset the failure count in the closed state, so unrelated failures accumulate until the breaker trips." + disposition: candidate + status: "partly-present-here — recordSuccess only resets in half-open (src/providers/circuit-breaker.ts:47-54), but recordFailure already zeroes the count when the previous failure is older than the 60s window (src/providers/circuit-breaker.ts:63-65). Failures do not accumulate forever; the real gap is that successes never reduce the count inside a window." + url: https://github.com/rohitg00/agentmemory/pull/1350 + - number: 1351 + title: "perf(search): reuse one graph view per store and bound traversal" + kind: fix + relevance: high + in_fork: 3/5 + churn: 703 + paths: + - src/functions/graph-retrieval.ts + - src/state/hybrid-search.ts + - src/state/kv.ts + note: "Rebuilds the graph view per search and traverses unbounded; reuses one view per store and caps the traversal." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1351 + - number: 1367 + title: "fix(summarize): detect wrapped noop provider so keyless installs skip the pipeline" + kind: fix + relevance: high + in_fork: 2/2 + churn: 27 + paths: + - src/functions/summarize.ts + - test/summarize.test.ts + note: "The noop provider is wrapped, so the no_provider early return never fires and keyless installs run the whole summarize pipeline on every Stop hook." + disposition: candidate + status: "present-here — Every provider is wrapped: createProvider returns ResilientProvider (src/providers/index.ts:55) whose name is `resilient()` (src/providers/resilient.ts:9). summarize.ts:263 compares name === \"noop\", which can never match, so keyless installs run the whole summarize pipeline. graph.ts:926 already uses .includes(\"noop\") — the fix has a precedent in this tree." + url: https://github.com/rohitg00/agentmemory/pull/1367 + - number: 1368 + title: "fix(reflect): read bounded graph snapshot and cap cluster prompt" + kind: fix + relevance: high + in_fork: 6/6 + churn: 326 + paths: + - .env.example + - plugin/skills/agentmemory-config/REFERENCE.md + - src/functions/graph.ts + - src/functions/reflect.ts + - src/prompts/reflect.ts + - test/reflect.test.ts + note: "mem::reflect enumerates the full graph and blows the invocation limit on a large store; bounds the snapshot and caps the cluster prompt." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1368 + - number: 218 + title: "fix(viewer): prevent tab bar crush and fix graph canvas overflow" + kind: fix + relevance: med + in_fork: 1/1 + churn: 12 + paths: + - src/viewer/index.html + note: "Two viewer CSS bugs: tab bar collapses to ~8px and the graph canvas overflows." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/218 + - number: 223 + title: "feat(smart-search): add format parameter (full/narrative/compact) | 添加 format 参数" + kind: feature + relevance: med + in_fork: 1/1 + churn: 48 + paths: + - src/functions/smart-search.ts + note: "format=full/narrative/compact on mem::smart-search, matching mem::search." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/223 + - number: 224 + title: "feat(search): add CJK character bigram tokenization | 添加 CJK Bigram 分词" + kind: feature + relevance: med + in_fork: 1/1 + churn: 17 + paths: + - src/state/search-index.ts + note: "CJK bigram tokenization in the BM25 index; without it CJK text is effectively unsearchable." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/224 + - number: 225 + title: "feat(embedding): configurable local model, cache dir, and HF mirror | 嵌入模型可配置" + kind: feature + relevance: med + in_fork: 1/1 + churn: 38 + paths: + - src/providers/embedding/local.ts + note: "Env-configurable local embedding model, cache dir and HF mirror." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/225 + - number: 266 + title: "fix: suppress floating promise in keyed-mutex to prevent unhandled-rejection warnings" + kind: fix + relevance: med + in_fork: 1/1 + churn: 6 + paths: + - src/state/keyed-mutex.ts + note: "Floating promise in withKeyedLock can raise unhandled-rejection warnings." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/266 + - number: 273 + title: "feat: opt-in fail-loud when AGENTMEMORY_URL is unreachable" + kind: fix + relevance: med + in_fork: 2/4 + churn: 131 + paths: + - src/mcp/rest-proxy.ts + - test/mcp-standalone-proxy.test.ts + note: "The MCP shim silently falls back to local in-memory mode when AGENTMEMORY_URL is unreachable; this makes it opt-in loud." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/273 + - number: 319 + title: "fix(fs-watcher): load agentmemory env file" + kind: fix + relevance: med + in_fork: 3/3 + churn: 194 + paths: + - integrations/filesystem-watcher/README.md + - integrations/filesystem-watcher/watcher.mjs + - test/fs-watcher.test.ts + note: "fs-watcher never loads ~/.agentmemory/.env, so its config is silently ignored." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/319 + - number: 365 + title: "fix: tolerate partial dashboard payloads" + kind: fix + relevance: med + in_fork: 1/2 + churn: 278 + paths: + - src/viewer/index.html + note: "Dashboard crashes on partial payloads instead of rendering empty lists." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/365 + - number: 465 + title: "feat(connect): automate Hermes config merge" + kind: host + relevance: med + in_fork: 3/3 + churn: 299 + paths: + - src/cli/connect/hermes.ts + - src/cli/connect/util.ts + - test/cli-connect.test.ts + note: "Turns the Hermes connect stub into a real ~/.hermes/config.yaml merge." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/465 + - number: 467 + title: "fix(embeddings): allow custom OpenAI embedding path" + kind: fix + relevance: med + in_fork: 4/5 + churn: 57 + paths: + - .env.example + - src/providers/_openai-shared.ts + - src/providers/embedding/openai.ts + - test/embedding-provider.test.ts + note: "OPENAI_EMBEDDING_PATH for OpenAI-compatible endpoints that do not use /v1/embeddings." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/467 + - number: 468 + title: "fix(memory): audit remember attribution" + kind: fix + relevance: med + in_fork: 8/9 + churn: 279 + paths: + - src/functions/remember.ts + - src/mcp/server.ts + - src/mcp/standalone.ts + - src/mcp/tools-registry.ts + - src/types.ts + - test/mcp-standalone-proxy.test.ts + - test/mcp-standalone.test.ts + - test/remember-forget-audit.test.ts + note: "mem::remember records no audit row and drops sessionId/tags from attribution." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/468 + - number: 502 + title: "fix: run graph extraction on manual session end" + kind: fix + relevance: med + in_fork: 2/3 + churn: 180 + paths: + - src/triggers/api.ts + - src/triggers/events.ts + note: "POST /session/end skips the stopped-session pipeline, so graph extraction never runs on a manual end." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/502 + - number: 529 + title: "fix(viewer): show explicit error banner when dashboard endpoints fail" + kind: fix + relevance: med + in_fork: 8/9 + churn: 227 + paths: + - plugin/hooks/hooks.codex.json + - plugin/hooks/hooks.json + - src/config.ts + - src/index.ts + - src/mcp/standalone.ts + - src/viewer/index.html + - test/env-loader.test.ts + - test/mcp-standalone-proxy.test.ts + note: "Dashboard shows 0 memories rather than an error when the backend is down." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/529 + - number: 568 + title: "feat(graph): auto-trigger mem::graph-extract on mem::remember" + kind: feature + relevance: med + in_fork: 2/2 + churn: 34 + paths: + - src/functions/remember.ts + - test/cross-project-isolation.test.ts + note: "mem::remember never triggers graph-extract, so explicit saves never enter the graph." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/568 + - number: 569 + title: "feat(provider): AGENTMEMORY_DISABLE_THINKING to recover structured output on Qwen3/GLM/Kimi" + kind: feature + relevance: med + in_fork: 3/3 + churn: 32 + paths: + - .env.example + - plugin/skills/agentmemory-config/REFERENCE.md + - src/providers/openai.ts + note: "AGENTMEMORY_DISABLE_THINKING to recover structured output from hybrid-reasoning models (Qwen3/GLM/Kimi)." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/569 + - number: 610 + title: "fix: iii reconnect route loss + Voyage env config + heap calc against actual ceiling" + kind: fix + relevance: med + in_fork: 3/3 + churn: 413 + paths: + - src/health/thresholds.ts + - src/index.ts + - src/providers/embedding/voyage.ts + note: "Three unrelated fixes; the heap-ceiling one duplicates #1317 and the iii reconnect one does not apply here." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/610 + - number: 665 + title: "fix: pass agentId per-call for integration-scoped memory" + kind: fix + relevance: med + in_fork: 6/8 + churn: 214 + paths: + - integrations/hermes/__init__.py + - integrations/openclaw/plugin.mjs + - src/config.ts + - src/mcp/server.ts + - test/agent-id-scope.test.ts + - test/openclaw-plugin.test.ts + note: "Integrations send no agentId, so every memory lands unscoped even with multi-agent isolation on." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/665 + - number: 689 + title: "feat(team): per-request userId + TEAM_MODE=private enforcement" + kind: fix + relevance: med + in_fork: 5/7 + churn: 393 + paths: + - src/config.ts + - src/functions/team.ts + - src/mcp/server.ts + - src/mcp/tools-registry.ts + - test/team.test.ts + note: "TEAM_MODE=private was read but never enforced, and team-share accepted any sharedBy value." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/689 + - number: 742 + title: "fix: LLM provider works with subscription proxies + honor SUMMARIZE_CHUNK_SIZE from .env" + kind: fix + relevance: med + in_fork: 2/2 + churn: 19 + paths: + - src/functions/summarize.ts + - src/providers/anthropic.ts + note: "Folds the Anthropic system prompt into messages for subscription proxies, and honors SUMMARIZE_CHUNK_SIZE." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/742 + - number: 802 + title: "fix: prefer embedding API key for OpenAI embeddings" + kind: fix + relevance: med + in_fork: 2/2 + churn: 23 + paths: + - src/providers/embedding/index.ts + - test/embedding-provider.test.ts + note: "createEmbeddingProvider passes OPENAI_API_KEY over a set OPENAI_EMBEDDING_API_KEY; same defect as #832." + disposition: already-fixed + status: "fixed-here — OPENAI_EMBEDDING_API_KEY takes precedence (src/providers/embedding/openai.ts:61)." + url: https://github.com/rohitg00/agentmemory/pull/802 + - number: 832 + title: "Fix OpenAI embedding provider key selection" + kind: fix + relevance: med + in_fork: 2/2 + churn: 16 + paths: + - src/providers/embedding/index.ts + - test/embedding-provider.test.ts + note: "Prefer OPENAI_EMBEDDING_API_KEY in the embedding factory; cleaner duplicate of #802." + disposition: already-fixed + status: "fixed-here — same as #802." + url: https://github.com/rohitg00/agentmemory/pull/832 + - number: 846 + title: "Add stdio MCP resources and prompts" + kind: feature + relevance: med + in_fork: 2/2 + churn: 556 + paths: + - src/mcp/standalone.ts + - test/mcp-standalone.test.ts + note: "Resources and prompts capabilities on the stdio MCP shim, proxied to the running server." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/846 + - number: 862 + title: "Allow XENOVA_CACHE_HOME to redirect local embedding model path" + kind: fix + relevance: med + in_fork: 1/1 + churn: 18 + paths: + - src/providers/embedding/local.ts + note: "XENOVA_CACHE_HOME to redirect the local embedding model path out of node_modules." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/862 + - number: 927 + title: "fix(cli): add clear warning when import-jsonl brings zero files" + kind: fix + relevance: med + in_fork: 1/1 + churn: 6 + paths: + - src/cli.ts + note: "import-jsonl reports success when it imported zero files." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/927 + - number: 953 + title: "fix: preserve Zed settings during connect" + kind: fix + relevance: med + in_fork: 5/5 + churn: 146 + paths: + - package.json + - src/cli/connect/json-mcp-adapter.ts + - src/cli/connect/util.ts + - src/cli/connect/zed.ts + - test/connect-new-agents.test.ts + note: "connect zed overwrites existing settings.json instead of merging JSONC." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/953 + - number: 970 + title: "fix: make consolidation timeouts configurable" + kind: fix + relevance: med + in_fork: 4/13 + churn: 270 + paths: + - .env.example + - src/config.ts + - src/functions/consolidate.ts + - src/index.ts + note: "Consolidate per-concept and worker invocation timeouts hardcoded; adjacent to this fork's own LLM-timeout work." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/970 + - number: 974 + title: "fix(context,compress-synthetic): conversation observations render with full content" + kind: fix + relevance: med + in_fork: 5/6 + churn: 102 + paths: + - .github/workflows/ci.yml + - package.json + - src/functions/compress-synthetic.ts + - src/functions/context.ts + - website/package.json + note: "tool_name 'conversation' observations render as type 'other' with no content in injected context." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/974 + - number: 1011 + title: "feat(replay): support OpenAI chat-format JSONL in parseJsonlText" + kind: feature + relevance: med + in_fork: 2/3 + churn: 129 + paths: + - src/replay/jsonl-parser.ts + - test/replay.test.ts + note: "parseJsonlText only knows the Claude Code transcript shape; OpenAI chat-format JSONL imports produce zero observations." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1011 + - number: 1023 + title: "fix(replay): surface compressed observation content in replay detail" + kind: fix + relevance: med + in_fork: 2/2 + churn: 153 + paths: + - src/functions/replay.ts + - test/replay.test.ts + note: "Replay detail panel is empty because rawFromCompressed() drops the compressed content." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1023 + - number: 1037 + title: "fix: CJK-aware remember dedup with negation guard (#1021)" + kind: fix + relevance: med + in_fork: 2/5 + churn: 395 + paths: + - src/functions/remember.ts + - src/state/schema.ts + note: "remember dedup tokenizes on whitespace, so repeated CJK preferences never dedupe." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1037 + - number: 1089 + title: "feat: forward agentId on remember + Hermes multi-profile project tagging" + kind: fix + relevance: med + in_fork: 12/14 + churn: 1064 + paths: + - integrations/hermes/README.md + - integrations/hermes/__init__.py + - src/config.ts + - src/functions/remember.ts + - src/mcp/server.ts + - src/mcp/standalone.ts + - src/mcp/tools-registry.ts + - src/triggers/api.ts + - src/triggers/events.ts + - test/agent-id-scope.test.ts + # +2 more + note: "remember and memory_save drop agentId, and standalone MCP drops project despite advertising it." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1089 + - number: 1177 + title: "feat(health): surface search-index freshness" + kind: feature + relevance: med + in_fork: 3/5 + churn: 189 + paths: + - src/health/monitor.ts + - src/health/thresholds.ts + - src/types.ts + note: "Health surfaces search-index freshness; today a broken persister is visible only as a throttled warn line." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1177 + - number: 1215 + title: "fix(embedding): route transformers cacheDir to user home cache" + kind: fix + relevance: med + in_fork: 5/7 + churn: 210 + paths: + - __mocks__/@huggingface/transformers.ts + - src/providers/embedding/clip.ts + - src/providers/embedding/local.ts + - src/state/reranker.ts + - test/local-embedding-provider.test.ts + note: "transformers writes its model cache next to its own package, which fails on global or containerized installs." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1215 + - number: 1290 + title: "fix(metrics): window failure rate to recent activity + track lastFailureAt" + kind: fix + relevance: med + in_fork: 3/4 + churn: 125 + paths: + - src/eval/metrics-store.ts + - src/health/monitor.ts + - src/types.ts + note: "Health reports a cumulative failure rate, so a fixed bug leaves a stale high number forever." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1290 + - number: 1291 + title: "fix(metrics): serialize MetricsStore.record per function" + kind: fix + relevance: med + in_fork: 1/2 + churn: 130 + paths: + - src/eval/metrics-store.ts + note: "MetricsStore.record() loses updates: concurrent callers meet in the kv.get() gap." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1291 + - number: 1293 + title: "fix(hooks): retry a failed observe POST instead of dropping it" + kind: fix + relevance: med + in_fork: 16/18 + churn: 654 + paths: + - plugin/scripts/notification.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/prompt-submit.mjs + - plugin/scripts/session-end.mjs + - plugin/scripts/subagent-start.mjs + - plugin/scripts/subagent-stop.mjs + - plugin/scripts/task-completed.mjs + - src/hooks/notification.ts + - src/hooks/post-tool-failure.ts + # +6 more + note: "Adds retry/queue to hook observe POSTs; conflicts with this fork's fire-and-forget hook contract, so take the diagnosis, not the design." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1293 + - number: 1308 + title: "fix(pipeline): classify telemetry observations and extract semantic fields for non-tool events" + kind: fix + relevance: med + in_fork: 8/13 + churn: 1416 + paths: + - plugin/opencode/agentmemory-capture.ts + - src/functions/compress-synthetic.ts + - src/functions/consolidate.ts + - src/functions/context.ts + - src/functions/observe.ts + - src/functions/summarize.ts + - src/prompts/summary.ts + - src/types.ts + note: "Non-tool hook events carry payload data that mem::observe never extracts, so telemetry observations are contentless." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1308 + - number: 1311 + title: "fix(opencode): skip replayed history observation on session fork" + kind: host + relevance: med + in_fork: 1/3 + churn: 348 + paths: + - plugin/opencode/agentmemory-capture.ts + note: "Forking an OpenCode session re-observes the whole conversation history as new observations." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1311 + - number: 1318 + title: "fix(replay): reinforce lesson confidence on JSONL re-import" + kind: fix + relevance: med + in_fork: 2/3 + churn: 99 + paths: + - src/functions/lessons.ts + - src/functions/replay.ts + note: "JSONL re-import bumps reinforcements but never confidence, unlike reinforceLesson()." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1318 + - number: 1322 + title: "fix(memory): reject leaked tool-call args in remember" + kind: fix + relevance: med + in_fork: 1/2 + churn: 185 + paths: + - src/functions/remember.ts + note: "A mis-encoded tool call writes its trailing arguments into memory content as literal text." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1322 + - number: 1323 + title: "fix(mcp): stop masking tool errors as unknown-tool fallback" + kind: fix + relevance: med + in_fork: 4/4 + churn: 57 + paths: + - src/mcp/rest-proxy.ts + - src/mcp/server.ts + - src/mcp/standalone.ts + - test/mcp-standalone-proxy.test.ts + note: "Any non-ok proxy response is treated as unreachable, hiding real tool errors behind an unknown-tool fallback." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1323 + - number: 1327 + title: "fix(clip): encode text with CLIP text tower so text→image vision-search works" + kind: fix + relevance: med + in_fork: 2/2 + churn: 96 + paths: + - src/providers/embedding/clip.ts + - test/clip-embedding-provider.test.ts + note: "ClipEmbeddingProvider encoded text with the image tower, so text-to-image vision-search always failed." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1327 + - number: 1336 + title: "fix(slots): line-boundary truncation in slot reflection to prevent mid-line slicing" + kind: fix + relevance: med + in_fork: 34/51 + churn: 7795 + paths: + - .gitignore + - plugin/opencode/agentmemory-capture.ts + - src/functions/audit.ts + - src/functions/compress-synthetic.ts + - src/functions/compress.ts + - src/functions/consolidation-pipeline.ts + - src/functions/diagnostics.ts + - src/functions/graph.ts + - src/functions/observe.ts + - src/functions/reflect.ts + # +24 more + note: "Line-boundary truncation in slot reflection instead of a raw mid-line slice; the fix is small but the PR carries 7.8k churn across 51 files." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1336 + - number: 1363 + title: "feat(scope): dynamic project identity and tiered observation lifecycle" + kind: feature + relevance: med + in_fork: 57/100 + churn: 13022 + paths: + - .gitignore + - CONTEXT.md + - docs/agents/domain.md + - docs/agents/issue-tracker.md + - plugin/opencode/agentmemory-capture.ts + - plugin/scripts/notification.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/prompt-submit.mjs + # +47 more + note: "Git-remote-derived canonical project slugs and a tiered observation lifecycle; the right-scope idea is good, the 13k-churn PR is not." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1363 + - number: 1369 + title: "fix(embeddings): send OPENAI_EMBEDDING_DIMENSIONS as the dimensions field" + kind: fix + relevance: med + in_fork: 3/4 + churn: 218 + paths: + - .env.example + - src/providers/embedding/openai.ts + - test/embedding-provider.test.ts + note: "OPENAI_EMBEDDING_DIMENSIONS is read into the provider but never sent in the request body, breaking matryoshka models." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1369 + - number: 194 + title: "feat: add --host flag and AGENTMEMORY_HOST for configurable bind address" + kind: feature + relevance: low + in_fork: 6/6 + churn: 114 + paths: + - src/auth.ts + - src/cli.ts + - src/config.ts + - src/index.ts + - src/types.ts + - src/viewer/server.ts + note: "--host/AGENTMEMORY_HOST to bind off localhost; the fork already runs one local daemon." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/194 + - number: 219 + title: "feat(providers): add Azure OpenAI provider" + kind: provider + relevance: low + in_fork: 4/5 + churn: 109 + paths: + - src/config.ts + - src/providers/index.ts + - src/types.ts + - src/viewer/index.html + note: "Azure OpenAI LLM provider." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/219 + - number: 220 + title: "fix(providers): support Azure AI Foundry (Anthropic) endpoint and corporate proxy" + kind: provider + relevance: low + in_fork: 21/25 + churn: 579 + paths: + - package.json + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/pre-tool-use.mjs + - plugin/scripts/prompt-submit.mjs + - plugin/scripts/session-end.mjs + - plugin/scripts/session-start.mjs + # +11 more + note: "Azure OpenAI / AI Foundry plus HTTP CONNECT corporate-proxy support; overlaps #594." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/220 + - number: 226 + title: "feat(health): configurable health check thresholds via env vars | 健康阈值可配置" + kind: feature + relevance: low + in_fork: 1/1 + churn: 14 + paths: + - src/health/thresholds.ts + note: "Health thresholds via env; the defaults false-alarm on small hosts." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/226 + - number: 227 + title: "feat(shutdown): graceful shutdown timeout with force exit | 优雅关闭超时" + kind: fix + relevance: low + in_fork: 1/1 + churn: 7 + paths: + - src/index.ts + note: "Force-exit if graceful shutdown hangs on the iii WebSocket — a failure mode this fork does not have." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/227 + - number: 241 + title: "feat: hierarchical outline index for long markdown artifacts" + kind: feature + relevance: low + in_fork: 7/16 + churn: 1328 + paths: + - plugin/.claude-plugin/plugin.json + - src/index.ts + - src/mcp/server.ts + - src/mcp/tools-registry.ts + - src/state/schema.ts + - src/triggers/api.ts + - src/types.ts + note: "PageIndex-style outline index, 3 MCP tools + 3 endpoints; a new subsystem." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/241 + - number: 245 + title: "feat: add Codex Desktop hooks integration" + kind: host + relevance: low + in_fork: 0/4 + churn: 635 + note: "Codex Desktop hook bridge; Codex is not a supported host here." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/245 + - number: 267 + title: "Enhance auto-forget with redundancy tracking" + kind: feature + relevance: low + in_fork: 1/1 + churn: 76 + paths: + - src/functions/auto-forget.ts + note: "Redundancy tracking in auto-forget; CodeRabbit-authored, thin rationale." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/267 + - number: 302 + title: "fix(openclaw): register memory capability for memory slot" + kind: host + relevance: low + in_fork: 2/2 + churn: 19 + paths: + - integrations/openclaw/README.md + - integrations/openclaw/plugin.mjs + note: "OpenClaw memory-slot capability registration." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/302 + - number: 333 + title: "Refactor health monitoring logic and snapshot collection" + kind: chore + relevance: low + in_fork: 1/1 + churn: 61 + paths: + - src/health/monitor.ts + note: "Health monitor refactor, 5s cadence; CodeRabbit-authored." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/333 + - number: 376 + title: "feat: configurable bind hosts for iii-engine and viewer" + kind: feature + relevance: low + in_fork: 2/3 + churn: 47 + paths: + - src/cli.ts + - src/viewer/server.ts + note: "Configurable bind host for engine and viewer; overlaps #194." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/376 + - number: 378 + title: "build(docker): unify per-platform deploys behind single GHCR image" + kind: deploy + relevance: low + in_fork: 0/16 + churn: 793 + note: "Single GHCR image for all platform deploys; no file here." + disposition: wont-fix + wont_fix_reason: "deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/pull/378 + - number: 464 + title: "docs: refresh integration capability counts" + kind: docs + relevance: low + in_fork: 6/8 + churn: 62 + paths: + - .env.example + - assets/tags/light/stat-tests.svg + - assets/tags/stat-tests.svg + - integrations/hermes/README.md + - integrations/openclaw/README.md + - test/consistency.test.ts + note: "Refreshes stale tool/test counts in integration docs." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/464 + - number: 488 + title: "fix(hermes): keep plugin hook manifest in sync" + kind: fix + relevance: low + in_fork: 2/2 + churn: 57 + paths: + - integrations/hermes/plugin.yaml + - test/consistency.test.ts + note: "Hermes plugin.yaml missing hook names, plus a manifest consistency guard." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/488 + - number: 528 + title: "fix(cli): tie iii engine lifecycle and skip prompts in non-TTY context" + kind: fix + relevance: low + in_fork: 8/9 + churn: 195 + paths: + - plugin/hooks/hooks.codex.json + - plugin/hooks/hooks.json + - src/cli.ts + - src/config.ts + - src/index.ts + - src/mcp/standalone.ts + - test/env-loader.test.ts + - test/mcp-standalone-proxy.test.ts + note: "TTY heuristic orphans iii.exe; no iii engine in this fork." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/528 + - number: 543 + title: "Improve Hermes manual install status messaging" + kind: chore + relevance: low + in_fork: 2/2 + churn: 25 + paths: + - src/cli/connect/hermes.ts + - src/viewer/index.html + note: "Replaces the Hermes 'stub' install status with clearer wording." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/543 + - number: 558 + title: "Add Azure OpenAI provider configuration" + kind: provider + relevance: low + in_fork: 9/11 + churn: 285 + paths: + - .env.example + - src/cli.ts + - src/cli/doctor-diagnostics.ts + - src/cli/onboarding.ts + - src/config.ts + - src/functions/summarize.ts + - src/providers/index.ts + - src/providers/openai.ts + - test/openai-shared.test.ts + note: "Azure OpenAI config path; third competing Azure PR with #219/#594." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/558 + - number: 566 + title: "docs: sync MCP tool counts across metadata" + kind: docs + relevance: low + in_fork: 4/5 + churn: 37 + paths: + - .env.example + - plugin/.claude-plugin/plugin.json + - src/mcp/standalone.ts + - website/components/Compare.tsx + note: "Tool-count sync across metadata." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/566 + - number: 583 + title: "Add optional external_id metadata passthrough for memory retrieval results" + kind: feature + relevance: low + in_fork: 8/11 + churn: 219 + paths: + - src/functions/remember.ts + - src/functions/search.ts + - src/mcp/server.ts + - src/mcp/standalone.ts + - src/mcp/tools-registry.ts + - src/state/memory-utils.ts + - src/triggers/api.ts + - src/types.ts + note: "external_id + metadata passthrough for imported memories." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/583 + - number: 594 + title: "feat(providers): add Azure OpenAI / AI Foundry provider with HTTP CONNECT proxy support" + kind: provider + relevance: low + in_fork: 20/21 + churn: 354 + paths: + - package.json + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/pre-tool-use.mjs + - plugin/scripts/prompt-submit.mjs + - plugin/scripts/session-end.mjs + - plugin/scripts/session-start.mjs + # +10 more + note: "Azure OpenAI / AI Foundry with proxy support; overlaps #220/#558." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/594 + - number: 604 + title: "feat(pi): add full lifecycle hooks to pi integration" + kind: host + relevance: low + in_fork: 1/1 + churn: 246 + paths: + - integrations/pi/index.ts + note: "pi integration from 3 to 6 lifecycle hooks." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/604 + - number: 606 + title: "feat(providers): add DeepSeek provider" + kind: provider + relevance: low + in_fork: 2/4 + churn: 106 + paths: + - src/providers/index.ts + - src/types.ts + note: "DeepSeek embedding provider." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/606 + - number: 607 + title: "feat(cli): allow AGENTMEMORY_IMPORT_TIMEOUT_MS override for import-jsonl" + kind: fix + relevance: low + in_fork: 1/1 + churn: 20 + paths: + - src/cli.ts + note: "AGENTMEMORY_IMPORT_TIMEOUT_MS instead of a hardcoded 120s import ceiling." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/607 + - number: 617 + title: "feat: add privacy-safe audit receipts" + kind: feature + relevance: low + in_fork: 6/7 + churn: 196 + paths: + - src/functions/audit.ts + - src/mcp/server.ts + - src/mcp/standalone.ts + - src/mcp/tools-registry.ts + - src/triggers/api.ts + - test/audit.test.ts + note: "Hashed privacy-safe audit receipt format." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/617 + - number: 624 + title: "fix(cli): honor --force on unresponsive engine; detect listening PIDs on Windows" + kind: fix + relevance: low + in_fork: 1/2 + churn: 183 + paths: + - src/cli.ts + note: "Windows: --force ignored on a wedged engine socket." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/pull/624 + - number: 630 + title: "feat(connect): add Kilo CLI adapter" + kind: host + relevance: low + in_fork: 1/2 + churn: 114 + paths: + - src/cli/connect/index.ts + note: "Kilo CLI connect adapter." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/630 + - number: 634 + title: "fix(windows): make agentmemory actually start on Windows (watch path + IPv4 engine WS + configurable timeout)" + kind: fix + relevance: low + in_fork: 2/4 + churn: 44 + paths: + - src/cli.ts + - src/config.ts + note: "Windows startup failure rooted in the iii engine watch path and WS binding." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/634 + - number: 672 + title: "feat(viewer): add timeline sort toggle" + kind: feature + relevance: low + in_fork: 2/2 + churn: 127 + paths: + - src/viewer/index.html + - test/viewer-session-id.test.ts + note: "Viewer timeline newest/oldest sort toggle." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/672 + - number: 679 + title: "feat: add memory metacognition foundation" + kind: feature + relevance: low + in_fork: 4/15 + churn: 2864 + paths: + - src/index.ts + - src/state/schema.ts + - src/triggers/api.ts + - src/types.ts + note: "Metacognition phase 1: policy, write candidates, readback, 8 endpoints." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/679 + - number: 693 + title: "fix(cli): prioritize user iii config lookup" + kind: fix + relevance: low + in_fork: 3/7 + churn: 190 + paths: + - .gitignore + - package.json + - src/cli.ts + note: "iii-config lookup precedence; no iii engine here." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/693 + - number: 694 + title: "fix(viewer): preserve dashboard scroll and show API errors" + kind: feature + relevance: low + in_fork: 2/2 + churn: 190 + paths: + - src/viewer/index.html + - test/viewer-session-id.test.ts + note: "Preserve dashboard scroll across refreshes plus API error toasts." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/694 + - number: 699 + title: "feat(cli): materialize ~/.agentmemory/config/iii-config.yaml with absolute paths" + kind: fix + relevance: low + in_fork: 1/4 + churn: 378 + paths: + - src/cli.ts + note: "Materializes ~/.agentmemory/config/iii-config.yaml with absolute paths." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/699 + - number: 711 + title: "feat: add AGENTMEMORY_OUTPUT_LANG to control generated-text language" + kind: feature + relevance: low + in_fork: 2/3 + churn: 74 + paths: + - .env.example + - src/providers/resilient.ts + note: "AGENTMEMORY_OUTPUT_LANG for generated memory text; overlaps #914." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/711 + - number: 721 + title: "fix(viewer): correct Token Savings calculation to match CLI" + kind: fix + relevance: low + in_fork: 1/1 + churn: 2 + paths: + - src/viewer/index.html + note: "Viewer token-savings formula disagrees with the CLI and reads 0%." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/721 + - number: 741 + title: "feat: AWS Bedrock provider (LLM + embeddings) with SSO + auth-refresh" + kind: provider + relevance: low + in_fork: 9/16 + churn: 1338 + paths: + - .env.example + - package.json + - src/config.ts + - src/functions/compress-file.ts + - src/providers/embedding/index.ts + - src/providers/index.ts + - src/providers/resilient.ts + - src/types.ts + - test/compress-file.test.ts + note: "AWS Bedrock LLM + embeddings with SigV4 and SSO auth refresh." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/741 + - number: 756 + title: "feat(embedding): support configurable vector dimensions for OpenRouter provider" + kind: feature + relevance: low + in_fork: 2/2 + churn: 65 + paths: + - src/providers/embedding/openrouter.ts + - test/embedding-provider.test.ts + note: "OPENROUTER_EMBEDDING_DIMENSIONS." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/756 + - number: 799 + title: "fix: handle undefined manifest value in loadShardedData" + kind: fix + relevance: low + in_fork: 0/1 + churn: 2 + note: "Undefined-vs-null manifest check crashes the sharded loader on upgrade; the file does not exist in this fork." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/799 + - number: 818 + title: "feat: upgrade MiniMax default model to M3" + kind: chore + relevance: low + in_fork: 8/8 + churn: 20 + paths: + - .env.example + - src/cli/onboarding.ts + - src/config.ts + - src/providers/index.ts + - src/providers/minimax.ts + - test/fallback-model-resolution.test.ts + - test/fetch-timeout.test.ts + - test/minimax-provider.test.ts + note: "MiniMax default model to M3; duplicates #1056." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/818 + - number: 822 + title: "fix(codex): declare agentmemory MCP server as stdio" + kind: host + relevance: low + in_fork: 0/2 + churn: 79 + note: "type = stdio in the Codex MCP block." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/822 + - number: 841 + title: "feat(deploy): add systemd service template" + kind: deploy + relevance: low + in_fork: 0/3 + churn: 324 + note: "systemd unit template; no deploy/ tree in this fork." + disposition: wont-fix + wont_fix_reason: "deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/pull/841 + - number: 860 + title: "[codex] Fix OpenClaw terminal capture" + kind: host + relevance: low + draft: true + in_fork: 2/2 + churn: 614 + paths: + - integrations/openclaw/plugin.mjs + - test/openclaw-plugin.test.ts + note: "DRAFT. OpenClaw terminal capture through llm_output/agent_end." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/860 + - number: 891 + title: "Hermes plugin: stable project scoping + close sessions on process exit" + kind: fix + relevance: low + in_fork: 1/1 + churn: 114 + paths: + - integrations/hermes/__init__.py + note: "Hermes project scoping under ephemeral worktrees, plus session close on exit." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/891 + - number: 914 + title: "Add configurable prompt output language" + kind: feature + relevance: low + in_fork: 6/8 + churn: 136 + paths: + - .env.example + - plugin/skills/agentmemory-config/REFERENCE.md + - src/prompts/compression.ts + - src/prompts/graph-extraction.ts + - src/prompts/reflect.ts + - src/prompts/summary.ts + note: "AGENTMEMORY_OUTPUT_LANGUAGE across compression/summary/graph/reflect prompts; overlaps #711." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/914 + - number: 920 + title: "feat(connect): add Qoder CLI CN adapter" + kind: host + relevance: low + in_fork: 1/5 + churn: 451 + paths: + - src/cli/connect/index.ts + note: "Qoder CLI CN connect adapter." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/920 + - number: 923 + title: "fly: Enhance Dockerfile with local embeddings installation" + kind: deploy + relevance: low + in_fork: 0/1 + churn: 7 + note: "Fly Dockerfile preloads local embedding weights." + disposition: wont-fix + wont_fix_reason: "deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/pull/923 + - number: 963 + title: "feat(providers): add configurable OpenRouter and Gemini base URLs" + kind: feature + relevance: low + in_fork: 8/12 + churn: 311 + paths: + - .env.example + - src/config.ts + - src/providers/embedding/gemini.ts + - src/providers/embedding/openrouter.ts + - src/providers/index.ts + - src/providers/openrouter.ts + - test/fallback-model-resolution.test.ts + - test/fetch-timeout.test.ts + note: "OPENROUTER_BASE_URL and GEMINI_BASE_URL, and splits Gemini into its own provider." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/963 + - number: 967 + title: "ci(deps)(deps): bump actions/checkout from 6 to 7" + kind: deps + relevance: low + in_fork: 1/2 + churn: 4 + paths: + - .github/workflows/ci.yml + note: "dependabot: actions/checkout 6 to 7." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/967 + - number: 1000 + title: "Add wire support for IBM Bob" + kind: host + relevance: low + in_fork: 1/3 + churn: 17 + paths: + - src/cli/connect/index.ts + note: "IBM Bob connect adapter." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1000 + - number: 1012 + title: "feat(hermes): capture tool calls individually and remove content truncation in sync_turn" + kind: fix + relevance: low + in_fork: 2/2 + churn: 123 + paths: + - integrations/hermes/__init__.py + - test/hermes-plugin.test.ts + note: "Hermes sync_turn truncates tool_input/tool_output and collapses tool calls." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1012 + - number: 1016 + title: "Support Codex pre-tool-use targets" + kind: host + relevance: low + draft: true + in_fork: 5/6 + churn: 433 + paths: + - plugin/hooks/hooks.codex.json + - plugin/scripts/pre-tool-use.mjs + - src/hooks/pre-tool-use.ts + - test/codex-connect-hooks.test.ts + - test/context-injection.test.ts + note: "DRAFT. Codex-native PreToolUse payload adaptation." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1016 + - number: 1049 + title: "feat: add Amp (Sourcegraph) integration with auto-capture plugin" + kind: host + relevance: low + in_fork: 3/8 + churn: 782 + paths: + - package.json + - src/cli/connect/index.ts + - test/cli-connect.test.ts + note: "Amp (Sourcegraph) integration with auto-capture plugin." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1049 + - number: 1053 + title: "deps(website)(deps-dev): bump typescript from 6.0.3 to 7.0.2 in /website" + kind: deps + relevance: low + in_fork: 1/1 + churn: 2 + paths: + - website/package.json + note: "dependabot: website typescript 6 to 7." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1053 + - number: 1055 + title: "feat: durable candidates MVP + scoped traceable recall + Codex archive watcher" + kind: feature + relevance: low + in_fork: 51/92 + churn: 7774 + paths: + - .env.example + - .gitignore + - package.json + - plugin/plugin.json + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/pre-tool-use.mjs + # +41 more + note: "Durable candidates MVP, traceable recall and a Codex archive watcher; 7.7k churn across 92 files." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1055 + - number: 1056 + title: "Update MiniMax provider defaults for MiniMax-M3" + kind: chore + relevance: low + in_fork: 7/8 + churn: 112 + paths: + - .env.example + - src/cli/onboarding.ts + - src/config.ts + - src/providers/index.ts + - src/providers/minimax.ts + - test/fallback-model-resolution.test.ts + - test/minimax-provider.test.ts + note: "MiniMax M3 defaults plus base-URL normalization; supersedes #1032, duplicates #818." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1056 + - number: 1076 + title: "docs(hermes): enable copied provider plugin" + kind: docs + relevance: low + draft: true + in_fork: 1/2 + churn: 10 + paths: + - integrations/hermes/README.md + note: "DRAFT. Documents the hermes plugins enable step." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1076 + - number: 1082 + title: "ci(deps)(deps): bump actions/setup-node from 6 to 7" + kind: deps + relevance: low + in_fork: 1/2 + churn: 4 + paths: + - .github/workflows/ci.yml + note: "dependabot: actions/setup-node 6 to 7." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1082 + - number: 1084 + title: "deps(deps-dev): bump typescript from 6.0.3 to 7.0.2" + kind: deps + relevance: low + in_fork: 1/1 + churn: 2 + paths: + - package.json + note: "dependabot: typescript 6 to 7." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1084 + - number: 1085 + title: "deps(deps-dev): bump @types/node from 25.9.5 to 26.1.1" + kind: deps + relevance: low + in_fork: 1/1 + churn: 2 + paths: + - package.json + note: "dependabot: @types/node 25 to 26." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1085 + - number: 1111 + title: "feat(providers): add Cloudflare Workers AI as an LLM and embedding provider" + kind: provider + relevance: low + in_fork: 12/17 + churn: 676 + paths: + - .env.example + - src/cli.ts + - src/cli/doctor-diagnostics.ts + - src/cli/onboarding.ts + - src/config.ts + - src/functions/consolidation-pipeline.ts + - src/functions/summarize.ts + - src/providers/embedding/index.ts + - src/providers/index.ts + - src/types.ts + # +2 more + note: "Cloudflare Workers AI as LLM and embedding provider." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1111 + - number: 1112 + title: "feat(cursor): workspace adapter on top of the marketplace plugin" + kind: host + relevance: low + in_fork: 2/20 + churn: 3972 + paths: + - .gitignore + - tsdown.config.ts + note: "Cursor workspace adapter; Cursor is not supported here." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1112 + - number: 1139 + title: "fix: make build and test suite pass on Windows" + kind: fix + relevance: low + in_fork: 6/7 + churn: 136 + paths: + - package.json + - test/cli-remove.test.ts + - test/compress-file.test.ts + - test/copilot-plugin.test.ts + - test/obsidian-export.test.ts + - test/slots-flag-gate.test.ts + note: "Cross-platform build script and Windows test fixes." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/pull/1139 + - number: 1147 + title: "fix(docs): sync REST endpoint counts + skills reference (unblocks CI on main)" + kind: docs + relevance: low + in_fork: 2/4 + churn: 8 + paths: + - plugin/skills/agentmemory-rest-api/REFERENCE.md + - src/index.ts + note: "Endpoint-count sync to unblock upstream CI." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1147 + - number: 1150 + title: "fix(cli): refresh Codex hooks when MCP is already wired" + kind: host + relevance: low + in_fork: 3/4 + churn: 169 + paths: + - plugin/skills/agentmemory-agents/REFERENCE.md + - plugin/skills/agentmemory-rest-api/REFERENCE.md + - test/codex-connect-hooks.test.ts + note: "connect codex --with-hooks skips hook install when MCP is already wired." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1150 + - number: 1164 + title: "feat: add docker-compose deployment and config for local embeddings" + kind: deploy + relevance: low + in_fork: 2/8 + churn: 229 + paths: + - src/index.ts + - src/providers/embedding/local.ts + note: "docker-compose deployment plus configurable local embedding model/dimensions." + disposition: wont-fix + wont_fix_reason: "deploy target this fork does not carry" + url: https://github.com/rohitg00/agentmemory/pull/1164 + - number: 1172 + title: "docs: document Novita AI as an OpenAI-compatible LLM provider" + kind: docs + relevance: low + in_fork: 7/9 + churn: 241 + paths: + - .env.example + - src/config.ts + - src/providers/_openai-shared.ts + - src/providers/index.ts + - src/providers/openai.ts + - test/fallback-model-resolution.test.ts + - test/openai-shared.test.ts + note: "Documents Novita AI as an OpenAI-compatible endpoint." + disposition: wont-fix + wont_fix_reason: "upstream doc/count sync or dependency bump" + url: https://github.com/rohitg00/agentmemory/pull/1172 + - number: 1185 + title: "fix(pi): scope memory_save memories to the current project" + kind: host + relevance: low + in_fork: 1/1 + churn: 2 + paths: + - integrations/pi/index.ts + note: "pi memory_save had no project, so its memories landed global." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1185 + - number: 1186 + title: "feat(pi): summarize and end the session on quit" + kind: host + relevance: low + in_fork: 1/1 + churn: 30 + paths: + - integrations/pi/index.ts + note: "pi never ended sessions, leaving zombies with no summary." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1186 + - number: 1206 + title: "feat(pi): observe per-tool results (PostToolUse parity)" + kind: host + relevance: low + in_fork: 1/1 + churn: 41 + paths: + - integrations/pi/index.ts + note: "pi per-tool observations for PostToolUse parity." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1206 + - number: 1207 + title: "feat(pi): robustness — client dedup, session/start, prompt_submit, larger turn capture" + kind: host + relevance: low + in_fork: 1/1 + churn: 52 + paths: + - integrations/pi/index.ts + note: "pi client-side dedup, session/start, prompt_submit, larger turn capture." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1207 + - number: 1222 + title: "feat: klaatcode support (cli adapter, native hooks)" + kind: host + relevance: low + in_fork: 19/25 + churn: 559 + paths: + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/prompt-submit.mjs + - plugin/scripts/session-end.mjs + - plugin/scripts/session-start.mjs + - plugin/scripts/subagent-start.mjs + - plugin/scripts/subagent-stop.mjs + # +9 more + note: "Klaat Code connect adapter and native hooks." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1222 + - number: 1227 + title: "fix(pi): attribute sessions to Pi cwd" + kind: host + relevance: low + in_fork: 2/2 + churn: 15 + paths: + - integrations/pi/index.ts + - test/connect-pi.test.ts + note: "pi attributes sessions to ctx.cwd." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1227 + - number: 1234 + title: "fix: reject state reads without keys" + kind: fix + relevance: low + in_fork: 1/2 + churn: 23 + paths: + - src/state/kv.ts + note: "StateKV rejects missing/empty keys before hitting the engine." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1234 + - number: 1248 + title: "feat: expose hook REST endpoints as MCP tools" + kind: feature + relevance: low + in_fork: 2/2 + churn: 407 + paths: + - src/mcp/server.ts + - src/mcp/tools-registry.ts + note: "Exposes 6 hook REST endpoints as MCP tools for hostless MCP clients." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1248 + - number: 1257 + title: "Project: Windows USB portable kit (in-tree + runtime pack)" + kind: feature + relevance: low + in_fork: 14/36 + churn: 1506 + paths: + - .gitignore + - plugin/scripts/notification.mjs + - plugin/scripts/post-commit.mjs + - plugin/scripts/post-tool-failure.mjs + - plugin/scripts/post-tool-use.mjs + - plugin/scripts/pre-compact.mjs + - plugin/scripts/pre-tool-use.mjs + - plugin/scripts/prompt-submit.mjs + - plugin/scripts/session-end.mjs + - plugin/scripts/session-start.mjs + # +4 more + note: "Windows USB portable kit under agentmemory-portable/." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/pull/1257 + - number: 1261 + title: "fix(test): point USERPROFILE at the temp home on Windows" + kind: test + relevance: low + in_fork: 1/1 + churn: 12 + paths: + - test/slots-flag-gate.test.ts + note: "Windows: point USERPROFILE at the temp home." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/pull/1261 + - number: 1262 + title: "fix(test): normalise fs mock paths so they match on Windows" + kind: test + relevance: low + in_fork: 2/2 + churn: 35 + paths: + - test/compress-file.test.ts + - test/obsidian-export.test.ts + note: "Windows: normalize fs mock paths." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/pull/1262 + - number: 1263 + title: "fix(test): drop POSIX-only assumptions from six suites" + kind: test + relevance: low + in_fork: 2/6 + churn: 30 + paths: + - test/cli-remove.test.ts + - test/copilot-plugin.test.ts + note: "Windows: drop POSIX assumptions from six suites." + disposition: wont-fix + wont_fix_reason: "Windows — CI runs ubuntu and macos only" + url: https://github.com/rohitg00/agentmemory/pull/1263 + - number: 1301 + title: "fix(opencode): dynamic project repository detection from tool execution and workspace paths" + kind: host + relevance: low + in_fork: 1/2 + churn: 511 + paths: + - plugin/opencode/agentmemory-capture.ts + note: "OpenCode resolves the project directory once at startup and stays locked to it." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1301 + - number: 1320 + title: "feat: Kimi Code CLI plugin support" + kind: host + relevance: low + in_fork: 0/3 + churn: 103 + note: "Kimi Code CLI plugin manifest." + disposition: wont-fix + wont_fix_reason: "no connect adapter for this host in src/cli/connect/" + url: https://github.com/rohitg00/agentmemory/pull/1320 + - number: 1355 + title: "feat: add Requesty provider (chat + embeddings)" + kind: provider + relevance: low + in_fork: 17/32 + churn: 469 + paths: + - .env.example + - src/cli.ts + - src/cli/doctor-diagnostics.ts + - src/cli/onboarding.ts + - src/config.ts + - src/functions/consolidation-pipeline.ts + - src/functions/summarize.ts + - src/providers/embedding/index.ts + - src/providers/index.ts + - src/types.ts + # +7 more + note: "Requesty router as LLM and embedding provider." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1355 + - number: 1356 + title: "mcp-http: per-request agent attribution for the shared bridge" + kind: feature + relevance: low + in_fork: 57/100 + churn: 18717 + paths: + - .env.example + - .github/workflows/ci.yml + - assets/tags/light/stat-tools.svg + - assets/tags/stat-tools.svg + - benchmark/README.md + - integrations/hermes/README.md + - integrations/hermes/__init__.py + - integrations/openclaw/README.md + - integrations/openclaw/plugin.mjs + - integrations/pi/README.md + # +47 more + note: "Per-request agent attribution on the shared Streamable HTTP MCP bridge; 18.7k churn across 100 files." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1356 + - number: 1357 + title: "fix(cli): stop interpolating $HOME-derived paths into the iii installer shell command" + kind: fix + relevance: low + in_fork: 1/2 + churn: 125 + paths: + - src/cli.ts + note: "Shell injection through $HOME-derived paths in the iii installer command; this fork has no iii installer." + disposition: wont-fix + wont_fix_reason: "no iii engine here" + url: https://github.com/rohitg00/agentmemory/pull/1357 + - number: 1375 + title: "feat: add OrcaRouter as a first-class provider with API-key and OAuth 2.0 + PKCE login" + kind: provider + relevance: low + in_fork: 16/33 + churn: 6469 + paths: + - .env.example + - .gitignore + - package.json + - plugin/skills/agentmemory-rest-api/REFERENCE.md + - src/cli.ts + - src/cli/onboarding.ts + - src/config.ts + - src/index.ts + - src/providers/embedding/index.ts + - src/providers/index.ts + # +6 more + note: "OrcaRouter as a first-class provider with OAuth 2.0 + PKCE login." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1375 + - number: 1376 + title: "feat(providers): dedicated opencode provider for OpenCode Go relay" + kind: provider + relevance: low + in_fork: 4/7 + churn: 246 + paths: + - src/config.ts + - src/providers/index.ts + - src/providers/openai.ts + - src/types.ts + note: "Dedicated provider for the OpenCode Go relay, which requires an x-opencode-session header." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1376 + - number: 1380 + title: "deps(website)(deps-dev): bump @types/node from 25.9.8 to 26.6.1 in /website" + kind: deps + relevance: low + in_fork: 1/1 + churn: 2 + paths: + - website/package.json + note: "dependabot: website @types/node 25 to 26." + disposition: candidate + url: https://github.com/rohitg00/agentmemory/pull/1380 From 01bd9e36a2fe2ec12d76a85f992fe619974ad164 Mon Sep 17 00:00:00 2001 From: neal Date: Tue, 22 Sep 2026 06:36:46 -0400 Subject: [PATCH 05/10] docs: define Session Summary in the glossary Generated-By: Claude Fable 5.1 --- CONTEXT.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CONTEXT.md b/CONTEXT.md index f95c59a16e..4e2d717a76 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -33,6 +33,12 @@ A durable distilled record derived from Observations, intended to be recalled la are content-addressed, so the same content captured twice is one Memory. _Avoid_: note, fact, item +**Session Summary**: +The distilled account of one Session, produced from its Observations at the Session's end. +A Session Summary is current until an Observation arrives after it was written, and a +current one is reused rather than reproduced. +_Avoid_: session digest, recap + **Entity**: A named thing the Agent worked with — a file, a symbol, a service, a concept — held as a node in the graph. From 22ccb000f821b11187b522318421159a0f092a7b Mon Sep 17 00:00:00 2001 From: neal Date: Tue, 22 Sep 2026 06:39:04 -0400 Subject: [PATCH 06/10] fix(summarize): take the no-op early exit behind the resilient wrapper Every provider is wrapped as resilient(), so the === "noop" check never matched and a keyless install ran the whole summarize pipeline. One predicate looks through the wrapper; summarize and graph Extraction both use it. Closes #32. Refs #31, #1367. Generated-By: Claude Fable 5.1 --- src/functions/graph.ts | 3 +- src/functions/summarize.ts | 3 +- src/providers/noop.ts | 8 ++ test/graph-heuristic-extract.test.ts | 2 +- test/noop-provider-predicate.test.ts | 125 +++++++++++++++++++++++++++ 5 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 test/noop-provider-predicate.test.ts diff --git a/src/functions/graph.ts b/src/functions/graph.ts index bedd1d73f2..0d1c6c35f2 100644 --- a/src/functions/graph.ts +++ b/src/functions/graph.ts @@ -29,6 +29,7 @@ import { buildGraphExtractionPrompt, } from "../prompts/graph-extraction.js"; import { isGraphExtractionEnabled } from "../config.js"; +import { isNoopProvider } from "../providers/noop.js"; import { capSourceIds } from "./graph-provenance.js"; import { recordAudit } from "./audit.js"; import { logger } from "../logger.js"; @@ -923,7 +924,7 @@ export function registerGraphFunction( } const llmEnabled = - isGraphExtractionEnabled() && !provider.name.includes("noop"); + isGraphExtractionEnabled() && !isNoopProvider(provider); let llmError: string | undefined; if (llmEnabled) { const prompt = buildGraphExtractionPrompt( diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts index 2a5c75088a..40658b089b 100644 --- a/src/functions/summarize.ts +++ b/src/functions/summarize.ts @@ -19,6 +19,7 @@ import { validateOutput } from "../eval/validator.js"; import { scoreSummary } from "../eval/quality.js"; import type { MetricsStore } from "../eval/metrics-store.js"; import { safeAudit } from "./audit.js"; +import { isNoopProvider } from "../providers/noop.js"; import { logger } from "../logger.js"; // Per-chunk observation budget when a session is too large to fit in one @@ -260,7 +261,7 @@ export function registerSummarizeFunction( return { success: false, error: "no_observations" }; } - if (provider.name === "noop") { + if (isNoopProvider(provider)) { logger.info("Summarize skipped — no LLM provider configured", { sessionId, }); diff --git a/src/providers/noop.ts b/src/providers/noop.ts index 6e74f9aa75..7ce1639f5a 100644 --- a/src/providers/noop.ts +++ b/src/providers/noop.ts @@ -18,3 +18,11 @@ export class NoopProvider implements MemoryProvider { return ""; } } + +/** + * Every provider is wrapped as `resilient()`, so callers must look + * through the wrapper rather than compare against "noop" directly. + */ +export function isNoopProvider(provider: Pick): boolean { + return /^(?:resilient\()*noop\)*$/.test(provider.name); +} diff --git a/test/graph-heuristic-extract.test.ts b/test/graph-heuristic-extract.test.ts index e56a2ae3e5..118674df89 100644 --- a/test/graph-heuristic-extract.test.ts +++ b/test/graph-heuristic-extract.test.ts @@ -115,7 +115,7 @@ describe("keyless graph extraction wiring", () => { const graph = readFileSync("src/functions/graph.ts", "utf-8"); expect(graph).toMatch(/extractGraphHeuristics\(data\.observations\)/); expect(graph).toMatch( - /isGraphExtractionEnabled\(\) && !provider\.name\.includes\("noop"\)/, + /isGraphExtractionEnabled\(\) && !isNoopProvider\(provider\)/, ); }); }); diff --git a/test/noop-provider-predicate.test.ts b/test/noop-provider-predicate.test.ts new file mode 100644 index 0000000000..84cdc26bf7 --- /dev/null +++ b/test/noop-provider-predicate.test.ts @@ -0,0 +1,125 @@ +import { describe, it, expect, vi } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +vi.mock("../src/state/schema.js", () => ({ + KV: { + sessions: "sessions", + summaries: "summaries", + observations: (sessionId: string) => `obs:${sessionId}`, + audit: "audit", + }, +})); + +vi.mock("../src/eval/schemas.js", () => ({ SummaryOutputSchema: {} })); +vi.mock("../src/eval/validator.js", () => ({ + validateOutput: () => ({ valid: true, result: { errors: [] } }), +})); +vi.mock("../src/eval/quality.js", () => ({ scoreSummary: () => 100 })); +vi.mock("../src/functions/audit.js", () => ({ safeAudit: vi.fn() })); + +import { isNoopProvider, NoopProvider } from "../src/providers/noop.js"; +import { ResilientProvider } from "../src/providers/resilient.js"; +import { registerSummarizeFunction } from "../src/functions/summarize.js"; +import type { MemoryProvider, Session, CompressedObservation } from "../src/types.js"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => + (store.get(scope)?.get(key) as T) ?? null, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async () => {}, + list: async (scope: string): Promise => + Array.from(store.get(scope)?.values() ?? []) as T[], + }; +} + +function mockSdk() { + const functions = new Map(); + return { + functions, + registerFunction: (id: string, handler: Function) => { + functions.set(id, handler); + }, + registerTrigger: () => {}, + trigger: async () => ({}), + }; +} + +function namedProvider(name: string) { + const calls: string[] = []; + const provider: MemoryProvider & { calls: string[] } = { + name, + calls, + compress: async () => { + calls.push("compress"); + return ""; + }, + summarize: async () => { + calls.push("summarize"); + return ""; + }, + }; + return provider; +} + +describe("isNoopProvider", () => { + it("matches the bare no-op provider", () => { + expect(isNoopProvider(new NoopProvider())).toBe(true); + }); + + it("matches the no-op provider inside the resilient wrapper", () => { + expect(isNoopProvider(new ResilientProvider(new NoopProvider()))).toBe(true); + expect(isNoopProvider(namedProvider("resilient(noop)"))).toBe(true); + }); + + it("rejects real providers and chains that merely contain a no-op", () => { + expect(isNoopProvider(namedProvider("resilient(openai)"))).toBe(false); + expect(isNoopProvider(namedProvider("resilient(fallback(noop -> agent-sdk))"))).toBe(false); + expect(isNoopProvider(namedProvider("noopish"))).toBe(false); + }); +}); + +describe("mem::summarize with a wrapped no-op provider", () => { + it("returns no_provider without calling the provider", async () => { + const sdk = mockSdk(); + const kv = mockKV(); + const sessionId = "ses_keyless"; + const session: Session = { + id: sessionId, + project: "p", + cwd: "/tmp", + startedAt: new Date().toISOString(), + status: "completed", + observationCount: 1, + }; + await kv.set("sessions", sessionId, session); + const obs: CompressedObservation = { + id: "obs_0", + sessionId, + timestamp: new Date().toISOString(), + type: "conversation", + title: "obs 0", + facts: [], + narrative: "n", + concepts: [], + files: [], + importance: 5, + }; + await kv.set(`obs:${sessionId}`, obs.id, obs); + + const provider = namedProvider("resilient(noop)"); + registerSummarizeFunction(sdk as any, kv as any, provider); + const result = await sdk.functions.get("mem::summarize")!({ sessionId }); + + expect(result).toMatchObject({ success: false, error: "no_provider" }); + expect(provider.calls).toEqual([]); + }); +}); From bac54573d3bd0cebab7b45e17b0fefb193a6f901 Mon Sep 17 00:00:00 2001 From: neal Date: Tue, 22 Sep 2026 06:43:49 -0400 Subject: [PATCH 07/10] fix(summarize): pack chunks by measured tokens against a 50k budget Chunks were cut at a fixed 400 Observations, but per-Observation size varies 9x across the store, so a capped Session could exceed the broker's practical latency and time out. Observations are now measured with the provider's tokenize route (llama.cpp-style POST /tokenize, forwarded outside the circuit breaker) and estimated at chars/3 when there is none, then packed in order to SUMMARIZE_CHUNK_TOKENS (default 50,000) with the system prompt's overhead reserved. SUMMARIZE_CHUNK_SIZE is gone. The chunk concurrency default drops from 6 to 2: it was tuned for iii's 180s cap, and the timeout basis is measured at 2 on one GPU. Closes #33. Refs #31. Generated-By: Claude Fable 5.1 --- .env.example | 4 +- src/functions/summarize.ts | 149 +++++++++++++++++++++++++------ src/prompts/summary.ts | 16 ++-- src/providers/agent-sdk.ts | 2 +- src/providers/fallback-chain.ts | 6 ++ src/providers/openai.ts | 25 ++++++ src/providers/resilient.ts | 6 ++ src/types.ts | 1 + test/openai-count-tokens.test.ts | 66 ++++++++++++++ test/summarize.test.ts | 99 +++++++++++++++++--- 10 files changed, 327 insertions(+), 47 deletions(-) create mode 100644 test/openai-count-tokens.test.ts diff --git a/.env.example b/.env.example index 2e14d7941c..1a1c5c6c3a 100644 --- a/.env.example +++ b/.env.example @@ -119,8 +119,8 @@ # AGENTMEMORY_GRAPH_WEIGHT=0.2 # Graph traversal bonus on smart-search ranking # TOKEN_BUDGET=2000 # Max tokens injected via mem::context per session # MAX_OBS_PER_SESSION=500 # Per-session observation cap before consolidation kicks in -# SUMMARIZE_CHUNK_SIZE=400 # When mem::summarize sees a session larger than this, it chunks observations and map-reduces (chunk-summarize → reduce-merge) to stay within the LLM's context window. Default 400 ≈ 50k tokens per chunk at ~110 tok/obs. Native sessions are capped by MAX_OBS_PER_SESSION; chunking primarily matters for bulk-imported jsonl sessions, which bypass that cap. -# SUMMARIZE_CHUNK_CONCURRENCY=6 # Parallel chunk LLM calls during chunked summarize. Default 6 fits ~100-chunk sessions under iii's 180s function-invocation timeout at typical ~8s/call. High-throughput providers (Novita, DeepInfra, DeepSeek) commonly allow 100+ concurrent — bump this for very large imported sessions. +# SUMMARIZE_CHUNK_TOKENS=50000 # Prompt-token budget per chunk when mem::summarize map-reduces a large session (chunk-summarize → reduce-merge). Observations are measured with the provider's tokenize route when it has one (llama.cpp-style POST /tokenize) and estimated at chars/3 otherwise; the ~400-token system prompt is reserved inside this budget. A 50k chunk summarizes cold in 60–89s on a local 35B model. +# SUMMARIZE_CHUNK_CONCURRENCY=2 # Parallel chunk LLM calls during chunked summarize. A local broker serialises chunks on one GPU, so more concurrency only stretches each call: AGENTMEMORY_LLM_TIMEOUT_MS is sized for 2. Raise it for hosted providers that run chunks in parallel, and re-measure the timeout if you do. # --- Retrieval ranking ------------------------------------------------- # Every flag below defaults to the historical behaviour. Turn them on one diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts index 40658b089b..9d838249f5 100644 --- a/src/functions/summarize.ts +++ b/src/functions/summarize.ts @@ -10,6 +10,7 @@ import { StateKV } from "../state/kv.js"; import { SUMMARY_SYSTEM, buildSummaryPrompt, + renderSummaryObservation, REDUCE_SYSTEM, buildReducePrompt, } from "../prompts/summary.js"; @@ -22,26 +23,28 @@ import { safeAudit } from "./audit.js"; import { isNoopProvider } from "../providers/noop.js"; import { logger } from "../logger.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 -// comfortably in 128k-window models. Override via SUMMARIZE_CHUNK_SIZE. -const CHUNK_SIZE_DEFAULT = 400; -// Concurrent in-flight chunk calls. 6 keeps a 100-chunk session under -// iii's 180s function-invocation timeout at ~8s/call while staying -// inside generous-but-not-unlimited provider rate limits (well below -// OpenAI free tier's 500 RPM). High-throughput providers -// (Novita / DeepInfra / DeepSeek) typically allow 100+ concurrent — set -// SUMMARIZE_CHUNK_CONCURRENCY higher to cover ~1000+ chunk sessions. -const CHUNK_CONCURRENCY_DEFAULT = 6; +// Per-chunk prompt budget in tokens when a Session is too large to fit in +// one LLM call. Measured on the Operator's broker: a 50k-token chunk +// summarizes cold in 60–89s solo. Override via SUMMARIZE_CHUNK_TOKENS. +const CHUNK_TOKENS_DEFAULT = 50_000; +// Tokens the system prompt and chat template add on top of the rendered +// Observations, measured on the Operator's broker. +const PROMPT_OVERHEAD_TOKENS = 400; +// Concurrent in-flight chunk calls. The Operator's broker serialises chunks +// on one GPU, and AGENTMEMORY_LLM_TIMEOUT_MS was measured at 2 — raise +// SUMMARIZE_CHUNK_CONCURRENCY only with the timeout re-measured. +const CHUNK_CONCURRENCY_DEFAULT = 2; +// Parallel tokenize calls while measuring a Session's Observations. +const COUNT_CONCURRENCY = 16; // Bail on the merged summary if more than this fraction of chunks fail // to parse — a half-blind narrative is worse than a clean error. const MAX_SKIP_RATIO = 0.5; -function getChunkSize(): number { - const raw = process.env.SUMMARIZE_CHUNK_SIZE; - if (!raw) return CHUNK_SIZE_DEFAULT; +function getChunkTokens(): number { + const raw = process.env.SUMMARIZE_CHUNK_TOKENS; + if (!raw) return CHUNK_TOKENS_DEFAULT; const n = parseInt(raw, 10); - return Number.isFinite(n) && n > 0 ? n : CHUNK_SIZE_DEFAULT; + return Number.isFinite(n) && n > 0 ? n : CHUNK_TOKENS_DEFAULT; } function getChunkConcurrency(): number { @@ -51,6 +54,83 @@ function getChunkConcurrency(): number { return Number.isFinite(n) && n > 0 ? n : CHUNK_CONCURRENCY_DEFAULT; } +// The estimate idiom this tree already uses; it overcounts measured +// content by ~17%, the safe direction for a budget. +function estimateTokens(text: string): number { + return Math.ceil(text.length / 3); +} + +async function mapWithConcurrency( + items: T[], + concurrency: number, + fn: (item: T) => Promise, +): Promise { + const out: R[] = new Array(items.length); + for (let start = 0; start < items.length; start += concurrency) { + const batch = items.slice(start, start + concurrency); + const results = await Promise.all(batch.map(fn)); + results.forEach((r, j) => { + out[start + j] = r; + }); + } + return out; +} + +async function countObservationTokens( + provider: MemoryProvider, + texts: string[], + sessionId: string, +): Promise { + if (provider.countTokens) { + try { + return await mapWithConcurrency(texts, COUNT_CONCURRENCY, (t) => + provider.countTokens!(t), + ); + } catch (err) { + logger.warn("Token count failed, packing chunks by estimate", { + sessionId, + error: err instanceof Error ? err.message : String(err), + }); + } + } + return texts.map(estimateTokens); +} + +// Greedy in-order packing. An Observation that alone exceeds the budget +// becomes its own chunk: dropping it would lose Session history, and the +// provider's own context error is the right failure for that chunk. +function packChunks( + compressed: CompressedObservation[], + counts: number[], + budget: number, + sessionId: string, +): CompressedObservation[][] { + const payloadBudget = budget - PROMPT_OVERHEAD_TOKENS; + const chunks: CompressedObservation[][] = []; + let current: CompressedObservation[] = []; + let used = 0; + compressed.forEach((obs, i) => { + const tokens = counts[i] ?? 0; + if (current.length > 0 && used + tokens > payloadBudget) { + chunks.push(current); + current = []; + used = 0; + } + if (tokens > payloadBudget) { + logger.warn("Observation exceeds the chunk budget on its own", { + sessionId, + observationId: obs.id, + tokens, + budget, + }); + } + current.push(obs); + used += tokens; + }); + if (current.length > 0) chunks.push(current); + return chunks; +} + // One chunk call with retry-once. Returns null when both attempts fail — // whether by parse failure, provider 4xx (content rejected by upstream // filters), or transient network/5xx errors that didn't recover on retry. @@ -91,9 +171,9 @@ async function summarizeChunkWithRetry( return null; } -// Returns the final summary XML string. For sessions ≤ chunk size, this is -// a single LLM call (legacy behavior). For larger sessions, observations -// are split into chunks processed in parallel batches, each chunk retried +// Returns the final summary XML string. For sessions that fit the token +// budget, this is a single LLM call. For larger sessions, observations +// are packed into chunks processed in parallel batches, each chunk retried // once on parse failure, persistently-bad chunks skipped, and remaining // partials merged via a reduce call. async function produceSummaryXml( @@ -107,8 +187,21 @@ async function produceSummaryXml( chunks: number; skipped?: number; }> { - const chunkSize = getChunkSize(); - if (compressed.length <= chunkSize) { + const budget = getChunkTokens(); + const texts = compressed.map(renderSummaryObservation); + // The estimate never undercounts, so a Session that fits by estimate is + // summarized in one call without a tokenize round trip. + const estimated = texts.reduce((n, t) => n + estimateTokens(t), 0); + const chunks = + estimated + PROMPT_OVERHEAD_TOKENS <= budget + ? [compressed] + : packChunks( + compressed, + await countObservationTokens(provider, texts, sessionId), + budget, + sessionId, + ); + if (chunks.length === 1) { const response = await provider.summarize( SUMMARY_SYSTEM, buildSummaryPrompt(compressed), @@ -116,15 +209,11 @@ async function produceSummaryXml( return { response, mode: "single", chunks: 1 }; } - const chunks: CompressedObservation[][] = []; - for (let i = 0; i < compressed.length; i += chunkSize) { - chunks.push(compressed.slice(i, i + chunkSize)); - } const concurrency = getChunkConcurrency(); logger.info("Summarize chunking session", { sessionId, chunks: chunks.length, - chunkSize, + budget, concurrency, totalObservations: compressed.length, }); @@ -166,16 +255,22 @@ async function produceSummaryXml( }); } + const chunkStarts: number[] = []; + chunks.reduce((offset, chunk) => { + chunkStarts.push(offset); + return offset + chunk.length; + }, 0); const reduceInput = partials.map((p) => { const originalIdx = partialByIdx.indexOf(p); + const start = chunkStarts[originalIdx] ?? 0; return { title: p.title, narrative: p.narrative, keyDecisions: p.keyDecisions, filesModified: p.filesModified, concepts: p.concepts, - obsRangeStart: originalIdx * chunkSize + 1, - obsRangeEnd: Math.min((originalIdx + 1) * chunkSize, compressed.length), + obsRangeStart: start + 1, + obsRangeEnd: start + chunks[originalIdx]!.length, }; }); const response = await provider.summarize( diff --git a/src/prompts/summary.ts b/src/prompts/summary.ts index bd04021277..fe3db33695 100644 --- a/src/prompts/summary.ts +++ b/src/prompts/summary.ts @@ -22,18 +22,22 @@ Rules: - List all files that were created or modified - Concepts should be searchable terms for future context retrieval` -export function buildSummaryPrompt(observations: Array<{ +export interface SummaryObservation { type: string title: string facts: string[] narrative: string files: string[] concepts: string[] -}>): string { - const lines = observations.map((obs, i) => { - const facts = obs.facts.map((f) => ` - ${f}`).join('\n') - return `[${i + 1}] ${obs.type}: ${obs.title}\n${obs.narrative}\nFacts:\n${facts}\nFiles: ${obs.files.join(', ')}` - }) +} + +export function renderSummaryObservation(obs: SummaryObservation, index: number): string { + const facts = obs.facts.map((f) => ` - ${f}`).join('\n') + return `[${index + 1}] ${obs.type}: ${obs.title}\n${obs.narrative}\nFacts:\n${facts}\nFiles: ${obs.files.join(', ')}` +} + +export function buildSummaryPrompt(observations: SummaryObservation[]): string { + const lines = observations.map(renderSummaryObservation) return `Session observations (${observations.length} total):\n\n${lines.join('\n\n---\n\n')}` } diff --git a/src/providers/agent-sdk.ts b/src/providers/agent-sdk.ts index 7d65685df8..37c8fc1c79 100644 --- a/src/providers/agent-sdk.ts +++ b/src/providers/agent-sdk.ts @@ -40,7 +40,7 @@ let sdkOriginalEnv: string | undefined // observation into a child, and children that wedge ignore SIGTERM. Cap // the number that may exist at a time. Callers over the cap wait for a // slot rather than being refused, because legitimate concurrency here is -// the chunked summarize fan-out (SUMMARIZE_CHUNK_CONCURRENCY, default 6) +// the chunked summarize fan-out (SUMMARIZE_CHUNK_CONCURRENCY, default 2) // and refusing those chunks would trip the skip-ratio bailout and lose // the whole summary. const MAX_CONCURRENT_DEFAULT = 2 diff --git a/src/providers/fallback-chain.ts b/src/providers/fallback-chain.ts index e2c979f929..da8352f77c 100644 --- a/src/providers/fallback-chain.ts +++ b/src/providers/fallback-chain.ts @@ -2,9 +2,15 @@ import type { MemoryProvider } from "../types.js"; export class FallbackChainProvider implements MemoryProvider { name: string; + // Counts follow the primary: that is the model the text is chunked for. + countTokens?: (text: string) => Promise; constructor(private providers: MemoryProvider[]) { this.name = `fallback(${providers.map((p) => p.name).join(" -> ")})`; + const primary = providers[0]; + if (primary?.countTokens) { + this.countTokens = (text) => primary.countTokens!(text); + } } async compress(systemPrompt: string, userPrompt: string): Promise { diff --git a/src/providers/openai.ts b/src/providers/openai.ts index 31ee158ebc..b4a019582b 100644 --- a/src/providers/openai.ts +++ b/src/providers/openai.ts @@ -11,6 +11,7 @@ import { const DEFAULT_MODEL = "gpt-5.6-luna"; const DEFAULT_TIMEOUT_MS = 60_000; +const TOKENIZE_TIMEOUT_MS = 10_000; /** * OpenAI-compatible LLM provider. @@ -75,6 +76,30 @@ export class OpenAIProvider implements MemoryProvider { return this.call(systemPrompt, userPrompt); } + // llama.cpp-style servers expose POST /tokenize at the server root, beside + // /v1. Anything without it answers non-2xx and the caller falls back to an + // estimate, so a count never blocks the work it measures. + async countTokens(text: string): Promise { + const url = `${this.baseUrl.replace(/\/v1$/, "")}/tokenize`; + const response = await fetchWithTimeout( + url, + { + method: "POST", + headers: buildAuthHeaders(this.apiKey, this.isAzure), + body: JSON.stringify({ model: this.model, content: text }), + }, + TOKENIZE_TIMEOUT_MS, + ); + if (!response.ok) { + throw new Error(`tokenize error (${response.status}) at ${url}`); + } + const data = (await response.json()) as { tokens?: unknown[] }; + if (!Array.isArray(data.tokens)) { + throw new Error(`tokenize returned no token array from ${url}`); + } + return data.tokens.length; + } + private async call(systemPrompt: string, userPrompt: string): Promise { const url = buildChatUrl(this.baseUrl, this.isAzure, this.azureApiVersion); const body: Record = { diff --git a/src/providers/resilient.ts b/src/providers/resilient.ts index 95ece40c96..c3778513c1 100644 --- a/src/providers/resilient.ts +++ b/src/providers/resilient.ts @@ -4,9 +4,15 @@ import { CircuitBreaker } from "./circuit-breaker.js"; export class ResilientProvider implements MemoryProvider { private breaker = new CircuitBreaker(); name: string; + // A failed count is a fallback for the caller, not a provider failure, + // so it is forwarded outside the breaker. + countTokens?: (text: string) => Promise; constructor(private inner: MemoryProvider) { this.name = `resilient(${inner.name})`; + if (inner.countTokens) { + this.countTokens = (text) => inner.countTokens!(text); + } } private async call(fn: () => Promise): Promise { diff --git a/src/types.ts b/src/types.ts index bc26bb17a8..c4b5410e05 100644 --- a/src/types.ts +++ b/src/types.ts @@ -187,6 +187,7 @@ export interface MemoryProvider { compress(systemPrompt: string, userPrompt: string): Promise; summarize(systemPrompt: string, userPrompt: string): Promise; describeImage?(imageData: string, mimeType: string, prompt: string): Promise; + countTokens?(text: string): Promise; } export interface AgentMemoryConfig { diff --git a/test/openai-count-tokens.test.ts b/test/openai-count-tokens.test.ts new file mode 100644 index 0000000000..b1f3cbd487 --- /dev/null +++ b/test/openai-count-tokens.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { OpenAIProvider } from "../src/providers/openai.js"; +import { ResilientProvider } from "../src/providers/resilient.js"; +import type { MemoryProvider } from "../src/types.js"; + +function jsonResponse(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +describe("OpenAIProvider.countTokens", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("posts the configured model and text to the broker's tokenize route and returns the token count", async () => { + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(jsonResponse(200, { tokens: [1, 2, 3, 4, 5] })); + const provider = new OpenAIProvider("key", "general", 4096, "http://broker:4010/v1"); + + const count = await provider.countTokens("hello world"); + + expect(count).toBe(5); + const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]; + expect(url).toBe("http://broker:4010/tokenize"); + expect(JSON.parse(init.body as string)).toEqual({ model: "general", content: "hello world" }); + }); + + it("throws on a non-2xx answer so the caller falls back to the estimate", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue(jsonResponse(404, { error: "no such route" })); + const provider = new OpenAIProvider("key", "gpt-4o", 4096, "https://api.openai.com"); + + await expect(provider.countTokens("hello")).rejects.toThrow(/404/); + }); +}); + +describe("ResilientProvider.countTokens", () => { + it("forwards the inner count without touching the circuit breaker", async () => { + const inner: MemoryProvider = { + name: "inner", + compress: async () => "", + summarize: async () => "", + countTokens: async () => { + throw new Error("tokenize down"); + }, + }; + const resilient = new ResilientProvider(inner); + + await expect(resilient.countTokens!("x")).rejects.toThrow("tokenize down"); + await expect(resilient.countTokens!("x")).rejects.toThrow("tokenize down"); + await expect(resilient.countTokens!("x")).rejects.toThrow("tokenize down"); + expect(resilient.circuitState).toMatchObject({ state: "closed", failures: 0 }); + }); + + it("is absent when the inner provider cannot count", () => { + const inner: MemoryProvider = { + name: "inner", + compress: async () => "", + summarize: async () => "", + }; + expect(new ResilientProvider(inner).countTokens).toBeUndefined(); + }); +}); diff --git a/test/summarize.test.ts b/test/summarize.test.ts index 4723da8781..097b20c5a8 100644 --- a/test/summarize.test.ts +++ b/test/summarize.test.ts @@ -84,6 +84,12 @@ function makeObs(i: number, sessionId: string): CompressedObservation { }; } +// Fake count: every Observation is TOKENS_PER_OBS tokens, so a budget of +// PROMPT_OVERHEAD + n * TOKENS_PER_OBS packs exactly n Observations per chunk. +const TOKENS_PER_OBS = 10; +const PROMPT_OVERHEAD = 400; +const budgetFor = (obsPerChunk: number) => String(PROMPT_OVERHEAD + obsPerChunk * TOKENS_PER_OBS); + function makeProvider(responses: string[]): MemoryProvider & { calls: Array<{ system: string; user: string }>; } { @@ -93,6 +99,7 @@ function makeProvider(responses: string[]): MemoryProvider & { name: "test", calls, compress: async () => "", + countTokens: async () => TOKENS_PER_OBS, summarize: async (system: string, user: string) => { calls.push({ system, user }); const r = responses[i] ?? responses[responses.length - 1]; @@ -150,7 +157,7 @@ describe("mem::summarize chunking", () => { const ORIGINAL_ENV = { ...process.env }; beforeEach(() => { - delete process.env.SUMMARIZE_CHUNK_SIZE; + delete process.env.SUMMARIZE_CHUNK_TOKENS; delete process.env.SUMMARIZE_CHUNK_CONCURRENCY; }); @@ -183,7 +190,7 @@ describe("mem::summarize chunking", () => { }); it("large session map-reduces: N chunk calls + 1 reduce call", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; // serial keeps call ordering deterministic const provider = makeProvider([ summaryXml({ title: "Chunk 1", decisions: ["dA"], files: ["src/a.ts"], concepts: ["ca"] }), @@ -222,8 +229,8 @@ describe("mem::summarize chunking", () => { expect(stored?.keyDecisions).toEqual(["dA", "dB", "dC"]); }); - it("SUMMARIZE_CHUNK_SIZE env override is respected", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "50"; + it("SUMMARIZE_CHUNK_TOKENS env override is respected", async () => { + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(50); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; const provider = makeProvider([ summaryXml({ title: "chunk" }), @@ -246,7 +253,7 @@ describe("mem::summarize chunking", () => { }); it("flaky chunk: parse fails once, retried, then succeeds — no skip", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; const provider = makeProvider([ summaryXml({ title: "ok1" }), @@ -271,7 +278,7 @@ describe("mem::summarize chunking", () => { }); it("persistently-broken chunk is skipped, reduce still runs on remaining partials", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; const provider = makeProvider([ summaryXml({ title: "ok1" }), @@ -303,7 +310,7 @@ describe("mem::summarize chunking", () => { }); it("too many skipped chunks bails out with a clear error", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; // 3 chunks, 2 fully broken → >50% skipped → bail. const provider = makeProvider([ @@ -324,13 +331,14 @@ describe("mem::summarize chunking", () => { }); it("provider error on one chunk after retry is skipped, not propagated", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; let i = 0; const provider: MemoryProvider & { calls: any[] } = { name: "test", calls: [], compress: async () => "", + countTokens: async () => TOKENS_PER_OBS, summarize: async (system: string, user: string) => { (provider as any).calls.push({ system, user }); i += 1; @@ -357,13 +365,14 @@ describe("mem::summarize chunking", () => { }); it("every chunk failing on provider error trips too_many_chunks_skipped", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; // 3 chunks, all chunk calls throw → 3/3 skipped → bail. const provider: MemoryProvider & { calls: any[] } = { name: "test", calls: [], compress: async () => "", + countTokens: async () => TOKENS_PER_OBS, summarize: async (system: string, user: string) => { (provider as any).calls.push({ system, user }); throw new Error("OpenAI API error (400): invalid request"); @@ -382,7 +391,7 @@ describe("mem::summarize chunking", () => { }); it("chunks run in parallel batches according to SUMMARIZE_CHUNK_CONCURRENCY", async () => { - process.env.SUMMARIZE_CHUNK_SIZE = "100"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(100); process.env.SUMMARIZE_CHUNK_CONCURRENCY = "2"; let inflight = 0; let maxInflight = 0; @@ -403,7 +412,7 @@ describe("mem::summarize chunking", () => { }; const { handler } = await setupHandler({ sessionId: "ses_par", - obsCount: 400, // 4 chunks at chunkSize=100 + obsCount: 400, // 4 chunks of 100 Observations provider, }); @@ -415,6 +424,74 @@ describe("mem::summarize chunking", () => { expect(maxInflight).toBe(2); }); + it("packs Observations by measured tokens: every chunk fits the budget, order kept", async () => { + process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; + process.env.SUMMARIZE_CHUNK_TOKENS = String(PROMPT_OVERHEAD + 250); + const calls: string[] = []; + // One token per character makes the prompt text its own measure. + const provider: MemoryProvider = { + name: "test", + compress: async () => "", + countTokens: async (text: string) => text.length, + summarize: async (system: string, user: string) => { + calls.push(user); + return summaryXml({ title: system.includes("merging") ? "merged" : "chunk" }); + }, + }; + const { handler } = await setupHandler({ sessionId: "ses_tok", obsCount: 12, provider }); + + const result: any = await handler({ sessionId: "ses_tok" }); + + expect(result.success).toBe(true); + const chunkPrompts = calls.slice(0, -1); + expect(chunkPrompts.length).toBeGreaterThan(1); + const seen: number[] = []; + for (const prompt of chunkPrompts) { + const bodies = prompt.split("\n\n---\n\n"); + const measured = bodies.reduce((n, b) => n + b.length, 0); + expect(measured).toBeLessThanOrEqual(250 + bodies.length * 40); + for (const m of prompt.matchAll(/conversation: obs (\d+)/g)) seen.push(Number(m[1])); + } + expect(seen).toEqual(Array.from({ length: 12 }, (_, i) => i)); + }); + + it("falls back to the chars/3 estimate when the count operation throws", async () => { + process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; + process.env.SUMMARIZE_CHUNK_TOKENS = "500"; + const provider = makeProvider([summaryXml({ title: "chunk" }), summaryXml({ title: "merged" })]); + provider.countTokens = async () => { + throw new Error("tokenize down"); + }; + const { handler, kv } = await setupHandler({ sessionId: "ses_fb", obsCount: 40, provider }); + + const result: any = await handler({ sessionId: "ses_fb" }); + + expect(result.success).toBe(true); + // ~80 chars per Observation ≈ 27 estimated tokens; 40 of them exceed a + // 100-token payload budget, so the session chunked and reduced. + expect(provider.calls.length).toBeGreaterThan(2); + expect(provider.calls.at(-1)!.system).toContain("merging"); + expect((await kv.get("summaries", "ses_fb") as any).title).toBe("merged"); + }); + + it("an Observation larger than the budget forms its own chunk", async () => { + process.env.SUMMARIZE_CHUNK_CONCURRENCY = "1"; + process.env.SUMMARIZE_CHUNK_TOKENS = budgetFor(3); + const provider = makeProvider([summaryXml({ title: "chunk" }), summaryXml({ title: "merged" })]); + provider.countTokens = async (text: string) => (text.includes("obs 2\n") ? 100 : TOKENS_PER_OBS); + const { handler } = await setupHandler({ sessionId: "ses_big", obsCount: 5, provider }); + + const result: any = await handler({ sessionId: "ses_big" }); + + expect(result.success).toBe(true); + const chunkPrompts = provider.calls.slice(0, -1).map((c) => c.user); + // [0,1] fit, [2] alone, [3,4] fit → 3 chunks + reduce. + expect(chunkPrompts).toHaveLength(3); + expect(chunkPrompts[1]).toContain("obs 2"); + expect(chunkPrompts[1]).not.toContain("obs 1"); + expect(chunkPrompts[1]).not.toContain("obs 3"); + }); + // #783: markdown-wrapped XML used to silently fail parsing because // the tag regex looked for in the raw payload. stripXmlWrappers // now peels ```xml ... ``` fences and conversational pre/postamble From 90b3d401def49d74e2ca4bf3d618697a322f7533 Mon Sep 17 00:00:00 2001 From: neal <neal@dev.lan> Date: Tue, 22 Sep 2026 06:45:03 -0400 Subject: [PATCH 08/10] fix(summarize): reuse a current Session Summary instead of reproducing it A Session Summary is current until an Observation arrives after it was written; Observations are append-only within a Session, so a stored summary whose Observation count matches the Session's is returned without an LLM call. force: true on mem::summarize and POST /agentmemory/summarize bypasses the reuse. This closes the retry loop on Sessions that summarize and are stopped again with nothing new. Closes #34. Refs #31, #572. Generated-By: Claude Fable 5.1 --- src/functions/summarize.ts | 15 +- src/triggers/api.ts | 7039 +++++++++++++++-------------- test/summarize-rest-force.test.ts | 63 + test/summarize.test.ts | 56 + 4 files changed, 3653 insertions(+), 3520 deletions(-) create mode 100644 test/summarize-rest-force.test.ts diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts index 9d838249f5..b352108c94 100644 --- a/src/functions/summarize.ts +++ b/src/functions/summarize.ts @@ -329,7 +329,7 @@ export function registerSummarizeFunction( metricsStore?: MetricsStore, ): void { sdk.registerFunction("mem::summarize", - async (data: { sessionId: string } | undefined) => { + async (data: { sessionId: string; force?: boolean } | undefined) => { const startMs = Date.now(); if (!data || typeof data.sessionId !== "string" || !data.sessionId.trim()) { return { success: false, error: "sessionId is required" }; @@ -356,6 +356,19 @@ export function registerSummarizeFunction( return { success: false, error: "no_observations" }; } + // Observations are append-only within a Session, so a stored summary + // whose count matches is current and is reused rather than reproduced. + if (!data.force) { + const existing = await kv.get<SessionSummary>(KV.summaries, sessionId); + if (existing && existing.observationCount === compressed.length) { + logger.info("Session Summary current, reused", { + sessionId, + observationCount: compressed.length, + }); + return { success: true, summary: existing, reused: true }; + } + } + if (isNoopProvider(provider)) { logger.info("Summarize skipped — no LLM provider configured", { sessionId, diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 08ff40089b..8c0398dfa5 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -1,3519 +1,3520 @@ -import { TriggerAction, type ISdk, type ApiRequest } from "../engine/types.js"; -import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js"; -import { withKeyedLock } from "../state/keyed-mutex.js"; -import { KV } from "../state/schema.js"; -import { StateKV } from "../state/kv.js"; -import { graphLegDisabled } from "../state/graph-indexes.js"; -import { checkPayloadSize, isOversizedPayload } from "../state/payload-bound.js"; -import { getLatestHealth } from "../health/monitor.js"; -import type { MetricsStore } from "../eval/metrics-store.js"; -import type { ResilientProvider } from "../providers/resilient.js"; -import { VERSION } from "../version.js"; -import { timingSafeCompare } from "../auth.js"; -import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js"; -import { renderViewerDocument } from "../viewer/document.js"; -import { getBoundViewerPort, getViewerSkipped } from "../viewer/server.js"; -import { MAX_FILES_UPPER_BOUND } from "../functions/replay.js"; -import { logger } from "../logger.js"; -import { - isGraphExtractionEnabled, - isConsolidationEnabled, - isAutoCompressEnabled, - isContextInjectionEnabled, - detectEmbeddingProvider, - detectLlmProviderKind, - getAgentId, - isAgentScopeIsolated, - loadConfig, -} from "../config.js"; - -type Response = { - status_code: number; - headers?: Record<string, string>; - body: unknown; -}; - -function parseOptionalInt(raw: unknown): number | undefined { - if (raw === undefined || raw === null || raw === "") return undefined; - const n = typeof raw === "number" ? raw : parseInt(String(raw), 10); - return Number.isFinite(n) ? n : undefined; -} - -function checkAuth( - req: ApiRequest, - secret: string | undefined, -): Response | null { - if (!secret) return null; - const auth = req.headers?.["authorization"] || req.headers?.["Authorization"]; - if ( - typeof auth !== "string" || - !timingSafeCompare(auth, `Bearer ${secret}`) - ) { - return { status_code: 401, body: { error: "unauthorized" } }; - } - return null; -} - -function requireConfiguredSecret( - secret: string | undefined, - feature: string, -): Response | null { - if (secret) return null; - return { - status_code: 503, - body: { error: `${feature} requires AGENTMEMORY_SECRET` }, - }; -} - -function flagDisabledResponse(opts: { - error: string; - flag: string; - enableHow: string; - docsHref: string; -}): Response { - return { - status_code: 503, - body: opts, - }; -} - -function graphDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Knowledge graph not enabled", - flag: "GRAPH_EXTRACTION_ENABLED", - enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.", - docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", - }); -} - -function consolidationDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Consolidation pipeline not enabled", - flag: "CONSOLIDATION_ENABLED", - enableHow: "Set CONSOLIDATION_ENABLED=true and restart. Requires an LLM provider key.", - docsHref: "https://github.com/rohitg00/agentmemory#consolidation", - }); -} - -function slotsDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Memory slots not enabled", - flag: "AGENTMEMORY_SLOTS", - enableHow: "Set AGENTMEMORY_SLOTS=true (in ~/.agentmemory/.env or the shell) and restart.", - docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", - }); -} - -function reflectDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Slot reflection not enabled", - flag: "AGENTMEMORY_REFLECT", - enableHow: "Set AGENTMEMORY_REFLECT=true (in ~/.agentmemory/.env or the shell) and restart. Requires AGENTMEMORY_SLOTS=true.", - docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", - }); -} - -function asNonEmptyString(value: unknown): string | null { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed ? trimmed : null; -} - -function parseOptionalFiniteNumber(value: unknown): number | undefined | null { - if (value === undefined || value === null) return undefined; - if (typeof value === "number") return Number.isFinite(value) ? value : null; - if (typeof value === "string") { - const trimmed = value.trim(); - if (!trimmed) return undefined; - const parsed = Number(trimmed); - return Number.isFinite(parsed) ? parsed : null; - } - return null; -} - -function parseOptionalPositiveInt(value: unknown): number | undefined | null { - const parsed = parseOptionalFiniteNumber(value); - if (parsed === undefined || parsed === null) return parsed; - if (!Number.isInteger(parsed) || parsed < 1) return null; - return parsed; -} - -export function registerApiTriggers( - sdk: ISdk, - kv: StateKV, - secret?: string, - metricsStore?: MetricsStore, - provider?: ResilientProvider | { circuitState?: unknown }, -): void { - sdk.registerFunction( - "middleware::api-auth", - async (input: { - request?: { headers?: Record<string, string | undefined> }; - }) => { - if (!secret) return { action: "continue" }; - const headers = input?.request?.headers || {}; - const auth = headers["authorization"] || headers["Authorization"]; - if ( - typeof auth !== "string" || - !timingSafeCompare(auth, `Bearer ${secret}`) - ) { - return { - action: "respond", - response: { status_code: 401, body: { error: "unauthorized" } }, - }; - } - return { action: "continue" }; - }, - ); - - // Shared instance metadata for livez and health so the two never - // drift. streamsPort lets the viewer resolve its stream WebSocket - // target from the server instead of port arithmetic, which broke - // whenever the viewer bound a fallback port. Config is boot-static, - // so read it once instead of rebuilding the merged env per request. - const bootStreamsPort = loadConfig().streamsPort; - const instanceInfo = () => ({ - service: "agentmemory", - viewerPort: getBoundViewerPort(), - viewerSkipped: getViewerSkipped(), - streamsPort: bootStreamsPort, - }); - - sdk.registerFunction("api::liveness", - async (): Promise<Response> => ({ - status_code: 200, - body: { status: "ok", ...instanceInfo() }, - }), - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::liveness", - config: { api_path: "/agentmemory/livez", http_method: "GET" }, - }); - - sdk.registerFunction("api::config-flags", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const providerKind = detectLlmProviderKind(); - const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none"; - const flags = [ - { - key: "GRAPH_EXTRACTION_ENABLED", - label: "Knowledge graph extraction", - enabled: isGraphExtractionEnabled(), - default: false, - affects: ["Graph", "Dashboard"], - needsLlm: true, - description: "Extracts entities and relations from observations into a knowledge graph.", - enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.", - docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", - }, - { - key: "CONSOLIDATION_ENABLED", - label: "Memory consolidation", - enabled: isConsolidationEnabled(), - default: false, - affects: ["Dashboard", "Memories", "Crystals"], - needsLlm: true, - description: "Periodically summarizes sessions into semantic facts + procedures.", - enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.", - docsHref: "https://github.com/rohitg00/agentmemory#consolidation", - }, - { - key: "AGENTMEMORY_AUTO_COMPRESS", - label: "LLM-powered observation compression", - enabled: isAutoCompressEnabled(), - default: false, - affects: ["Memories", "Timeline"], - needsLlm: true, - description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.", - enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.", - docsHref: "https://github.com/rohitg00/agentmemory/issues/138", - }, - { - key: "AGENTMEMORY_INJECT_CONTEXT", - label: "In-conversation context injection", - enabled: isContextInjectionEnabled(), - default: false, - affects: ["Hooks"], - needsLlm: false, - description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.", - enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.", - docsHref: "https://github.com/rohitg00/agentmemory/issues/143", - }, - ]; - return { - status_code: 200, - body: { - version: VERSION, - provider: providerKind, - embeddingProvider, - flags, - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::config-flags", - config: { - api_path: "/agentmemory/config/flags", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::health", - async (req: ApiRequest): Promise<Response> => { - const health = await getLatestHealth(kv); - const functionMetrics = metricsStore ? await metricsStore.getAll() : []; - const circuitBreaker = - provider && "circuitState" in provider ? provider.circuitState : null; - - const status = health?.status || "healthy"; - const statusCode = status === "critical" ? 503 : 200; - - return { - status_code: statusCode, - body: { - status, - version: VERSION, - health: health || null, - functionMetrics, - circuitBreaker, - ...instanceInfo(), - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::health", - config: { - api_path: "/agentmemory/health", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::observe", - async (req: ApiRequest<HookPayload>): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const hookType = asNonEmptyString(body.hookType); - const sessionId = asNonEmptyString(body.sessionId); - const project = asNonEmptyString(body.project); - const cwd = asNonEmptyString(body.cwd); - const timestamp = asNonEmptyString(body.timestamp); - if (!hookType || !sessionId || !project || !cwd || !timestamp) { - return { - status_code: 400, - body: { - error: - "hookType, sessionId, project, cwd, and timestamp are required strings", - }, - }; - } - const payload: HookPayload = { - hookType: hookType as HookPayload["hookType"], - sessionId, - project, - cwd, - timestamp, - data: body.data, - }; - const result = await sdk.trigger({ function_id: "mem::observe", payload }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::observe", - config: { - api_path: "/agentmemory/observe", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::context", - async ( - req: ApiRequest<{ - sessionId: string; - project: string; - budget?: number; - agentId?: string; - }>, - ): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body.sessionId); - const project = asNonEmptyString(body.project); - if (!sessionId || !project) { - return { - status_code: 400, - body: { error: "sessionId and project are required strings" }, - }; - } - const budget = parseOptionalPositiveInt(body.budget); - if (budget === null) { - return { - status_code: 400, - body: { error: "budget must be a positive integer" }, - }; - } - // Propagate agentId so mem::context applies the same cross-agent - // isolation filter as mem::search. Honors body.agentId, ?agentId=, - // or the worker's AGENT_ID fallback under AGENTMEMORY_AGENT_SCOPE=isolated. - const queryAgentId = - typeof (req as { query_params?: Record<string, string> }) - .query_params?.["agentId"] === "string" - ? (req as { query_params: Record<string, string> }) - .query_params["agentId"] - : undefined; - const bodyAgentId = - typeof body.agentId === "string" && body.agentId.trim().length > 0 - ? (body.agentId as string).trim() - : undefined; - const payload: { - sessionId: string; - project: string; - budget?: number; - agentId?: string; - } = { - sessionId, - project, - }; - if (budget !== undefined) payload.budget = budget; - const agentId = bodyAgentId ?? queryAgentId; - if (agentId !== undefined) payload.agentId = agentId; - const result = await sdk.trigger({ function_id: "mem::context", payload }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::context", - config: { - api_path: "/agentmemory/context", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::search", - async ( - req: ApiRequest<{ - query: string; - limit?: number; - project?: string; - cwd?: string; - format?: string; - token_budget?: number; - agentId?: string; - }>, - ): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const queryAgentId = - typeof (req as { query_params?: Record<string, string> }) - .query_params?.["agentId"] === "string" - ? (req as { query_params: Record<string, string> }) - .query_params["agentId"] - : undefined; - if (typeof body.query !== "string" || !body.query.trim()) { - return { status_code: 400, body: { error: "query is required and must be a non-empty string" } }; - } - if ( - body.limit !== undefined && - (!Number.isInteger(body.limit) || (body.limit as number) < 1) - ) { - return { status_code: 400, body: { error: "limit must be a positive integer" } }; - } - if (body.project !== undefined && typeof body.project !== "string") { - return { status_code: 400, body: { error: "project must be a string" } }; - } - if (body.cwd !== undefined && typeof body.cwd !== "string") { - return { status_code: 400, body: { error: "cwd must be a string" } }; - } - if ( - body.format !== undefined && - (typeof body.format !== "string" || - !["full", "compact", "narrative"].includes(body.format.trim().toLowerCase())) - ) { - return { - status_code: 400, - body: { error: "format must be one of: full, compact, narrative" }, - }; - } - if ( - body.token_budget !== undefined && - (!Number.isInteger(body.token_budget) || (body.token_budget as number) < 1) - ) { - return { - status_code: 400, - body: { error: "token_budget must be a positive integer" }, - }; - } - // #817: propagate agentId so the upstream isolation filter - // applies. Honors body.agentId (POST body), ?agentId=... query - // param, or implicit fallback to the worker's AGENT_ID when - // AGENTMEMORY_AGENT_SCOPE=isolated. - const bodyAgentId = - typeof body.agentId === "string" && body.agentId.trim().length > 0 - ? (body.agentId as string).trim() - : undefined; - const payload = { - query: body.query.trim(), - limit: body.limit as number | undefined, - project: body.project as string | undefined, - cwd: body.cwd as string | undefined, - format: - typeof body.format === "string" - ? body.format.trim().toLowerCase() - : undefined, - token_budget: body.token_budget as number | undefined, - agentId: bodyAgentId ?? queryAgentId, - }; - const result = await sdk.trigger({ function_id: "mem::search", payload: payload }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::search", - config: { - api_path: "/agentmemory/search", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::compress-file", - async (req: ApiRequest<{ filePath: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const filePath = asNonEmptyString(body.filePath); - if (!filePath) { - return { - status_code: 400, - body: { error: "filePath is required and must be a non-empty string" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::compress-file", - payload: { filePath }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::compress-file", - config: { api_path: "/agentmemory/compress-file", http_method: "POST" }, - }); - - sdk.registerFunction("api::replay::load", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); - if (!sessionId) { - return { status_code: 400, body: { error: "sessionId is required" } }; - } - const result = await sdk.trigger({ - function_id: "mem::replay::load", - payload: { sessionId }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::replay::load", - config: { api_path: "/agentmemory/replay/load", http_method: "GET" }, - }); - - sdk.registerFunction("api::replay::sessions", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessions = await kv.list<Session>(KV.sessions); - sessions.sort((a, b) => - (b.startedAt || "").localeCompare(a.startedAt || ""), - ); - return { status_code: 200, body: { success: true, sessions } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::replay::sessions", - config: { api_path: "/agentmemory/replay/sessions", http_method: "GET" }, - }); - - sdk.registerFunction("api::replay::import", - async ( - req: ApiRequest<{ path?: string; maxFiles?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const payload: { path?: string; maxFiles?: number } = {}; - if (body.path !== undefined) { - if (typeof body.path !== "string" || body.path.trim().length === 0) { - return { - status_code: 400, - body: { error: "path must be a non-empty string" }, - }; - } - payload.path = body.path.trim(); - } - if (body.maxFiles !== undefined) { - const n = body.maxFiles as number; - if ( - !Number.isInteger(n) || - n < 1 || - n > MAX_FILES_UPPER_BOUND - ) { - return { - status_code: 400, - body: { - error: `maxFiles must be an integer between 1 and ${MAX_FILES_UPPER_BOUND}`, - }, - }; - } - payload.maxFiles = n; - } - const result = await sdk.trigger({ - function_id: "mem::replay::import-jsonl", - payload, - }); - return { status_code: 202, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::replay::import", - config: { api_path: "/agentmemory/replay/import-jsonl", http_method: "POST" }, - }); - - sdk.registerFunction("api::session::start", - async ( - req: ApiRequest<{ sessionId: string; project: string; cwd: string }>, - ): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body.sessionId); - const project = asNonEmptyString(body.project); - const cwd = asNonEmptyString(body.cwd); - if (!sessionId || !project || !cwd) { - return { - status_code: 400, - body: { - error: "sessionId, project, and cwd are required non-empty strings", - }, - }; - } - const title = typeof body.title === "string" ? body.title.trim() : undefined; - // allow session/start to override AGENT_ID from request body - // (multi-agent runtimes that route many roles through one server - // process). Falls back to the AGENT_ID env on the server. - const requestAgentId = - typeof body.agentId === "string" && body.agentId.trim().length > 0 - ? body.agentId.trim().slice(0, 128) - : undefined; - const agentId = requestAgentId ?? getAgentId(); - const session: Session = { - id: sessionId, - project, - cwd, - startedAt: new Date().toISOString(), - status: "active", - observationCount: 0, - ...(title ? { summary: title.slice(0, 200) } : {}), - ...(title ? { firstPrompt: title.slice(0, 200) } : {}), - ...(agentId ? { agentId } : {}), - }; - await kv.set(KV.sessions, sessionId, session); - const contextResult = await sdk.trigger< - { sessionId: string; project: string; agentId?: string }, - { context: string } - >({ - function_id: "mem::context", - payload: { sessionId, project, ...(agentId ? { agentId } : {}) }, - }); - return { - status_code: 200, - body: { session, context: contextResult.context }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::start", - config: { - api_path: "/agentmemory/session/start", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::session::end", - async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => { - const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId); - if (!sessionId) { - return { - status_code: 400, - body: { error: "sessionId is required and must be a non-empty string" }, - }; - } - await kv.update(KV.sessions, sessionId, [ - { type: "set", path: "endedAt", value: new Date().toISOString() }, - { type: "set", path: "status", value: "completed" }, - ]); - // Fan out session-stopped lifecycle (non-blocking). - try { - sdk.trigger({ - function_id: "event::session::stopped", - payload: { sessionId }, - action: TriggerAction.Void(), - }); - } catch (err) { - logger.warn("event::session::stopped trigger failed", { - sessionId, - error: err instanceof Error ? err.message : String(err), - }); - } - return { status_code: 200, body: { success: true } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::end", - config: { - api_path: "/agentmemory/session/end", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::summarize", - async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => { - const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId); - if (!sessionId) { - return { status_code: 400, body: { error: "sessionId is required" } }; - } - const result = await sdk.trigger({ - function_id: "mem::summarize", - payload: { sessionId }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::summarize", - config: { - api_path: "/agentmemory/summarize", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::session::commit", - async (req: ApiRequest): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sha = asNonEmptyString(body.sha); - if (!sha) { - return { - status_code: 400, - body: { error: "sha is required and must be a non-empty string" }, - }; - } - const sessionId = asNonEmptyString(body.sessionId) ?? undefined; - const branch = asNonEmptyString(body.branch) ?? undefined; - const repo = asNonEmptyString(body.repo) ?? undefined; - const message = asNonEmptyString(body.message) ?? undefined; - const author = asNonEmptyString(body.author) ?? undefined; - const authoredAt = asNonEmptyString(body.authoredAt) ?? undefined; - const files = Array.isArray(body.files) - ? (body.files as unknown[]).filter( - (f): f is string => typeof f === "string" && f.length > 0, - ) - : undefined; - - const link = await withKeyedLock(`commit:${sha}`, async () => { - const existing = await kv.get<CommitLink>(KV.commits, sha); - const sessionSet = new Set<string>(existing?.sessionIds ?? []); - if (sessionId) sessionSet.add(sessionId); - const merged: CommitLink = { - sha, - shortSha: existing?.shortSha ?? sha.slice(0, 7), - branch: branch ?? existing?.branch, - repo: repo ?? existing?.repo, - message: message ?? existing?.message, - author: author ?? existing?.author, - authoredAt: authoredAt ?? existing?.authoredAt, - files: files ?? existing?.files, - sessionIds: Array.from(sessionSet), - linkedAt: existing?.linkedAt ?? new Date().toISOString(), - }; - await kv.set(KV.commits, sha, merged); - return merged; - }); - - if (sessionId) { - await withKeyedLock(`session:${sessionId}`, async () => { - const session = await kv.get<Session>(KV.sessions, sessionId); - if (!session) return; - const shaSet = new Set<string>(session.commitShas ?? []); - shaSet.add(sha); - session.commitShas = Array.from(shaSet); - await kv.set(KV.sessions, sessionId, session); - }); - } - - return { status_code: 200, body: { commit: link } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::commit", - config: { - api_path: "/agentmemory/session/commit", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::session::by-commit", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sha = asNonEmptyString(req.query_params?.["sha"]); - if (!sha) { - return { - status_code: 400, - body: { error: "sha is required and must be a non-empty string" }, - }; - } - const link = await kv.get<CommitLink>(KV.commits, sha); - if (!link) { - return { - status_code: 404, - body: { error: "no sessions linked to this commit" }, - }; - } - const fetched = await Promise.all( - (link.sessionIds ?? []).map((sid) => kv.get<Session>(KV.sessions, sid)), - ); - const sessions = fetched.filter((s): s is Session => s !== null); - return { status_code: 200, body: { commit: link, sessions } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::by-commit", - config: { - api_path: "/agentmemory/session/by-commit", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::commits", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const branch = asNonEmptyString(req.query_params?.["branch"]); - const repo = asNonEmptyString(req.query_params?.["repo"]); - const rawLimit = parseOptionalInt(req.query_params?.["limit"]); - const limit = Math.max(1, Math.min(500, rawLimit ?? 100)); - const all = await kv.list<CommitLink>(KV.commits); - const filtered = all - .filter((c) => !branch || c.branch === branch) - .filter((c) => !repo || c.repo === repo) - .sort((a, b) => ((a.linkedAt ?? "") < (b.linkedAt ?? "") ? 1 : -1)) - .slice(0, limit); - return { status_code: 200, body: { commits: filtered } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::commits", - config: { - api_path: "/agentmemory/commits", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::sessions", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessions = await kv.list<Session>(KV.sessions); - const normalizedAgentId = - typeof req.query_params?.["agentId"] === "string" - ? req.query_params["agentId"].trim() - : undefined; - const wildcardAgent = normalizedAgentId === "*"; - const explicitAgentId = - normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; - const filterAgentId = wildcardAgent - ? undefined - : explicitAgentId ?? - (isAgentScopeIsolated() ? getAgentId() : undefined); - const filtered = filterAgentId - ? sessions.filter((s) => s.agentId === filterAgentId) - : sessions; - // Bounded fan-out: each kv.get is a full engine invocation, so - // Promise.all over hundreds of sessions saturates the invocation - // pool. Batch in chunks of 10 (parallel within a chunk, sequential - // across chunks); the summaries array stays index-aligned with - // `filtered`. - const summaries: Array<SessionSummary | null> = []; - for (let batch = 0; batch < filtered.length; batch += 10) { - const chunk = filtered.slice(batch, batch + 10); - const results = await Promise.all( - chunk.map((s) => - kv.get<SessionSummary>(KV.summaries, s.id).catch(() => null), - ), - ); - summaries.push(...results); - } - const withSummary = filtered.map((s, i) => - summaries[i] ? { ...s, summary: summaries[i] } : s, - ); - return { status_code: 200, body: { sessions: withSummary } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::sessions", - config: { api_path: "/agentmemory/sessions", http_method: "GET" }, - }); - - sdk.registerFunction("api::observations", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); - if (!sessionId) - return { status_code: 400, body: { error: "sessionId required" } }; - const observations = await kv.list<CompressedObservation>( - KV.observations(sessionId), - ); - const normalizedAgentId = - typeof req.query_params?.["agentId"] === "string" - ? req.query_params["agentId"].trim() - : undefined; - const wildcardAgent = normalizedAgentId === "*"; - const explicitAgentId = - normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; - const filterAgentId = wildcardAgent - ? undefined - : explicitAgentId ?? - (isAgentScopeIsolated() ? getAgentId() : undefined); - const filtered = filterAgentId - ? observations.filter((o) => o.agentId === filterAgentId) - : observations; - return { status_code: 200, body: { observations: filtered } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::observations", - config: { api_path: "/agentmemory/observations", http_method: "GET" }, - }); - - sdk.registerFunction("api::file-context", - async ( - req: ApiRequest<{ sessionId: string; files: string[] }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::file-context", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::file-context", - config: { api_path: "/agentmemory/file-context", http_method: "POST" }, - }); - - sdk.registerFunction("api::enrich", - async ( - req: ApiRequest<{ - sessionId: string; - files: string[]; - terms?: string[]; - toolName?: string; - project?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !req.body?.sessionId || - typeof req.body.sessionId !== "string" || - !Array.isArray(req.body?.files) || - req.body.files.length === 0 || - !req.body.files.every((f: unknown) => typeof f === "string") - ) { - return { - status_code: 400, - body: { - error: "sessionId (string) and files (string[]) are required", - }, - }; - } - if ( - req.body.terms !== undefined && - (!Array.isArray(req.body.terms) || - !req.body.terms.every((t: unknown) => typeof t === "string")) - ) { - return { - status_code: 400, - body: { error: "terms must be an array of strings" }, - }; - } - if ( - req.body.project !== undefined && - (typeof req.body.project !== "string" || !req.body.project.trim()) - ) { - return { - status_code: 400, - body: { error: "project must be a non-empty string" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::enrich", - payload: { - sessionId: req.body.sessionId, - files: req.body.files, - ...(req.body.terms !== undefined && { terms: req.body.terms }), - ...(req.body.toolName !== undefined && { toolName: req.body.toolName }), - ...(req.body.project !== undefined && { project: req.body.project }), - }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::enrich", - config: { api_path: "/agentmemory/enrich", http_method: "POST" }, - }); - - sdk.registerFunction("api::remember", - async ( - req: ApiRequest<{ - content: string; - type?: string; - concepts?: string[]; - files?: string[]; - ttlDays?: number; - sourceObservationIds?: string[]; - project?: string; - agentId?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !req.body?.content || - typeof req.body.content !== "string" || - !req.body.content.trim() - ) { - return { status_code: 400, body: { error: "content is required" } }; - } - if ( - req.body.project !== undefined && - (typeof req.body.project !== "string" || !req.body.project.trim()) - ) { - return { status_code: 400, body: { error: "project must be a non-empty string" } }; - } - const result = await sdk.trigger({ - function_id: "mem::remember", - payload: { - content: req.body.content, - ...(req.body.type !== undefined && { type: req.body.type }), - ...(req.body.concepts !== undefined && { concepts: req.body.concepts }), - ...(req.body.files !== undefined && { files: req.body.files }), - ...(req.body.ttlDays !== undefined && { ttlDays: req.body.ttlDays }), - ...(req.body.sourceObservationIds !== undefined && { sourceObservationIds: req.body.sourceObservationIds }), - ...(req.body.project !== undefined && { project: req.body.project }), - ...(typeof req.body.agentId === "string" && req.body.agentId.trim() - ? { agentId: req.body.agentId.trim() } - : {}), - }, - }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::remember", - config: { api_path: "/agentmemory/remember", http_method: "POST" }, - }); - - sdk.registerFunction("api::forget", - async ( - req: ApiRequest<{ - sessionId?: string; - observationIds?: string[]; - memoryId?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessionId = - typeof req.body?.sessionId === "string" ? req.body.sessionId : undefined; - const memoryId = - typeof req.body?.memoryId === "string" ? req.body.memoryId : undefined; - if (!sessionId && !memoryId) { - return { - status_code: 400, - body: { error: "sessionId or memoryId is required" }, - }; - } - const rawObservationIds = req.body?.observationIds; - // Dropping the non-strings and forwarding what is left would turn a - // malformed list into an empty one, and an empty list is the whole- - // session wipe. Refuse instead of widening what was asked for. - if ( - rawObservationIds !== undefined && - (!Array.isArray(rawObservationIds) || - !rawObservationIds.every((id) => typeof id === "string")) - ) { - return { - status_code: 400, - body: { error: "observationIds must be an array of strings" }, - }; - } - const result = (await sdk.trigger({ - function_id: "mem::forget", - payload: { - ...(sessionId !== undefined && { sessionId }), - ...(memoryId !== undefined && { memoryId }), - ...(rawObservationIds !== undefined && { observationIds: rawObservationIds }), - }, - })) as { success: boolean; error?: string }; - // The refusals mem::forget raises are bad requests, not results. - if (!result.success) { - return { status_code: 400, body: result }; - } - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::forget", - config: { api_path: "/agentmemory/forget", http_method: "POST" }, - }); - - sdk.registerFunction("api::consolidate", - async ( - req: ApiRequest<{ project?: string; minObservations?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::consolidate", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::consolidate", - config: { api_path: "/agentmemory/consolidate", http_method: "POST" }, - }); - - sdk.registerFunction("api::patterns", - async (req: ApiRequest<{ project?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::patterns", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::patterns", - config: { api_path: "/agentmemory/patterns", http_method: "POST" }, - }); - - sdk.registerFunction("api::generate-rules", - async (req: ApiRequest<{ project?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::generate-rules", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::generate-rules", - config: { api_path: "/agentmemory/generate-rules", http_method: "POST" }, - }); - - sdk.registerFunction("api::migrate", - async ( - req: ApiRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const hasStep = - typeof req.body?.step === "string" && req.body.step.trim().length > 0; - const hasDbPath = - typeof req.body?.dbPath === "string" && req.body.dbPath.trim().length > 0; - if (!hasStep && !hasDbPath) { - return { - status_code: 400, - body: { error: "Either step (string) or dbPath (string) is required" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::migrate", - payload: { - ...(req.body.step !== undefined && { step: req.body.step }), - ...(req.body.dbPath !== undefined && { dbPath: req.body.dbPath }), - ...(req.body.dryRun !== undefined && { dryRun: req.body.dryRun }), - }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::migrate", - config: { api_path: "/agentmemory/migrate", http_method: "POST" }, - }); - - sdk.registerFunction("api::evict", - async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const dryRun = - req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; - const result = await sdk.trigger({ function_id: "mem::evict", payload: { dryRun } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::evict", - config: { api_path: "/agentmemory/evict", http_method: "POST" }, - }); - - sdk.registerFunction("api::smart-search", - async ( - req: ApiRequest<{ - query?: string; - expandIds?: Array<string | { obsId: string; sessionId: string }>; - limit?: number; - project?: string; - includeLessons?: boolean; - agentId?: string; - sessionId?: string; - source?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !req.body?.query && - (!req.body?.expandIds || req.body.expandIds.length === 0) - ) { - return { - status_code: 400, - body: { error: "query or expandIds is required" }, - }; - } - // #771: route the X-Agentmemory-Source header into the payload so - // the followup-rate diagnostic can skip viewer-originated calls. - // Body wins if both are set (advanced callers explicitly override). - const headers = (req.headers || {}) as Record<string, string | string[] | undefined>; - const sourceHeader = headers["x-agentmemory-source"] ?? headers["X-Agentmemory-Source"]; - const sourceFromHeader = Array.isArray(sourceHeader) ? sourceHeader[0] : sourceHeader; - // Whitelist payload fields explicitly — REST endpoints never pass - // the raw request body through to sdk.trigger (AGENTS.md security - // section). Drops unknown fields so a misbehaving client can't - // inject downstream-only options. - const payload = { - query: req.body?.query, - expandIds: req.body?.expandIds, - limit: req.body?.limit, - project: req.body?.project, - includeLessons: req.body?.includeLessons, - agentId: req.body?.agentId, - sessionId: req.body?.sessionId, - source: req.body?.source ?? sourceFromHeader, - }; - const result = await sdk.trigger({ function_id: "mem::smart-search", payload }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::smart-search", - config: { api_path: "/agentmemory/smart-search", http_method: "POST" }, - }); - - // #771: read-back endpoint for the followup-rate diagnostic. Returns - // a directional signal — overcounts on legitimate query refinement — - // so help text + the CLI status line carry the same caveat. - sdk.registerFunction("api::diagnostic-followup", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ - function_id: "mem::diagnostic::followup-stats", - payload: {}, - }); - return { - status_code: 200, - body: { - ...(result as Record<string, unknown>), - caveat: - "Directional signal: overcounts on legitimate query refinement. " + - "Tune via AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS.", - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::diagnostic-followup", - config: { - api_path: "/agentmemory/diagnostics/followup", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::timeline", - async ( - req: ApiRequest<{ - anchor: string; - project?: string; - before?: number; - after?: number; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.anchor) { - return { status_code: 400, body: { error: "anchor is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::timeline", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::timeline", - config: { api_path: "/agentmemory/timeline", http_method: "POST" }, - }); - - sdk.registerFunction("api::profile", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const project = req.query_params["project"] as string; - if (!project) { - return { - status_code: 400, - body: { error: "project query param is required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::profile", payload: { project } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::profile", - config: { api_path: "/agentmemory/profile", http_method: "GET" }, - }); - - sdk.registerFunction("api::export", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - // mem::export already supports maxSessions/offset internally, - // but the HTTP endpoint hardcoded an empty payload — so /export on a - // real corpus (40 sessions × 34K observations × 8K memories) hit the - // iii engine invocation timeout and `agentmemory status` reported 0. - // Pass through the query-string pagination so callers can chunk. - const rawMax = req.query_params?.["maxSessions"]; - const rawOffset = req.query_params?.["offset"]; - const payload: { maxSessions?: number; offset?: number } = {}; - if (typeof rawMax === "string") { - const n = Number(rawMax); - if (Number.isInteger(n) && n > 0) payload.maxSessions = n; - } - if (typeof rawOffset === "string") { - const n = Number(rawOffset); - if (Number.isInteger(n) && n >= 0) payload.offset = n; - } - const result = await sdk.trigger({ - function_id: "mem::export", - payload, - }); - // mem::export refuses an oversized payload rather than serializing it; - // over HTTP that refusal is a 413, not a 200 carrying an error body. - if (isOversizedPayload(result)) return { status_code: 413, body: result }; - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::export", - config: { api_path: "/agentmemory/export", http_method: "GET" }, - }); - - sdk.registerFunction("api::import", - async ( - req: ApiRequest<{ - exportData: unknown; - strategy?: "merge" | "replace" | "skip"; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.exportData) { - return { status_code: 400, body: { error: "exportData is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::import", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::import", - config: { api_path: "/agentmemory/import", http_method: "POST" }, - }); - - sdk.registerFunction("api::relations", - async ( - req: ApiRequest<{ sourceId: string; targetId: string; type: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.sourceId || !req.body?.targetId || !req.body?.type) { - return { - status_code: 400, - body: { error: "sourceId, targetId, and type are required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::relate", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::relations", - config: { api_path: "/agentmemory/relations", http_method: "POST" }, - }); - - sdk.registerFunction("api::evolve", - async ( - req: ApiRequest<{ - memoryId: string; - newContent: string; - newTitle?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.memoryId || !req.body?.newContent) { - return { - status_code: 400, - body: { error: "memoryId and newContent are required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::evolve", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::evolve", - config: { api_path: "/agentmemory/evolve", http_method: "POST" }, - }); - - sdk.registerFunction("api::auto-forget", - async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const dryRun = - req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; - const result = await sdk.trigger({ function_id: "mem::auto-forget", payload: { dryRun } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::auto-forget", - config: { api_path: "/agentmemory/auto-forget", http_method: "POST" }, - }); - - sdk.registerFunction("api::claude-bridge-read", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::claude-bridge-read", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { - status_code: 404, - body: { error: "Claude bridge not enabled" }, - }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::claude-bridge-read", - config: { api_path: "/agentmemory/claude-bridge/read", http_method: "GET" }, - }); - - sdk.registerFunction("api::claude-bridge-sync", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::claude-bridge-sync", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { - status_code: 404, - body: { error: "Claude bridge not enabled" }, - }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::claude-bridge-sync", - config: { - api_path: "/agentmemory/claude-bridge/sync", - http_method: "POST", - }, - }); - - sdk.registerFunction("api::graph-query", - async ( - req: ApiRequest<{ - startNodeId?: string; - nodeType?: string; - maxDepth?: number; - query?: string; - limit?: number; - offset?: number; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - // Whitelist payload fields explicitly; AGENTS.md security rule: - // REST endpoints never pass raw req.body through to sdk.trigger. - const payload = { - startNodeId: req.body?.startNodeId, - nodeType: req.body?.nodeType, - maxDepth: req.body?.maxDepth, - query: req.body?.query, - limit: req.body?.limit, - offset: req.body?.offset, - }; - try { - const result = await sdk.trigger({ function_id: "mem::graph-query", payload }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-query", - config: { api_path: "/agentmemory/graph/query", http_method: "POST" }, - }); - - sdk.registerFunction("api::graph-stats", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::graph-stats", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-stats", - config: { api_path: "/agentmemory/graph/stats", http_method: "GET" }, - }); - - // #814: explicit snapshot rebuild endpoint. Pays the full graph - // enumeration once and persists a top-degree subgraph + aggregate - // counts so subsequent /graph/query and /graph/stats calls skip the - // unbounded kv.list. Operator-grade endpoint exposed for the viewer - // banner action and CLI repair. - sdk.registerFunction("api::graph-snapshot-rebuild", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ - function_id: "mem::graph-snapshot-rebuild", - payload: {}, - }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-snapshot-rebuild", - config: { api_path: "/agentmemory/graph/snapshot-rebuild", http_method: "POST" }, - }); - - // #814 v2: clean-restart endpoint for legacy corpora too large for - // safe rebuild. Wipes graph state without touching observations, so - // recall + history stay intact while the graph rebuilds incrementally - // from new extracts (or a one-shot /graph/build replay). - sdk.registerFunction("api::graph-reset", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ - function_id: "mem::graph-reset", - payload: {}, - }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-reset", - config: { api_path: "/agentmemory/graph/reset", http_method: "POST" }, - }); - - sdk.registerFunction("api::graph-extract", - async (req: ApiRequest<{ observations: unknown[] }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !Array.isArray(req.body?.observations) || - req.body.observations.length === 0 - ) { - return { - status_code: 400, - body: { error: "observations array is required" }, - }; - } - try { - const result = await sdk.trigger({ function_id: "mem::graph-extract", payload: req.body }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-extract", - config: { api_path: "/agentmemory/graph/extract", http_method: "POST" }, - }); - - // Backfill the knowledge graph from existing compressed observations. - // Viewer calls this when the graph is empty (#666). Iterates every - // session, collects observations that have a `title` (compressed only), - // and feeds them through `mem::graph-extract` in batches. - sdk.registerFunction("api::graph-build", - async (req: ApiRequest<{ batchSize?: number }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const batchSize = Math.max( - 1, - Math.min(100, Number((req.body as { batchSize?: number })?.batchSize) || 25), - ); - try { - const sessions = await kv.list<Session>(KV.sessions); - let totalNodes = 0; - let totalEdges = 0; - let batchesRun = 0; - for (const session of sessions) { - const sid = session?.id; - if (typeof sid !== "string" || sid.length === 0) continue; - const observations = await kv.list<CompressedObservation>(KV.observations(sid)); - const compressed = observations.filter((o) => o && typeof o.title === "string" && o.title.length > 0); - if (compressed.length === 0) continue; - for (let i = 0; i < compressed.length; i += batchSize) { - const batch = compressed.slice(i, i + batchSize); - try { - const result = (await sdk.trigger({ - function_id: "mem::graph-extract", - payload: { observations: batch }, - })) as { success?: boolean; nodesAdded?: number; edgesAdded?: number }; - if (result?.success) { - totalNodes += Number(result.nodesAdded) || 0; - totalEdges += Number(result.edgesAdded) || 0; - } - batchesRun++; - } catch (err) { - logger.warn("graph-build batch failed", { - sessionId: sid, - batchIndex: Math.floor(i / batchSize), - error: err instanceof Error ? err.message : String(err), - }); - } - } - } - return { - status_code: 200, - body: { - success: true, - sessions: sessions.length, - batches: batchesRun, - nodes: totalNodes, - edges: totalEdges, - }, - }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-build", - config: { api_path: "/agentmemory/graph/build", http_method: "POST" }, - }); - - // Import graphify's structural graph (graphify-out/graph.json) into the - // memory graph. Deterministic, no LLM call; idempotent via the graph - // name-index upsert. - sdk.registerFunction("api::graph-import-graphify", - async (req: ApiRequest<{ path?: string; cwd?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const { path, cwd } = req.body ?? {}; - if ( - (path !== undefined && typeof path !== "string") || - (cwd !== undefined && typeof cwd !== "string") - ) { - return { - status_code: 400, - body: { error: "path and cwd must be strings when provided" }, - }; - } - try { - const result = await sdk.trigger({ - function_id: "mem::graph::import-graphify", - payload: { - ...(path !== undefined ? { path } : {}), - ...(cwd !== undefined ? { cwd } : {}), - }, - }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-import-graphify", - config: { api_path: "/agentmemory/graph/import-graphify", http_method: "POST" }, - }); - - // Re-run compression for observations that a failed mem::compress left in - // raw shape - present in KV but in neither search index, so unretrievable. - // Two sources: mem:compress-pending (parked by the failure path, full raw - // preserved) and raw-shaped records in KV.observations (the historical - // orphans that predate that fix). Sequential and limit-bounded on purpose: - // this exists to be run after a provider outage, and firing hundreds of - // concurrent LLM calls at a provider that has just stopped returning 529s - // is how you cause the next one. - sdk.registerFunction("api::recompress-orphans", - async (req: ApiRequest<{ limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body || {}) as { limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }; - const limit = Math.max(1, Math.min(1000, Number(body.limit) || 50)); - const dryRun = body.dryRun === true; - // Records captured before this instant skip the one-hour grace. The - // cutover passes its freeze timestamp: nothing captured before the - // freeze can still have a compression in flight on the new daemon. - const graceBypassBefore = typeof body.graceBypassBefore === "string" ? new Date(body.graceBypassBefore).getTime() : NaN; - if (typeof body.graceBypassBefore === "string" && !Number.isFinite(graceBypassBefore)) { - return { status_code: 400, body: { error: "graceBypassBefore must be an ISO timestamp" } }; - } - // Give quarantined entries (attempts >= MAX_ATTEMPTS) one more shot. - // Meant for after a compression-pipeline fix lands: what was a - // deterministic failure may compress cleanly under the new code. - const requeueQuarantined = body.requeueQuarantined === true; - const GRACE_MS = 60 * 60 * 1000; - const now = Date.now(); - - const MAX_ATTEMPTS = 5; - const targets: Array<{ observationId: string; sessionId: string; raw: unknown }> = []; - - // Raw-shaped orphans FIRST: they are the records no search can return, - // so the batch budget belongs to them. Parked entries are already - // findable as degraded synthetics - re-compressing them is a quality - // upgrade, not a rescue. (The first version of this endpoint did the - // opposite and starved the raw ones: every failed parked entry was - // re-parked, so the pending queue never shrank and always ate the - // whole budget.) - let rawOrphans = 0; - for (const session of await kv.list<Session>(KV.sessions)) { - const sid = session?.id; - if (typeof sid !== "string" || sid.length === 0) continue; - for (const o of await kv.list<Record<string, unknown>>(KV.observations(sid))) { - const oid = o?.["id"]; - if (typeof oid !== "string") continue; - if (typeof o["narrative"] === "string") continue; - if (typeof o["hookType"] !== "string") continue; - const ts = new Date(String(o["timestamp"])).getTime(); - const bypass = Number.isFinite(graceBypassBefore) && Number.isFinite(ts) && ts < graceBypassBefore; - if (Number.isFinite(ts) && now - ts < GRACE_MS && !bypass) continue; - rawOrphans++; - if (targets.length < limit) { - targets.push({ observationId: oid, sessionId: sid, raw: o }); - } - } - } - - const queued = new Set(targets.map((t) => t.observationId)); - let parked = 0; - let quarantined = 0; - for (const p of await kv.list<{ - observationId?: string; - sessionId?: string; - raw?: unknown; - attempts?: number; - }>(KV.compressPending)) { - if (typeof p?.observationId !== "string" || typeof p?.sessionId !== "string") continue; - if (queued.has(p.observationId)) continue; - if ((p.attempts ?? 0) >= MAX_ATTEMPTS) { - quarantined++; - if (!requeueQuarantined) continue; - } else { - parked++; - } - if (targets.length < limit) { - targets.push({ observationId: p.observationId, sessionId: p.sessionId, raw: p.raw }); - } - } - - if (dryRun) { - return { - status_code: 200, - body: { - success: true, - dryRun: true, - rawOrphans, - parked, - quarantined, - queued: targets.length, - limit, - }, - }; - } - - let recompressed = 0; - let stillFailing = 0; - for (const t of targets) { - try { - const result = (await sdk.trigger({ - function_id: "mem::compress", - payload: t, - })) as { success?: boolean } | null; - if (result?.success) recompressed++; - else stillFailing++; - } catch { - stillFailing++; - } - // Bail out rather than grind through hundreds of doomed calls when - // the provider is clearly still down. Not for requeueQuarantined - // batches: there every target is a known deterministic failure, so - // ten straight losses say nothing about the provider. - if (!requeueQuarantined && stillFailing >= 10 && recompressed === 0) { - logger.warn("recompress-orphans aborting: provider still failing", { - attempted: recompressed + stillFailing, - }); - break; - } - } - - logger.info("recompress-orphans finished", { - rawOrphans, - parked, - quarantined, - queued: targets.length, - recompressed, - stillFailing, - }); - return { - status_code: 200, - body: { - success: true, - rawOrphans, - parked, - quarantined, - queued: targets.length, - recompressed, - stillFailing, - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::recompress-orphans", - config: { api_path: "/agentmemory/recompress-orphans", http_method: "POST" }, - }); - - sdk.registerFunction("api::consolidate-pipeline", - async (req: ApiRequest<{ tier?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: req.body || {}, - }); - return { status_code: 200, body: result }; - } catch { - return consolidationDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::consolidate-pipeline", - config: { - api_path: "/agentmemory/consolidate-pipeline", - http_method: "POST", - }, - }); - - sdk.registerFunction("api::team-share", - async ( - req: ApiRequest<{ itemId: string; itemType: string; project?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.itemId || !req.body?.itemType) { - return { - status_code: 400, - body: { error: "itemId and itemType are required" }, - }; - } - try { - const result = await sdk.trigger({ function_id: "mem::team-share", payload: req.body }); - return { status_code: 201, body: result }; - } catch { - return { status_code: 404, body: { error: "Team memory not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::team-share", - config: { api_path: "/agentmemory/team/share", http_method: "POST" }, - }); - - sdk.registerFunction("api::team-feed", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const limit = parsedLimit ?? 20; - const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { limit } }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Team memory not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::team-feed", - config: { api_path: "/agentmemory/team/feed", http_method: "GET" }, - }); - - sdk.registerFunction("api::team-profile", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::team-profile", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Team memory not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::team-profile", - config: { api_path: "/agentmemory/team/profile", http_method: "GET" }, - }); - - sdk.registerFunction("api::audit", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const entries = await sdk.trigger({ function_id: "mem::audit-query", payload: { - operation: req.query_params?.["operation"], - limit: parsedLimit ?? 50, - } }); - return { status_code: 200, body: { entries, success: true } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::audit", - config: { api_path: "/agentmemory/audit", http_method: "GET" }, - }); - - sdk.registerFunction("api::governance-delete", - async ( - req: ApiRequest<{ memoryIds: string[]; reason?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.memoryIds || !Array.isArray(req.body.memoryIds)) { - return { - status_code: 400, - body: { error: "memoryIds array is required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::governance-delete", - config: { - api_path: "/agentmemory/governance/memories", - http_method: "DELETE", - }, - }); - - sdk.registerFunction("api::governance-bulk", - async ( - req: ApiRequest<{ - type?: string[]; - dateFrom?: string; - dateTo?: string; - qualityBelow?: number; - dryRun?: boolean; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::governance-bulk", payload: req.body || {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::governance-bulk", - config: { - api_path: "/agentmemory/governance/bulk-delete", - http_method: "POST", - }, - }); - - sdk.registerFunction("api::snapshots", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-list", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Snapshots not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::snapshots", - config: { api_path: "/agentmemory/snapshots", http_method: "GET" }, - }); - - sdk.registerFunction("api::snapshot-create", - async (req: ApiRequest<{ message?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: req.body || {}, - }); - return { status_code: 201, body: result }; - } catch { - return { status_code: 404, body: { error: "Snapshots not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::snapshot-create", - config: { api_path: "/agentmemory/snapshot/create", http_method: "POST" }, - }); - - sdk.registerFunction("api::snapshot-restore", - async (req: ApiRequest<{ commitHash: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.commitHash) { - return { status_code: 400, body: { error: "commitHash is required" } }; - } - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-restore", payload: req.body }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Snapshots not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::snapshot-restore", - config: { api_path: "/agentmemory/snapshot/restore", http_method: "POST" }, - }); - - sdk.registerFunction("api::memories", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const memories = await kv.list<import("../types.js").Memory>(KV.memories); - const latest = req.query_params?.["latest"] === "true"; - // agentId filter. Request param wins, env AGENT_ID (when - // scope=isolated) is the fallback. Shared mode keeps the tag but - // does not restrict the list endpoint. Pass agentId=* to opt out - // of the env scope entirely. includeOrphans=true surfaces - // pre-AGENT_ID memories whose agentId is undefined. - const normalizedAgentId = - typeof req.query_params?.["agentId"] === "string" - ? req.query_params["agentId"].trim() - : undefined; - const wildcardAgent = normalizedAgentId === "*"; - const explicitAgentId = - normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; - const includeOrphans = - req.query_params?.["includeOrphans"] === "true"; - const filterAgentId = wildcardAgent - ? undefined - : explicitAgentId ?? (isAgentScopeIsolated() ? getAgentId() : undefined); - let filtered = latest ? memories.filter((m) => m.isLatest) : memories; - if (filterAgentId) { - filtered = filtered.filter( - (m) => - m.agentId === filterAgentId || - (includeOrphans && m.agentId === undefined), - ); - } - - // viewer + `agentmemory status` were hitting this endpoint to - // count memories. On a real corpus (8K+ memories) the unbounded - // response either timed out at the iii engine boundary ("Invocation - // stopped") or arrived too large for the viewer to render — so the - // UI showed 0 memories despite a healthy store. Two opt-in modes: - // ?count=true — totals only, no payload - // ?limit=N&offset=M — page slice (default unlimited for back-compat) - if (req.query_params?.["count"] === "true") { - // Match the SAME scope that the list path applies — returning - // unfiltered totals here would leak cross-agent counts to a - // caller that's blocked from the underlying rows. - return { - status_code: 200, - body: { - total: filtered.length, - latestCount: filtered.filter((m) => m.isLatest).length, - }, - }; - } - - const rawLimit = req.query_params?.["limit"]; - const rawOffset = req.query_params?.["offset"]; - const parsedLimit = - typeof rawLimit === "string" ? Number(rawLimit) : Number.NaN; - const parsedOffset = - typeof rawOffset === "string" ? Number(rawOffset) : Number.NaN; - const limit = - Number.isInteger(parsedLimit) && parsedLimit > 0 - ? Math.min(parsedLimit, 5000) - : undefined; - const offset = - Number.isInteger(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0; - const sliced = - limit !== undefined ? filtered.slice(offset, offset + limit) : filtered; - - return { - status_code: 200, - body: { - memories: sliced, - total: filtered.length, - offset, - limit: limit ?? null, - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::memories", - config: { api_path: "/agentmemory/memories", http_method: "GET" }, - }); - - sdk.registerFunction("api::memory-by-id", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const id = req.path_params?.["id"]; - if (!id || typeof id !== "string") { - return { status_code: 400, body: { error: "id path parameter is required" } }; - } - const memory = await kv.get<import("../types.js").Memory>(KV.memories, id); - if (!memory) { - return { status_code: 404, body: { error: `memory not found: ${id}` } }; - } - return { status_code: 200, body: { memory } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::memory-by-id", - config: { api_path: "/agentmemory/memories/:id", http_method: "GET" }, - }); - - // The route an operator reaches for first. Without it, removing one - // memory means discovering either /agentmemory/forget or the - // governance bulk paths, and the filter-based one invites deleting by - // date window and hoping the window held only the target. - sdk.registerFunction("api::memory-delete", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const id = req.path_params?.["id"]; - if (!id || typeof id !== "string") { - return { status_code: 400, body: { error: "id path parameter is required" } }; - } - const result = await sdk.trigger({ - function_id: "mem::forget", - payload: { memoryId: id }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::memory-delete", - config: { api_path: "/agentmemory/memories/:id", http_method: "DELETE" }, - }); - - sdk.registerFunction("api::semantic-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); - return { status_code: 200, body: { semantic } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::semantic-list", - config: { api_path: "/agentmemory/semantic", http_method: "GET" }, - }); - - sdk.registerFunction("api::procedural-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); - return { status_code: 200, body: { procedural } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::procedural-list", - config: { api_path: "/agentmemory/procedural", http_method: "GET" }, - }); - - sdk.registerFunction("api::relations-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); - return { status_code: 200, body: { relations } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::relations-list", - config: { api_path: "/agentmemory/relations", http_method: "GET" }, - }); - - sdk.registerFunction("api::vision-search", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const queryText = asNonEmptyString(body["queryText"]); - const queryImageRef = asNonEmptyString(body["queryImageRef"]); - const queryImageBase64 = asNonEmptyString(body["queryImageBase64"]); - const sessionId = asNonEmptyString(body["sessionId"]); - if (!queryText && !queryImageRef && !queryImageBase64) { - return { - status_code: 400, - body: { error: "queryText, queryImageRef, or queryImageBase64 required" }, - }; - } - const topKParsed = parseOptionalPositiveInt(body["topK"]); - if (topKParsed === null) { - return { status_code: 400, body: { error: "topK must be a positive integer" } }; - } - const payload: Record<string, unknown> = {}; - if (queryText) payload["queryText"] = queryText; - if (queryImageRef) payload["queryImageRef"] = queryImageRef; - if (queryImageBase64) payload["queryImageBase64"] = queryImageBase64; - if (sessionId) payload["sessionId"] = sessionId; - if (topKParsed !== undefined) payload["topK"] = Math.min(50, topKParsed); - const result = await sdk.trigger({ function_id: "mem::vision-search", payload }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::vision-search", - config: { api_path: "/agentmemory/vision-search", http_method: "POST" }, - }); - - sdk.registerFunction("api::vision-embed", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const imageRef = asNonEmptyString(body["imageRef"]); - const sessionId = asNonEmptyString(body["sessionId"]); - const observationId = asNonEmptyString(body["observationId"]); - if (!imageRef) { - return { status_code: 400, body: { error: "imageRef is required" } }; - } - const payload: Record<string, unknown> = { imageRef }; - if (sessionId) payload["sessionId"] = sessionId; - if (observationId) payload["observationId"] = observationId; - const result = await sdk.trigger({ function_id: "mem::vision-embed", payload }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::vision-embed", - config: { api_path: "/agentmemory/vision-embed", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-list", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-list", - config: { api_path: "/agentmemory/slots", http_method: "GET" }, - }); - - sdk.registerFunction("api::slot-get", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const label = asNonEmptyString(req.query_params?.["label"]); - if (!label) return { status_code: 400, body: { error: "label query param required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-get", - config: { api_path: "/agentmemory/slot", http_method: "GET" }, - }); - - sdk.registerFunction("api::slot-create", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const label = asNonEmptyString(body["label"]); - if (!label) return { status_code: 400, body: { error: "label required" } }; - // Reject malformed inputs instead of silently dropping them. - if (body["content"] !== undefined && typeof body["content"] !== "string") { - return { status_code: 400, body: { error: "content must be a string" } }; - } - if (body["description"] !== undefined && typeof body["description"] !== "string") { - return { status_code: 400, body: { error: "description must be a string" } }; - } - if (body["pinned"] !== undefined && typeof body["pinned"] !== "boolean") { - return { status_code: 400, body: { error: "pinned must be a boolean" } }; - } - if ( - body["scope"] !== undefined && - body["scope"] !== "project" && - body["scope"] !== "global" - ) { - return { status_code: 400, body: { error: "scope must be 'project' or 'global'" } }; - } - const sizeLimit = parseOptionalPositiveInt(body["sizeLimit"]); - if (sizeLimit === null) { - return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } }; - } - if (sizeLimit !== undefined && sizeLimit > 20000) { - return { status_code: 400, body: { error: "sizeLimit must be <= 20000" } }; - } - const payload: Record<string, unknown> = { label }; - if (typeof body["content"] === "string") payload["content"] = body["content"]; - if (typeof body["description"] === "string") payload["description"] = body["description"]; - if (sizeLimit !== undefined) payload["sizeLimit"] = sizeLimit; - if (typeof body["pinned"] === "boolean") payload["pinned"] = body["pinned"]; - if (body["scope"] === "project" || body["scope"] === "global") payload["scope"] = body["scope"]; - const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("exists") ? 409 : 400, body: resp }; - } - return { status_code: 201, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-create", - config: { api_path: "/agentmemory/slot", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-append", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const label = asNonEmptyString(body["label"]); - const text = typeof body["text"] === "string" ? body["text"] : null; - if (!label || !text) return { status_code: 400, body: { error: "label and text required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - const notFound = resp.error?.includes("not found"); - const overLimit = resp.error?.includes("exceed"); - return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-append", - config: { api_path: "/agentmemory/slot/append", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-replace", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const label = asNonEmptyString(body["label"]); - const content = body["content"]; - if (!label || typeof content !== "string") { - return { status_code: 400, body: { error: "label and content (string) required" } }; - } - const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - const notFound = resp.error?.includes("not found"); - const overLimit = resp.error?.includes("exceed"); - return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-replace", - config: { api_path: "/agentmemory/slot/replace", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-delete", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const label = asNonEmptyString(req.query_params?.["label"]); - if (!label) return { status_code: 400, body: { error: "label query param required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-delete", - config: { api_path: "/agentmemory/slot", http_method: "DELETE" }, - }); - - sdk.registerFunction("api::slot-reflect", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - if (!isReflectEnabled()) return reflectDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body["sessionId"]); - if (!sessionId) return { status_code: 400, body: { error: "sessionId required" } }; - const maxObservations = parseOptionalPositiveInt(body["maxObservations"]); - if (maxObservations === null) return { status_code: 400, body: { error: "maxObservations must be a positive integer" } }; - const payload: Record<string, unknown> = { sessionId }; - if (maxObservations !== undefined) payload["maxObservations"] = maxObservations; - const result = await sdk.trigger({ function_id: "mem::slot-reflect", payload }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-reflect", - config: { api_path: "/agentmemory/slot/reflect", http_method: "POST" }, - }); - - sdk.registerFunction("api::action-create", - async ( - req: ApiRequest<{ - title: string; - description?: string; - priority?: number; - createdBy?: string; - project?: string; - tags?: string[]; - parentId?: string; - edges?: Array<{ type: string; targetActionId: string }>; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.title) { - return { status_code: 400, body: { error: "title is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-create", - config: { api_path: "/agentmemory/actions", http_method: "POST" }, - }); - - sdk.registerFunction("api::action-update", - async ( - req: ApiRequest<{ - actionId: string; - status?: string; - title?: string; - description?: string; - priority?: number; - result?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId) { - return { status_code: 400, body: { error: "actionId is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-update", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-update", - config: { api_path: "/agentmemory/actions/update", http_method: "POST" }, - }); - - sdk.registerFunction("api::action-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::action-list", payload: { - status: req.query_params?.["status"], - project: req.query_params?.["project"], - parentId: req.query_params?.["parentId"], - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-list", - config: { api_path: "/agentmemory/actions", http_method: "GET" }, - }); - - sdk.registerFunction("api::action-get", - async (req: ApiRequest<{ actionId: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const actionId = req.query_params?.["actionId"] as string; - if (!actionId) { - return { status_code: 400, body: { error: "actionId required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-get", payload: { actionId } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-get", - config: { api_path: "/agentmemory/actions/get", http_method: "GET" }, - }); - - sdk.registerFunction("api::action-edge", - async ( - req: ApiRequest<{ - sourceActionId: string; - targetActionId: string; - type: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) { - return { status_code: 400, body: { error: "sourceActionId, targetActionId, and type are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-edge-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-edge", - config: { api_path: "/agentmemory/actions/edges", http_method: "POST" }, - }); - - sdk.registerFunction("api::frontier", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const result = await sdk.trigger({ function_id: "mem::frontier", payload: { - project: req.query_params?.["project"], - agentId: req.query_params?.["agentId"], - limit: parsedLimit, - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::frontier", - config: { api_path: "/agentmemory/frontier", http_method: "GET" }, - }); - - sdk.registerFunction("api::next", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::next", payload: { - project: req.query_params?.["project"], - agentId: req.query_params?.["agentId"], - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::next", - config: { api_path: "/agentmemory/next", http_method: "GET" }, - }); - - sdk.registerFunction("api::lease-acquire", - async ( - req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId || !req.body?.agentId) { - return { status_code: 400, body: { error: "actionId and agentId are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::lease-acquire", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::lease-acquire", - config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" }, - }); - - sdk.registerFunction("api::lease-release", - async ( - req: ApiRequest<{ actionId: string; agentId: string; result?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId || !req.body?.agentId) { - return { status_code: 400, body: { error: "actionId and agentId are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::lease-release", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::lease-release", - config: { api_path: "/agentmemory/leases/release", http_method: "POST" }, - }); - - sdk.registerFunction("api::lease-renew", - async ( - req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId || !req.body?.agentId) { - return { status_code: 400, body: { error: "actionId and agentId are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::lease-renew", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::lease-renew", - config: { api_path: "/agentmemory/leases/renew", http_method: "POST" }, - }); - - sdk.registerFunction("api::routine-create", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.name || !req.body?.steps) { - return { - status_code: 400, - body: { error: "name and steps are required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::routine-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-create", - config: { api_path: "/agentmemory/routines", http_method: "POST" }, - }); - - sdk.registerFunction("api::routine-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::routine-list", payload: { - frozen: req.query_params?.["frozen"] === "true" ? true : undefined, - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-list", - config: { api_path: "/agentmemory/routines", http_method: "GET" }, - }); - - sdk.registerFunction("api::routine-run", - async ( - req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.routineId) { - return { status_code: 400, body: { error: "routineId is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::routine-run", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-run", - config: { api_path: "/agentmemory/routines/run", http_method: "POST" }, - }); - - sdk.registerFunction("api::routine-status", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const runId = req.query_params?.["runId"] as string; - if (!runId) { - return { status_code: 400, body: { error: "runId query param required" } }; - } - const result = await sdk.trigger({ function_id: "mem::routine-status", payload: { runId } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-status", - config: { api_path: "/agentmemory/routines/status", http_method: "GET" }, - }); - - sdk.registerFunction("api::signal-send", - async ( - req: ApiRequest<{ - from: string; - to?: string; - content: string; - type?: string; - replyTo?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.from || !req.body?.content) { - return { status_code: 400, body: { error: "from and content are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::signal-send", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::signal-send", - config: { api_path: "/agentmemory/signals/send", http_method: "POST" }, - }); - - sdk.registerFunction("api::signal-read", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const agentId = req.query_params?.["agentId"] as string; - if (!agentId) { - return { status_code: 400, body: { error: "agentId query param required" } }; - } - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const result = await sdk.trigger({ function_id: "mem::signal-read", payload: { - agentId, - unreadOnly: req.query_params?.["unreadOnly"] === "true", - threadId: req.query_params?.["threadId"], - limit: parsedLimit, - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::signal-read", - config: { api_path: "/agentmemory/signals", http_method: "GET" }, - }); - - sdk.registerFunction("api::checkpoint-create", - async ( - req: ApiRequest<{ - name: string; - description?: string; - type?: string; - linkedActionIds?: string[]; - expiresInMs?: number; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.name) { - return { status_code: 400, body: { error: "name is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::checkpoint-create", - config: { api_path: "/agentmemory/checkpoints", http_method: "POST" }, - }); - - sdk.registerFunction("api::checkpoint-resolve", - async ( - req: ApiRequest<{ - checkpointId: string; - status: string; - resolvedBy?: string; - result?: unknown; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.checkpointId || !req.body?.status) { - return { status_code: 400, body: { error: "checkpointId and status are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::checkpoint-resolve", - config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" }, - }); - - sdk.registerFunction("api::checkpoint-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { - status: req.query_params?.["status"], - type: req.query_params?.["type"], - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::checkpoint-list", - config: { api_path: "/agentmemory/checkpoints", http_method: "GET" }, - }); - - sdk.registerFunction("api::mesh-register", - async ( - req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>, - ): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.url || !req.body?.name) { - return { status_code: 400, body: { error: "url and name are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::mesh-register", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-register", - config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" }, - }); - - sdk.registerFunction("api::mesh-list", - async (req: ApiRequest): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::mesh-list", payload: {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-list", - config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" }, - }); - - sdk.registerFunction("api::mesh-sync", - async ( - req: ApiRequest<{ peerId?: string; direction?: string }>, - ): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::mesh-sync", payload: req.body || {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-sync", - config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" }, - }); - - sdk.registerFunction("api::mesh-receive", - async (req: ApiRequest): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::mesh-receive", payload: req.body || {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-receive", - config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" }, - }); - - sdk.registerFunction("api::mesh-export", - async (req: ApiRequest): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const since = req.query_params?.["since"] as string; - if (since) { - const parsed = new Date(since).getTime(); - if (Number.isNaN(parsed)) { - return { status_code: 400, body: { error: "Invalid 'since' date format" } }; - } - } - const project = req.query_params?.["project"] as string | undefined; - const sinceTime = since ? new Date(since).getTime() : 0; - const df = <T>(items: T[], field: "updatedAt" | "createdAt") => - items.filter((i) => new Date((i as Record<string, unknown>)[field] as string).getTime() > sinceTime); - let memories = await kv.list<import("../types.js").Memory>(KV.memories); - let actions = await kv.list<import("../types.js").Action>(KV.actions); - if (project) { - memories = memories.filter((m) => m.project === project); - actions = actions.filter((a) => a.project === project); - } - const body: Record<string, unknown> = { - memories: df(memories, "updatedAt"), - actions: df(actions, "updatedAt"), - }; - if (!project) { - const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); - const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); - const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); - body.semantic = df(semantic, "updatedAt"); - body.procedural = df(procedural, "updatedAt"); - body.relations = df(relations, "createdAt"); - // B-mode: graph frozen — never enumerate the graph scope for the - // mesh-sync delta body. - if (!graphLegDisabled()) { - const graphNodes = await kv.list<import("../types.js").GraphNode>(KV.graphNodes); - const graphEdges = await kv.list<import("../types.js").GraphEdge>(KV.graphEdges); - body.graphNodes = graphNodes.filter( - (n) => new Date(n.updatedAt || n.createdAt).getTime() > sinceTime, - ); - body.graphEdges = df(graphEdges, "createdAt"); - } - } - // Fail an oversized export with 413 rather than on heap. - const oversized = checkPayloadSize( - body, - "use ?since to fetch only changes after a timestamp, or ?project to scope the export", - ); - if (oversized) return { status_code: 413, body: oversized }; - return { status_code: 200, body }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-export", - config: { api_path: "/agentmemory/mesh/export", http_method: "GET" }, - }); - - sdk.registerFunction("api::flow-compress", - async ( - req: ApiRequest<{ - runId?: string; - actionIds?: string[]; - project?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::flow-compress", payload: req.body || {} }); - return { status_code: 200, body: result }; - } catch { - return { - status_code: 404, - body: { error: "Flow compression requires a provider" }, - }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::flow-compress", - config: { api_path: "/agentmemory/flow/compress", http_method: "POST" }, - }); - - sdk.registerFunction("api::branch-detect", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); - const result = await sdk.trigger({ function_id: "mem::detect-worktree", payload: { cwd } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::branch-detect", - config: { api_path: "/agentmemory/branch/detect", http_method: "GET" }, - }); - - sdk.registerFunction("api::branch-worktrees", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); - const result = await sdk.trigger({ function_id: "mem::list-worktrees", payload: { cwd } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::branch-worktrees", - config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" }, - }); - - sdk.registerFunction("api::branch-sessions", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); - const result = await sdk.trigger({ function_id: "mem::branch-sessions", payload: { cwd } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::branch-sessions", - config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" }, - }); - - sdk.registerFunction("api::viewer", - async (req: ApiRequest): Promise<Response> => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const rendered = renderViewerDocument(); - if (rendered.found) { - return { - status_code: 200, - headers: { - "Content-Type": "text/html", - "Content-Security-Policy": rendered.csp, - }, - body: rendered.html, - }; - } - return { - status_code: 404, - headers: { - "Content-Type": "text/html", - }, - body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>", - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::viewer", - config: { api_path: "/agentmemory/viewer", http_method: "GET" }, - }); - - sdk.registerFunction("api::sentinel-create", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.name) return { status_code: 400, body: { error: "name is required" } }; - const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-trigger", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-check", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-cancel", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sentinel-cancel", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const result = await sdk.trigger({ function_id: "mem::sentinel-list", payload: { status: params.status, type: params.type } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } }); - - sdk.registerFunction("api::sketch-create", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.title) return { status_code: 400, body: { error: "title is required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-add", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sketchId || !body?.title) return { status_code: 400, body: { error: "sketchId and title are required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-add", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-promote", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-discard", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-discard", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const result = await sdk.trigger({ function_id: "mem::sketch-list", payload: { status: params.status, project: params.project } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } }); - - sdk.registerFunction("api::sketch-gc", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } }); - - sdk.registerFunction("api::crystallize", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.actionIds) return { status_code: 400, body: { error: "actionIds is required" } }; - const result = await sdk.trigger({ function_id: "mem::crystallize", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } }); - - sdk.registerFunction("api::crystal-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const limit = parseOptionalPositiveInt(params.limit); - if (limit === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: limit" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { project: params.project, sessionId: params.sessionId, limit } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } }); - - sdk.registerFunction("api::auto-crystallize", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::auto-crystallize", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } }); - - sdk.registerFunction("api::diagnose", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::diagnose", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } }); - - sdk.registerFunction("api::heal", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::heal", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } }); - - sdk.registerFunction("api::facet-tag", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.targetId || !body?.dimension || !body?.value) return { status_code: 400, body: { error: "targetId, dimension, and value are required" } }; - const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } }); - - sdk.registerFunction("api::facet-untag", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.targetId || !body?.dimension) return { status_code: 400, body: { error: "targetId and dimension are required" } }; - const result = await sdk.trigger({ function_id: "mem::facet-untag", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } }); - - sdk.registerFunction("api::facet-query", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::facet-query", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } }); - - sdk.registerFunction("api::facet-get", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - if (!params.targetId) return { status_code: 400, body: { error: "targetId query param is required" } }; - const result = await sdk.trigger({ function_id: "mem::facet-get", payload: { targetId: params.targetId } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } }); - - sdk.registerFunction("api::facet-stats", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const result = await sdk.trigger({ function_id: "mem::facet-stats", payload: { targetType: params.targetType } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } }); - - sdk.registerFunction("api::verify", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.id || typeof body.id !== "string") return { status_code: 400, body: { error: "id is required" } }; - const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: body.id } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } }); - - sdk.registerFunction("api::cascade-update", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") { - return { status_code: 400, body: { error: "supersededMemoryId is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::cascade-update", payload: { supersededMemoryId: body.supersededMemoryId } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-save", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.content || typeof body.content !== "string") return { status_code: 400, body: { error: "content is required" } }; - const tags = typeof body.tags === "string" ? (body.tags as string).split(",").map((t: string) => t.trim()).filter(Boolean) : Array.isArray(body.tags) ? body.tags : []; - const result = (await sdk.trigger({ - function_id: "mem::lesson-save", - payload: { - content: body.content, - context: body.context || "", - confidence: typeof body.confidence === "number" ? body.confidence : undefined, - project: typeof body.project === "string" ? body.project : undefined, - tags, - source: "manual", - }, - })) as { action?: string }; - const statusCode = result?.action === "created" ? 201 : 200; - return { status_code: statusCode, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const minConfidence = parseOptionalFiniteNumber(params.minConfidence); - if (minConfidence === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: minConfidence" }, - }; - } - const limit = parseOptionalPositiveInt(params.limit); - if (limit === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: limit" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: { - project: params.project, - source: params.source, - minConfidence, - limit, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } }); - - sdk.registerFunction("api::lesson-search", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; - const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-strengthen", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.lessonId || typeof body.lessonId !== "string") return { status_code: 400, body: { error: "lessonId is required" } }; - const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: body.lessonId } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-delete", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const lessonId = typeof body?.lessonId === "string" ? body.lessonId.trim() : ""; - if (!lessonId) return { status_code: 400, body: { error: "lessonId is required" } }; - const result = await sdk.trigger({ function_id: "mem::lesson-delete", payload: { lessonId } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false && resp.error === "lesson not found") { - return { status_code: 404, body: { error: "lesson not found" } }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } }); - - sdk.registerFunction("api::obsidian-export", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = (req.body as Record<string, unknown>) || {}; - const vaultDir = asNonEmptyString(body.vaultDir); - if (!vaultDir) { - return { - status_code: 400, - body: { error: "vaultDir must be a non-empty string" }, - }; - } - const types = typeof body.types === "string" ? body.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined; - const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir, types } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } }); - - sdk.registerFunction("api::reflect", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = (req.body as Record<string, unknown>) || {}; - const result = await sdk.trigger({ function_id: "mem::reflect", payload: { - project: typeof body.project === "string" ? body.project : undefined, - maxClusters: typeof body.maxClusters === "number" ? body.maxClusters : undefined, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } }); - - sdk.registerFunction("api::insight-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const minConfidence = parseOptionalFiniteNumber(params.minConfidence); - if (minConfidence === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: minConfidence" }, - }; - } - const limit = parseOptionalPositiveInt(params.limit); - if (limit === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: limit" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::insight-list", payload: { - project: params.project, - minConfidence, - limit, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } }); - - sdk.registerFunction("api::insight-search", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; - const result = await sdk.trigger({ function_id: "mem::insight-search", payload: { - query: body.query, - project: typeof body.project === "string" ? body.project : undefined, - minConfidence: typeof body.minConfidence === "number" ? body.minConfidence : undefined, - limit: typeof body.limit === "number" ? body.limit : undefined, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } }); -} +import { TriggerAction, type ISdk, type ApiRequest } from "../engine/types.js"; +import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js"; +import { withKeyedLock } from "../state/keyed-mutex.js"; +import { KV } from "../state/schema.js"; +import { StateKV } from "../state/kv.js"; +import { graphLegDisabled } from "../state/graph-indexes.js"; +import { checkPayloadSize, isOversizedPayload } from "../state/payload-bound.js"; +import { getLatestHealth } from "../health/monitor.js"; +import type { MetricsStore } from "../eval/metrics-store.js"; +import type { ResilientProvider } from "../providers/resilient.js"; +import { VERSION } from "../version.js"; +import { timingSafeCompare } from "../auth.js"; +import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js"; +import { renderViewerDocument } from "../viewer/document.js"; +import { getBoundViewerPort, getViewerSkipped } from "../viewer/server.js"; +import { MAX_FILES_UPPER_BOUND } from "../functions/replay.js"; +import { logger } from "../logger.js"; +import { + isGraphExtractionEnabled, + isConsolidationEnabled, + isAutoCompressEnabled, + isContextInjectionEnabled, + detectEmbeddingProvider, + detectLlmProviderKind, + getAgentId, + isAgentScopeIsolated, + loadConfig, +} from "../config.js"; + +type Response = { + status_code: number; + headers?: Record<string, string>; + body: unknown; +}; + +function parseOptionalInt(raw: unknown): number | undefined { + if (raw === undefined || raw === null || raw === "") return undefined; + const n = typeof raw === "number" ? raw : parseInt(String(raw), 10); + return Number.isFinite(n) ? n : undefined; +} + +function checkAuth( + req: ApiRequest, + secret: string | undefined, +): Response | null { + if (!secret) return null; + const auth = req.headers?.["authorization"] || req.headers?.["Authorization"]; + if ( + typeof auth !== "string" || + !timingSafeCompare(auth, `Bearer ${secret}`) + ) { + return { status_code: 401, body: { error: "unauthorized" } }; + } + return null; +} + +function requireConfiguredSecret( + secret: string | undefined, + feature: string, +): Response | null { + if (secret) return null; + return { + status_code: 503, + body: { error: `${feature} requires AGENTMEMORY_SECRET` }, + }; +} + +function flagDisabledResponse(opts: { + error: string; + flag: string; + enableHow: string; + docsHref: string; +}): Response { + return { + status_code: 503, + body: opts, + }; +} + +function graphDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Knowledge graph not enabled", + flag: "GRAPH_EXTRACTION_ENABLED", + enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.", + docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", + }); +} + +function consolidationDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Consolidation pipeline not enabled", + flag: "CONSOLIDATION_ENABLED", + enableHow: "Set CONSOLIDATION_ENABLED=true and restart. Requires an LLM provider key.", + docsHref: "https://github.com/rohitg00/agentmemory#consolidation", + }); +} + +function slotsDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Memory slots not enabled", + flag: "AGENTMEMORY_SLOTS", + enableHow: "Set AGENTMEMORY_SLOTS=true (in ~/.agentmemory/.env or the shell) and restart.", + docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", + }); +} + +function reflectDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Slot reflection not enabled", + flag: "AGENTMEMORY_REFLECT", + enableHow: "Set AGENTMEMORY_REFLECT=true (in ~/.agentmemory/.env or the shell) and restart. Requires AGENTMEMORY_SLOTS=true.", + docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", + }); +} + +function asNonEmptyString(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed ? trimmed : null; +} + +function parseOptionalFiniteNumber(value: unknown): number | undefined | null { + if (value === undefined || value === null) return undefined; + if (typeof value === "number") return Number.isFinite(value) ? value : null; + if (typeof value === "string") { + const trimmed = value.trim(); + if (!trimmed) return undefined; + const parsed = Number(trimmed); + return Number.isFinite(parsed) ? parsed : null; + } + return null; +} + +function parseOptionalPositiveInt(value: unknown): number | undefined | null { + const parsed = parseOptionalFiniteNumber(value); + if (parsed === undefined || parsed === null) return parsed; + if (!Number.isInteger(parsed) || parsed < 1) return null; + return parsed; +} + +export function registerApiTriggers( + sdk: ISdk, + kv: StateKV, + secret?: string, + metricsStore?: MetricsStore, + provider?: ResilientProvider | { circuitState?: unknown }, +): void { + sdk.registerFunction( + "middleware::api-auth", + async (input: { + request?: { headers?: Record<string, string | undefined> }; + }) => { + if (!secret) return { action: "continue" }; + const headers = input?.request?.headers || {}; + const auth = headers["authorization"] || headers["Authorization"]; + if ( + typeof auth !== "string" || + !timingSafeCompare(auth, `Bearer ${secret}`) + ) { + return { + action: "respond", + response: { status_code: 401, body: { error: "unauthorized" } }, + }; + } + return { action: "continue" }; + }, + ); + + // Shared instance metadata for livez and health so the two never + // drift. streamsPort lets the viewer resolve its stream WebSocket + // target from the server instead of port arithmetic, which broke + // whenever the viewer bound a fallback port. Config is boot-static, + // so read it once instead of rebuilding the merged env per request. + const bootStreamsPort = loadConfig().streamsPort; + const instanceInfo = () => ({ + service: "agentmemory", + viewerPort: getBoundViewerPort(), + viewerSkipped: getViewerSkipped(), + streamsPort: bootStreamsPort, + }); + + sdk.registerFunction("api::liveness", + async (): Promise<Response> => ({ + status_code: 200, + body: { status: "ok", ...instanceInfo() }, + }), + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::liveness", + config: { api_path: "/agentmemory/livez", http_method: "GET" }, + }); + + sdk.registerFunction("api::config-flags", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const providerKind = detectLlmProviderKind(); + const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none"; + const flags = [ + { + key: "GRAPH_EXTRACTION_ENABLED", + label: "Knowledge graph extraction", + enabled: isGraphExtractionEnabled(), + default: false, + affects: ["Graph", "Dashboard"], + needsLlm: true, + description: "Extracts entities and relations from observations into a knowledge graph.", + enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.", + docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", + }, + { + key: "CONSOLIDATION_ENABLED", + label: "Memory consolidation", + enabled: isConsolidationEnabled(), + default: false, + affects: ["Dashboard", "Memories", "Crystals"], + needsLlm: true, + description: "Periodically summarizes sessions into semantic facts + procedures.", + enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.", + docsHref: "https://github.com/rohitg00/agentmemory#consolidation", + }, + { + key: "AGENTMEMORY_AUTO_COMPRESS", + label: "LLM-powered observation compression", + enabled: isAutoCompressEnabled(), + default: false, + affects: ["Memories", "Timeline"], + needsLlm: true, + description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.", + enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.", + docsHref: "https://github.com/rohitg00/agentmemory/issues/138", + }, + { + key: "AGENTMEMORY_INJECT_CONTEXT", + label: "In-conversation context injection", + enabled: isContextInjectionEnabled(), + default: false, + affects: ["Hooks"], + needsLlm: false, + description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.", + enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.", + docsHref: "https://github.com/rohitg00/agentmemory/issues/143", + }, + ]; + return { + status_code: 200, + body: { + version: VERSION, + provider: providerKind, + embeddingProvider, + flags, + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::config-flags", + config: { + api_path: "/agentmemory/config/flags", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::health", + async (req: ApiRequest): Promise<Response> => { + const health = await getLatestHealth(kv); + const functionMetrics = metricsStore ? await metricsStore.getAll() : []; + const circuitBreaker = + provider && "circuitState" in provider ? provider.circuitState : null; + + const status = health?.status || "healthy"; + const statusCode = status === "critical" ? 503 : 200; + + return { + status_code: statusCode, + body: { + status, + version: VERSION, + health: health || null, + functionMetrics, + circuitBreaker, + ...instanceInfo(), + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::health", + config: { + api_path: "/agentmemory/health", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::observe", + async (req: ApiRequest<HookPayload>): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const hookType = asNonEmptyString(body.hookType); + const sessionId = asNonEmptyString(body.sessionId); + const project = asNonEmptyString(body.project); + const cwd = asNonEmptyString(body.cwd); + const timestamp = asNonEmptyString(body.timestamp); + if (!hookType || !sessionId || !project || !cwd || !timestamp) { + return { + status_code: 400, + body: { + error: + "hookType, sessionId, project, cwd, and timestamp are required strings", + }, + }; + } + const payload: HookPayload = { + hookType: hookType as HookPayload["hookType"], + sessionId, + project, + cwd, + timestamp, + data: body.data, + }; + const result = await sdk.trigger({ function_id: "mem::observe", payload }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::observe", + config: { + api_path: "/agentmemory/observe", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::context", + async ( + req: ApiRequest<{ + sessionId: string; + project: string; + budget?: number; + agentId?: string; + }>, + ): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body.sessionId); + const project = asNonEmptyString(body.project); + if (!sessionId || !project) { + return { + status_code: 400, + body: { error: "sessionId and project are required strings" }, + }; + } + const budget = parseOptionalPositiveInt(body.budget); + if (budget === null) { + return { + status_code: 400, + body: { error: "budget must be a positive integer" }, + }; + } + // Propagate agentId so mem::context applies the same cross-agent + // isolation filter as mem::search. Honors body.agentId, ?agentId=, + // or the worker's AGENT_ID fallback under AGENTMEMORY_AGENT_SCOPE=isolated. + const queryAgentId = + typeof (req as { query_params?: Record<string, string> }) + .query_params?.["agentId"] === "string" + ? (req as { query_params: Record<string, string> }) + .query_params["agentId"] + : undefined; + const bodyAgentId = + typeof body.agentId === "string" && body.agentId.trim().length > 0 + ? (body.agentId as string).trim() + : undefined; + const payload: { + sessionId: string; + project: string; + budget?: number; + agentId?: string; + } = { + sessionId, + project, + }; + if (budget !== undefined) payload.budget = budget; + const agentId = bodyAgentId ?? queryAgentId; + if (agentId !== undefined) payload.agentId = agentId; + const result = await sdk.trigger({ function_id: "mem::context", payload }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::context", + config: { + api_path: "/agentmemory/context", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::search", + async ( + req: ApiRequest<{ + query: string; + limit?: number; + project?: string; + cwd?: string; + format?: string; + token_budget?: number; + agentId?: string; + }>, + ): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const queryAgentId = + typeof (req as { query_params?: Record<string, string> }) + .query_params?.["agentId"] === "string" + ? (req as { query_params: Record<string, string> }) + .query_params["agentId"] + : undefined; + if (typeof body.query !== "string" || !body.query.trim()) { + return { status_code: 400, body: { error: "query is required and must be a non-empty string" } }; + } + if ( + body.limit !== undefined && + (!Number.isInteger(body.limit) || (body.limit as number) < 1) + ) { + return { status_code: 400, body: { error: "limit must be a positive integer" } }; + } + if (body.project !== undefined && typeof body.project !== "string") { + return { status_code: 400, body: { error: "project must be a string" } }; + } + if (body.cwd !== undefined && typeof body.cwd !== "string") { + return { status_code: 400, body: { error: "cwd must be a string" } }; + } + if ( + body.format !== undefined && + (typeof body.format !== "string" || + !["full", "compact", "narrative"].includes(body.format.trim().toLowerCase())) + ) { + return { + status_code: 400, + body: { error: "format must be one of: full, compact, narrative" }, + }; + } + if ( + body.token_budget !== undefined && + (!Number.isInteger(body.token_budget) || (body.token_budget as number) < 1) + ) { + return { + status_code: 400, + body: { error: "token_budget must be a positive integer" }, + }; + } + // #817: propagate agentId so the upstream isolation filter + // applies. Honors body.agentId (POST body), ?agentId=... query + // param, or implicit fallback to the worker's AGENT_ID when + // AGENTMEMORY_AGENT_SCOPE=isolated. + const bodyAgentId = + typeof body.agentId === "string" && body.agentId.trim().length > 0 + ? (body.agentId as string).trim() + : undefined; + const payload = { + query: body.query.trim(), + limit: body.limit as number | undefined, + project: body.project as string | undefined, + cwd: body.cwd as string | undefined, + format: + typeof body.format === "string" + ? body.format.trim().toLowerCase() + : undefined, + token_budget: body.token_budget as number | undefined, + agentId: bodyAgentId ?? queryAgentId, + }; + const result = await sdk.trigger({ function_id: "mem::search", payload: payload }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::search", + config: { + api_path: "/agentmemory/search", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::compress-file", + async (req: ApiRequest<{ filePath: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const filePath = asNonEmptyString(body.filePath); + if (!filePath) { + return { + status_code: 400, + body: { error: "filePath is required and must be a non-empty string" }, + }; + } + const result = await sdk.trigger({ + function_id: "mem::compress-file", + payload: { filePath }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::compress-file", + config: { api_path: "/agentmemory/compress-file", http_method: "POST" }, + }); + + sdk.registerFunction("api::replay::load", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); + if (!sessionId) { + return { status_code: 400, body: { error: "sessionId is required" } }; + } + const result = await sdk.trigger({ + function_id: "mem::replay::load", + payload: { sessionId }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::replay::load", + config: { api_path: "/agentmemory/replay/load", http_method: "GET" }, + }); + + sdk.registerFunction("api::replay::sessions", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessions = await kv.list<Session>(KV.sessions); + sessions.sort((a, b) => + (b.startedAt || "").localeCompare(a.startedAt || ""), + ); + return { status_code: 200, body: { success: true, sessions } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::replay::sessions", + config: { api_path: "/agentmemory/replay/sessions", http_method: "GET" }, + }); + + sdk.registerFunction("api::replay::import", + async ( + req: ApiRequest<{ path?: string; maxFiles?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const payload: { path?: string; maxFiles?: number } = {}; + if (body.path !== undefined) { + if (typeof body.path !== "string" || body.path.trim().length === 0) { + return { + status_code: 400, + body: { error: "path must be a non-empty string" }, + }; + } + payload.path = body.path.trim(); + } + if (body.maxFiles !== undefined) { + const n = body.maxFiles as number; + if ( + !Number.isInteger(n) || + n < 1 || + n > MAX_FILES_UPPER_BOUND + ) { + return { + status_code: 400, + body: { + error: `maxFiles must be an integer between 1 and ${MAX_FILES_UPPER_BOUND}`, + }, + }; + } + payload.maxFiles = n; + } + const result = await sdk.trigger({ + function_id: "mem::replay::import-jsonl", + payload, + }); + return { status_code: 202, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::replay::import", + config: { api_path: "/agentmemory/replay/import-jsonl", http_method: "POST" }, + }); + + sdk.registerFunction("api::session::start", + async ( + req: ApiRequest<{ sessionId: string; project: string; cwd: string }>, + ): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body.sessionId); + const project = asNonEmptyString(body.project); + const cwd = asNonEmptyString(body.cwd); + if (!sessionId || !project || !cwd) { + return { + status_code: 400, + body: { + error: "sessionId, project, and cwd are required non-empty strings", + }, + }; + } + const title = typeof body.title === "string" ? body.title.trim() : undefined; + // allow session/start to override AGENT_ID from request body + // (multi-agent runtimes that route many roles through one server + // process). Falls back to the AGENT_ID env on the server. + const requestAgentId = + typeof body.agentId === "string" && body.agentId.trim().length > 0 + ? body.agentId.trim().slice(0, 128) + : undefined; + const agentId = requestAgentId ?? getAgentId(); + const session: Session = { + id: sessionId, + project, + cwd, + startedAt: new Date().toISOString(), + status: "active", + observationCount: 0, + ...(title ? { summary: title.slice(0, 200) } : {}), + ...(title ? { firstPrompt: title.slice(0, 200) } : {}), + ...(agentId ? { agentId } : {}), + }; + await kv.set(KV.sessions, sessionId, session); + const contextResult = await sdk.trigger< + { sessionId: string; project: string; agentId?: string }, + { context: string } + >({ + function_id: "mem::context", + payload: { sessionId, project, ...(agentId ? { agentId } : {}) }, + }); + return { + status_code: 200, + body: { session, context: contextResult.context }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::start", + config: { + api_path: "/agentmemory/session/start", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::end", + async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => { + const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId); + if (!sessionId) { + return { + status_code: 400, + body: { error: "sessionId is required and must be a non-empty string" }, + }; + } + await kv.update(KV.sessions, sessionId, [ + { type: "set", path: "endedAt", value: new Date().toISOString() }, + { type: "set", path: "status", value: "completed" }, + ]); + // Fan out session-stopped lifecycle (non-blocking). + try { + sdk.trigger({ + function_id: "event::session::stopped", + payload: { sessionId }, + action: TriggerAction.Void(), + }); + } catch (err) { + logger.warn("event::session::stopped trigger failed", { + sessionId, + error: err instanceof Error ? err.message : String(err), + }); + } + return { status_code: 200, body: { success: true } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::end", + config: { + api_path: "/agentmemory/session/end", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::summarize", + async (req: ApiRequest<{ sessionId: string; force?: boolean }>): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body.sessionId); + if (!sessionId) { + return { status_code: 400, body: { error: "sessionId is required" } }; + } + const result = await sdk.trigger({ + function_id: "mem::summarize", + payload: { sessionId, force: body.force === true }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::summarize", + config: { + api_path: "/agentmemory/summarize", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::commit", + async (req: ApiRequest): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sha = asNonEmptyString(body.sha); + if (!sha) { + return { + status_code: 400, + body: { error: "sha is required and must be a non-empty string" }, + }; + } + const sessionId = asNonEmptyString(body.sessionId) ?? undefined; + const branch = asNonEmptyString(body.branch) ?? undefined; + const repo = asNonEmptyString(body.repo) ?? undefined; + const message = asNonEmptyString(body.message) ?? undefined; + const author = asNonEmptyString(body.author) ?? undefined; + const authoredAt = asNonEmptyString(body.authoredAt) ?? undefined; + const files = Array.isArray(body.files) + ? (body.files as unknown[]).filter( + (f): f is string => typeof f === "string" && f.length > 0, + ) + : undefined; + + const link = await withKeyedLock(`commit:${sha}`, async () => { + const existing = await kv.get<CommitLink>(KV.commits, sha); + const sessionSet = new Set<string>(existing?.sessionIds ?? []); + if (sessionId) sessionSet.add(sessionId); + const merged: CommitLink = { + sha, + shortSha: existing?.shortSha ?? sha.slice(0, 7), + branch: branch ?? existing?.branch, + repo: repo ?? existing?.repo, + message: message ?? existing?.message, + author: author ?? existing?.author, + authoredAt: authoredAt ?? existing?.authoredAt, + files: files ?? existing?.files, + sessionIds: Array.from(sessionSet), + linkedAt: existing?.linkedAt ?? new Date().toISOString(), + }; + await kv.set(KV.commits, sha, merged); + return merged; + }); + + if (sessionId) { + await withKeyedLock(`session:${sessionId}`, async () => { + const session = await kv.get<Session>(KV.sessions, sessionId); + if (!session) return; + const shaSet = new Set<string>(session.commitShas ?? []); + shaSet.add(sha); + session.commitShas = Array.from(shaSet); + await kv.set(KV.sessions, sessionId, session); + }); + } + + return { status_code: 200, body: { commit: link } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::commit", + config: { + api_path: "/agentmemory/session/commit", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::by-commit", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sha = asNonEmptyString(req.query_params?.["sha"]); + if (!sha) { + return { + status_code: 400, + body: { error: "sha is required and must be a non-empty string" }, + }; + } + const link = await kv.get<CommitLink>(KV.commits, sha); + if (!link) { + return { + status_code: 404, + body: { error: "no sessions linked to this commit" }, + }; + } + const fetched = await Promise.all( + (link.sessionIds ?? []).map((sid) => kv.get<Session>(KV.sessions, sid)), + ); + const sessions = fetched.filter((s): s is Session => s !== null); + return { status_code: 200, body: { commit: link, sessions } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::by-commit", + config: { + api_path: "/agentmemory/session/by-commit", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::commits", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const branch = asNonEmptyString(req.query_params?.["branch"]); + const repo = asNonEmptyString(req.query_params?.["repo"]); + const rawLimit = parseOptionalInt(req.query_params?.["limit"]); + const limit = Math.max(1, Math.min(500, rawLimit ?? 100)); + const all = await kv.list<CommitLink>(KV.commits); + const filtered = all + .filter((c) => !branch || c.branch === branch) + .filter((c) => !repo || c.repo === repo) + .sort((a, b) => ((a.linkedAt ?? "") < (b.linkedAt ?? "") ? 1 : -1)) + .slice(0, limit); + return { status_code: 200, body: { commits: filtered } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::commits", + config: { + api_path: "/agentmemory/commits", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::sessions", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessions = await kv.list<Session>(KV.sessions); + const normalizedAgentId = + typeof req.query_params?.["agentId"] === "string" + ? req.query_params["agentId"].trim() + : undefined; + const wildcardAgent = normalizedAgentId === "*"; + const explicitAgentId = + normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; + const filterAgentId = wildcardAgent + ? undefined + : explicitAgentId ?? + (isAgentScopeIsolated() ? getAgentId() : undefined); + const filtered = filterAgentId + ? sessions.filter((s) => s.agentId === filterAgentId) + : sessions; + // Bounded fan-out: each kv.get is a full engine invocation, so + // Promise.all over hundreds of sessions saturates the invocation + // pool. Batch in chunks of 10 (parallel within a chunk, sequential + // across chunks); the summaries array stays index-aligned with + // `filtered`. + const summaries: Array<SessionSummary | null> = []; + for (let batch = 0; batch < filtered.length; batch += 10) { + const chunk = filtered.slice(batch, batch + 10); + const results = await Promise.all( + chunk.map((s) => + kv.get<SessionSummary>(KV.summaries, s.id).catch(() => null), + ), + ); + summaries.push(...results); + } + const withSummary = filtered.map((s, i) => + summaries[i] ? { ...s, summary: summaries[i] } : s, + ); + return { status_code: 200, body: { sessions: withSummary } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::sessions", + config: { api_path: "/agentmemory/sessions", http_method: "GET" }, + }); + + sdk.registerFunction("api::observations", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); + if (!sessionId) + return { status_code: 400, body: { error: "sessionId required" } }; + const observations = await kv.list<CompressedObservation>( + KV.observations(sessionId), + ); + const normalizedAgentId = + typeof req.query_params?.["agentId"] === "string" + ? req.query_params["agentId"].trim() + : undefined; + const wildcardAgent = normalizedAgentId === "*"; + const explicitAgentId = + normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; + const filterAgentId = wildcardAgent + ? undefined + : explicitAgentId ?? + (isAgentScopeIsolated() ? getAgentId() : undefined); + const filtered = filterAgentId + ? observations.filter((o) => o.agentId === filterAgentId) + : observations; + return { status_code: 200, body: { observations: filtered } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::observations", + config: { api_path: "/agentmemory/observations", http_method: "GET" }, + }); + + sdk.registerFunction("api::file-context", + async ( + req: ApiRequest<{ sessionId: string; files: string[] }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::file-context", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::file-context", + config: { api_path: "/agentmemory/file-context", http_method: "POST" }, + }); + + sdk.registerFunction("api::enrich", + async ( + req: ApiRequest<{ + sessionId: string; + files: string[]; + terms?: string[]; + toolName?: string; + project?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !req.body?.sessionId || + typeof req.body.sessionId !== "string" || + !Array.isArray(req.body?.files) || + req.body.files.length === 0 || + !req.body.files.every((f: unknown) => typeof f === "string") + ) { + return { + status_code: 400, + body: { + error: "sessionId (string) and files (string[]) are required", + }, + }; + } + if ( + req.body.terms !== undefined && + (!Array.isArray(req.body.terms) || + !req.body.terms.every((t: unknown) => typeof t === "string")) + ) { + return { + status_code: 400, + body: { error: "terms must be an array of strings" }, + }; + } + if ( + req.body.project !== undefined && + (typeof req.body.project !== "string" || !req.body.project.trim()) + ) { + return { + status_code: 400, + body: { error: "project must be a non-empty string" }, + }; + } + const result = await sdk.trigger({ + function_id: "mem::enrich", + payload: { + sessionId: req.body.sessionId, + files: req.body.files, + ...(req.body.terms !== undefined && { terms: req.body.terms }), + ...(req.body.toolName !== undefined && { toolName: req.body.toolName }), + ...(req.body.project !== undefined && { project: req.body.project }), + }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::enrich", + config: { api_path: "/agentmemory/enrich", http_method: "POST" }, + }); + + sdk.registerFunction("api::remember", + async ( + req: ApiRequest<{ + content: string; + type?: string; + concepts?: string[]; + files?: string[]; + ttlDays?: number; + sourceObservationIds?: string[]; + project?: string; + agentId?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !req.body?.content || + typeof req.body.content !== "string" || + !req.body.content.trim() + ) { + return { status_code: 400, body: { error: "content is required" } }; + } + if ( + req.body.project !== undefined && + (typeof req.body.project !== "string" || !req.body.project.trim()) + ) { + return { status_code: 400, body: { error: "project must be a non-empty string" } }; + } + const result = await sdk.trigger({ + function_id: "mem::remember", + payload: { + content: req.body.content, + ...(req.body.type !== undefined && { type: req.body.type }), + ...(req.body.concepts !== undefined && { concepts: req.body.concepts }), + ...(req.body.files !== undefined && { files: req.body.files }), + ...(req.body.ttlDays !== undefined && { ttlDays: req.body.ttlDays }), + ...(req.body.sourceObservationIds !== undefined && { sourceObservationIds: req.body.sourceObservationIds }), + ...(req.body.project !== undefined && { project: req.body.project }), + ...(typeof req.body.agentId === "string" && req.body.agentId.trim() + ? { agentId: req.body.agentId.trim() } + : {}), + }, + }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::remember", + config: { api_path: "/agentmemory/remember", http_method: "POST" }, + }); + + sdk.registerFunction("api::forget", + async ( + req: ApiRequest<{ + sessionId?: string; + observationIds?: string[]; + memoryId?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessionId = + typeof req.body?.sessionId === "string" ? req.body.sessionId : undefined; + const memoryId = + typeof req.body?.memoryId === "string" ? req.body.memoryId : undefined; + if (!sessionId && !memoryId) { + return { + status_code: 400, + body: { error: "sessionId or memoryId is required" }, + }; + } + const rawObservationIds = req.body?.observationIds; + // Dropping the non-strings and forwarding what is left would turn a + // malformed list into an empty one, and an empty list is the whole- + // session wipe. Refuse instead of widening what was asked for. + if ( + rawObservationIds !== undefined && + (!Array.isArray(rawObservationIds) || + !rawObservationIds.every((id) => typeof id === "string")) + ) { + return { + status_code: 400, + body: { error: "observationIds must be an array of strings" }, + }; + } + const result = (await sdk.trigger({ + function_id: "mem::forget", + payload: { + ...(sessionId !== undefined && { sessionId }), + ...(memoryId !== undefined && { memoryId }), + ...(rawObservationIds !== undefined && { observationIds: rawObservationIds }), + }, + })) as { success: boolean; error?: string }; + // The refusals mem::forget raises are bad requests, not results. + if (!result.success) { + return { status_code: 400, body: result }; + } + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::forget", + config: { api_path: "/agentmemory/forget", http_method: "POST" }, + }); + + sdk.registerFunction("api::consolidate", + async ( + req: ApiRequest<{ project?: string; minObservations?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::consolidate", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::consolidate", + config: { api_path: "/agentmemory/consolidate", http_method: "POST" }, + }); + + sdk.registerFunction("api::patterns", + async (req: ApiRequest<{ project?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::patterns", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::patterns", + config: { api_path: "/agentmemory/patterns", http_method: "POST" }, + }); + + sdk.registerFunction("api::generate-rules", + async (req: ApiRequest<{ project?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::generate-rules", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::generate-rules", + config: { api_path: "/agentmemory/generate-rules", http_method: "POST" }, + }); + + sdk.registerFunction("api::migrate", + async ( + req: ApiRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const hasStep = + typeof req.body?.step === "string" && req.body.step.trim().length > 0; + const hasDbPath = + typeof req.body?.dbPath === "string" && req.body.dbPath.trim().length > 0; + if (!hasStep && !hasDbPath) { + return { + status_code: 400, + body: { error: "Either step (string) or dbPath (string) is required" }, + }; + } + const result = await sdk.trigger({ + function_id: "mem::migrate", + payload: { + ...(req.body.step !== undefined && { step: req.body.step }), + ...(req.body.dbPath !== undefined && { dbPath: req.body.dbPath }), + ...(req.body.dryRun !== undefined && { dryRun: req.body.dryRun }), + }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::migrate", + config: { api_path: "/agentmemory/migrate", http_method: "POST" }, + }); + + sdk.registerFunction("api::evict", + async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const dryRun = + req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; + const result = await sdk.trigger({ function_id: "mem::evict", payload: { dryRun } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::evict", + config: { api_path: "/agentmemory/evict", http_method: "POST" }, + }); + + sdk.registerFunction("api::smart-search", + async ( + req: ApiRequest<{ + query?: string; + expandIds?: Array<string | { obsId: string; sessionId: string }>; + limit?: number; + project?: string; + includeLessons?: boolean; + agentId?: string; + sessionId?: string; + source?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !req.body?.query && + (!req.body?.expandIds || req.body.expandIds.length === 0) + ) { + return { + status_code: 400, + body: { error: "query or expandIds is required" }, + }; + } + // #771: route the X-Agentmemory-Source header into the payload so + // the followup-rate diagnostic can skip viewer-originated calls. + // Body wins if both are set (advanced callers explicitly override). + const headers = (req.headers || {}) as Record<string, string | string[] | undefined>; + const sourceHeader = headers["x-agentmemory-source"] ?? headers["X-Agentmemory-Source"]; + const sourceFromHeader = Array.isArray(sourceHeader) ? sourceHeader[0] : sourceHeader; + // Whitelist payload fields explicitly — REST endpoints never pass + // the raw request body through to sdk.trigger (AGENTS.md security + // section). Drops unknown fields so a misbehaving client can't + // inject downstream-only options. + const payload = { + query: req.body?.query, + expandIds: req.body?.expandIds, + limit: req.body?.limit, + project: req.body?.project, + includeLessons: req.body?.includeLessons, + agentId: req.body?.agentId, + sessionId: req.body?.sessionId, + source: req.body?.source ?? sourceFromHeader, + }; + const result = await sdk.trigger({ function_id: "mem::smart-search", payload }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::smart-search", + config: { api_path: "/agentmemory/smart-search", http_method: "POST" }, + }); + + // #771: read-back endpoint for the followup-rate diagnostic. Returns + // a directional signal — overcounts on legitimate query refinement — + // so help text + the CLI status line carry the same caveat. + sdk.registerFunction("api::diagnostic-followup", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ + function_id: "mem::diagnostic::followup-stats", + payload: {}, + }); + return { + status_code: 200, + body: { + ...(result as Record<string, unknown>), + caveat: + "Directional signal: overcounts on legitimate query refinement. " + + "Tune via AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS.", + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::diagnostic-followup", + config: { + api_path: "/agentmemory/diagnostics/followup", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::timeline", + async ( + req: ApiRequest<{ + anchor: string; + project?: string; + before?: number; + after?: number; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.anchor) { + return { status_code: 400, body: { error: "anchor is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::timeline", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::timeline", + config: { api_path: "/agentmemory/timeline", http_method: "POST" }, + }); + + sdk.registerFunction("api::profile", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const project = req.query_params["project"] as string; + if (!project) { + return { + status_code: 400, + body: { error: "project query param is required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::profile", payload: { project } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::profile", + config: { api_path: "/agentmemory/profile", http_method: "GET" }, + }); + + sdk.registerFunction("api::export", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + // mem::export already supports maxSessions/offset internally, + // but the HTTP endpoint hardcoded an empty payload — so /export on a + // real corpus (40 sessions × 34K observations × 8K memories) hit the + // iii engine invocation timeout and `agentmemory status` reported 0. + // Pass through the query-string pagination so callers can chunk. + const rawMax = req.query_params?.["maxSessions"]; + const rawOffset = req.query_params?.["offset"]; + const payload: { maxSessions?: number; offset?: number } = {}; + if (typeof rawMax === "string") { + const n = Number(rawMax); + if (Number.isInteger(n) && n > 0) payload.maxSessions = n; + } + if (typeof rawOffset === "string") { + const n = Number(rawOffset); + if (Number.isInteger(n) && n >= 0) payload.offset = n; + } + const result = await sdk.trigger({ + function_id: "mem::export", + payload, + }); + // mem::export refuses an oversized payload rather than serializing it; + // over HTTP that refusal is a 413, not a 200 carrying an error body. + if (isOversizedPayload(result)) return { status_code: 413, body: result }; + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::export", + config: { api_path: "/agentmemory/export", http_method: "GET" }, + }); + + sdk.registerFunction("api::import", + async ( + req: ApiRequest<{ + exportData: unknown; + strategy?: "merge" | "replace" | "skip"; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.exportData) { + return { status_code: 400, body: { error: "exportData is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::import", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::import", + config: { api_path: "/agentmemory/import", http_method: "POST" }, + }); + + sdk.registerFunction("api::relations", + async ( + req: ApiRequest<{ sourceId: string; targetId: string; type: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.sourceId || !req.body?.targetId || !req.body?.type) { + return { + status_code: 400, + body: { error: "sourceId, targetId, and type are required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::relate", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::relations", + config: { api_path: "/agentmemory/relations", http_method: "POST" }, + }); + + sdk.registerFunction("api::evolve", + async ( + req: ApiRequest<{ + memoryId: string; + newContent: string; + newTitle?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.memoryId || !req.body?.newContent) { + return { + status_code: 400, + body: { error: "memoryId and newContent are required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::evolve", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::evolve", + config: { api_path: "/agentmemory/evolve", http_method: "POST" }, + }); + + sdk.registerFunction("api::auto-forget", + async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const dryRun = + req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; + const result = await sdk.trigger({ function_id: "mem::auto-forget", payload: { dryRun } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::auto-forget", + config: { api_path: "/agentmemory/auto-forget", http_method: "POST" }, + }); + + sdk.registerFunction("api::claude-bridge-read", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::claude-bridge-read", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { + status_code: 404, + body: { error: "Claude bridge not enabled" }, + }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::claude-bridge-read", + config: { api_path: "/agentmemory/claude-bridge/read", http_method: "GET" }, + }); + + sdk.registerFunction("api::claude-bridge-sync", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::claude-bridge-sync", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { + status_code: 404, + body: { error: "Claude bridge not enabled" }, + }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::claude-bridge-sync", + config: { + api_path: "/agentmemory/claude-bridge/sync", + http_method: "POST", + }, + }); + + sdk.registerFunction("api::graph-query", + async ( + req: ApiRequest<{ + startNodeId?: string; + nodeType?: string; + maxDepth?: number; + query?: string; + limit?: number; + offset?: number; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + // Whitelist payload fields explicitly; AGENTS.md security rule: + // REST endpoints never pass raw req.body through to sdk.trigger. + const payload = { + startNodeId: req.body?.startNodeId, + nodeType: req.body?.nodeType, + maxDepth: req.body?.maxDepth, + query: req.body?.query, + limit: req.body?.limit, + offset: req.body?.offset, + }; + try { + const result = await sdk.trigger({ function_id: "mem::graph-query", payload }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-query", + config: { api_path: "/agentmemory/graph/query", http_method: "POST" }, + }); + + sdk.registerFunction("api::graph-stats", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::graph-stats", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-stats", + config: { api_path: "/agentmemory/graph/stats", http_method: "GET" }, + }); + + // #814: explicit snapshot rebuild endpoint. Pays the full graph + // enumeration once and persists a top-degree subgraph + aggregate + // counts so subsequent /graph/query and /graph/stats calls skip the + // unbounded kv.list. Operator-grade endpoint exposed for the viewer + // banner action and CLI repair. + sdk.registerFunction("api::graph-snapshot-rebuild", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ + function_id: "mem::graph-snapshot-rebuild", + payload: {}, + }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-snapshot-rebuild", + config: { api_path: "/agentmemory/graph/snapshot-rebuild", http_method: "POST" }, + }); + + // #814 v2: clean-restart endpoint for legacy corpora too large for + // safe rebuild. Wipes graph state without touching observations, so + // recall + history stay intact while the graph rebuilds incrementally + // from new extracts (or a one-shot /graph/build replay). + sdk.registerFunction("api::graph-reset", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ + function_id: "mem::graph-reset", + payload: {}, + }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-reset", + config: { api_path: "/agentmemory/graph/reset", http_method: "POST" }, + }); + + sdk.registerFunction("api::graph-extract", + async (req: ApiRequest<{ observations: unknown[] }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !Array.isArray(req.body?.observations) || + req.body.observations.length === 0 + ) { + return { + status_code: 400, + body: { error: "observations array is required" }, + }; + } + try { + const result = await sdk.trigger({ function_id: "mem::graph-extract", payload: req.body }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-extract", + config: { api_path: "/agentmemory/graph/extract", http_method: "POST" }, + }); + + // Backfill the knowledge graph from existing compressed observations. + // Viewer calls this when the graph is empty (#666). Iterates every + // session, collects observations that have a `title` (compressed only), + // and feeds them through `mem::graph-extract` in batches. + sdk.registerFunction("api::graph-build", + async (req: ApiRequest<{ batchSize?: number }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const batchSize = Math.max( + 1, + Math.min(100, Number((req.body as { batchSize?: number })?.batchSize) || 25), + ); + try { + const sessions = await kv.list<Session>(KV.sessions); + let totalNodes = 0; + let totalEdges = 0; + let batchesRun = 0; + for (const session of sessions) { + const sid = session?.id; + if (typeof sid !== "string" || sid.length === 0) continue; + const observations = await kv.list<CompressedObservation>(KV.observations(sid)); + const compressed = observations.filter((o) => o && typeof o.title === "string" && o.title.length > 0); + if (compressed.length === 0) continue; + for (let i = 0; i < compressed.length; i += batchSize) { + const batch = compressed.slice(i, i + batchSize); + try { + const result = (await sdk.trigger({ + function_id: "mem::graph-extract", + payload: { observations: batch }, + })) as { success?: boolean; nodesAdded?: number; edgesAdded?: number }; + if (result?.success) { + totalNodes += Number(result.nodesAdded) || 0; + totalEdges += Number(result.edgesAdded) || 0; + } + batchesRun++; + } catch (err) { + logger.warn("graph-build batch failed", { + sessionId: sid, + batchIndex: Math.floor(i / batchSize), + error: err instanceof Error ? err.message : String(err), + }); + } + } + } + return { + status_code: 200, + body: { + success: true, + sessions: sessions.length, + batches: batchesRun, + nodes: totalNodes, + edges: totalEdges, + }, + }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-build", + config: { api_path: "/agentmemory/graph/build", http_method: "POST" }, + }); + + // Import graphify's structural graph (graphify-out/graph.json) into the + // memory graph. Deterministic, no LLM call; idempotent via the graph + // name-index upsert. + sdk.registerFunction("api::graph-import-graphify", + async (req: ApiRequest<{ path?: string; cwd?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const { path, cwd } = req.body ?? {}; + if ( + (path !== undefined && typeof path !== "string") || + (cwd !== undefined && typeof cwd !== "string") + ) { + return { + status_code: 400, + body: { error: "path and cwd must be strings when provided" }, + }; + } + try { + const result = await sdk.trigger({ + function_id: "mem::graph::import-graphify", + payload: { + ...(path !== undefined ? { path } : {}), + ...(cwd !== undefined ? { cwd } : {}), + }, + }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-import-graphify", + config: { api_path: "/agentmemory/graph/import-graphify", http_method: "POST" }, + }); + + // Re-run compression for observations that a failed mem::compress left in + // raw shape - present in KV but in neither search index, so unretrievable. + // Two sources: mem:compress-pending (parked by the failure path, full raw + // preserved) and raw-shaped records in KV.observations (the historical + // orphans that predate that fix). Sequential and limit-bounded on purpose: + // this exists to be run after a provider outage, and firing hundreds of + // concurrent LLM calls at a provider that has just stopped returning 529s + // is how you cause the next one. + sdk.registerFunction("api::recompress-orphans", + async (req: ApiRequest<{ limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body || {}) as { limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }; + const limit = Math.max(1, Math.min(1000, Number(body.limit) || 50)); + const dryRun = body.dryRun === true; + // Records captured before this instant skip the one-hour grace. The + // cutover passes its freeze timestamp: nothing captured before the + // freeze can still have a compression in flight on the new daemon. + const graceBypassBefore = typeof body.graceBypassBefore === "string" ? new Date(body.graceBypassBefore).getTime() : NaN; + if (typeof body.graceBypassBefore === "string" && !Number.isFinite(graceBypassBefore)) { + return { status_code: 400, body: { error: "graceBypassBefore must be an ISO timestamp" } }; + } + // Give quarantined entries (attempts >= MAX_ATTEMPTS) one more shot. + // Meant for after a compression-pipeline fix lands: what was a + // deterministic failure may compress cleanly under the new code. + const requeueQuarantined = body.requeueQuarantined === true; + const GRACE_MS = 60 * 60 * 1000; + const now = Date.now(); + + const MAX_ATTEMPTS = 5; + const targets: Array<{ observationId: string; sessionId: string; raw: unknown }> = []; + + // Raw-shaped orphans FIRST: they are the records no search can return, + // so the batch budget belongs to them. Parked entries are already + // findable as degraded synthetics - re-compressing them is a quality + // upgrade, not a rescue. (The first version of this endpoint did the + // opposite and starved the raw ones: every failed parked entry was + // re-parked, so the pending queue never shrank and always ate the + // whole budget.) + let rawOrphans = 0; + for (const session of await kv.list<Session>(KV.sessions)) { + const sid = session?.id; + if (typeof sid !== "string" || sid.length === 0) continue; + for (const o of await kv.list<Record<string, unknown>>(KV.observations(sid))) { + const oid = o?.["id"]; + if (typeof oid !== "string") continue; + if (typeof o["narrative"] === "string") continue; + if (typeof o["hookType"] !== "string") continue; + const ts = new Date(String(o["timestamp"])).getTime(); + const bypass = Number.isFinite(graceBypassBefore) && Number.isFinite(ts) && ts < graceBypassBefore; + if (Number.isFinite(ts) && now - ts < GRACE_MS && !bypass) continue; + rawOrphans++; + if (targets.length < limit) { + targets.push({ observationId: oid, sessionId: sid, raw: o }); + } + } + } + + const queued = new Set(targets.map((t) => t.observationId)); + let parked = 0; + let quarantined = 0; + for (const p of await kv.list<{ + observationId?: string; + sessionId?: string; + raw?: unknown; + attempts?: number; + }>(KV.compressPending)) { + if (typeof p?.observationId !== "string" || typeof p?.sessionId !== "string") continue; + if (queued.has(p.observationId)) continue; + if ((p.attempts ?? 0) >= MAX_ATTEMPTS) { + quarantined++; + if (!requeueQuarantined) continue; + } else { + parked++; + } + if (targets.length < limit) { + targets.push({ observationId: p.observationId, sessionId: p.sessionId, raw: p.raw }); + } + } + + if (dryRun) { + return { + status_code: 200, + body: { + success: true, + dryRun: true, + rawOrphans, + parked, + quarantined, + queued: targets.length, + limit, + }, + }; + } + + let recompressed = 0; + let stillFailing = 0; + for (const t of targets) { + try { + const result = (await sdk.trigger({ + function_id: "mem::compress", + payload: t, + })) as { success?: boolean } | null; + if (result?.success) recompressed++; + else stillFailing++; + } catch { + stillFailing++; + } + // Bail out rather than grind through hundreds of doomed calls when + // the provider is clearly still down. Not for requeueQuarantined + // batches: there every target is a known deterministic failure, so + // ten straight losses say nothing about the provider. + if (!requeueQuarantined && stillFailing >= 10 && recompressed === 0) { + logger.warn("recompress-orphans aborting: provider still failing", { + attempted: recompressed + stillFailing, + }); + break; + } + } + + logger.info("recompress-orphans finished", { + rawOrphans, + parked, + quarantined, + queued: targets.length, + recompressed, + stillFailing, + }); + return { + status_code: 200, + body: { + success: true, + rawOrphans, + parked, + quarantined, + queued: targets.length, + recompressed, + stillFailing, + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::recompress-orphans", + config: { api_path: "/agentmemory/recompress-orphans", http_method: "POST" }, + }); + + sdk.registerFunction("api::consolidate-pipeline", + async (req: ApiRequest<{ tier?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: req.body || {}, + }); + return { status_code: 200, body: result }; + } catch { + return consolidationDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::consolidate-pipeline", + config: { + api_path: "/agentmemory/consolidate-pipeline", + http_method: "POST", + }, + }); + + sdk.registerFunction("api::team-share", + async ( + req: ApiRequest<{ itemId: string; itemType: string; project?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.itemId || !req.body?.itemType) { + return { + status_code: 400, + body: { error: "itemId and itemType are required" }, + }; + } + try { + const result = await sdk.trigger({ function_id: "mem::team-share", payload: req.body }); + return { status_code: 201, body: result }; + } catch { + return { status_code: 404, body: { error: "Team memory not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::team-share", + config: { api_path: "/agentmemory/team/share", http_method: "POST" }, + }); + + sdk.registerFunction("api::team-feed", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const limit = parsedLimit ?? 20; + const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { limit } }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Team memory not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::team-feed", + config: { api_path: "/agentmemory/team/feed", http_method: "GET" }, + }); + + sdk.registerFunction("api::team-profile", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::team-profile", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Team memory not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::team-profile", + config: { api_path: "/agentmemory/team/profile", http_method: "GET" }, + }); + + sdk.registerFunction("api::audit", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const entries = await sdk.trigger({ function_id: "mem::audit-query", payload: { + operation: req.query_params?.["operation"], + limit: parsedLimit ?? 50, + } }); + return { status_code: 200, body: { entries, success: true } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::audit", + config: { api_path: "/agentmemory/audit", http_method: "GET" }, + }); + + sdk.registerFunction("api::governance-delete", + async ( + req: ApiRequest<{ memoryIds: string[]; reason?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.memoryIds || !Array.isArray(req.body.memoryIds)) { + return { + status_code: 400, + body: { error: "memoryIds array is required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::governance-delete", + config: { + api_path: "/agentmemory/governance/memories", + http_method: "DELETE", + }, + }); + + sdk.registerFunction("api::governance-bulk", + async ( + req: ApiRequest<{ + type?: string[]; + dateFrom?: string; + dateTo?: string; + qualityBelow?: number; + dryRun?: boolean; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::governance-bulk", payload: req.body || {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::governance-bulk", + config: { + api_path: "/agentmemory/governance/bulk-delete", + http_method: "POST", + }, + }); + + sdk.registerFunction("api::snapshots", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-list", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Snapshots not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::snapshots", + config: { api_path: "/agentmemory/snapshots", http_method: "GET" }, + }); + + sdk.registerFunction("api::snapshot-create", + async (req: ApiRequest<{ message?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: req.body || {}, + }); + return { status_code: 201, body: result }; + } catch { + return { status_code: 404, body: { error: "Snapshots not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::snapshot-create", + config: { api_path: "/agentmemory/snapshot/create", http_method: "POST" }, + }); + + sdk.registerFunction("api::snapshot-restore", + async (req: ApiRequest<{ commitHash: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.commitHash) { + return { status_code: 400, body: { error: "commitHash is required" } }; + } + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-restore", payload: req.body }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Snapshots not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::snapshot-restore", + config: { api_path: "/agentmemory/snapshot/restore", http_method: "POST" }, + }); + + sdk.registerFunction("api::memories", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const memories = await kv.list<import("../types.js").Memory>(KV.memories); + const latest = req.query_params?.["latest"] === "true"; + // agentId filter. Request param wins, env AGENT_ID (when + // scope=isolated) is the fallback. Shared mode keeps the tag but + // does not restrict the list endpoint. Pass agentId=* to opt out + // of the env scope entirely. includeOrphans=true surfaces + // pre-AGENT_ID memories whose agentId is undefined. + const normalizedAgentId = + typeof req.query_params?.["agentId"] === "string" + ? req.query_params["agentId"].trim() + : undefined; + const wildcardAgent = normalizedAgentId === "*"; + const explicitAgentId = + normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; + const includeOrphans = + req.query_params?.["includeOrphans"] === "true"; + const filterAgentId = wildcardAgent + ? undefined + : explicitAgentId ?? (isAgentScopeIsolated() ? getAgentId() : undefined); + let filtered = latest ? memories.filter((m) => m.isLatest) : memories; + if (filterAgentId) { + filtered = filtered.filter( + (m) => + m.agentId === filterAgentId || + (includeOrphans && m.agentId === undefined), + ); + } + + // viewer + `agentmemory status` were hitting this endpoint to + // count memories. On a real corpus (8K+ memories) the unbounded + // response either timed out at the iii engine boundary ("Invocation + // stopped") or arrived too large for the viewer to render — so the + // UI showed 0 memories despite a healthy store. Two opt-in modes: + // ?count=true — totals only, no payload + // ?limit=N&offset=M — page slice (default unlimited for back-compat) + if (req.query_params?.["count"] === "true") { + // Match the SAME scope that the list path applies — returning + // unfiltered totals here would leak cross-agent counts to a + // caller that's blocked from the underlying rows. + return { + status_code: 200, + body: { + total: filtered.length, + latestCount: filtered.filter((m) => m.isLatest).length, + }, + }; + } + + const rawLimit = req.query_params?.["limit"]; + const rawOffset = req.query_params?.["offset"]; + const parsedLimit = + typeof rawLimit === "string" ? Number(rawLimit) : Number.NaN; + const parsedOffset = + typeof rawOffset === "string" ? Number(rawOffset) : Number.NaN; + const limit = + Number.isInteger(parsedLimit) && parsedLimit > 0 + ? Math.min(parsedLimit, 5000) + : undefined; + const offset = + Number.isInteger(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0; + const sliced = + limit !== undefined ? filtered.slice(offset, offset + limit) : filtered; + + return { + status_code: 200, + body: { + memories: sliced, + total: filtered.length, + offset, + limit: limit ?? null, + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::memories", + config: { api_path: "/agentmemory/memories", http_method: "GET" }, + }); + + sdk.registerFunction("api::memory-by-id", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const id = req.path_params?.["id"]; + if (!id || typeof id !== "string") { + return { status_code: 400, body: { error: "id path parameter is required" } }; + } + const memory = await kv.get<import("../types.js").Memory>(KV.memories, id); + if (!memory) { + return { status_code: 404, body: { error: `memory not found: ${id}` } }; + } + return { status_code: 200, body: { memory } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::memory-by-id", + config: { api_path: "/agentmemory/memories/:id", http_method: "GET" }, + }); + + // The route an operator reaches for first. Without it, removing one + // memory means discovering either /agentmemory/forget or the + // governance bulk paths, and the filter-based one invites deleting by + // date window and hoping the window held only the target. + sdk.registerFunction("api::memory-delete", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const id = req.path_params?.["id"]; + if (!id || typeof id !== "string") { + return { status_code: 400, body: { error: "id path parameter is required" } }; + } + const result = await sdk.trigger({ + function_id: "mem::forget", + payload: { memoryId: id }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::memory-delete", + config: { api_path: "/agentmemory/memories/:id", http_method: "DELETE" }, + }); + + sdk.registerFunction("api::semantic-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); + return { status_code: 200, body: { semantic } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::semantic-list", + config: { api_path: "/agentmemory/semantic", http_method: "GET" }, + }); + + sdk.registerFunction("api::procedural-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); + return { status_code: 200, body: { procedural } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::procedural-list", + config: { api_path: "/agentmemory/procedural", http_method: "GET" }, + }); + + sdk.registerFunction("api::relations-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); + return { status_code: 200, body: { relations } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::relations-list", + config: { api_path: "/agentmemory/relations", http_method: "GET" }, + }); + + sdk.registerFunction("api::vision-search", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const queryText = asNonEmptyString(body["queryText"]); + const queryImageRef = asNonEmptyString(body["queryImageRef"]); + const queryImageBase64 = asNonEmptyString(body["queryImageBase64"]); + const sessionId = asNonEmptyString(body["sessionId"]); + if (!queryText && !queryImageRef && !queryImageBase64) { + return { + status_code: 400, + body: { error: "queryText, queryImageRef, or queryImageBase64 required" }, + }; + } + const topKParsed = parseOptionalPositiveInt(body["topK"]); + if (topKParsed === null) { + return { status_code: 400, body: { error: "topK must be a positive integer" } }; + } + const payload: Record<string, unknown> = {}; + if (queryText) payload["queryText"] = queryText; + if (queryImageRef) payload["queryImageRef"] = queryImageRef; + if (queryImageBase64) payload["queryImageBase64"] = queryImageBase64; + if (sessionId) payload["sessionId"] = sessionId; + if (topKParsed !== undefined) payload["topK"] = Math.min(50, topKParsed); + const result = await sdk.trigger({ function_id: "mem::vision-search", payload }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::vision-search", + config: { api_path: "/agentmemory/vision-search", http_method: "POST" }, + }); + + sdk.registerFunction("api::vision-embed", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const imageRef = asNonEmptyString(body["imageRef"]); + const sessionId = asNonEmptyString(body["sessionId"]); + const observationId = asNonEmptyString(body["observationId"]); + if (!imageRef) { + return { status_code: 400, body: { error: "imageRef is required" } }; + } + const payload: Record<string, unknown> = { imageRef }; + if (sessionId) payload["sessionId"] = sessionId; + if (observationId) payload["observationId"] = observationId; + const result = await sdk.trigger({ function_id: "mem::vision-embed", payload }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::vision-embed", + config: { api_path: "/agentmemory/vision-embed", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-list", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-list", + config: { api_path: "/agentmemory/slots", http_method: "GET" }, + }); + + sdk.registerFunction("api::slot-get", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const label = asNonEmptyString(req.query_params?.["label"]); + if (!label) return { status_code: 400, body: { error: "label query param required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-get", + config: { api_path: "/agentmemory/slot", http_method: "GET" }, + }); + + sdk.registerFunction("api::slot-create", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const label = asNonEmptyString(body["label"]); + if (!label) return { status_code: 400, body: { error: "label required" } }; + // Reject malformed inputs instead of silently dropping them. + if (body["content"] !== undefined && typeof body["content"] !== "string") { + return { status_code: 400, body: { error: "content must be a string" } }; + } + if (body["description"] !== undefined && typeof body["description"] !== "string") { + return { status_code: 400, body: { error: "description must be a string" } }; + } + if (body["pinned"] !== undefined && typeof body["pinned"] !== "boolean") { + return { status_code: 400, body: { error: "pinned must be a boolean" } }; + } + if ( + body["scope"] !== undefined && + body["scope"] !== "project" && + body["scope"] !== "global" + ) { + return { status_code: 400, body: { error: "scope must be 'project' or 'global'" } }; + } + const sizeLimit = parseOptionalPositiveInt(body["sizeLimit"]); + if (sizeLimit === null) { + return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } }; + } + if (sizeLimit !== undefined && sizeLimit > 20000) { + return { status_code: 400, body: { error: "sizeLimit must be <= 20000" } }; + } + const payload: Record<string, unknown> = { label }; + if (typeof body["content"] === "string") payload["content"] = body["content"]; + if (typeof body["description"] === "string") payload["description"] = body["description"]; + if (sizeLimit !== undefined) payload["sizeLimit"] = sizeLimit; + if (typeof body["pinned"] === "boolean") payload["pinned"] = body["pinned"]; + if (body["scope"] === "project" || body["scope"] === "global") payload["scope"] = body["scope"]; + const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("exists") ? 409 : 400, body: resp }; + } + return { status_code: 201, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-create", + config: { api_path: "/agentmemory/slot", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-append", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const label = asNonEmptyString(body["label"]); + const text = typeof body["text"] === "string" ? body["text"] : null; + if (!label || !text) return { status_code: 400, body: { error: "label and text required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + const notFound = resp.error?.includes("not found"); + const overLimit = resp.error?.includes("exceed"); + return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-append", + config: { api_path: "/agentmemory/slot/append", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-replace", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const label = asNonEmptyString(body["label"]); + const content = body["content"]; + if (!label || typeof content !== "string") { + return { status_code: 400, body: { error: "label and content (string) required" } }; + } + const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + const notFound = resp.error?.includes("not found"); + const overLimit = resp.error?.includes("exceed"); + return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-replace", + config: { api_path: "/agentmemory/slot/replace", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-delete", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const label = asNonEmptyString(req.query_params?.["label"]); + if (!label) return { status_code: 400, body: { error: "label query param required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-delete", + config: { api_path: "/agentmemory/slot", http_method: "DELETE" }, + }); + + sdk.registerFunction("api::slot-reflect", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + if (!isReflectEnabled()) return reflectDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body["sessionId"]); + if (!sessionId) return { status_code: 400, body: { error: "sessionId required" } }; + const maxObservations = parseOptionalPositiveInt(body["maxObservations"]); + if (maxObservations === null) return { status_code: 400, body: { error: "maxObservations must be a positive integer" } }; + const payload: Record<string, unknown> = { sessionId }; + if (maxObservations !== undefined) payload["maxObservations"] = maxObservations; + const result = await sdk.trigger({ function_id: "mem::slot-reflect", payload }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-reflect", + config: { api_path: "/agentmemory/slot/reflect", http_method: "POST" }, + }); + + sdk.registerFunction("api::action-create", + async ( + req: ApiRequest<{ + title: string; + description?: string; + priority?: number; + createdBy?: string; + project?: string; + tags?: string[]; + parentId?: string; + edges?: Array<{ type: string; targetActionId: string }>; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.title) { + return { status_code: 400, body: { error: "title is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-create", + config: { api_path: "/agentmemory/actions", http_method: "POST" }, + }); + + sdk.registerFunction("api::action-update", + async ( + req: ApiRequest<{ + actionId: string; + status?: string; + title?: string; + description?: string; + priority?: number; + result?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId) { + return { status_code: 400, body: { error: "actionId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-update", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-update", + config: { api_path: "/agentmemory/actions/update", http_method: "POST" }, + }); + + sdk.registerFunction("api::action-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::action-list", payload: { + status: req.query_params?.["status"], + project: req.query_params?.["project"], + parentId: req.query_params?.["parentId"], + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-list", + config: { api_path: "/agentmemory/actions", http_method: "GET" }, + }); + + sdk.registerFunction("api::action-get", + async (req: ApiRequest<{ actionId: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const actionId = req.query_params?.["actionId"] as string; + if (!actionId) { + return { status_code: 400, body: { error: "actionId required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-get", payload: { actionId } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-get", + config: { api_path: "/agentmemory/actions/get", http_method: "GET" }, + }); + + sdk.registerFunction("api::action-edge", + async ( + req: ApiRequest<{ + sourceActionId: string; + targetActionId: string; + type: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) { + return { status_code: 400, body: { error: "sourceActionId, targetActionId, and type are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-edge-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-edge", + config: { api_path: "/agentmemory/actions/edges", http_method: "POST" }, + }); + + sdk.registerFunction("api::frontier", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const result = await sdk.trigger({ function_id: "mem::frontier", payload: { + project: req.query_params?.["project"], + agentId: req.query_params?.["agentId"], + limit: parsedLimit, + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::frontier", + config: { api_path: "/agentmemory/frontier", http_method: "GET" }, + }); + + sdk.registerFunction("api::next", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::next", payload: { + project: req.query_params?.["project"], + agentId: req.query_params?.["agentId"], + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::next", + config: { api_path: "/agentmemory/next", http_method: "GET" }, + }); + + sdk.registerFunction("api::lease-acquire", + async ( + req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId || !req.body?.agentId) { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lease-acquire", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::lease-acquire", + config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" }, + }); + + sdk.registerFunction("api::lease-release", + async ( + req: ApiRequest<{ actionId: string; agentId: string; result?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId || !req.body?.agentId) { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lease-release", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::lease-release", + config: { api_path: "/agentmemory/leases/release", http_method: "POST" }, + }); + + sdk.registerFunction("api::lease-renew", + async ( + req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId || !req.body?.agentId) { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lease-renew", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::lease-renew", + config: { api_path: "/agentmemory/leases/renew", http_method: "POST" }, + }); + + sdk.registerFunction("api::routine-create", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.name || !req.body?.steps) { + return { + status_code: 400, + body: { error: "name and steps are required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::routine-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-create", + config: { api_path: "/agentmemory/routines", http_method: "POST" }, + }); + + sdk.registerFunction("api::routine-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::routine-list", payload: { + frozen: req.query_params?.["frozen"] === "true" ? true : undefined, + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-list", + config: { api_path: "/agentmemory/routines", http_method: "GET" }, + }); + + sdk.registerFunction("api::routine-run", + async ( + req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.routineId) { + return { status_code: 400, body: { error: "routineId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::routine-run", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-run", + config: { api_path: "/agentmemory/routines/run", http_method: "POST" }, + }); + + sdk.registerFunction("api::routine-status", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const runId = req.query_params?.["runId"] as string; + if (!runId) { + return { status_code: 400, body: { error: "runId query param required" } }; + } + const result = await sdk.trigger({ function_id: "mem::routine-status", payload: { runId } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-status", + config: { api_path: "/agentmemory/routines/status", http_method: "GET" }, + }); + + sdk.registerFunction("api::signal-send", + async ( + req: ApiRequest<{ + from: string; + to?: string; + content: string; + type?: string; + replyTo?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.from || !req.body?.content) { + return { status_code: 400, body: { error: "from and content are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::signal-send", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::signal-send", + config: { api_path: "/agentmemory/signals/send", http_method: "POST" }, + }); + + sdk.registerFunction("api::signal-read", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const agentId = req.query_params?.["agentId"] as string; + if (!agentId) { + return { status_code: 400, body: { error: "agentId query param required" } }; + } + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const result = await sdk.trigger({ function_id: "mem::signal-read", payload: { + agentId, + unreadOnly: req.query_params?.["unreadOnly"] === "true", + threadId: req.query_params?.["threadId"], + limit: parsedLimit, + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::signal-read", + config: { api_path: "/agentmemory/signals", http_method: "GET" }, + }); + + sdk.registerFunction("api::checkpoint-create", + async ( + req: ApiRequest<{ + name: string; + description?: string; + type?: string; + linkedActionIds?: string[]; + expiresInMs?: number; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.name) { + return { status_code: 400, body: { error: "name is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::checkpoint-create", + config: { api_path: "/agentmemory/checkpoints", http_method: "POST" }, + }); + + sdk.registerFunction("api::checkpoint-resolve", + async ( + req: ApiRequest<{ + checkpointId: string; + status: string; + resolvedBy?: string; + result?: unknown; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.checkpointId || !req.body?.status) { + return { status_code: 400, body: { error: "checkpointId and status are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::checkpoint-resolve", + config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" }, + }); + + sdk.registerFunction("api::checkpoint-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { + status: req.query_params?.["status"], + type: req.query_params?.["type"], + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::checkpoint-list", + config: { api_path: "/agentmemory/checkpoints", http_method: "GET" }, + }); + + sdk.registerFunction("api::mesh-register", + async ( + req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>, + ): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.url || !req.body?.name) { + return { status_code: 400, body: { error: "url and name are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::mesh-register", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-register", + config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" }, + }); + + sdk.registerFunction("api::mesh-list", + async (req: ApiRequest): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::mesh-list", payload: {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-list", + config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" }, + }); + + sdk.registerFunction("api::mesh-sync", + async ( + req: ApiRequest<{ peerId?: string; direction?: string }>, + ): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::mesh-sync", payload: req.body || {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-sync", + config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" }, + }); + + sdk.registerFunction("api::mesh-receive", + async (req: ApiRequest): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::mesh-receive", payload: req.body || {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-receive", + config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" }, + }); + + sdk.registerFunction("api::mesh-export", + async (req: ApiRequest): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const since = req.query_params?.["since"] as string; + if (since) { + const parsed = new Date(since).getTime(); + if (Number.isNaN(parsed)) { + return { status_code: 400, body: { error: "Invalid 'since' date format" } }; + } + } + const project = req.query_params?.["project"] as string | undefined; + const sinceTime = since ? new Date(since).getTime() : 0; + const df = <T>(items: T[], field: "updatedAt" | "createdAt") => + items.filter((i) => new Date((i as Record<string, unknown>)[field] as string).getTime() > sinceTime); + let memories = await kv.list<import("../types.js").Memory>(KV.memories); + let actions = await kv.list<import("../types.js").Action>(KV.actions); + if (project) { + memories = memories.filter((m) => m.project === project); + actions = actions.filter((a) => a.project === project); + } + const body: Record<string, unknown> = { + memories: df(memories, "updatedAt"), + actions: df(actions, "updatedAt"), + }; + if (!project) { + const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); + const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); + const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); + body.semantic = df(semantic, "updatedAt"); + body.procedural = df(procedural, "updatedAt"); + body.relations = df(relations, "createdAt"); + // B-mode: graph frozen — never enumerate the graph scope for the + // mesh-sync delta body. + if (!graphLegDisabled()) { + const graphNodes = await kv.list<import("../types.js").GraphNode>(KV.graphNodes); + const graphEdges = await kv.list<import("../types.js").GraphEdge>(KV.graphEdges); + body.graphNodes = graphNodes.filter( + (n) => new Date(n.updatedAt || n.createdAt).getTime() > sinceTime, + ); + body.graphEdges = df(graphEdges, "createdAt"); + } + } + // Fail an oversized export with 413 rather than on heap. + const oversized = checkPayloadSize( + body, + "use ?since to fetch only changes after a timestamp, or ?project to scope the export", + ); + if (oversized) return { status_code: 413, body: oversized }; + return { status_code: 200, body }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-export", + config: { api_path: "/agentmemory/mesh/export", http_method: "GET" }, + }); + + sdk.registerFunction("api::flow-compress", + async ( + req: ApiRequest<{ + runId?: string; + actionIds?: string[]; + project?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::flow-compress", payload: req.body || {} }); + return { status_code: 200, body: result }; + } catch { + return { + status_code: 404, + body: { error: "Flow compression requires a provider" }, + }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::flow-compress", + config: { api_path: "/agentmemory/flow/compress", http_method: "POST" }, + }); + + sdk.registerFunction("api::branch-detect", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); + const result = await sdk.trigger({ function_id: "mem::detect-worktree", payload: { cwd } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::branch-detect", + config: { api_path: "/agentmemory/branch/detect", http_method: "GET" }, + }); + + sdk.registerFunction("api::branch-worktrees", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); + const result = await sdk.trigger({ function_id: "mem::list-worktrees", payload: { cwd } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::branch-worktrees", + config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" }, + }); + + sdk.registerFunction("api::branch-sessions", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); + const result = await sdk.trigger({ function_id: "mem::branch-sessions", payload: { cwd } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::branch-sessions", + config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" }, + }); + + sdk.registerFunction("api::viewer", + async (req: ApiRequest): Promise<Response> => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const rendered = renderViewerDocument(); + if (rendered.found) { + return { + status_code: 200, + headers: { + "Content-Type": "text/html", + "Content-Security-Policy": rendered.csp, + }, + body: rendered.html, + }; + } + return { + status_code: 404, + headers: { + "Content-Type": "text/html", + }, + body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>", + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::viewer", + config: { api_path: "/agentmemory/viewer", http_method: "GET" }, + }); + + sdk.registerFunction("api::sentinel-create", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.name) return { status_code: 400, body: { error: "name is required" } }; + const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-trigger", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-check", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-cancel", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sentinel-cancel", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const result = await sdk.trigger({ function_id: "mem::sentinel-list", payload: { status: params.status, type: params.type } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } }); + + sdk.registerFunction("api::sketch-create", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.title) return { status_code: 400, body: { error: "title is required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-add", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sketchId || !body?.title) return { status_code: 400, body: { error: "sketchId and title are required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-add", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-promote", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-discard", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-discard", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const result = await sdk.trigger({ function_id: "mem::sketch-list", payload: { status: params.status, project: params.project } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } }); + + sdk.registerFunction("api::sketch-gc", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } }); + + sdk.registerFunction("api::crystallize", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.actionIds) return { status_code: 400, body: { error: "actionIds is required" } }; + const result = await sdk.trigger({ function_id: "mem::crystallize", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } }); + + sdk.registerFunction("api::crystal-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const limit = parseOptionalPositiveInt(params.limit); + if (limit === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: limit" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { project: params.project, sessionId: params.sessionId, limit } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } }); + + sdk.registerFunction("api::auto-crystallize", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::auto-crystallize", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } }); + + sdk.registerFunction("api::diagnose", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::diagnose", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } }); + + sdk.registerFunction("api::heal", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::heal", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } }); + + sdk.registerFunction("api::facet-tag", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.targetId || !body?.dimension || !body?.value) return { status_code: 400, body: { error: "targetId, dimension, and value are required" } }; + const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } }); + + sdk.registerFunction("api::facet-untag", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.targetId || !body?.dimension) return { status_code: 400, body: { error: "targetId and dimension are required" } }; + const result = await sdk.trigger({ function_id: "mem::facet-untag", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } }); + + sdk.registerFunction("api::facet-query", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::facet-query", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } }); + + sdk.registerFunction("api::facet-get", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + if (!params.targetId) return { status_code: 400, body: { error: "targetId query param is required" } }; + const result = await sdk.trigger({ function_id: "mem::facet-get", payload: { targetId: params.targetId } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } }); + + sdk.registerFunction("api::facet-stats", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const result = await sdk.trigger({ function_id: "mem::facet-stats", payload: { targetType: params.targetType } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } }); + + sdk.registerFunction("api::verify", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.id || typeof body.id !== "string") return { status_code: 400, body: { error: "id is required" } }; + const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: body.id } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } }); + + sdk.registerFunction("api::cascade-update", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") { + return { status_code: 400, body: { error: "supersededMemoryId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::cascade-update", payload: { supersededMemoryId: body.supersededMemoryId } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-save", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.content || typeof body.content !== "string") return { status_code: 400, body: { error: "content is required" } }; + const tags = typeof body.tags === "string" ? (body.tags as string).split(",").map((t: string) => t.trim()).filter(Boolean) : Array.isArray(body.tags) ? body.tags : []; + const result = (await sdk.trigger({ + function_id: "mem::lesson-save", + payload: { + content: body.content, + context: body.context || "", + confidence: typeof body.confidence === "number" ? body.confidence : undefined, + project: typeof body.project === "string" ? body.project : undefined, + tags, + source: "manual", + }, + })) as { action?: string }; + const statusCode = result?.action === "created" ? 201 : 200; + return { status_code: statusCode, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const minConfidence = parseOptionalFiniteNumber(params.minConfidence); + if (minConfidence === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: minConfidence" }, + }; + } + const limit = parseOptionalPositiveInt(params.limit); + if (limit === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: limit" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: { + project: params.project, + source: params.source, + minConfidence, + limit, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } }); + + sdk.registerFunction("api::lesson-search", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; + const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-strengthen", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.lessonId || typeof body.lessonId !== "string") return { status_code: 400, body: { error: "lessonId is required" } }; + const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: body.lessonId } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-delete", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const lessonId = typeof body?.lessonId === "string" ? body.lessonId.trim() : ""; + if (!lessonId) return { status_code: 400, body: { error: "lessonId is required" } }; + const result = await sdk.trigger({ function_id: "mem::lesson-delete", payload: { lessonId } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false && resp.error === "lesson not found") { + return { status_code: 404, body: { error: "lesson not found" } }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } }); + + sdk.registerFunction("api::obsidian-export", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = (req.body as Record<string, unknown>) || {}; + const vaultDir = asNonEmptyString(body.vaultDir); + if (!vaultDir) { + return { + status_code: 400, + body: { error: "vaultDir must be a non-empty string" }, + }; + } + const types = typeof body.types === "string" ? body.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined; + const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir, types } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } }); + + sdk.registerFunction("api::reflect", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = (req.body as Record<string, unknown>) || {}; + const result = await sdk.trigger({ function_id: "mem::reflect", payload: { + project: typeof body.project === "string" ? body.project : undefined, + maxClusters: typeof body.maxClusters === "number" ? body.maxClusters : undefined, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } }); + + sdk.registerFunction("api::insight-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const minConfidence = parseOptionalFiniteNumber(params.minConfidence); + if (minConfidence === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: minConfidence" }, + }; + } + const limit = parseOptionalPositiveInt(params.limit); + if (limit === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: limit" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::insight-list", payload: { + project: params.project, + minConfidence, + limit, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } }); + + sdk.registerFunction("api::insight-search", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; + const result = await sdk.trigger({ function_id: "mem::insight-search", payload: { + query: body.query, + project: typeof body.project === "string" ? body.project : undefined, + minConfidence: typeof body.minConfidence === "number" ? body.minConfidence : undefined, + limit: typeof body.limit === "number" ? body.limit : undefined, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } }); +} diff --git a/test/summarize-rest-force.test.ts b/test/summarize-rest-force.test.ts new file mode 100644 index 0000000000..656b424c36 --- /dev/null +++ b/test/summarize-rest-force.test.ts @@ -0,0 +1,63 @@ +import { describe, it, expect, vi } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +vi.mock("../src/state/keyed-mutex.js", () => ({ + withKeyedLock: <T>(_key: string, fn: () => Promise<T>) => fn(), +})); + +import { registerApiTriggers } from "../src/triggers/api.js"; + +function mockKV() { + const store = new Map<string, Map<string, unknown>>(); + return { + get: async <T>(scope: string, key: string): Promise<T | null> => + (store.get(scope)?.get(key) as T) ?? null, + set: async <T>(scope: string, key: string, data: T): Promise<T> => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async () => {}, + update: async () => {}, + list: async <T>(): Promise<T[]> => [], + }; +} + +function mockSdk() { + const fns = new Map<string, Function>(); + return { + fns, + registerFunction: (id: string, h: Function) => { + fns.set(id, h); + }, + registerTrigger: () => {}, + trigger: async (input: { function_id: string; payload?: unknown }) => + fns.get(input.function_id)?.(input.payload), + }; +} + +describe("POST /agentmemory/summarize", () => { + it("forwards only sessionId and a boolean force to mem::summarize", async () => { + const sdk = mockSdk(); + registerApiTriggers(sdk as any, mockKV() as any); + const received: unknown[] = []; + sdk.registerFunction("mem::summarize", async (payload: unknown) => { + received.push(payload); + return { success: true }; + }); + const route = sdk.fns.get("api::summarize")!; + + await route({ body: { sessionId: "ses_1", force: true, extra: "dropped" } }); + await route({ body: { sessionId: "ses_1" } }); + await route({ body: { sessionId: "ses_1", force: "yes" } }); + + expect(received).toEqual([ + { sessionId: "ses_1", force: true }, + { sessionId: "ses_1", force: false }, + { sessionId: "ses_1", force: false }, + ]); + }); +}); diff --git a/test/summarize.test.ts b/test/summarize.test.ts index 097b20c5a8..cd4b6e813e 100644 --- a/test/summarize.test.ts +++ b/test/summarize.test.ts @@ -557,3 +557,59 @@ describe("mem::summarize chunking", () => { expect(result.error).toBe("parse_failed"); }); }); + +describe("mem::summarize Session Summary reuse", () => { + const ORIGINAL_ENV = { ...process.env }; + afterEach(() => { + process.env = { ...ORIGINAL_ENV }; + }); + + async function withStoredSummary(sessionId: string, obsCount: number, storedCount: number) { + const provider = makeProvider([summaryXml({ title: "fresh" })]); + const { handler, kv } = await setupHandler({ sessionId, obsCount, provider }); + await kv.set("summaries", sessionId, { + sessionId, + project: "test-project", + createdAt: new Date().toISOString(), + title: "stored", + narrative: "n", + keyDecisions: [], + filesModified: [], + concepts: [], + observationCount: storedCount, + }); + return { handler, kv, provider }; + } + + it("returns the stored summary without calling the provider when its Observation count matches", async () => { + const { handler, provider } = await withStoredSummary("ses_cur", 10, 10); + + const result: any = await handler({ sessionId: "ses_cur" }); + + expect(result.success).toBe(true); + expect(result.summary.title).toBe("stored"); + expect(result.reused).toBe(true); + expect(provider.calls).toHaveLength(0); + }); + + it("reproduces the summary when Observations arrived since it was written", async () => { + const { handler, kv, provider } = await withStoredSummary("ses_stale", 12, 10); + + const result: any = await handler({ sessionId: "ses_stale" }); + + expect(result.success).toBe(true); + expect(result.summary.title).toBe("fresh"); + expect(provider.calls).toHaveLength(1); + expect((await kv.get("summaries", "ses_stale") as any).observationCount).toBe(12); + }); + + it("force: true calls the provider even when the summary is current", async () => { + const { handler, provider } = await withStoredSummary("ses_force", 10, 10); + + const result: any = await handler({ sessionId: "ses_force", force: true }); + + expect(result.success).toBe(true); + expect(result.summary.title).toBe("fresh"); + expect(provider.calls).toHaveLength(1); + }); +}); From 84da8a114f25962844ee855959954ecdf42dea20 Mon Sep 17 00:00:00 2001 From: neal <neal@dev.lan> Date: Tue, 22 Sep 2026 06:48:14 -0400 Subject: [PATCH 09/10] fix(providers): one circuit breaker per provider operation A Session whose summarize calls fail three times used to open the single breaker and stop compress and extraction for the recovery window, so one oversized Session stalled every Observation behind it. The resilient wrapper now keeps a breaker per operation (compress, summarize, describeImage). circuitState reports the most severe operation so /agentmemory/health and the CLI keep their shape; circuitStates exposes the per-operation map and health returns it as circuitBreakers. describeImage is now forwarded through the wrapper, which it never was. Closes #35. Refs #31, #1350. Generated-By: Claude Fable 5.1 --- src/providers/resilient.ts | 51 +++++++++++++++++---- src/triggers/api.ts | 5 ++- test/resilient-provider.test.ts | 78 +++++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 9 deletions(-) create mode 100644 test/resilient-provider.test.ts diff --git a/src/providers/resilient.ts b/src/providers/resilient.ts index c3778513c1..698c48c2c4 100644 --- a/src/providers/resilient.ts +++ b/src/providers/resilient.ts @@ -1,43 +1,78 @@ import type { MemoryProvider, CircuitBreakerState } from "../types.js"; import { CircuitBreaker } from "./circuit-breaker.js"; +export type ProviderOperation = "compress" | "summarize" | "describeImage"; + +const OPERATIONS: ProviderOperation[] = ["compress", "summarize", "describeImage"]; + +const SEVERITY: Record<CircuitBreakerState["state"], number> = { + closed: 0, + "half-open": 1, + open: 2, +}; + +// One breaker per operation: a provider that cannot summarize a long +// Session must not stop it compressing the next Observation. export class ResilientProvider implements MemoryProvider { - private breaker = new CircuitBreaker(); + private breakers = Object.fromEntries( + OPERATIONS.map((op) => [op, new CircuitBreaker()]), + ) as Record<ProviderOperation, CircuitBreaker>; name: string; // A failed count is a fallback for the caller, not a provider failure, // so it is forwarded outside the breaker. countTokens?: (text: string) => Promise<number>; + describeImage?: (imageData: string, mimeType: string, prompt: string) => Promise<string>; constructor(private inner: MemoryProvider) { this.name = `resilient(${inner.name})`; if (inner.countTokens) { this.countTokens = (text) => inner.countTokens!(text); } + if (inner.describeImage) { + this.describeImage = (imageData, mimeType, prompt) => + this.call("describeImage", () => + inner.describeImage!(imageData, mimeType, prompt), + ); + } } - private async call(fn: () => Promise<string>): Promise<string> { - if (!this.breaker.isAllowed) { + private async call( + operation: ProviderOperation, + fn: () => Promise<string>, + ): Promise<string> { + const breaker = this.breakers[operation]; + if (!breaker.isAllowed) { throw new Error("circuit_breaker_open"); } try { const result = await fn(); - this.breaker.recordSuccess(); + breaker.recordSuccess(); return result; } catch (err) { - this.breaker.recordFailure(); + breaker.recordFailure(); throw err; } } async compress(systemPrompt: string, userPrompt: string): Promise<string> { - return this.call(() => this.inner.compress(systemPrompt, userPrompt)); + return this.call("compress", () => this.inner.compress(systemPrompt, userPrompt)); } async summarize(systemPrompt: string, userPrompt: string): Promise<string> { - return this.call(() => this.inner.summarize(systemPrompt, userPrompt)); + return this.call("summarize", () => this.inner.summarize(systemPrompt, userPrompt)); + } + + get circuitStates(): Record<ProviderOperation, CircuitBreakerState> { + return Object.fromEntries( + OPERATIONS.map((op) => [op, this.breakers[op].getState()]), + ) as Record<ProviderOperation, CircuitBreakerState>; } + // Most severe operation wins, so a health consumer reading one state + // still sees an open breaker. get circuitState(): CircuitBreakerState { - return this.breaker.getState(); + return Object.values(this.circuitStates).reduce((worst, s) => + SEVERITY[s.state] > SEVERITY[worst.state] ? s : worst, + ); } } diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 8c0398dfa5..0d49571a2d 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -143,7 +143,7 @@ export function registerApiTriggers( kv: StateKV, secret?: string, metricsStore?: MetricsStore, - provider?: ResilientProvider | { circuitState?: unknown }, + provider?: ResilientProvider | { circuitState?: unknown; circuitStates?: unknown }, ): void { sdk.registerFunction( "middleware::api-auth", @@ -270,6 +270,8 @@ export function registerApiTriggers( const functionMetrics = metricsStore ? await metricsStore.getAll() : []; const circuitBreaker = provider && "circuitState" in provider ? provider.circuitState : null; + const circuitBreakers = + provider && "circuitStates" in provider ? provider.circuitStates : null; const status = health?.status || "healthy"; const statusCode = status === "critical" ? 503 : 200; @@ -282,6 +284,7 @@ export function registerApiTriggers( health: health || null, functionMetrics, circuitBreaker, + circuitBreakers, ...instanceInfo(), }, }; diff --git a/test/resilient-provider.test.ts b/test/resilient-provider.test.ts new file mode 100644 index 0000000000..15c7630dc1 --- /dev/null +++ b/test/resilient-provider.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect } from "vitest"; +import { ResilientProvider } from "../src/providers/resilient.js"; +import type { MemoryProvider } from "../src/types.js"; + +function fakeProvider(overrides: Partial<MemoryProvider> = {}): MemoryProvider { + return { + name: "fake", + compress: async () => "compressed", + summarize: async () => "summarized", + ...overrides, + }; +} + +async function failTimes(fn: () => Promise<unknown>, n: number) { + for (let i = 0; i < n; i++) { + await expect(fn()).rejects.toThrow(); + } +} + +describe("ResilientProvider per-operation breakers", () => { + it("keeps compress allowed after summarize's breaker opens", async () => { + const provider = new ResilientProvider( + fakeProvider({ summarize: async () => { throw new Error("boom"); } }), + ); + + await failTimes(() => provider.summarize("s", "u"), 3); + + expect(provider.circuitStates.summarize.state).toBe("open"); + expect(provider.circuitStates.compress.state).toBe("closed"); + await expect(provider.compress("s", "u")).resolves.toBe("compressed"); + await expect(provider.summarize("s", "u")).rejects.toThrow("circuit_breaker_open"); + }); + + it("reports the most severe state as the aggregate, in today's shape", async () => { + const provider = new ResilientProvider( + fakeProvider({ compress: async () => { throw new Error("boom"); } }), + ); + expect(provider.circuitState).toEqual({ + state: "closed", + failures: 0, + lastFailureAt: null, + openedAt: null, + }); + + await failTimes(() => provider.compress("s", "u"), 3); + + const aggregate = provider.circuitState; + expect(aggregate.state).toBe("open"); + expect(aggregate.failures).toBe(3); + expect(Object.keys(aggregate).sort()).toEqual( + ["failures", "lastFailureAt", "openedAt", "state"], + ); + }); + + it("exposes one state per operation", () => { + const provider = new ResilientProvider(fakeProvider()); + expect(Object.keys(provider.circuitStates).sort()).toEqual( + ["compress", "describeImage", "summarize"], + ); + for (const s of Object.values(provider.circuitStates)) { + expect(s.state).toBe("closed"); + } + }); + + it("forwards describeImage through its own breaker only when the inner provider has one", async () => { + const plain = new ResilientProvider(fakeProvider()); + expect(plain.describeImage).toBeUndefined(); + + const vision = new ResilientProvider( + fakeProvider({ describeImage: async () => { throw new Error("boom"); } }), + ); + await failTimes(() => vision.describeImage!("img", "image/png", "p"), 3); + + expect(vision.circuitStates.describeImage.state).toBe("open"); + expect(vision.circuitStates.compress.state).toBe("closed"); + await expect(vision.compress("s", "u")).resolves.toBe("compressed"); + }); +}); From cbfed9e91bdeb1ab63fe2084724578405d2ce161 Mon Sep 17 00:00:00 2001 From: neal <neal@dev.lan> Date: Tue, 22 Sep 2026 07:15:34 -0400 Subject: [PATCH 10/10] fix(summarize): apply PR #45 review corrections - Restore CRLF line endings in src/triggers/api.ts; the earlier edit had rewritten the whole file to LF. - Session Summary reuse now keys on Observation count AND the last Observation id (new optional SessionSummary.lastObservationId); a delete followed by a new Observation no longer passes as current, and a summary stored before the field existed is regenerated. - Always measure tokens when the provider can count; the estimate is only the fallback. OpenAIProvider remembers a 404 from /tokenize and stops asking for the life of the instance. - Measure once per summarize, outside the 2-attempt retry, via planChunks. - Charge each Observation its prompt separator (4 tokens) and floor SUMMARIZE_CHUNK_TOKENS at the prompt overhead plus one. - Chunk fan-out goes through mapWithConcurrency; chunk offsets use a for loop. - isNoopProvider unwraps only balanced resilient(...) layers. Refs #31 Generated-By: Claude Fable 5.1 --- src/functions/summarize.ts | 119 +- src/providers/noop.ts | 8 +- src/providers/openai.ts | 12 +- src/triggers/api.ts | 7046 +++++++++++++++--------------- src/types.ts | 1 + test/openai-count-tokens.test.ts | 25 + test/summarize.test.ts | 58 +- 7 files changed, 3678 insertions(+), 3591 deletions(-) diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts index b352108c94..54ff691350 100644 --- a/src/functions/summarize.ts +++ b/src/functions/summarize.ts @@ -30,6 +30,8 @@ const CHUNK_TOKENS_DEFAULT = 50_000; // Tokens the system prompt and chat template add on top of the rendered // Observations, measured on the Operator's broker. const PROMPT_OVERHEAD_TOKENS = 400; +// Tokens buildSummaryPrompt spends joining one Observation to the next. +const SEPARATOR_TOKENS = 4; // Concurrent in-flight chunk calls. The Operator's broker serialises chunks // on one GPU, and AGENTMEMORY_LLM_TIMEOUT_MS was measured at 2 — raise // SUMMARIZE_CHUNK_CONCURRENCY only with the timeout re-measured. @@ -40,11 +42,14 @@ const COUNT_CONCURRENCY = 16; // to parse — a half-blind narrative is worse than a clean error. const MAX_SKIP_RATIO = 0.5; +// A budget at or below the prompt overhead leaves no room for any +// Observation, so it is floored to one payload token. function getChunkTokens(): number { const raw = process.env.SUMMARIZE_CHUNK_TOKENS; if (!raw) return CHUNK_TOKENS_DEFAULT; const n = parseInt(raw, 10); - return Number.isFinite(n) && n > 0 ? n : CHUNK_TOKENS_DEFAULT; + if (!Number.isFinite(n) || n <= 0) return CHUNK_TOKENS_DEFAULT; + return Math.max(n, PROMPT_OVERHEAD_TOKENS + 1); } function getChunkConcurrency(): number { @@ -110,7 +115,7 @@ function packChunks( let current: CompressedObservation[] = []; let used = 0; compressed.forEach((obs, i) => { - const tokens = counts[i] ?? 0; + const tokens = (counts[i] ?? 0) + SEPARATOR_TOKENS; if (current.length > 0 && used + tokens > payloadBudget) { chunks.push(current); current = []; @@ -171,14 +176,35 @@ async function summarizeChunkWithRetry( return null; } -// Returns the final summary XML string. For sessions that fit the token -// budget, this is a single LLM call. For larger sessions, observations -// are packed into chunks processed in parallel batches, each chunk retried -// once on parse failure, persistently-bad chunks skipped, and remaining +// Measures every Observation once and packs them against the chunk budget. +async function planChunks( + provider: MemoryProvider, + compressed: CompressedObservation[], + sessionId: string, +): Promise<CompressedObservation[][]> { + const budget = getChunkTokens(); + const texts = compressed.map(renderSummaryObservation); + const counts = await countObservationTokens(provider, texts, sessionId); + const chunks = packChunks(compressed, counts, budget, sessionId); + if (chunks.length > 1) { + logger.info("Summarize chunking session", { + sessionId, + chunks: chunks.length, + budget, + concurrency: getChunkConcurrency(), + totalObservations: compressed.length, + }); + } + return chunks; +} + +// Returns the final summary XML string. A single chunk is one LLM call. +// Several are processed in parallel batches, each chunk retried once on +// parse failure, persistently-bad chunks skipped, and the remaining // partials merged via a reduce call. async function produceSummaryXml( provider: MemoryProvider, - compressed: CompressedObservation[], + chunks: CompressedObservation[][], sessionId: string, project: string, ): Promise<{ @@ -187,57 +213,22 @@ async function produceSummaryXml( chunks: number; skipped?: number; }> { - const budget = getChunkTokens(); - const texts = compressed.map(renderSummaryObservation); - // The estimate never undercounts, so a Session that fits by estimate is - // summarized in one call without a tokenize round trip. - const estimated = texts.reduce((n, t) => n + estimateTokens(t), 0); - const chunks = - estimated + PROMPT_OVERHEAD_TOKENS <= budget - ? [compressed] - : packChunks( - compressed, - await countObservationTokens(provider, texts, sessionId), - budget, - sessionId, - ); if (chunks.length === 1) { const response = await provider.summarize( SUMMARY_SYSTEM, - buildSummaryPrompt(compressed), + buildSummaryPrompt(chunks[0]!), ); return { response, mode: "single", chunks: 1 }; } - const concurrency = getChunkConcurrency(); - logger.info("Summarize chunking session", { - sessionId, - chunks: chunks.length, - budget, - concurrency, - totalObservations: compressed.length, - }); - - // Sparse array preserves chunk → index mapping after parallel resolution, - // so the reduce step sees partials in chronological order even when some - // were skipped. - const partialByIdx: Array<SessionSummary | null> = new Array(chunks.length).fill(null); - for (let batchStart = 0; batchStart < chunks.length; batchStart += concurrency) { - const batch = chunks.slice(batchStart, batchStart + concurrency); - await Promise.all( - batch.map(async (chunk, j) => { - const idx = batchStart + j; - partialByIdx[idx] = await summarizeChunkWithRetry( - provider, - chunk, - sessionId, - project, - idx, - chunks.length, - ); - }), - ); - } + // Results keep chunk order, so the reduce step sees partials in + // chronological order even when some were skipped. + const partialByIdx = await mapWithConcurrency( + chunks.map((chunk, idx) => ({ chunk, idx })), + getChunkConcurrency(), + ({ chunk, idx }) => + summarizeChunkWithRetry(provider, chunk, sessionId, project, idx, chunks.length), + ); const skipped = partialByIdx.filter((p) => p === null).length; const partials = partialByIdx.filter((p): p is SessionSummary => p !== null); @@ -256,10 +247,10 @@ async function produceSummaryXml( } const chunkStarts: number[] = []; - chunks.reduce((offset, chunk) => { + for (let offset = 0, i = 0; i < chunks.length; i++) { chunkStarts.push(offset); - return offset + chunk.length; - }, 0); + offset += chunks[i]!.length; + } const reduceInput = partials.map((p) => { const originalIdx = partialByIdx.indexOf(p); const start = chunkStarts[originalIdx] ?? 0; @@ -356,11 +347,17 @@ export function registerSummarizeFunction( return { success: false, error: "no_observations" }; } - // Observations are append-only within a Session, so a stored summary - // whose count matches is current and is reused rather than reproduced. + // A stored summary is current when both the Observation count and the + // last Observation id still match: a delete followed by a new + // Observation keeps the count but moves the id. + const lastObservationId = compressed[compressed.length - 1]!.id; if (!data.force) { const existing = await kv.get<SessionSummary>(KV.summaries, sessionId); - if (existing && existing.observationCount === compressed.length) { + if ( + existing && + existing.observationCount === compressed.length && + existing.lastObservationId === lastObservationId + ) { logger.info("Session Summary current, reused", { sessionId, observationCount: compressed.length, @@ -391,10 +388,11 @@ export function registerSummarizeFunction( let response = ""; let mode = "single"; let chunks = 1; + const planned = await planChunks(provider, compressed, sessionId); for (let attempt = 1; attempt <= 2; attempt++) { const produced = await produceSummaryXml( provider, - compressed, + planned, sessionId, session.project, ); @@ -418,7 +416,10 @@ export function registerSummarizeFunction( session.project, compressed.length, ); - if (summary) break; + if (summary) { + summary.lastObservationId = lastObservationId; + break; + } logger.warn("Failed to parse summary XML", { sessionId, attempt }); } diff --git a/src/providers/noop.ts b/src/providers/noop.ts index 7ce1639f5a..7f63383724 100644 --- a/src/providers/noop.ts +++ b/src/providers/noop.ts @@ -19,10 +19,16 @@ export class NoopProvider implements MemoryProvider { } } +const RESILIENT_PREFIX = "resilient("; + /** * Every provider is wrapped as `resilient(<inner>)`, so callers must look * through the wrapper rather than compare against "noop" directly. */ export function isNoopProvider(provider: Pick<MemoryProvider, "name">): boolean { - return /^(?:resilient\()*noop\)*$/.test(provider.name); + let name = provider.name; + while (name.startsWith(RESILIENT_PREFIX) && name.endsWith(")")) { + name = name.slice(RESILIENT_PREFIX.length, -1); + } + return name === "noop"; } diff --git a/src/providers/openai.ts b/src/providers/openai.ts index b4a019582b..13aeccaa2f 100644 --- a/src/providers/openai.ts +++ b/src/providers/openai.ts @@ -55,6 +55,7 @@ export class OpenAIProvider implements MemoryProvider { private timeoutMs: number; private isAzure: boolean; private azureApiVersion: string; + private tokenizeUnavailable = false; constructor(apiKey: string, model: string, maxTokens: number, baseURL?: string) { this.apiKey = apiKey; @@ -77,10 +78,14 @@ export class OpenAIProvider implements MemoryProvider { } // llama.cpp-style servers expose POST /tokenize at the server root, beside - // /v1. Anything without it answers non-2xx and the caller falls back to an - // estimate, so a count never blocks the work it measures. + // /v1. Anything without it answers 404 once and is never asked again for + // the life of this provider; the caller falls back to an estimate, so a + // count never blocks the work it measures. async countTokens(text: string): Promise<number> { const url = `${this.baseUrl.replace(/\/v1$/, "")}/tokenize`; + if (this.tokenizeUnavailable) { + throw new Error(`tokenize unavailable at ${url}`); + } const response = await fetchWithTimeout( url, { @@ -90,6 +95,9 @@ export class OpenAIProvider implements MemoryProvider { }, TOKENIZE_TIMEOUT_MS, ); + if (response.status === 404) { + this.tokenizeUnavailable = true; + } if (!response.ok) { throw new Error(`tokenize error (${response.status}) at ${url}`); } diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 0d49571a2d..d6b570a58a 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -1,3523 +1,3523 @@ -import { TriggerAction, type ISdk, type ApiRequest } from "../engine/types.js"; -import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js"; -import { withKeyedLock } from "../state/keyed-mutex.js"; -import { KV } from "../state/schema.js"; -import { StateKV } from "../state/kv.js"; -import { graphLegDisabled } from "../state/graph-indexes.js"; -import { checkPayloadSize, isOversizedPayload } from "../state/payload-bound.js"; -import { getLatestHealth } from "../health/monitor.js"; -import type { MetricsStore } from "../eval/metrics-store.js"; -import type { ResilientProvider } from "../providers/resilient.js"; -import { VERSION } from "../version.js"; -import { timingSafeCompare } from "../auth.js"; -import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js"; -import { renderViewerDocument } from "../viewer/document.js"; -import { getBoundViewerPort, getViewerSkipped } from "../viewer/server.js"; -import { MAX_FILES_UPPER_BOUND } from "../functions/replay.js"; -import { logger } from "../logger.js"; -import { - isGraphExtractionEnabled, - isConsolidationEnabled, - isAutoCompressEnabled, - isContextInjectionEnabled, - detectEmbeddingProvider, - detectLlmProviderKind, - getAgentId, - isAgentScopeIsolated, - loadConfig, -} from "../config.js"; - -type Response = { - status_code: number; - headers?: Record<string, string>; - body: unknown; -}; - -function parseOptionalInt(raw: unknown): number | undefined { - if (raw === undefined || raw === null || raw === "") return undefined; - const n = typeof raw === "number" ? raw : parseInt(String(raw), 10); - return Number.isFinite(n) ? n : undefined; -} - -function checkAuth( - req: ApiRequest, - secret: string | undefined, -): Response | null { - if (!secret) return null; - const auth = req.headers?.["authorization"] || req.headers?.["Authorization"]; - if ( - typeof auth !== "string" || - !timingSafeCompare(auth, `Bearer ${secret}`) - ) { - return { status_code: 401, body: { error: "unauthorized" } }; - } - return null; -} - -function requireConfiguredSecret( - secret: string | undefined, - feature: string, -): Response | null { - if (secret) return null; - return { - status_code: 503, - body: { error: `${feature} requires AGENTMEMORY_SECRET` }, - }; -} - -function flagDisabledResponse(opts: { - error: string; - flag: string; - enableHow: string; - docsHref: string; -}): Response { - return { - status_code: 503, - body: opts, - }; -} - -function graphDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Knowledge graph not enabled", - flag: "GRAPH_EXTRACTION_ENABLED", - enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.", - docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", - }); -} - -function consolidationDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Consolidation pipeline not enabled", - flag: "CONSOLIDATION_ENABLED", - enableHow: "Set CONSOLIDATION_ENABLED=true and restart. Requires an LLM provider key.", - docsHref: "https://github.com/rohitg00/agentmemory#consolidation", - }); -} - -function slotsDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Memory slots not enabled", - flag: "AGENTMEMORY_SLOTS", - enableHow: "Set AGENTMEMORY_SLOTS=true (in ~/.agentmemory/.env or the shell) and restart.", - docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", - }); -} - -function reflectDisabledResponse(): Response { - return flagDisabledResponse({ - error: "Slot reflection not enabled", - flag: "AGENTMEMORY_REFLECT", - enableHow: "Set AGENTMEMORY_REFLECT=true (in ~/.agentmemory/.env or the shell) and restart. Requires AGENTMEMORY_SLOTS=true.", - docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", - }); -} - -function asNonEmptyString(value: unknown): string | null { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed ? trimmed : null; -} - -function parseOptionalFiniteNumber(value: unknown): number | undefined | null { - if (value === undefined || value === null) return undefined; - if (typeof value === "number") return Number.isFinite(value) ? value : null; - if (typeof value === "string") { - const trimmed = value.trim(); - if (!trimmed) return undefined; - const parsed = Number(trimmed); - return Number.isFinite(parsed) ? parsed : null; - } - return null; -} - -function parseOptionalPositiveInt(value: unknown): number | undefined | null { - const parsed = parseOptionalFiniteNumber(value); - if (parsed === undefined || parsed === null) return parsed; - if (!Number.isInteger(parsed) || parsed < 1) return null; - return parsed; -} - -export function registerApiTriggers( - sdk: ISdk, - kv: StateKV, - secret?: string, - metricsStore?: MetricsStore, - provider?: ResilientProvider | { circuitState?: unknown; circuitStates?: unknown }, -): void { - sdk.registerFunction( - "middleware::api-auth", - async (input: { - request?: { headers?: Record<string, string | undefined> }; - }) => { - if (!secret) return { action: "continue" }; - const headers = input?.request?.headers || {}; - const auth = headers["authorization"] || headers["Authorization"]; - if ( - typeof auth !== "string" || - !timingSafeCompare(auth, `Bearer ${secret}`) - ) { - return { - action: "respond", - response: { status_code: 401, body: { error: "unauthorized" } }, - }; - } - return { action: "continue" }; - }, - ); - - // Shared instance metadata for livez and health so the two never - // drift. streamsPort lets the viewer resolve its stream WebSocket - // target from the server instead of port arithmetic, which broke - // whenever the viewer bound a fallback port. Config is boot-static, - // so read it once instead of rebuilding the merged env per request. - const bootStreamsPort = loadConfig().streamsPort; - const instanceInfo = () => ({ - service: "agentmemory", - viewerPort: getBoundViewerPort(), - viewerSkipped: getViewerSkipped(), - streamsPort: bootStreamsPort, - }); - - sdk.registerFunction("api::liveness", - async (): Promise<Response> => ({ - status_code: 200, - body: { status: "ok", ...instanceInfo() }, - }), - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::liveness", - config: { api_path: "/agentmemory/livez", http_method: "GET" }, - }); - - sdk.registerFunction("api::config-flags", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const providerKind = detectLlmProviderKind(); - const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none"; - const flags = [ - { - key: "GRAPH_EXTRACTION_ENABLED", - label: "Knowledge graph extraction", - enabled: isGraphExtractionEnabled(), - default: false, - affects: ["Graph", "Dashboard"], - needsLlm: true, - description: "Extracts entities and relations from observations into a knowledge graph.", - enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.", - docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", - }, - { - key: "CONSOLIDATION_ENABLED", - label: "Memory consolidation", - enabled: isConsolidationEnabled(), - default: false, - affects: ["Dashboard", "Memories", "Crystals"], - needsLlm: true, - description: "Periodically summarizes sessions into semantic facts + procedures.", - enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.", - docsHref: "https://github.com/rohitg00/agentmemory#consolidation", - }, - { - key: "AGENTMEMORY_AUTO_COMPRESS", - label: "LLM-powered observation compression", - enabled: isAutoCompressEnabled(), - default: false, - affects: ["Memories", "Timeline"], - needsLlm: true, - description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.", - enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.", - docsHref: "https://github.com/rohitg00/agentmemory/issues/138", - }, - { - key: "AGENTMEMORY_INJECT_CONTEXT", - label: "In-conversation context injection", - enabled: isContextInjectionEnabled(), - default: false, - affects: ["Hooks"], - needsLlm: false, - description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.", - enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.", - docsHref: "https://github.com/rohitg00/agentmemory/issues/143", - }, - ]; - return { - status_code: 200, - body: { - version: VERSION, - provider: providerKind, - embeddingProvider, - flags, - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::config-flags", - config: { - api_path: "/agentmemory/config/flags", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::health", - async (req: ApiRequest): Promise<Response> => { - const health = await getLatestHealth(kv); - const functionMetrics = metricsStore ? await metricsStore.getAll() : []; - const circuitBreaker = - provider && "circuitState" in provider ? provider.circuitState : null; - const circuitBreakers = - provider && "circuitStates" in provider ? provider.circuitStates : null; - - const status = health?.status || "healthy"; - const statusCode = status === "critical" ? 503 : 200; - - return { - status_code: statusCode, - body: { - status, - version: VERSION, - health: health || null, - functionMetrics, - circuitBreaker, - circuitBreakers, - ...instanceInfo(), - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::health", - config: { - api_path: "/agentmemory/health", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::observe", - async (req: ApiRequest<HookPayload>): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const hookType = asNonEmptyString(body.hookType); - const sessionId = asNonEmptyString(body.sessionId); - const project = asNonEmptyString(body.project); - const cwd = asNonEmptyString(body.cwd); - const timestamp = asNonEmptyString(body.timestamp); - if (!hookType || !sessionId || !project || !cwd || !timestamp) { - return { - status_code: 400, - body: { - error: - "hookType, sessionId, project, cwd, and timestamp are required strings", - }, - }; - } - const payload: HookPayload = { - hookType: hookType as HookPayload["hookType"], - sessionId, - project, - cwd, - timestamp, - data: body.data, - }; - const result = await sdk.trigger({ function_id: "mem::observe", payload }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::observe", - config: { - api_path: "/agentmemory/observe", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::context", - async ( - req: ApiRequest<{ - sessionId: string; - project: string; - budget?: number; - agentId?: string; - }>, - ): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body.sessionId); - const project = asNonEmptyString(body.project); - if (!sessionId || !project) { - return { - status_code: 400, - body: { error: "sessionId and project are required strings" }, - }; - } - const budget = parseOptionalPositiveInt(body.budget); - if (budget === null) { - return { - status_code: 400, - body: { error: "budget must be a positive integer" }, - }; - } - // Propagate agentId so mem::context applies the same cross-agent - // isolation filter as mem::search. Honors body.agentId, ?agentId=, - // or the worker's AGENT_ID fallback under AGENTMEMORY_AGENT_SCOPE=isolated. - const queryAgentId = - typeof (req as { query_params?: Record<string, string> }) - .query_params?.["agentId"] === "string" - ? (req as { query_params: Record<string, string> }) - .query_params["agentId"] - : undefined; - const bodyAgentId = - typeof body.agentId === "string" && body.agentId.trim().length > 0 - ? (body.agentId as string).trim() - : undefined; - const payload: { - sessionId: string; - project: string; - budget?: number; - agentId?: string; - } = { - sessionId, - project, - }; - if (budget !== undefined) payload.budget = budget; - const agentId = bodyAgentId ?? queryAgentId; - if (agentId !== undefined) payload.agentId = agentId; - const result = await sdk.trigger({ function_id: "mem::context", payload }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::context", - config: { - api_path: "/agentmemory/context", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::search", - async ( - req: ApiRequest<{ - query: string; - limit?: number; - project?: string; - cwd?: string; - format?: string; - token_budget?: number; - agentId?: string; - }>, - ): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const queryAgentId = - typeof (req as { query_params?: Record<string, string> }) - .query_params?.["agentId"] === "string" - ? (req as { query_params: Record<string, string> }) - .query_params["agentId"] - : undefined; - if (typeof body.query !== "string" || !body.query.trim()) { - return { status_code: 400, body: { error: "query is required and must be a non-empty string" } }; - } - if ( - body.limit !== undefined && - (!Number.isInteger(body.limit) || (body.limit as number) < 1) - ) { - return { status_code: 400, body: { error: "limit must be a positive integer" } }; - } - if (body.project !== undefined && typeof body.project !== "string") { - return { status_code: 400, body: { error: "project must be a string" } }; - } - if (body.cwd !== undefined && typeof body.cwd !== "string") { - return { status_code: 400, body: { error: "cwd must be a string" } }; - } - if ( - body.format !== undefined && - (typeof body.format !== "string" || - !["full", "compact", "narrative"].includes(body.format.trim().toLowerCase())) - ) { - return { - status_code: 400, - body: { error: "format must be one of: full, compact, narrative" }, - }; - } - if ( - body.token_budget !== undefined && - (!Number.isInteger(body.token_budget) || (body.token_budget as number) < 1) - ) { - return { - status_code: 400, - body: { error: "token_budget must be a positive integer" }, - }; - } - // #817: propagate agentId so the upstream isolation filter - // applies. Honors body.agentId (POST body), ?agentId=... query - // param, or implicit fallback to the worker's AGENT_ID when - // AGENTMEMORY_AGENT_SCOPE=isolated. - const bodyAgentId = - typeof body.agentId === "string" && body.agentId.trim().length > 0 - ? (body.agentId as string).trim() - : undefined; - const payload = { - query: body.query.trim(), - limit: body.limit as number | undefined, - project: body.project as string | undefined, - cwd: body.cwd as string | undefined, - format: - typeof body.format === "string" - ? body.format.trim().toLowerCase() - : undefined, - token_budget: body.token_budget as number | undefined, - agentId: bodyAgentId ?? queryAgentId, - }; - const result = await sdk.trigger({ function_id: "mem::search", payload: payload }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::search", - config: { - api_path: "/agentmemory/search", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::compress-file", - async (req: ApiRequest<{ filePath: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const filePath = asNonEmptyString(body.filePath); - if (!filePath) { - return { - status_code: 400, - body: { error: "filePath is required and must be a non-empty string" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::compress-file", - payload: { filePath }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::compress-file", - config: { api_path: "/agentmemory/compress-file", http_method: "POST" }, - }); - - sdk.registerFunction("api::replay::load", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); - if (!sessionId) { - return { status_code: 400, body: { error: "sessionId is required" } }; - } - const result = await sdk.trigger({ - function_id: "mem::replay::load", - payload: { sessionId }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::replay::load", - config: { api_path: "/agentmemory/replay/load", http_method: "GET" }, - }); - - sdk.registerFunction("api::replay::sessions", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessions = await kv.list<Session>(KV.sessions); - sessions.sort((a, b) => - (b.startedAt || "").localeCompare(a.startedAt || ""), - ); - return { status_code: 200, body: { success: true, sessions } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::replay::sessions", - config: { api_path: "/agentmemory/replay/sessions", http_method: "GET" }, - }); - - sdk.registerFunction("api::replay::import", - async ( - req: ApiRequest<{ path?: string; maxFiles?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const payload: { path?: string; maxFiles?: number } = {}; - if (body.path !== undefined) { - if (typeof body.path !== "string" || body.path.trim().length === 0) { - return { - status_code: 400, - body: { error: "path must be a non-empty string" }, - }; - } - payload.path = body.path.trim(); - } - if (body.maxFiles !== undefined) { - const n = body.maxFiles as number; - if ( - !Number.isInteger(n) || - n < 1 || - n > MAX_FILES_UPPER_BOUND - ) { - return { - status_code: 400, - body: { - error: `maxFiles must be an integer between 1 and ${MAX_FILES_UPPER_BOUND}`, - }, - }; - } - payload.maxFiles = n; - } - const result = await sdk.trigger({ - function_id: "mem::replay::import-jsonl", - payload, - }); - return { status_code: 202, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::replay::import", - config: { api_path: "/agentmemory/replay/import-jsonl", http_method: "POST" }, - }); - - sdk.registerFunction("api::session::start", - async ( - req: ApiRequest<{ sessionId: string; project: string; cwd: string }>, - ): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body.sessionId); - const project = asNonEmptyString(body.project); - const cwd = asNonEmptyString(body.cwd); - if (!sessionId || !project || !cwd) { - return { - status_code: 400, - body: { - error: "sessionId, project, and cwd are required non-empty strings", - }, - }; - } - const title = typeof body.title === "string" ? body.title.trim() : undefined; - // allow session/start to override AGENT_ID from request body - // (multi-agent runtimes that route many roles through one server - // process). Falls back to the AGENT_ID env on the server. - const requestAgentId = - typeof body.agentId === "string" && body.agentId.trim().length > 0 - ? body.agentId.trim().slice(0, 128) - : undefined; - const agentId = requestAgentId ?? getAgentId(); - const session: Session = { - id: sessionId, - project, - cwd, - startedAt: new Date().toISOString(), - status: "active", - observationCount: 0, - ...(title ? { summary: title.slice(0, 200) } : {}), - ...(title ? { firstPrompt: title.slice(0, 200) } : {}), - ...(agentId ? { agentId } : {}), - }; - await kv.set(KV.sessions, sessionId, session); - const contextResult = await sdk.trigger< - { sessionId: string; project: string; agentId?: string }, - { context: string } - >({ - function_id: "mem::context", - payload: { sessionId, project, ...(agentId ? { agentId } : {}) }, - }); - return { - status_code: 200, - body: { session, context: contextResult.context }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::start", - config: { - api_path: "/agentmemory/session/start", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::session::end", - async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => { - const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId); - if (!sessionId) { - return { - status_code: 400, - body: { error: "sessionId is required and must be a non-empty string" }, - }; - } - await kv.update(KV.sessions, sessionId, [ - { type: "set", path: "endedAt", value: new Date().toISOString() }, - { type: "set", path: "status", value: "completed" }, - ]); - // Fan out session-stopped lifecycle (non-blocking). - try { - sdk.trigger({ - function_id: "event::session::stopped", - payload: { sessionId }, - action: TriggerAction.Void(), - }); - } catch (err) { - logger.warn("event::session::stopped trigger failed", { - sessionId, - error: err instanceof Error ? err.message : String(err), - }); - } - return { status_code: 200, body: { success: true } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::end", - config: { - api_path: "/agentmemory/session/end", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::summarize", - async (req: ApiRequest<{ sessionId: string; force?: boolean }>): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body.sessionId); - if (!sessionId) { - return { status_code: 400, body: { error: "sessionId is required" } }; - } - const result = await sdk.trigger({ - function_id: "mem::summarize", - payload: { sessionId, force: body.force === true }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::summarize", - config: { - api_path: "/agentmemory/summarize", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::session::commit", - async (req: ApiRequest): Promise<Response> => { - const body = (req.body ?? {}) as Record<string, unknown>; - const sha = asNonEmptyString(body.sha); - if (!sha) { - return { - status_code: 400, - body: { error: "sha is required and must be a non-empty string" }, - }; - } - const sessionId = asNonEmptyString(body.sessionId) ?? undefined; - const branch = asNonEmptyString(body.branch) ?? undefined; - const repo = asNonEmptyString(body.repo) ?? undefined; - const message = asNonEmptyString(body.message) ?? undefined; - const author = asNonEmptyString(body.author) ?? undefined; - const authoredAt = asNonEmptyString(body.authoredAt) ?? undefined; - const files = Array.isArray(body.files) - ? (body.files as unknown[]).filter( - (f): f is string => typeof f === "string" && f.length > 0, - ) - : undefined; - - const link = await withKeyedLock(`commit:${sha}`, async () => { - const existing = await kv.get<CommitLink>(KV.commits, sha); - const sessionSet = new Set<string>(existing?.sessionIds ?? []); - if (sessionId) sessionSet.add(sessionId); - const merged: CommitLink = { - sha, - shortSha: existing?.shortSha ?? sha.slice(0, 7), - branch: branch ?? existing?.branch, - repo: repo ?? existing?.repo, - message: message ?? existing?.message, - author: author ?? existing?.author, - authoredAt: authoredAt ?? existing?.authoredAt, - files: files ?? existing?.files, - sessionIds: Array.from(sessionSet), - linkedAt: existing?.linkedAt ?? new Date().toISOString(), - }; - await kv.set(KV.commits, sha, merged); - return merged; - }); - - if (sessionId) { - await withKeyedLock(`session:${sessionId}`, async () => { - const session = await kv.get<Session>(KV.sessions, sessionId); - if (!session) return; - const shaSet = new Set<string>(session.commitShas ?? []); - shaSet.add(sha); - session.commitShas = Array.from(shaSet); - await kv.set(KV.sessions, sessionId, session); - }); - } - - return { status_code: 200, body: { commit: link } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::commit", - config: { - api_path: "/agentmemory/session/commit", - http_method: "POST", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::session::by-commit", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sha = asNonEmptyString(req.query_params?.["sha"]); - if (!sha) { - return { - status_code: 400, - body: { error: "sha is required and must be a non-empty string" }, - }; - } - const link = await kv.get<CommitLink>(KV.commits, sha); - if (!link) { - return { - status_code: 404, - body: { error: "no sessions linked to this commit" }, - }; - } - const fetched = await Promise.all( - (link.sessionIds ?? []).map((sid) => kv.get<Session>(KV.sessions, sid)), - ); - const sessions = fetched.filter((s): s is Session => s !== null); - return { status_code: 200, body: { commit: link, sessions } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::session::by-commit", - config: { - api_path: "/agentmemory/session/by-commit", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::commits", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const branch = asNonEmptyString(req.query_params?.["branch"]); - const repo = asNonEmptyString(req.query_params?.["repo"]); - const rawLimit = parseOptionalInt(req.query_params?.["limit"]); - const limit = Math.max(1, Math.min(500, rawLimit ?? 100)); - const all = await kv.list<CommitLink>(KV.commits); - const filtered = all - .filter((c) => !branch || c.branch === branch) - .filter((c) => !repo || c.repo === repo) - .sort((a, b) => ((a.linkedAt ?? "") < (b.linkedAt ?? "") ? 1 : -1)) - .slice(0, limit); - return { status_code: 200, body: { commits: filtered } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::commits", - config: { - api_path: "/agentmemory/commits", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::sessions", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessions = await kv.list<Session>(KV.sessions); - const normalizedAgentId = - typeof req.query_params?.["agentId"] === "string" - ? req.query_params["agentId"].trim() - : undefined; - const wildcardAgent = normalizedAgentId === "*"; - const explicitAgentId = - normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; - const filterAgentId = wildcardAgent - ? undefined - : explicitAgentId ?? - (isAgentScopeIsolated() ? getAgentId() : undefined); - const filtered = filterAgentId - ? sessions.filter((s) => s.agentId === filterAgentId) - : sessions; - // Bounded fan-out: each kv.get is a full engine invocation, so - // Promise.all over hundreds of sessions saturates the invocation - // pool. Batch in chunks of 10 (parallel within a chunk, sequential - // across chunks); the summaries array stays index-aligned with - // `filtered`. - const summaries: Array<SessionSummary | null> = []; - for (let batch = 0; batch < filtered.length; batch += 10) { - const chunk = filtered.slice(batch, batch + 10); - const results = await Promise.all( - chunk.map((s) => - kv.get<SessionSummary>(KV.summaries, s.id).catch(() => null), - ), - ); - summaries.push(...results); - } - const withSummary = filtered.map((s, i) => - summaries[i] ? { ...s, summary: summaries[i] } : s, - ); - return { status_code: 200, body: { sessions: withSummary } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::sessions", - config: { api_path: "/agentmemory/sessions", http_method: "GET" }, - }); - - sdk.registerFunction("api::observations", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); - if (!sessionId) - return { status_code: 400, body: { error: "sessionId required" } }; - const observations = await kv.list<CompressedObservation>( - KV.observations(sessionId), - ); - const normalizedAgentId = - typeof req.query_params?.["agentId"] === "string" - ? req.query_params["agentId"].trim() - : undefined; - const wildcardAgent = normalizedAgentId === "*"; - const explicitAgentId = - normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; - const filterAgentId = wildcardAgent - ? undefined - : explicitAgentId ?? - (isAgentScopeIsolated() ? getAgentId() : undefined); - const filtered = filterAgentId - ? observations.filter((o) => o.agentId === filterAgentId) - : observations; - return { status_code: 200, body: { observations: filtered } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::observations", - config: { api_path: "/agentmemory/observations", http_method: "GET" }, - }); - - sdk.registerFunction("api::file-context", - async ( - req: ApiRequest<{ sessionId: string; files: string[] }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::file-context", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::file-context", - config: { api_path: "/agentmemory/file-context", http_method: "POST" }, - }); - - sdk.registerFunction("api::enrich", - async ( - req: ApiRequest<{ - sessionId: string; - files: string[]; - terms?: string[]; - toolName?: string; - project?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !req.body?.sessionId || - typeof req.body.sessionId !== "string" || - !Array.isArray(req.body?.files) || - req.body.files.length === 0 || - !req.body.files.every((f: unknown) => typeof f === "string") - ) { - return { - status_code: 400, - body: { - error: "sessionId (string) and files (string[]) are required", - }, - }; - } - if ( - req.body.terms !== undefined && - (!Array.isArray(req.body.terms) || - !req.body.terms.every((t: unknown) => typeof t === "string")) - ) { - return { - status_code: 400, - body: { error: "terms must be an array of strings" }, - }; - } - if ( - req.body.project !== undefined && - (typeof req.body.project !== "string" || !req.body.project.trim()) - ) { - return { - status_code: 400, - body: { error: "project must be a non-empty string" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::enrich", - payload: { - sessionId: req.body.sessionId, - files: req.body.files, - ...(req.body.terms !== undefined && { terms: req.body.terms }), - ...(req.body.toolName !== undefined && { toolName: req.body.toolName }), - ...(req.body.project !== undefined && { project: req.body.project }), - }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::enrich", - config: { api_path: "/agentmemory/enrich", http_method: "POST" }, - }); - - sdk.registerFunction("api::remember", - async ( - req: ApiRequest<{ - content: string; - type?: string; - concepts?: string[]; - files?: string[]; - ttlDays?: number; - sourceObservationIds?: string[]; - project?: string; - agentId?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !req.body?.content || - typeof req.body.content !== "string" || - !req.body.content.trim() - ) { - return { status_code: 400, body: { error: "content is required" } }; - } - if ( - req.body.project !== undefined && - (typeof req.body.project !== "string" || !req.body.project.trim()) - ) { - return { status_code: 400, body: { error: "project must be a non-empty string" } }; - } - const result = await sdk.trigger({ - function_id: "mem::remember", - payload: { - content: req.body.content, - ...(req.body.type !== undefined && { type: req.body.type }), - ...(req.body.concepts !== undefined && { concepts: req.body.concepts }), - ...(req.body.files !== undefined && { files: req.body.files }), - ...(req.body.ttlDays !== undefined && { ttlDays: req.body.ttlDays }), - ...(req.body.sourceObservationIds !== undefined && { sourceObservationIds: req.body.sourceObservationIds }), - ...(req.body.project !== undefined && { project: req.body.project }), - ...(typeof req.body.agentId === "string" && req.body.agentId.trim() - ? { agentId: req.body.agentId.trim() } - : {}), - }, - }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::remember", - config: { api_path: "/agentmemory/remember", http_method: "POST" }, - }); - - sdk.registerFunction("api::forget", - async ( - req: ApiRequest<{ - sessionId?: string; - observationIds?: string[]; - memoryId?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const sessionId = - typeof req.body?.sessionId === "string" ? req.body.sessionId : undefined; - const memoryId = - typeof req.body?.memoryId === "string" ? req.body.memoryId : undefined; - if (!sessionId && !memoryId) { - return { - status_code: 400, - body: { error: "sessionId or memoryId is required" }, - }; - } - const rawObservationIds = req.body?.observationIds; - // Dropping the non-strings and forwarding what is left would turn a - // malformed list into an empty one, and an empty list is the whole- - // session wipe. Refuse instead of widening what was asked for. - if ( - rawObservationIds !== undefined && - (!Array.isArray(rawObservationIds) || - !rawObservationIds.every((id) => typeof id === "string")) - ) { - return { - status_code: 400, - body: { error: "observationIds must be an array of strings" }, - }; - } - const result = (await sdk.trigger({ - function_id: "mem::forget", - payload: { - ...(sessionId !== undefined && { sessionId }), - ...(memoryId !== undefined && { memoryId }), - ...(rawObservationIds !== undefined && { observationIds: rawObservationIds }), - }, - })) as { success: boolean; error?: string }; - // The refusals mem::forget raises are bad requests, not results. - if (!result.success) { - return { status_code: 400, body: result }; - } - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::forget", - config: { api_path: "/agentmemory/forget", http_method: "POST" }, - }); - - sdk.registerFunction("api::consolidate", - async ( - req: ApiRequest<{ project?: string; minObservations?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::consolidate", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::consolidate", - config: { api_path: "/agentmemory/consolidate", http_method: "POST" }, - }); - - sdk.registerFunction("api::patterns", - async (req: ApiRequest<{ project?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::patterns", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::patterns", - config: { api_path: "/agentmemory/patterns", http_method: "POST" }, - }); - - sdk.registerFunction("api::generate-rules", - async (req: ApiRequest<{ project?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::generate-rules", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::generate-rules", - config: { api_path: "/agentmemory/generate-rules", http_method: "POST" }, - }); - - sdk.registerFunction("api::migrate", - async ( - req: ApiRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const hasStep = - typeof req.body?.step === "string" && req.body.step.trim().length > 0; - const hasDbPath = - typeof req.body?.dbPath === "string" && req.body.dbPath.trim().length > 0; - if (!hasStep && !hasDbPath) { - return { - status_code: 400, - body: { error: "Either step (string) or dbPath (string) is required" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::migrate", - payload: { - ...(req.body.step !== undefined && { step: req.body.step }), - ...(req.body.dbPath !== undefined && { dbPath: req.body.dbPath }), - ...(req.body.dryRun !== undefined && { dryRun: req.body.dryRun }), - }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::migrate", - config: { api_path: "/agentmemory/migrate", http_method: "POST" }, - }); - - sdk.registerFunction("api::evict", - async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const dryRun = - req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; - const result = await sdk.trigger({ function_id: "mem::evict", payload: { dryRun } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::evict", - config: { api_path: "/agentmemory/evict", http_method: "POST" }, - }); - - sdk.registerFunction("api::smart-search", - async ( - req: ApiRequest<{ - query?: string; - expandIds?: Array<string | { obsId: string; sessionId: string }>; - limit?: number; - project?: string; - includeLessons?: boolean; - agentId?: string; - sessionId?: string; - source?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !req.body?.query && - (!req.body?.expandIds || req.body.expandIds.length === 0) - ) { - return { - status_code: 400, - body: { error: "query or expandIds is required" }, - }; - } - // #771: route the X-Agentmemory-Source header into the payload so - // the followup-rate diagnostic can skip viewer-originated calls. - // Body wins if both are set (advanced callers explicitly override). - const headers = (req.headers || {}) as Record<string, string | string[] | undefined>; - const sourceHeader = headers["x-agentmemory-source"] ?? headers["X-Agentmemory-Source"]; - const sourceFromHeader = Array.isArray(sourceHeader) ? sourceHeader[0] : sourceHeader; - // Whitelist payload fields explicitly — REST endpoints never pass - // the raw request body through to sdk.trigger (AGENTS.md security - // section). Drops unknown fields so a misbehaving client can't - // inject downstream-only options. - const payload = { - query: req.body?.query, - expandIds: req.body?.expandIds, - limit: req.body?.limit, - project: req.body?.project, - includeLessons: req.body?.includeLessons, - agentId: req.body?.agentId, - sessionId: req.body?.sessionId, - source: req.body?.source ?? sourceFromHeader, - }; - const result = await sdk.trigger({ function_id: "mem::smart-search", payload }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::smart-search", - config: { api_path: "/agentmemory/smart-search", http_method: "POST" }, - }); - - // #771: read-back endpoint for the followup-rate diagnostic. Returns - // a directional signal — overcounts on legitimate query refinement — - // so help text + the CLI status line carry the same caveat. - sdk.registerFunction("api::diagnostic-followup", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ - function_id: "mem::diagnostic::followup-stats", - payload: {}, - }); - return { - status_code: 200, - body: { - ...(result as Record<string, unknown>), - caveat: - "Directional signal: overcounts on legitimate query refinement. " + - "Tune via AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS.", - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::diagnostic-followup", - config: { - api_path: "/agentmemory/diagnostics/followup", - http_method: "GET", - middleware_function_ids: ["middleware::api-auth"], - }, - }); - - sdk.registerFunction("api::timeline", - async ( - req: ApiRequest<{ - anchor: string; - project?: string; - before?: number; - after?: number; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.anchor) { - return { status_code: 400, body: { error: "anchor is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::timeline", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::timeline", - config: { api_path: "/agentmemory/timeline", http_method: "POST" }, - }); - - sdk.registerFunction("api::profile", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const project = req.query_params["project"] as string; - if (!project) { - return { - status_code: 400, - body: { error: "project query param is required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::profile", payload: { project } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::profile", - config: { api_path: "/agentmemory/profile", http_method: "GET" }, - }); - - sdk.registerFunction("api::export", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - // mem::export already supports maxSessions/offset internally, - // but the HTTP endpoint hardcoded an empty payload — so /export on a - // real corpus (40 sessions × 34K observations × 8K memories) hit the - // iii engine invocation timeout and `agentmemory status` reported 0. - // Pass through the query-string pagination so callers can chunk. - const rawMax = req.query_params?.["maxSessions"]; - const rawOffset = req.query_params?.["offset"]; - const payload: { maxSessions?: number; offset?: number } = {}; - if (typeof rawMax === "string") { - const n = Number(rawMax); - if (Number.isInteger(n) && n > 0) payload.maxSessions = n; - } - if (typeof rawOffset === "string") { - const n = Number(rawOffset); - if (Number.isInteger(n) && n >= 0) payload.offset = n; - } - const result = await sdk.trigger({ - function_id: "mem::export", - payload, - }); - // mem::export refuses an oversized payload rather than serializing it; - // over HTTP that refusal is a 413, not a 200 carrying an error body. - if (isOversizedPayload(result)) return { status_code: 413, body: result }; - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::export", - config: { api_path: "/agentmemory/export", http_method: "GET" }, - }); - - sdk.registerFunction("api::import", - async ( - req: ApiRequest<{ - exportData: unknown; - strategy?: "merge" | "replace" | "skip"; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.exportData) { - return { status_code: 400, body: { error: "exportData is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::import", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::import", - config: { api_path: "/agentmemory/import", http_method: "POST" }, - }); - - sdk.registerFunction("api::relations", - async ( - req: ApiRequest<{ sourceId: string; targetId: string; type: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.sourceId || !req.body?.targetId || !req.body?.type) { - return { - status_code: 400, - body: { error: "sourceId, targetId, and type are required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::relate", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::relations", - config: { api_path: "/agentmemory/relations", http_method: "POST" }, - }); - - sdk.registerFunction("api::evolve", - async ( - req: ApiRequest<{ - memoryId: string; - newContent: string; - newTitle?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.memoryId || !req.body?.newContent) { - return { - status_code: 400, - body: { error: "memoryId and newContent are required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::evolve", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::evolve", - config: { api_path: "/agentmemory/evolve", http_method: "POST" }, - }); - - sdk.registerFunction("api::auto-forget", - async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const dryRun = - req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; - const result = await sdk.trigger({ function_id: "mem::auto-forget", payload: { dryRun } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::auto-forget", - config: { api_path: "/agentmemory/auto-forget", http_method: "POST" }, - }); - - sdk.registerFunction("api::claude-bridge-read", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::claude-bridge-read", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { - status_code: 404, - body: { error: "Claude bridge not enabled" }, - }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::claude-bridge-read", - config: { api_path: "/agentmemory/claude-bridge/read", http_method: "GET" }, - }); - - sdk.registerFunction("api::claude-bridge-sync", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::claude-bridge-sync", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { - status_code: 404, - body: { error: "Claude bridge not enabled" }, - }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::claude-bridge-sync", - config: { - api_path: "/agentmemory/claude-bridge/sync", - http_method: "POST", - }, - }); - - sdk.registerFunction("api::graph-query", - async ( - req: ApiRequest<{ - startNodeId?: string; - nodeType?: string; - maxDepth?: number; - query?: string; - limit?: number; - offset?: number; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - // Whitelist payload fields explicitly; AGENTS.md security rule: - // REST endpoints never pass raw req.body through to sdk.trigger. - const payload = { - startNodeId: req.body?.startNodeId, - nodeType: req.body?.nodeType, - maxDepth: req.body?.maxDepth, - query: req.body?.query, - limit: req.body?.limit, - offset: req.body?.offset, - }; - try { - const result = await sdk.trigger({ function_id: "mem::graph-query", payload }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-query", - config: { api_path: "/agentmemory/graph/query", http_method: "POST" }, - }); - - sdk.registerFunction("api::graph-stats", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::graph-stats", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-stats", - config: { api_path: "/agentmemory/graph/stats", http_method: "GET" }, - }); - - // #814: explicit snapshot rebuild endpoint. Pays the full graph - // enumeration once and persists a top-degree subgraph + aggregate - // counts so subsequent /graph/query and /graph/stats calls skip the - // unbounded kv.list. Operator-grade endpoint exposed for the viewer - // banner action and CLI repair. - sdk.registerFunction("api::graph-snapshot-rebuild", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ - function_id: "mem::graph-snapshot-rebuild", - payload: {}, - }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-snapshot-rebuild", - config: { api_path: "/agentmemory/graph/snapshot-rebuild", http_method: "POST" }, - }); - - // #814 v2: clean-restart endpoint for legacy corpora too large for - // safe rebuild. Wipes graph state without touching observations, so - // recall + history stay intact while the graph rebuilds incrementally - // from new extracts (or a one-shot /graph/build replay). - sdk.registerFunction("api::graph-reset", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ - function_id: "mem::graph-reset", - payload: {}, - }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-reset", - config: { api_path: "/agentmemory/graph/reset", http_method: "POST" }, - }); - - sdk.registerFunction("api::graph-extract", - async (req: ApiRequest<{ observations: unknown[] }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if ( - !Array.isArray(req.body?.observations) || - req.body.observations.length === 0 - ) { - return { - status_code: 400, - body: { error: "observations array is required" }, - }; - } - try { - const result = await sdk.trigger({ function_id: "mem::graph-extract", payload: req.body }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-extract", - config: { api_path: "/agentmemory/graph/extract", http_method: "POST" }, - }); - - // Backfill the knowledge graph from existing compressed observations. - // Viewer calls this when the graph is empty (#666). Iterates every - // session, collects observations that have a `title` (compressed only), - // and feeds them through `mem::graph-extract` in batches. - sdk.registerFunction("api::graph-build", - async (req: ApiRequest<{ batchSize?: number }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const batchSize = Math.max( - 1, - Math.min(100, Number((req.body as { batchSize?: number })?.batchSize) || 25), - ); - try { - const sessions = await kv.list<Session>(KV.sessions); - let totalNodes = 0; - let totalEdges = 0; - let batchesRun = 0; - for (const session of sessions) { - const sid = session?.id; - if (typeof sid !== "string" || sid.length === 0) continue; - const observations = await kv.list<CompressedObservation>(KV.observations(sid)); - const compressed = observations.filter((o) => o && typeof o.title === "string" && o.title.length > 0); - if (compressed.length === 0) continue; - for (let i = 0; i < compressed.length; i += batchSize) { - const batch = compressed.slice(i, i + batchSize); - try { - const result = (await sdk.trigger({ - function_id: "mem::graph-extract", - payload: { observations: batch }, - })) as { success?: boolean; nodesAdded?: number; edgesAdded?: number }; - if (result?.success) { - totalNodes += Number(result.nodesAdded) || 0; - totalEdges += Number(result.edgesAdded) || 0; - } - batchesRun++; - } catch (err) { - logger.warn("graph-build batch failed", { - sessionId: sid, - batchIndex: Math.floor(i / batchSize), - error: err instanceof Error ? err.message : String(err), - }); - } - } - } - return { - status_code: 200, - body: { - success: true, - sessions: sessions.length, - batches: batchesRun, - nodes: totalNodes, - edges: totalEdges, - }, - }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-build", - config: { api_path: "/agentmemory/graph/build", http_method: "POST" }, - }); - - // Import graphify's structural graph (graphify-out/graph.json) into the - // memory graph. Deterministic, no LLM call; idempotent via the graph - // name-index upsert. - sdk.registerFunction("api::graph-import-graphify", - async (req: ApiRequest<{ path?: string; cwd?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const { path, cwd } = req.body ?? {}; - if ( - (path !== undefined && typeof path !== "string") || - (cwd !== undefined && typeof cwd !== "string") - ) { - return { - status_code: 400, - body: { error: "path and cwd must be strings when provided" }, - }; - } - try { - const result = await sdk.trigger({ - function_id: "mem::graph::import-graphify", - payload: { - ...(path !== undefined ? { path } : {}), - ...(cwd !== undefined ? { cwd } : {}), - }, - }); - return { status_code: 200, body: result }; - } catch { - return graphDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::graph-import-graphify", - config: { api_path: "/agentmemory/graph/import-graphify", http_method: "POST" }, - }); - - // Re-run compression for observations that a failed mem::compress left in - // raw shape - present in KV but in neither search index, so unretrievable. - // Two sources: mem:compress-pending (parked by the failure path, full raw - // preserved) and raw-shaped records in KV.observations (the historical - // orphans that predate that fix). Sequential and limit-bounded on purpose: - // this exists to be run after a provider outage, and firing hundreds of - // concurrent LLM calls at a provider that has just stopped returning 529s - // is how you cause the next one. - sdk.registerFunction("api::recompress-orphans", - async (req: ApiRequest<{ limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body || {}) as { limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }; - const limit = Math.max(1, Math.min(1000, Number(body.limit) || 50)); - const dryRun = body.dryRun === true; - // Records captured before this instant skip the one-hour grace. The - // cutover passes its freeze timestamp: nothing captured before the - // freeze can still have a compression in flight on the new daemon. - const graceBypassBefore = typeof body.graceBypassBefore === "string" ? new Date(body.graceBypassBefore).getTime() : NaN; - if (typeof body.graceBypassBefore === "string" && !Number.isFinite(graceBypassBefore)) { - return { status_code: 400, body: { error: "graceBypassBefore must be an ISO timestamp" } }; - } - // Give quarantined entries (attempts >= MAX_ATTEMPTS) one more shot. - // Meant for after a compression-pipeline fix lands: what was a - // deterministic failure may compress cleanly under the new code. - const requeueQuarantined = body.requeueQuarantined === true; - const GRACE_MS = 60 * 60 * 1000; - const now = Date.now(); - - const MAX_ATTEMPTS = 5; - const targets: Array<{ observationId: string; sessionId: string; raw: unknown }> = []; - - // Raw-shaped orphans FIRST: they are the records no search can return, - // so the batch budget belongs to them. Parked entries are already - // findable as degraded synthetics - re-compressing them is a quality - // upgrade, not a rescue. (The first version of this endpoint did the - // opposite and starved the raw ones: every failed parked entry was - // re-parked, so the pending queue never shrank and always ate the - // whole budget.) - let rawOrphans = 0; - for (const session of await kv.list<Session>(KV.sessions)) { - const sid = session?.id; - if (typeof sid !== "string" || sid.length === 0) continue; - for (const o of await kv.list<Record<string, unknown>>(KV.observations(sid))) { - const oid = o?.["id"]; - if (typeof oid !== "string") continue; - if (typeof o["narrative"] === "string") continue; - if (typeof o["hookType"] !== "string") continue; - const ts = new Date(String(o["timestamp"])).getTime(); - const bypass = Number.isFinite(graceBypassBefore) && Number.isFinite(ts) && ts < graceBypassBefore; - if (Number.isFinite(ts) && now - ts < GRACE_MS && !bypass) continue; - rawOrphans++; - if (targets.length < limit) { - targets.push({ observationId: oid, sessionId: sid, raw: o }); - } - } - } - - const queued = new Set(targets.map((t) => t.observationId)); - let parked = 0; - let quarantined = 0; - for (const p of await kv.list<{ - observationId?: string; - sessionId?: string; - raw?: unknown; - attempts?: number; - }>(KV.compressPending)) { - if (typeof p?.observationId !== "string" || typeof p?.sessionId !== "string") continue; - if (queued.has(p.observationId)) continue; - if ((p.attempts ?? 0) >= MAX_ATTEMPTS) { - quarantined++; - if (!requeueQuarantined) continue; - } else { - parked++; - } - if (targets.length < limit) { - targets.push({ observationId: p.observationId, sessionId: p.sessionId, raw: p.raw }); - } - } - - if (dryRun) { - return { - status_code: 200, - body: { - success: true, - dryRun: true, - rawOrphans, - parked, - quarantined, - queued: targets.length, - limit, - }, - }; - } - - let recompressed = 0; - let stillFailing = 0; - for (const t of targets) { - try { - const result = (await sdk.trigger({ - function_id: "mem::compress", - payload: t, - })) as { success?: boolean } | null; - if (result?.success) recompressed++; - else stillFailing++; - } catch { - stillFailing++; - } - // Bail out rather than grind through hundreds of doomed calls when - // the provider is clearly still down. Not for requeueQuarantined - // batches: there every target is a known deterministic failure, so - // ten straight losses say nothing about the provider. - if (!requeueQuarantined && stillFailing >= 10 && recompressed === 0) { - logger.warn("recompress-orphans aborting: provider still failing", { - attempted: recompressed + stillFailing, - }); - break; - } - } - - logger.info("recompress-orphans finished", { - rawOrphans, - parked, - quarantined, - queued: targets.length, - recompressed, - stillFailing, - }); - return { - status_code: 200, - body: { - success: true, - rawOrphans, - parked, - quarantined, - queued: targets.length, - recompressed, - stillFailing, - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::recompress-orphans", - config: { api_path: "/agentmemory/recompress-orphans", http_method: "POST" }, - }); - - sdk.registerFunction("api::consolidate-pipeline", - async (req: ApiRequest<{ tier?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: req.body || {}, - }); - return { status_code: 200, body: result }; - } catch { - return consolidationDisabledResponse(); - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::consolidate-pipeline", - config: { - api_path: "/agentmemory/consolidate-pipeline", - http_method: "POST", - }, - }); - - sdk.registerFunction("api::team-share", - async ( - req: ApiRequest<{ itemId: string; itemType: string; project?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.itemId || !req.body?.itemType) { - return { - status_code: 400, - body: { error: "itemId and itemType are required" }, - }; - } - try { - const result = await sdk.trigger({ function_id: "mem::team-share", payload: req.body }); - return { status_code: 201, body: result }; - } catch { - return { status_code: 404, body: { error: "Team memory not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::team-share", - config: { api_path: "/agentmemory/team/share", http_method: "POST" }, - }); - - sdk.registerFunction("api::team-feed", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const limit = parsedLimit ?? 20; - const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { limit } }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Team memory not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::team-feed", - config: { api_path: "/agentmemory/team/feed", http_method: "GET" }, - }); - - sdk.registerFunction("api::team-profile", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::team-profile", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Team memory not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::team-profile", - config: { api_path: "/agentmemory/team/profile", http_method: "GET" }, - }); - - sdk.registerFunction("api::audit", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const entries = await sdk.trigger({ function_id: "mem::audit-query", payload: { - operation: req.query_params?.["operation"], - limit: parsedLimit ?? 50, - } }); - return { status_code: 200, body: { entries, success: true } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::audit", - config: { api_path: "/agentmemory/audit", http_method: "GET" }, - }); - - sdk.registerFunction("api::governance-delete", - async ( - req: ApiRequest<{ memoryIds: string[]; reason?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.memoryIds || !Array.isArray(req.body.memoryIds)) { - return { - status_code: 400, - body: { error: "memoryIds array is required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::governance-delete", - config: { - api_path: "/agentmemory/governance/memories", - http_method: "DELETE", - }, - }); - - sdk.registerFunction("api::governance-bulk", - async ( - req: ApiRequest<{ - type?: string[]; - dateFrom?: string; - dateTo?: string; - qualityBelow?: number; - dryRun?: boolean; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::governance-bulk", payload: req.body || {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::governance-bulk", - config: { - api_path: "/agentmemory/governance/bulk-delete", - http_method: "POST", - }, - }); - - sdk.registerFunction("api::snapshots", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-list", payload: {} }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Snapshots not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::snapshots", - config: { api_path: "/agentmemory/snapshots", http_method: "GET" }, - }); - - sdk.registerFunction("api::snapshot-create", - async (req: ApiRequest<{ message?: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: req.body || {}, - }); - return { status_code: 201, body: result }; - } catch { - return { status_code: 404, body: { error: "Snapshots not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::snapshot-create", - config: { api_path: "/agentmemory/snapshot/create", http_method: "POST" }, - }); - - sdk.registerFunction("api::snapshot-restore", - async (req: ApiRequest<{ commitHash: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.commitHash) { - return { status_code: 400, body: { error: "commitHash is required" } }; - } - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-restore", payload: req.body }); - return { status_code: 200, body: result }; - } catch { - return { status_code: 404, body: { error: "Snapshots not enabled" } }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::snapshot-restore", - config: { api_path: "/agentmemory/snapshot/restore", http_method: "POST" }, - }); - - sdk.registerFunction("api::memories", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const memories = await kv.list<import("../types.js").Memory>(KV.memories); - const latest = req.query_params?.["latest"] === "true"; - // agentId filter. Request param wins, env AGENT_ID (when - // scope=isolated) is the fallback. Shared mode keeps the tag but - // does not restrict the list endpoint. Pass agentId=* to opt out - // of the env scope entirely. includeOrphans=true surfaces - // pre-AGENT_ID memories whose agentId is undefined. - const normalizedAgentId = - typeof req.query_params?.["agentId"] === "string" - ? req.query_params["agentId"].trim() - : undefined; - const wildcardAgent = normalizedAgentId === "*"; - const explicitAgentId = - normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; - const includeOrphans = - req.query_params?.["includeOrphans"] === "true"; - const filterAgentId = wildcardAgent - ? undefined - : explicitAgentId ?? (isAgentScopeIsolated() ? getAgentId() : undefined); - let filtered = latest ? memories.filter((m) => m.isLatest) : memories; - if (filterAgentId) { - filtered = filtered.filter( - (m) => - m.agentId === filterAgentId || - (includeOrphans && m.agentId === undefined), - ); - } - - // viewer + `agentmemory status` were hitting this endpoint to - // count memories. On a real corpus (8K+ memories) the unbounded - // response either timed out at the iii engine boundary ("Invocation - // stopped") or arrived too large for the viewer to render — so the - // UI showed 0 memories despite a healthy store. Two opt-in modes: - // ?count=true — totals only, no payload - // ?limit=N&offset=M — page slice (default unlimited for back-compat) - if (req.query_params?.["count"] === "true") { - // Match the SAME scope that the list path applies — returning - // unfiltered totals here would leak cross-agent counts to a - // caller that's blocked from the underlying rows. - return { - status_code: 200, - body: { - total: filtered.length, - latestCount: filtered.filter((m) => m.isLatest).length, - }, - }; - } - - const rawLimit = req.query_params?.["limit"]; - const rawOffset = req.query_params?.["offset"]; - const parsedLimit = - typeof rawLimit === "string" ? Number(rawLimit) : Number.NaN; - const parsedOffset = - typeof rawOffset === "string" ? Number(rawOffset) : Number.NaN; - const limit = - Number.isInteger(parsedLimit) && parsedLimit > 0 - ? Math.min(parsedLimit, 5000) - : undefined; - const offset = - Number.isInteger(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0; - const sliced = - limit !== undefined ? filtered.slice(offset, offset + limit) : filtered; - - return { - status_code: 200, - body: { - memories: sliced, - total: filtered.length, - offset, - limit: limit ?? null, - }, - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::memories", - config: { api_path: "/agentmemory/memories", http_method: "GET" }, - }); - - sdk.registerFunction("api::memory-by-id", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const id = req.path_params?.["id"]; - if (!id || typeof id !== "string") { - return { status_code: 400, body: { error: "id path parameter is required" } }; - } - const memory = await kv.get<import("../types.js").Memory>(KV.memories, id); - if (!memory) { - return { status_code: 404, body: { error: `memory not found: ${id}` } }; - } - return { status_code: 200, body: { memory } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::memory-by-id", - config: { api_path: "/agentmemory/memories/:id", http_method: "GET" }, - }); - - // The route an operator reaches for first. Without it, removing one - // memory means discovering either /agentmemory/forget or the - // governance bulk paths, and the filter-based one invites deleting by - // date window and hoping the window held only the target. - sdk.registerFunction("api::memory-delete", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const id = req.path_params?.["id"]; - if (!id || typeof id !== "string") { - return { status_code: 400, body: { error: "id path parameter is required" } }; - } - const result = await sdk.trigger({ - function_id: "mem::forget", - payload: { memoryId: id }, - }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::memory-delete", - config: { api_path: "/agentmemory/memories/:id", http_method: "DELETE" }, - }); - - sdk.registerFunction("api::semantic-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); - return { status_code: 200, body: { semantic } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::semantic-list", - config: { api_path: "/agentmemory/semantic", http_method: "GET" }, - }); - - sdk.registerFunction("api::procedural-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); - return { status_code: 200, body: { procedural } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::procedural-list", - config: { api_path: "/agentmemory/procedural", http_method: "GET" }, - }); - - sdk.registerFunction("api::relations-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); - return { status_code: 200, body: { relations } }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::relations-list", - config: { api_path: "/agentmemory/relations", http_method: "GET" }, - }); - - sdk.registerFunction("api::vision-search", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const queryText = asNonEmptyString(body["queryText"]); - const queryImageRef = asNonEmptyString(body["queryImageRef"]); - const queryImageBase64 = asNonEmptyString(body["queryImageBase64"]); - const sessionId = asNonEmptyString(body["sessionId"]); - if (!queryText && !queryImageRef && !queryImageBase64) { - return { - status_code: 400, - body: { error: "queryText, queryImageRef, or queryImageBase64 required" }, - }; - } - const topKParsed = parseOptionalPositiveInt(body["topK"]); - if (topKParsed === null) { - return { status_code: 400, body: { error: "topK must be a positive integer" } }; - } - const payload: Record<string, unknown> = {}; - if (queryText) payload["queryText"] = queryText; - if (queryImageRef) payload["queryImageRef"] = queryImageRef; - if (queryImageBase64) payload["queryImageBase64"] = queryImageBase64; - if (sessionId) payload["sessionId"] = sessionId; - if (topKParsed !== undefined) payload["topK"] = Math.min(50, topKParsed); - const result = await sdk.trigger({ function_id: "mem::vision-search", payload }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::vision-search", - config: { api_path: "/agentmemory/vision-search", http_method: "POST" }, - }); - - sdk.registerFunction("api::vision-embed", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const body = (req.body ?? {}) as Record<string, unknown>; - const imageRef = asNonEmptyString(body["imageRef"]); - const sessionId = asNonEmptyString(body["sessionId"]); - const observationId = asNonEmptyString(body["observationId"]); - if (!imageRef) { - return { status_code: 400, body: { error: "imageRef is required" } }; - } - const payload: Record<string, unknown> = { imageRef }; - if (sessionId) payload["sessionId"] = sessionId; - if (observationId) payload["observationId"] = observationId; - const result = await sdk.trigger({ function_id: "mem::vision-embed", payload }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::vision-embed", - config: { api_path: "/agentmemory/vision-embed", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-list", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-list", - config: { api_path: "/agentmemory/slots", http_method: "GET" }, - }); - - sdk.registerFunction("api::slot-get", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const label = asNonEmptyString(req.query_params?.["label"]); - if (!label) return { status_code: 400, body: { error: "label query param required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-get", - config: { api_path: "/agentmemory/slot", http_method: "GET" }, - }); - - sdk.registerFunction("api::slot-create", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const label = asNonEmptyString(body["label"]); - if (!label) return { status_code: 400, body: { error: "label required" } }; - // Reject malformed inputs instead of silently dropping them. - if (body["content"] !== undefined && typeof body["content"] !== "string") { - return { status_code: 400, body: { error: "content must be a string" } }; - } - if (body["description"] !== undefined && typeof body["description"] !== "string") { - return { status_code: 400, body: { error: "description must be a string" } }; - } - if (body["pinned"] !== undefined && typeof body["pinned"] !== "boolean") { - return { status_code: 400, body: { error: "pinned must be a boolean" } }; - } - if ( - body["scope"] !== undefined && - body["scope"] !== "project" && - body["scope"] !== "global" - ) { - return { status_code: 400, body: { error: "scope must be 'project' or 'global'" } }; - } - const sizeLimit = parseOptionalPositiveInt(body["sizeLimit"]); - if (sizeLimit === null) { - return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } }; - } - if (sizeLimit !== undefined && sizeLimit > 20000) { - return { status_code: 400, body: { error: "sizeLimit must be <= 20000" } }; - } - const payload: Record<string, unknown> = { label }; - if (typeof body["content"] === "string") payload["content"] = body["content"]; - if (typeof body["description"] === "string") payload["description"] = body["description"]; - if (sizeLimit !== undefined) payload["sizeLimit"] = sizeLimit; - if (typeof body["pinned"] === "boolean") payload["pinned"] = body["pinned"]; - if (body["scope"] === "project" || body["scope"] === "global") payload["scope"] = body["scope"]; - const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("exists") ? 409 : 400, body: resp }; - } - return { status_code: 201, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-create", - config: { api_path: "/agentmemory/slot", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-append", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const label = asNonEmptyString(body["label"]); - const text = typeof body["text"] === "string" ? body["text"] : null; - if (!label || !text) return { status_code: 400, body: { error: "label and text required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - const notFound = resp.error?.includes("not found"); - const overLimit = resp.error?.includes("exceed"); - return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-append", - config: { api_path: "/agentmemory/slot/append", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-replace", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const label = asNonEmptyString(body["label"]); - const content = body["content"]; - if (!label || typeof content !== "string") { - return { status_code: 400, body: { error: "label and content (string) required" } }; - } - const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - const notFound = resp.error?.includes("not found"); - const overLimit = resp.error?.includes("exceed"); - return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-replace", - config: { api_path: "/agentmemory/slot/replace", http_method: "POST" }, - }); - - sdk.registerFunction("api::slot-delete", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - const label = asNonEmptyString(req.query_params?.["label"]); - if (!label) return { status_code: 400, body: { error: "label query param required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false) { - return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-delete", - config: { api_path: "/agentmemory/slot", http_method: "DELETE" }, - }); - - sdk.registerFunction("api::slot-reflect", async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!isSlotsEnabled()) return slotsDisabledResponse(); - if (!isReflectEnabled()) return reflectDisabledResponse(); - const body = (req.body ?? {}) as Record<string, unknown>; - const sessionId = asNonEmptyString(body["sessionId"]); - if (!sessionId) return { status_code: 400, body: { error: "sessionId required" } }; - const maxObservations = parseOptionalPositiveInt(body["maxObservations"]); - if (maxObservations === null) return { status_code: 400, body: { error: "maxObservations must be a positive integer" } }; - const payload: Record<string, unknown> = { sessionId }; - if (maxObservations !== undefined) payload["maxObservations"] = maxObservations; - const result = await sdk.trigger({ function_id: "mem::slot-reflect", payload }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ - type: "http", - function_id: "api::slot-reflect", - config: { api_path: "/agentmemory/slot/reflect", http_method: "POST" }, - }); - - sdk.registerFunction("api::action-create", - async ( - req: ApiRequest<{ - title: string; - description?: string; - priority?: number; - createdBy?: string; - project?: string; - tags?: string[]; - parentId?: string; - edges?: Array<{ type: string; targetActionId: string }>; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.title) { - return { status_code: 400, body: { error: "title is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-create", - config: { api_path: "/agentmemory/actions", http_method: "POST" }, - }); - - sdk.registerFunction("api::action-update", - async ( - req: ApiRequest<{ - actionId: string; - status?: string; - title?: string; - description?: string; - priority?: number; - result?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId) { - return { status_code: 400, body: { error: "actionId is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-update", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-update", - config: { api_path: "/agentmemory/actions/update", http_method: "POST" }, - }); - - sdk.registerFunction("api::action-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::action-list", payload: { - status: req.query_params?.["status"], - project: req.query_params?.["project"], - parentId: req.query_params?.["parentId"], - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-list", - config: { api_path: "/agentmemory/actions", http_method: "GET" }, - }); - - sdk.registerFunction("api::action-get", - async (req: ApiRequest<{ actionId: string }>): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const actionId = req.query_params?.["actionId"] as string; - if (!actionId) { - return { status_code: 400, body: { error: "actionId required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-get", payload: { actionId } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-get", - config: { api_path: "/agentmemory/actions/get", http_method: "GET" }, - }); - - sdk.registerFunction("api::action-edge", - async ( - req: ApiRequest<{ - sourceActionId: string; - targetActionId: string; - type: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) { - return { status_code: 400, body: { error: "sourceActionId, targetActionId, and type are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::action-edge-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::action-edge", - config: { api_path: "/agentmemory/actions/edges", http_method: "POST" }, - }); - - sdk.registerFunction("api::frontier", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const result = await sdk.trigger({ function_id: "mem::frontier", payload: { - project: req.query_params?.["project"], - agentId: req.query_params?.["agentId"], - limit: parsedLimit, - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::frontier", - config: { api_path: "/agentmemory/frontier", http_method: "GET" }, - }); - - sdk.registerFunction("api::next", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::next", payload: { - project: req.query_params?.["project"], - agentId: req.query_params?.["agentId"], - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::next", - config: { api_path: "/agentmemory/next", http_method: "GET" }, - }); - - sdk.registerFunction("api::lease-acquire", - async ( - req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId || !req.body?.agentId) { - return { status_code: 400, body: { error: "actionId and agentId are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::lease-acquire", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::lease-acquire", - config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" }, - }); - - sdk.registerFunction("api::lease-release", - async ( - req: ApiRequest<{ actionId: string; agentId: string; result?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId || !req.body?.agentId) { - return { status_code: 400, body: { error: "actionId and agentId are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::lease-release", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::lease-release", - config: { api_path: "/agentmemory/leases/release", http_method: "POST" }, - }); - - sdk.registerFunction("api::lease-renew", - async ( - req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.actionId || !req.body?.agentId) { - return { status_code: 400, body: { error: "actionId and agentId are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::lease-renew", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::lease-renew", - config: { api_path: "/agentmemory/leases/renew", http_method: "POST" }, - }); - - sdk.registerFunction("api::routine-create", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.name || !req.body?.steps) { - return { - status_code: 400, - body: { error: "name and steps are required" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::routine-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-create", - config: { api_path: "/agentmemory/routines", http_method: "POST" }, - }); - - sdk.registerFunction("api::routine-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::routine-list", payload: { - frozen: req.query_params?.["frozen"] === "true" ? true : undefined, - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-list", - config: { api_path: "/agentmemory/routines", http_method: "GET" }, - }); - - sdk.registerFunction("api::routine-run", - async ( - req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.routineId) { - return { status_code: 400, body: { error: "routineId is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::routine-run", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-run", - config: { api_path: "/agentmemory/routines/run", http_method: "POST" }, - }); - - sdk.registerFunction("api::routine-status", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const runId = req.query_params?.["runId"] as string; - if (!runId) { - return { status_code: 400, body: { error: "runId query param required" } }; - } - const result = await sdk.trigger({ function_id: "mem::routine-status", payload: { runId } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::routine-status", - config: { api_path: "/agentmemory/routines/status", http_method: "GET" }, - }); - - sdk.registerFunction("api::signal-send", - async ( - req: ApiRequest<{ - from: string; - to?: string; - content: string; - type?: string; - replyTo?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.from || !req.body?.content) { - return { status_code: 400, body: { error: "from and content are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::signal-send", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::signal-send", - config: { api_path: "/agentmemory/signals/send", http_method: "POST" }, - }); - - sdk.registerFunction("api::signal-read", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const agentId = req.query_params?.["agentId"] as string; - if (!agentId) { - return { status_code: 400, body: { error: "agentId query param required" } }; - } - const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); - const result = await sdk.trigger({ function_id: "mem::signal-read", payload: { - agentId, - unreadOnly: req.query_params?.["unreadOnly"] === "true", - threadId: req.query_params?.["threadId"], - limit: parsedLimit, - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::signal-read", - config: { api_path: "/agentmemory/signals", http_method: "GET" }, - }); - - sdk.registerFunction("api::checkpoint-create", - async ( - req: ApiRequest<{ - name: string; - description?: string; - type?: string; - linkedActionIds?: string[]; - expiresInMs?: number; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.name) { - return { status_code: 400, body: { error: "name is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::checkpoint-create", - config: { api_path: "/agentmemory/checkpoints", http_method: "POST" }, - }); - - sdk.registerFunction("api::checkpoint-resolve", - async ( - req: ApiRequest<{ - checkpointId: string; - status: string; - resolvedBy?: string; - result?: unknown; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.checkpointId || !req.body?.status) { - return { status_code: 400, body: { error: "checkpointId and status are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: req.body }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::checkpoint-resolve", - config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" }, - }); - - sdk.registerFunction("api::checkpoint-list", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { - status: req.query_params?.["status"], - type: req.query_params?.["type"], - } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::checkpoint-list", - config: { api_path: "/agentmemory/checkpoints", http_method: "GET" }, - }); - - sdk.registerFunction("api::mesh-register", - async ( - req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>, - ): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - if (!req.body?.url || !req.body?.name) { - return { status_code: 400, body: { error: "url and name are required" } }; - } - const result = await sdk.trigger({ function_id: "mem::mesh-register", payload: req.body }); - return { status_code: 201, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-register", - config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" }, - }); - - sdk.registerFunction("api::mesh-list", - async (req: ApiRequest): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::mesh-list", payload: {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-list", - config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" }, - }); - - sdk.registerFunction("api::mesh-sync", - async ( - req: ApiRequest<{ peerId?: string; direction?: string }>, - ): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::mesh-sync", payload: req.body || {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-sync", - config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" }, - }); - - sdk.registerFunction("api::mesh-receive", - async (req: ApiRequest): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const result = await sdk.trigger({ function_id: "mem::mesh-receive", payload: req.body || {} }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-receive", - config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" }, - }); - - sdk.registerFunction("api::mesh-export", - async (req: ApiRequest): Promise<Response> => { - const secretErr = requireConfiguredSecret(secret, "mesh"); - if (secretErr) return secretErr; - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const since = req.query_params?.["since"] as string; - if (since) { - const parsed = new Date(since).getTime(); - if (Number.isNaN(parsed)) { - return { status_code: 400, body: { error: "Invalid 'since' date format" } }; - } - } - const project = req.query_params?.["project"] as string | undefined; - const sinceTime = since ? new Date(since).getTime() : 0; - const df = <T>(items: T[], field: "updatedAt" | "createdAt") => - items.filter((i) => new Date((i as Record<string, unknown>)[field] as string).getTime() > sinceTime); - let memories = await kv.list<import("../types.js").Memory>(KV.memories); - let actions = await kv.list<import("../types.js").Action>(KV.actions); - if (project) { - memories = memories.filter((m) => m.project === project); - actions = actions.filter((a) => a.project === project); - } - const body: Record<string, unknown> = { - memories: df(memories, "updatedAt"), - actions: df(actions, "updatedAt"), - }; - if (!project) { - const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); - const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); - const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); - body.semantic = df(semantic, "updatedAt"); - body.procedural = df(procedural, "updatedAt"); - body.relations = df(relations, "createdAt"); - // B-mode: graph frozen — never enumerate the graph scope for the - // mesh-sync delta body. - if (!graphLegDisabled()) { - const graphNodes = await kv.list<import("../types.js").GraphNode>(KV.graphNodes); - const graphEdges = await kv.list<import("../types.js").GraphEdge>(KV.graphEdges); - body.graphNodes = graphNodes.filter( - (n) => new Date(n.updatedAt || n.createdAt).getTime() > sinceTime, - ); - body.graphEdges = df(graphEdges, "createdAt"); - } - } - // Fail an oversized export with 413 rather than on heap. - const oversized = checkPayloadSize( - body, - "use ?since to fetch only changes after a timestamp, or ?project to scope the export", - ); - if (oversized) return { status_code: 413, body: oversized }; - return { status_code: 200, body }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::mesh-export", - config: { api_path: "/agentmemory/mesh/export", http_method: "GET" }, - }); - - sdk.registerFunction("api::flow-compress", - async ( - req: ApiRequest<{ - runId?: string; - actionIds?: string[]; - project?: string; - }>, - ): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - try { - const result = await sdk.trigger({ function_id: "mem::flow-compress", payload: req.body || {} }); - return { status_code: 200, body: result }; - } catch { - return { - status_code: 404, - body: { error: "Flow compression requires a provider" }, - }; - } - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::flow-compress", - config: { api_path: "/agentmemory/flow/compress", http_method: "POST" }, - }); - - sdk.registerFunction("api::branch-detect", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); - const result = await sdk.trigger({ function_id: "mem::detect-worktree", payload: { cwd } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::branch-detect", - config: { api_path: "/agentmemory/branch/detect", http_method: "GET" }, - }); - - sdk.registerFunction("api::branch-worktrees", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); - const result = await sdk.trigger({ function_id: "mem::list-worktrees", payload: { cwd } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::branch-worktrees", - config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" }, - }); - - sdk.registerFunction("api::branch-sessions", - async (req: ApiRequest): Promise<Response> => { - const authErr = checkAuth(req, secret); - if (authErr) return authErr; - const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); - const result = await sdk.trigger({ function_id: "mem::branch-sessions", payload: { cwd } }); - return { status_code: 200, body: result }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::branch-sessions", - config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" }, - }); - - sdk.registerFunction("api::viewer", - async (req: ApiRequest): Promise<Response> => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const rendered = renderViewerDocument(); - if (rendered.found) { - return { - status_code: 200, - headers: { - "Content-Type": "text/html", - "Content-Security-Policy": rendered.csp, - }, - body: rendered.html, - }; - } - return { - status_code: 404, - headers: { - "Content-Type": "text/html", - }, - body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>", - }; - }, - ); - sdk.registerTrigger({ - type: "http", - function_id: "api::viewer", - config: { api_path: "/agentmemory/viewer", http_method: "GET" }, - }); - - sdk.registerFunction("api::sentinel-create", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.name) return { status_code: 400, body: { error: "name is required" } }; - const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-trigger", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-check", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-cancel", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sentinel-cancel", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } }); - - sdk.registerFunction("api::sentinel-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const result = await sdk.trigger({ function_id: "mem::sentinel-list", payload: { status: params.status, type: params.type } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } }); - - sdk.registerFunction("api::sketch-create", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.title) return { status_code: 400, body: { error: "title is required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-add", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sketchId || !body?.title) return { status_code: 400, body: { error: "sketchId and title are required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-add", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-promote", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-discard", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; - const result = await sdk.trigger({ function_id: "mem::sketch-discard", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } }); - - sdk.registerFunction("api::sketch-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const result = await sdk.trigger({ function_id: "mem::sketch-list", payload: { status: params.status, project: params.project } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } }); - - sdk.registerFunction("api::sketch-gc", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } }); - - sdk.registerFunction("api::crystallize", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.actionIds) return { status_code: 400, body: { error: "actionIds is required" } }; - const result = await sdk.trigger({ function_id: "mem::crystallize", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } }); - - sdk.registerFunction("api::crystal-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const limit = parseOptionalPositiveInt(params.limit); - if (limit === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: limit" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { project: params.project, sessionId: params.sessionId, limit } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } }); - - sdk.registerFunction("api::auto-crystallize", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::auto-crystallize", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } }); - - sdk.registerFunction("api::diagnose", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::diagnose", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } }); - - sdk.registerFunction("api::heal", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::heal", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } }); - - sdk.registerFunction("api::facet-tag", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.targetId || !body?.dimension || !body?.value) return { status_code: 400, body: { error: "targetId, dimension, and value are required" } }; - const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } }); - - sdk.registerFunction("api::facet-untag", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.targetId || !body?.dimension) return { status_code: 400, body: { error: "targetId and dimension are required" } }; - const result = await sdk.trigger({ function_id: "mem::facet-untag", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } }); - - sdk.registerFunction("api::facet-query", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const result = await sdk.trigger({ function_id: "mem::facet-query", payload: body || {} }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } }); - - sdk.registerFunction("api::facet-get", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - if (!params.targetId) return { status_code: 400, body: { error: "targetId query param is required" } }; - const result = await sdk.trigger({ function_id: "mem::facet-get", payload: { targetId: params.targetId } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } }); - - sdk.registerFunction("api::facet-stats", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const result = await sdk.trigger({ function_id: "mem::facet-stats", payload: { targetType: params.targetType } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } }); - - sdk.registerFunction("api::verify", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.id || typeof body.id !== "string") return { status_code: 400, body: { error: "id is required" } }; - const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: body.id } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } }); - - sdk.registerFunction("api::cascade-update", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") { - return { status_code: 400, body: { error: "supersededMemoryId is required" } }; - } - const result = await sdk.trigger({ function_id: "mem::cascade-update", payload: { supersededMemoryId: body.supersededMemoryId } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-save", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.content || typeof body.content !== "string") return { status_code: 400, body: { error: "content is required" } }; - const tags = typeof body.tags === "string" ? (body.tags as string).split(",").map((t: string) => t.trim()).filter(Boolean) : Array.isArray(body.tags) ? body.tags : []; - const result = (await sdk.trigger({ - function_id: "mem::lesson-save", - payload: { - content: body.content, - context: body.context || "", - confidence: typeof body.confidence === "number" ? body.confidence : undefined, - project: typeof body.project === "string" ? body.project : undefined, - tags, - source: "manual", - }, - })) as { action?: string }; - const statusCode = result?.action === "created" ? 201 : 200; - return { status_code: statusCode, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const minConfidence = parseOptionalFiniteNumber(params.minConfidence); - if (minConfidence === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: minConfidence" }, - }; - } - const limit = parseOptionalPositiveInt(params.limit); - if (limit === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: limit" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: { - project: params.project, - source: params.source, - minConfidence, - limit, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } }); - - sdk.registerFunction("api::lesson-search", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; - const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: body }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-strengthen", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.lessonId || typeof body.lessonId !== "string") return { status_code: 400, body: { error: "lessonId is required" } }; - const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: body.lessonId } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } }); - - sdk.registerFunction("api::lesson-delete", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - const lessonId = typeof body?.lessonId === "string" ? body.lessonId.trim() : ""; - if (!lessonId) return { status_code: 400, body: { error: "lessonId is required" } }; - const result = await sdk.trigger({ function_id: "mem::lesson-delete", payload: { lessonId } }); - const resp = result as { success?: boolean; error?: string }; - if (resp?.success === false && resp.error === "lesson not found") { - return { status_code: 404, body: { error: "lesson not found" } }; - } - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } }); - - sdk.registerFunction("api::obsidian-export", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = (req.body as Record<string, unknown>) || {}; - const vaultDir = asNonEmptyString(body.vaultDir); - if (!vaultDir) { - return { - status_code: 400, - body: { error: "vaultDir must be a non-empty string" }, - }; - } - const types = typeof body.types === "string" ? body.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined; - const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir, types } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } }); - - sdk.registerFunction("api::reflect", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = (req.body as Record<string, unknown>) || {}; - const result = await sdk.trigger({ function_id: "mem::reflect", payload: { - project: typeof body.project === "string" ? body.project : undefined, - maxClusters: typeof body.maxClusters === "number" ? body.maxClusters : undefined, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } }); - - sdk.registerFunction("api::insight-list", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const params = req.query_params || {}; - const minConfidence = parseOptionalFiniteNumber(params.minConfidence); - if (minConfidence === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: minConfidence" }, - }; - } - const limit = parseOptionalPositiveInt(params.limit); - if (limit === null) { - return { - status_code: 400, - body: { error: "invalid numeric parameter: limit" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::insight-list", payload: { - project: params.project, - minConfidence, - limit, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } }); - - sdk.registerFunction("api::insight-search", async (req: ApiRequest) => { - const denied = checkAuth(req, secret); - if (denied) return denied; - const body = req.body as Record<string, unknown>; - if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; - const result = await sdk.trigger({ function_id: "mem::insight-search", payload: { - query: body.query, - project: typeof body.project === "string" ? body.project : undefined, - minConfidence: typeof body.minConfidence === "number" ? body.minConfidence : undefined, - limit: typeof body.limit === "number" ? body.limit : undefined, - } }); - return { status_code: 200, body: result }; - }); - sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } }); -} +import { TriggerAction, type ISdk, type ApiRequest } from "../engine/types.js"; +import type { Session, CompressedObservation, HookPayload, CommitLink, SessionSummary } from "../types.js"; +import { withKeyedLock } from "../state/keyed-mutex.js"; +import { KV } from "../state/schema.js"; +import { StateKV } from "../state/kv.js"; +import { graphLegDisabled } from "../state/graph-indexes.js"; +import { checkPayloadSize, isOversizedPayload } from "../state/payload-bound.js"; +import { getLatestHealth } from "../health/monitor.js"; +import type { MetricsStore } from "../eval/metrics-store.js"; +import type { ResilientProvider } from "../providers/resilient.js"; +import { VERSION } from "../version.js"; +import { timingSafeCompare } from "../auth.js"; +import { isSlotsEnabled, isReflectEnabled } from "../functions/slots.js"; +import { renderViewerDocument } from "../viewer/document.js"; +import { getBoundViewerPort, getViewerSkipped } from "../viewer/server.js"; +import { MAX_FILES_UPPER_BOUND } from "../functions/replay.js"; +import { logger } from "../logger.js"; +import { + isGraphExtractionEnabled, + isConsolidationEnabled, + isAutoCompressEnabled, + isContextInjectionEnabled, + detectEmbeddingProvider, + detectLlmProviderKind, + getAgentId, + isAgentScopeIsolated, + loadConfig, +} from "../config.js"; + +type Response = { + status_code: number; + headers?: Record<string, string>; + body: unknown; +}; + +function parseOptionalInt(raw: unknown): number | undefined { + if (raw === undefined || raw === null || raw === "") return undefined; + const n = typeof raw === "number" ? raw : parseInt(String(raw), 10); + return Number.isFinite(n) ? n : undefined; +} + +function checkAuth( + req: ApiRequest, + secret: string | undefined, +): Response | null { + if (!secret) return null; + const auth = req.headers?.["authorization"] || req.headers?.["Authorization"]; + if ( + typeof auth !== "string" || + !timingSafeCompare(auth, `Bearer ${secret}`) + ) { + return { status_code: 401, body: { error: "unauthorized" } }; + } + return null; +} + +function requireConfiguredSecret( + secret: string | undefined, + feature: string, +): Response | null { + if (secret) return null; + return { + status_code: 503, + body: { error: `${feature} requires AGENTMEMORY_SECRET` }, + }; +} + +function flagDisabledResponse(opts: { + error: string; + flag: string; + enableHow: string; + docsHref: string; +}): Response { + return { + status_code: 503, + body: opts, + }; +} + +function graphDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Knowledge graph not enabled", + flag: "GRAPH_EXTRACTION_ENABLED", + enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and restart. Requires an LLM provider key.", + docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", + }); +} + +function consolidationDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Consolidation pipeline not enabled", + flag: "CONSOLIDATION_ENABLED", + enableHow: "Set CONSOLIDATION_ENABLED=true and restart. Requires an LLM provider key.", + docsHref: "https://github.com/rohitg00/agentmemory#consolidation", + }); +} + +function slotsDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Memory slots not enabled", + flag: "AGENTMEMORY_SLOTS", + enableHow: "Set AGENTMEMORY_SLOTS=true (in ~/.agentmemory/.env or the shell) and restart.", + docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", + }); +} + +function reflectDisabledResponse(): Response { + return flagDisabledResponse({ + error: "Slot reflection not enabled", + flag: "AGENTMEMORY_REFLECT", + enableHow: "Set AGENTMEMORY_REFLECT=true (in ~/.agentmemory/.env or the shell) and restart. Requires AGENTMEMORY_SLOTS=true.", + docsHref: "https://github.com/rohitg00/agentmemory#memory-slots", + }); +} + +function asNonEmptyString(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed ? trimmed : null; +} + +function parseOptionalFiniteNumber(value: unknown): number | undefined | null { + if (value === undefined || value === null) return undefined; + if (typeof value === "number") return Number.isFinite(value) ? value : null; + if (typeof value === "string") { + const trimmed = value.trim(); + if (!trimmed) return undefined; + const parsed = Number(trimmed); + return Number.isFinite(parsed) ? parsed : null; + } + return null; +} + +function parseOptionalPositiveInt(value: unknown): number | undefined | null { + const parsed = parseOptionalFiniteNumber(value); + if (parsed === undefined || parsed === null) return parsed; + if (!Number.isInteger(parsed) || parsed < 1) return null; + return parsed; +} + +export function registerApiTriggers( + sdk: ISdk, + kv: StateKV, + secret?: string, + metricsStore?: MetricsStore, + provider?: ResilientProvider | { circuitState?: unknown; circuitStates?: unknown }, +): void { + sdk.registerFunction( + "middleware::api-auth", + async (input: { + request?: { headers?: Record<string, string | undefined> }; + }) => { + if (!secret) return { action: "continue" }; + const headers = input?.request?.headers || {}; + const auth = headers["authorization"] || headers["Authorization"]; + if ( + typeof auth !== "string" || + !timingSafeCompare(auth, `Bearer ${secret}`) + ) { + return { + action: "respond", + response: { status_code: 401, body: { error: "unauthorized" } }, + }; + } + return { action: "continue" }; + }, + ); + + // Shared instance metadata for livez and health so the two never + // drift. streamsPort lets the viewer resolve its stream WebSocket + // target from the server instead of port arithmetic, which broke + // whenever the viewer bound a fallback port. Config is boot-static, + // so read it once instead of rebuilding the merged env per request. + const bootStreamsPort = loadConfig().streamsPort; + const instanceInfo = () => ({ + service: "agentmemory", + viewerPort: getBoundViewerPort(), + viewerSkipped: getViewerSkipped(), + streamsPort: bootStreamsPort, + }); + + sdk.registerFunction("api::liveness", + async (): Promise<Response> => ({ + status_code: 200, + body: { status: "ok", ...instanceInfo() }, + }), + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::liveness", + config: { api_path: "/agentmemory/livez", http_method: "GET" }, + }); + + sdk.registerFunction("api::config-flags", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const providerKind = detectLlmProviderKind(); + const embeddingProvider = detectEmbeddingProvider() ? "embeddings" : "none"; + const flags = [ + { + key: "GRAPH_EXTRACTION_ENABLED", + label: "Knowledge graph extraction", + enabled: isGraphExtractionEnabled(), + default: false, + affects: ["Graph", "Dashboard"], + needsLlm: true, + description: "Extracts entities and relations from observations into a knowledge graph.", + enableHow: "Set GRAPH_EXTRACTION_ENABLED=true and provide an LLM key, then restart.", + docsHref: "https://github.com/rohitg00/agentmemory#knowledge-graph", + }, + { + key: "CONSOLIDATION_ENABLED", + label: "Memory consolidation", + enabled: isConsolidationEnabled(), + default: false, + affects: ["Dashboard", "Memories", "Crystals"], + needsLlm: true, + description: "Periodically summarizes sessions into semantic facts + procedures.", + enableHow: "Set CONSOLIDATION_ENABLED=true and provide an LLM key, then restart.", + docsHref: "https://github.com/rohitg00/agentmemory#consolidation", + }, + { + key: "AGENTMEMORY_AUTO_COMPRESS", + label: "LLM-powered observation compression", + enabled: isAutoCompressEnabled(), + default: false, + affects: ["Memories", "Timeline"], + needsLlm: true, + description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.", + enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.", + docsHref: "https://github.com/rohitg00/agentmemory/issues/138", + }, + { + key: "AGENTMEMORY_INJECT_CONTEXT", + label: "In-conversation context injection", + enabled: isContextInjectionEnabled(), + default: false, + affects: ["Hooks"], + needsLlm: false, + description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.", + enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.", + docsHref: "https://github.com/rohitg00/agentmemory/issues/143", + }, + ]; + return { + status_code: 200, + body: { + version: VERSION, + provider: providerKind, + embeddingProvider, + flags, + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::config-flags", + config: { + api_path: "/agentmemory/config/flags", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::health", + async (req: ApiRequest): Promise<Response> => { + const health = await getLatestHealth(kv); + const functionMetrics = metricsStore ? await metricsStore.getAll() : []; + const circuitBreaker = + provider && "circuitState" in provider ? provider.circuitState : null; + const circuitBreakers = + provider && "circuitStates" in provider ? provider.circuitStates : null; + + const status = health?.status || "healthy"; + const statusCode = status === "critical" ? 503 : 200; + + return { + status_code: statusCode, + body: { + status, + version: VERSION, + health: health || null, + functionMetrics, + circuitBreaker, + circuitBreakers, + ...instanceInfo(), + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::health", + config: { + api_path: "/agentmemory/health", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::observe", + async (req: ApiRequest<HookPayload>): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const hookType = asNonEmptyString(body.hookType); + const sessionId = asNonEmptyString(body.sessionId); + const project = asNonEmptyString(body.project); + const cwd = asNonEmptyString(body.cwd); + const timestamp = asNonEmptyString(body.timestamp); + if (!hookType || !sessionId || !project || !cwd || !timestamp) { + return { + status_code: 400, + body: { + error: + "hookType, sessionId, project, cwd, and timestamp are required strings", + }, + }; + } + const payload: HookPayload = { + hookType: hookType as HookPayload["hookType"], + sessionId, + project, + cwd, + timestamp, + data: body.data, + }; + const result = await sdk.trigger({ function_id: "mem::observe", payload }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::observe", + config: { + api_path: "/agentmemory/observe", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::context", + async ( + req: ApiRequest<{ + sessionId: string; + project: string; + budget?: number; + agentId?: string; + }>, + ): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body.sessionId); + const project = asNonEmptyString(body.project); + if (!sessionId || !project) { + return { + status_code: 400, + body: { error: "sessionId and project are required strings" }, + }; + } + const budget = parseOptionalPositiveInt(body.budget); + if (budget === null) { + return { + status_code: 400, + body: { error: "budget must be a positive integer" }, + }; + } + // Propagate agentId so mem::context applies the same cross-agent + // isolation filter as mem::search. Honors body.agentId, ?agentId=, + // or the worker's AGENT_ID fallback under AGENTMEMORY_AGENT_SCOPE=isolated. + const queryAgentId = + typeof (req as { query_params?: Record<string, string> }) + .query_params?.["agentId"] === "string" + ? (req as { query_params: Record<string, string> }) + .query_params["agentId"] + : undefined; + const bodyAgentId = + typeof body.agentId === "string" && body.agentId.trim().length > 0 + ? (body.agentId as string).trim() + : undefined; + const payload: { + sessionId: string; + project: string; + budget?: number; + agentId?: string; + } = { + sessionId, + project, + }; + if (budget !== undefined) payload.budget = budget; + const agentId = bodyAgentId ?? queryAgentId; + if (agentId !== undefined) payload.agentId = agentId; + const result = await sdk.trigger({ function_id: "mem::context", payload }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::context", + config: { + api_path: "/agentmemory/context", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::search", + async ( + req: ApiRequest<{ + query: string; + limit?: number; + project?: string; + cwd?: string; + format?: string; + token_budget?: number; + agentId?: string; + }>, + ): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const queryAgentId = + typeof (req as { query_params?: Record<string, string> }) + .query_params?.["agentId"] === "string" + ? (req as { query_params: Record<string, string> }) + .query_params["agentId"] + : undefined; + if (typeof body.query !== "string" || !body.query.trim()) { + return { status_code: 400, body: { error: "query is required and must be a non-empty string" } }; + } + if ( + body.limit !== undefined && + (!Number.isInteger(body.limit) || (body.limit as number) < 1) + ) { + return { status_code: 400, body: { error: "limit must be a positive integer" } }; + } + if (body.project !== undefined && typeof body.project !== "string") { + return { status_code: 400, body: { error: "project must be a string" } }; + } + if (body.cwd !== undefined && typeof body.cwd !== "string") { + return { status_code: 400, body: { error: "cwd must be a string" } }; + } + if ( + body.format !== undefined && + (typeof body.format !== "string" || + !["full", "compact", "narrative"].includes(body.format.trim().toLowerCase())) + ) { + return { + status_code: 400, + body: { error: "format must be one of: full, compact, narrative" }, + }; + } + if ( + body.token_budget !== undefined && + (!Number.isInteger(body.token_budget) || (body.token_budget as number) < 1) + ) { + return { + status_code: 400, + body: { error: "token_budget must be a positive integer" }, + }; + } + // #817: propagate agentId so the upstream isolation filter + // applies. Honors body.agentId (POST body), ?agentId=... query + // param, or implicit fallback to the worker's AGENT_ID when + // AGENTMEMORY_AGENT_SCOPE=isolated. + const bodyAgentId = + typeof body.agentId === "string" && body.agentId.trim().length > 0 + ? (body.agentId as string).trim() + : undefined; + const payload = { + query: body.query.trim(), + limit: body.limit as number | undefined, + project: body.project as string | undefined, + cwd: body.cwd as string | undefined, + format: + typeof body.format === "string" + ? body.format.trim().toLowerCase() + : undefined, + token_budget: body.token_budget as number | undefined, + agentId: bodyAgentId ?? queryAgentId, + }; + const result = await sdk.trigger({ function_id: "mem::search", payload: payload }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::search", + config: { + api_path: "/agentmemory/search", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::compress-file", + async (req: ApiRequest<{ filePath: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const filePath = asNonEmptyString(body.filePath); + if (!filePath) { + return { + status_code: 400, + body: { error: "filePath is required and must be a non-empty string" }, + }; + } + const result = await sdk.trigger({ + function_id: "mem::compress-file", + payload: { filePath }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::compress-file", + config: { api_path: "/agentmemory/compress-file", http_method: "POST" }, + }); + + sdk.registerFunction("api::replay::load", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); + if (!sessionId) { + return { status_code: 400, body: { error: "sessionId is required" } }; + } + const result = await sdk.trigger({ + function_id: "mem::replay::load", + payload: { sessionId }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::replay::load", + config: { api_path: "/agentmemory/replay/load", http_method: "GET" }, + }); + + sdk.registerFunction("api::replay::sessions", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessions = await kv.list<Session>(KV.sessions); + sessions.sort((a, b) => + (b.startedAt || "").localeCompare(a.startedAt || ""), + ); + return { status_code: 200, body: { success: true, sessions } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::replay::sessions", + config: { api_path: "/agentmemory/replay/sessions", http_method: "GET" }, + }); + + sdk.registerFunction("api::replay::import", + async ( + req: ApiRequest<{ path?: string; maxFiles?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const payload: { path?: string; maxFiles?: number } = {}; + if (body.path !== undefined) { + if (typeof body.path !== "string" || body.path.trim().length === 0) { + return { + status_code: 400, + body: { error: "path must be a non-empty string" }, + }; + } + payload.path = body.path.trim(); + } + if (body.maxFiles !== undefined) { + const n = body.maxFiles as number; + if ( + !Number.isInteger(n) || + n < 1 || + n > MAX_FILES_UPPER_BOUND + ) { + return { + status_code: 400, + body: { + error: `maxFiles must be an integer between 1 and ${MAX_FILES_UPPER_BOUND}`, + }, + }; + } + payload.maxFiles = n; + } + const result = await sdk.trigger({ + function_id: "mem::replay::import-jsonl", + payload, + }); + return { status_code: 202, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::replay::import", + config: { api_path: "/agentmemory/replay/import-jsonl", http_method: "POST" }, + }); + + sdk.registerFunction("api::session::start", + async ( + req: ApiRequest<{ sessionId: string; project: string; cwd: string }>, + ): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body.sessionId); + const project = asNonEmptyString(body.project); + const cwd = asNonEmptyString(body.cwd); + if (!sessionId || !project || !cwd) { + return { + status_code: 400, + body: { + error: "sessionId, project, and cwd are required non-empty strings", + }, + }; + } + const title = typeof body.title === "string" ? body.title.trim() : undefined; + // allow session/start to override AGENT_ID from request body + // (multi-agent runtimes that route many roles through one server + // process). Falls back to the AGENT_ID env on the server. + const requestAgentId = + typeof body.agentId === "string" && body.agentId.trim().length > 0 + ? body.agentId.trim().slice(0, 128) + : undefined; + const agentId = requestAgentId ?? getAgentId(); + const session: Session = { + id: sessionId, + project, + cwd, + startedAt: new Date().toISOString(), + status: "active", + observationCount: 0, + ...(title ? { summary: title.slice(0, 200) } : {}), + ...(title ? { firstPrompt: title.slice(0, 200) } : {}), + ...(agentId ? { agentId } : {}), + }; + await kv.set(KV.sessions, sessionId, session); + const contextResult = await sdk.trigger< + { sessionId: string; project: string; agentId?: string }, + { context: string } + >({ + function_id: "mem::context", + payload: { sessionId, project, ...(agentId ? { agentId } : {}) }, + }); + return { + status_code: 200, + body: { session, context: contextResult.context }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::start", + config: { + api_path: "/agentmemory/session/start", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::end", + async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => { + const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId); + if (!sessionId) { + return { + status_code: 400, + body: { error: "sessionId is required and must be a non-empty string" }, + }; + } + await kv.update(KV.sessions, sessionId, [ + { type: "set", path: "endedAt", value: new Date().toISOString() }, + { type: "set", path: "status", value: "completed" }, + ]); + // Fan out session-stopped lifecycle (non-blocking). + try { + sdk.trigger({ + function_id: "event::session::stopped", + payload: { sessionId }, + action: TriggerAction.Void(), + }); + } catch (err) { + logger.warn("event::session::stopped trigger failed", { + sessionId, + error: err instanceof Error ? err.message : String(err), + }); + } + return { status_code: 200, body: { success: true } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::end", + config: { + api_path: "/agentmemory/session/end", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::summarize", + async (req: ApiRequest<{ sessionId: string; force?: boolean }>): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body.sessionId); + if (!sessionId) { + return { status_code: 400, body: { error: "sessionId is required" } }; + } + const result = await sdk.trigger({ + function_id: "mem::summarize", + payload: { sessionId, force: body.force === true }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::summarize", + config: { + api_path: "/agentmemory/summarize", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::commit", + async (req: ApiRequest): Promise<Response> => { + const body = (req.body ?? {}) as Record<string, unknown>; + const sha = asNonEmptyString(body.sha); + if (!sha) { + return { + status_code: 400, + body: { error: "sha is required and must be a non-empty string" }, + }; + } + const sessionId = asNonEmptyString(body.sessionId) ?? undefined; + const branch = asNonEmptyString(body.branch) ?? undefined; + const repo = asNonEmptyString(body.repo) ?? undefined; + const message = asNonEmptyString(body.message) ?? undefined; + const author = asNonEmptyString(body.author) ?? undefined; + const authoredAt = asNonEmptyString(body.authoredAt) ?? undefined; + const files = Array.isArray(body.files) + ? (body.files as unknown[]).filter( + (f): f is string => typeof f === "string" && f.length > 0, + ) + : undefined; + + const link = await withKeyedLock(`commit:${sha}`, async () => { + const existing = await kv.get<CommitLink>(KV.commits, sha); + const sessionSet = new Set<string>(existing?.sessionIds ?? []); + if (sessionId) sessionSet.add(sessionId); + const merged: CommitLink = { + sha, + shortSha: existing?.shortSha ?? sha.slice(0, 7), + branch: branch ?? existing?.branch, + repo: repo ?? existing?.repo, + message: message ?? existing?.message, + author: author ?? existing?.author, + authoredAt: authoredAt ?? existing?.authoredAt, + files: files ?? existing?.files, + sessionIds: Array.from(sessionSet), + linkedAt: existing?.linkedAt ?? new Date().toISOString(), + }; + await kv.set(KV.commits, sha, merged); + return merged; + }); + + if (sessionId) { + await withKeyedLock(`session:${sessionId}`, async () => { + const session = await kv.get<Session>(KV.sessions, sessionId); + if (!session) return; + const shaSet = new Set<string>(session.commitShas ?? []); + shaSet.add(sha); + session.commitShas = Array.from(shaSet); + await kv.set(KV.sessions, sessionId, session); + }); + } + + return { status_code: 200, body: { commit: link } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::commit", + config: { + api_path: "/agentmemory/session/commit", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::by-commit", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sha = asNonEmptyString(req.query_params?.["sha"]); + if (!sha) { + return { + status_code: 400, + body: { error: "sha is required and must be a non-empty string" }, + }; + } + const link = await kv.get<CommitLink>(KV.commits, sha); + if (!link) { + return { + status_code: 404, + body: { error: "no sessions linked to this commit" }, + }; + } + const fetched = await Promise.all( + (link.sessionIds ?? []).map((sid) => kv.get<Session>(KV.sessions, sid)), + ); + const sessions = fetched.filter((s): s is Session => s !== null); + return { status_code: 200, body: { commit: link, sessions } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::by-commit", + config: { + api_path: "/agentmemory/session/by-commit", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::commits", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const branch = asNonEmptyString(req.query_params?.["branch"]); + const repo = asNonEmptyString(req.query_params?.["repo"]); + const rawLimit = parseOptionalInt(req.query_params?.["limit"]); + const limit = Math.max(1, Math.min(500, rawLimit ?? 100)); + const all = await kv.list<CommitLink>(KV.commits); + const filtered = all + .filter((c) => !branch || c.branch === branch) + .filter((c) => !repo || c.repo === repo) + .sort((a, b) => ((a.linkedAt ?? "") < (b.linkedAt ?? "") ? 1 : -1)) + .slice(0, limit); + return { status_code: 200, body: { commits: filtered } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::commits", + config: { + api_path: "/agentmemory/commits", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::sessions", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessions = await kv.list<Session>(KV.sessions); + const normalizedAgentId = + typeof req.query_params?.["agentId"] === "string" + ? req.query_params["agentId"].trim() + : undefined; + const wildcardAgent = normalizedAgentId === "*"; + const explicitAgentId = + normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; + const filterAgentId = wildcardAgent + ? undefined + : explicitAgentId ?? + (isAgentScopeIsolated() ? getAgentId() : undefined); + const filtered = filterAgentId + ? sessions.filter((s) => s.agentId === filterAgentId) + : sessions; + // Bounded fan-out: each kv.get is a full engine invocation, so + // Promise.all over hundreds of sessions saturates the invocation + // pool. Batch in chunks of 10 (parallel within a chunk, sequential + // across chunks); the summaries array stays index-aligned with + // `filtered`. + const summaries: Array<SessionSummary | null> = []; + for (let batch = 0; batch < filtered.length; batch += 10) { + const chunk = filtered.slice(batch, batch + 10); + const results = await Promise.all( + chunk.map((s) => + kv.get<SessionSummary>(KV.summaries, s.id).catch(() => null), + ), + ); + summaries.push(...results); + } + const withSummary = filtered.map((s, i) => + summaries[i] ? { ...s, summary: summaries[i] } : s, + ); + return { status_code: 200, body: { sessions: withSummary } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::sessions", + config: { api_path: "/agentmemory/sessions", http_method: "GET" }, + }); + + sdk.registerFunction("api::observations", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessionId = asNonEmptyString(req.query_params?.["sessionId"]); + if (!sessionId) + return { status_code: 400, body: { error: "sessionId required" } }; + const observations = await kv.list<CompressedObservation>( + KV.observations(sessionId), + ); + const normalizedAgentId = + typeof req.query_params?.["agentId"] === "string" + ? req.query_params["agentId"].trim() + : undefined; + const wildcardAgent = normalizedAgentId === "*"; + const explicitAgentId = + normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; + const filterAgentId = wildcardAgent + ? undefined + : explicitAgentId ?? + (isAgentScopeIsolated() ? getAgentId() : undefined); + const filtered = filterAgentId + ? observations.filter((o) => o.agentId === filterAgentId) + : observations; + return { status_code: 200, body: { observations: filtered } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::observations", + config: { api_path: "/agentmemory/observations", http_method: "GET" }, + }); + + sdk.registerFunction("api::file-context", + async ( + req: ApiRequest<{ sessionId: string; files: string[] }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::file-context", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::file-context", + config: { api_path: "/agentmemory/file-context", http_method: "POST" }, + }); + + sdk.registerFunction("api::enrich", + async ( + req: ApiRequest<{ + sessionId: string; + files: string[]; + terms?: string[]; + toolName?: string; + project?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !req.body?.sessionId || + typeof req.body.sessionId !== "string" || + !Array.isArray(req.body?.files) || + req.body.files.length === 0 || + !req.body.files.every((f: unknown) => typeof f === "string") + ) { + return { + status_code: 400, + body: { + error: "sessionId (string) and files (string[]) are required", + }, + }; + } + if ( + req.body.terms !== undefined && + (!Array.isArray(req.body.terms) || + !req.body.terms.every((t: unknown) => typeof t === "string")) + ) { + return { + status_code: 400, + body: { error: "terms must be an array of strings" }, + }; + } + if ( + req.body.project !== undefined && + (typeof req.body.project !== "string" || !req.body.project.trim()) + ) { + return { + status_code: 400, + body: { error: "project must be a non-empty string" }, + }; + } + const result = await sdk.trigger({ + function_id: "mem::enrich", + payload: { + sessionId: req.body.sessionId, + files: req.body.files, + ...(req.body.terms !== undefined && { terms: req.body.terms }), + ...(req.body.toolName !== undefined && { toolName: req.body.toolName }), + ...(req.body.project !== undefined && { project: req.body.project }), + }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::enrich", + config: { api_path: "/agentmemory/enrich", http_method: "POST" }, + }); + + sdk.registerFunction("api::remember", + async ( + req: ApiRequest<{ + content: string; + type?: string; + concepts?: string[]; + files?: string[]; + ttlDays?: number; + sourceObservationIds?: string[]; + project?: string; + agentId?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !req.body?.content || + typeof req.body.content !== "string" || + !req.body.content.trim() + ) { + return { status_code: 400, body: { error: "content is required" } }; + } + if ( + req.body.project !== undefined && + (typeof req.body.project !== "string" || !req.body.project.trim()) + ) { + return { status_code: 400, body: { error: "project must be a non-empty string" } }; + } + const result = await sdk.trigger({ + function_id: "mem::remember", + payload: { + content: req.body.content, + ...(req.body.type !== undefined && { type: req.body.type }), + ...(req.body.concepts !== undefined && { concepts: req.body.concepts }), + ...(req.body.files !== undefined && { files: req.body.files }), + ...(req.body.ttlDays !== undefined && { ttlDays: req.body.ttlDays }), + ...(req.body.sourceObservationIds !== undefined && { sourceObservationIds: req.body.sourceObservationIds }), + ...(req.body.project !== undefined && { project: req.body.project }), + ...(typeof req.body.agentId === "string" && req.body.agentId.trim() + ? { agentId: req.body.agentId.trim() } + : {}), + }, + }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::remember", + config: { api_path: "/agentmemory/remember", http_method: "POST" }, + }); + + sdk.registerFunction("api::forget", + async ( + req: ApiRequest<{ + sessionId?: string; + observationIds?: string[]; + memoryId?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sessionId = + typeof req.body?.sessionId === "string" ? req.body.sessionId : undefined; + const memoryId = + typeof req.body?.memoryId === "string" ? req.body.memoryId : undefined; + if (!sessionId && !memoryId) { + return { + status_code: 400, + body: { error: "sessionId or memoryId is required" }, + }; + } + const rawObservationIds = req.body?.observationIds; + // Dropping the non-strings and forwarding what is left would turn a + // malformed list into an empty one, and an empty list is the whole- + // session wipe. Refuse instead of widening what was asked for. + if ( + rawObservationIds !== undefined && + (!Array.isArray(rawObservationIds) || + !rawObservationIds.every((id) => typeof id === "string")) + ) { + return { + status_code: 400, + body: { error: "observationIds must be an array of strings" }, + }; + } + const result = (await sdk.trigger({ + function_id: "mem::forget", + payload: { + ...(sessionId !== undefined && { sessionId }), + ...(memoryId !== undefined && { memoryId }), + ...(rawObservationIds !== undefined && { observationIds: rawObservationIds }), + }, + })) as { success: boolean; error?: string }; + // The refusals mem::forget raises are bad requests, not results. + if (!result.success) { + return { status_code: 400, body: result }; + } + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::forget", + config: { api_path: "/agentmemory/forget", http_method: "POST" }, + }); + + sdk.registerFunction("api::consolidate", + async ( + req: ApiRequest<{ project?: string; minObservations?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::consolidate", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::consolidate", + config: { api_path: "/agentmemory/consolidate", http_method: "POST" }, + }); + + sdk.registerFunction("api::patterns", + async (req: ApiRequest<{ project?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::patterns", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::patterns", + config: { api_path: "/agentmemory/patterns", http_method: "POST" }, + }); + + sdk.registerFunction("api::generate-rules", + async (req: ApiRequest<{ project?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::generate-rules", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::generate-rules", + config: { api_path: "/agentmemory/generate-rules", http_method: "POST" }, + }); + + sdk.registerFunction("api::migrate", + async ( + req: ApiRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const hasStep = + typeof req.body?.step === "string" && req.body.step.trim().length > 0; + const hasDbPath = + typeof req.body?.dbPath === "string" && req.body.dbPath.trim().length > 0; + if (!hasStep && !hasDbPath) { + return { + status_code: 400, + body: { error: "Either step (string) or dbPath (string) is required" }, + }; + } + const result = await sdk.trigger({ + function_id: "mem::migrate", + payload: { + ...(req.body.step !== undefined && { step: req.body.step }), + ...(req.body.dbPath !== undefined && { dbPath: req.body.dbPath }), + ...(req.body.dryRun !== undefined && { dryRun: req.body.dryRun }), + }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::migrate", + config: { api_path: "/agentmemory/migrate", http_method: "POST" }, + }); + + sdk.registerFunction("api::evict", + async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const dryRun = + req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; + const result = await sdk.trigger({ function_id: "mem::evict", payload: { dryRun } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::evict", + config: { api_path: "/agentmemory/evict", http_method: "POST" }, + }); + + sdk.registerFunction("api::smart-search", + async ( + req: ApiRequest<{ + query?: string; + expandIds?: Array<string | { obsId: string; sessionId: string }>; + limit?: number; + project?: string; + includeLessons?: boolean; + agentId?: string; + sessionId?: string; + source?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !req.body?.query && + (!req.body?.expandIds || req.body.expandIds.length === 0) + ) { + return { + status_code: 400, + body: { error: "query or expandIds is required" }, + }; + } + // #771: route the X-Agentmemory-Source header into the payload so + // the followup-rate diagnostic can skip viewer-originated calls. + // Body wins if both are set (advanced callers explicitly override). + const headers = (req.headers || {}) as Record<string, string | string[] | undefined>; + const sourceHeader = headers["x-agentmemory-source"] ?? headers["X-Agentmemory-Source"]; + const sourceFromHeader = Array.isArray(sourceHeader) ? sourceHeader[0] : sourceHeader; + // Whitelist payload fields explicitly — REST endpoints never pass + // the raw request body through to sdk.trigger (AGENTS.md security + // section). Drops unknown fields so a misbehaving client can't + // inject downstream-only options. + const payload = { + query: req.body?.query, + expandIds: req.body?.expandIds, + limit: req.body?.limit, + project: req.body?.project, + includeLessons: req.body?.includeLessons, + agentId: req.body?.agentId, + sessionId: req.body?.sessionId, + source: req.body?.source ?? sourceFromHeader, + }; + const result = await sdk.trigger({ function_id: "mem::smart-search", payload }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::smart-search", + config: { api_path: "/agentmemory/smart-search", http_method: "POST" }, + }); + + // #771: read-back endpoint for the followup-rate diagnostic. Returns + // a directional signal — overcounts on legitimate query refinement — + // so help text + the CLI status line carry the same caveat. + sdk.registerFunction("api::diagnostic-followup", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ + function_id: "mem::diagnostic::followup-stats", + payload: {}, + }); + return { + status_code: 200, + body: { + ...(result as Record<string, unknown>), + caveat: + "Directional signal: overcounts on legitimate query refinement. " + + "Tune via AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS.", + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::diagnostic-followup", + config: { + api_path: "/agentmemory/diagnostics/followup", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::timeline", + async ( + req: ApiRequest<{ + anchor: string; + project?: string; + before?: number; + after?: number; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.anchor) { + return { status_code: 400, body: { error: "anchor is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::timeline", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::timeline", + config: { api_path: "/agentmemory/timeline", http_method: "POST" }, + }); + + sdk.registerFunction("api::profile", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const project = req.query_params["project"] as string; + if (!project) { + return { + status_code: 400, + body: { error: "project query param is required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::profile", payload: { project } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::profile", + config: { api_path: "/agentmemory/profile", http_method: "GET" }, + }); + + sdk.registerFunction("api::export", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + // mem::export already supports maxSessions/offset internally, + // but the HTTP endpoint hardcoded an empty payload — so /export on a + // real corpus (40 sessions × 34K observations × 8K memories) hit the + // iii engine invocation timeout and `agentmemory status` reported 0. + // Pass through the query-string pagination so callers can chunk. + const rawMax = req.query_params?.["maxSessions"]; + const rawOffset = req.query_params?.["offset"]; + const payload: { maxSessions?: number; offset?: number } = {}; + if (typeof rawMax === "string") { + const n = Number(rawMax); + if (Number.isInteger(n) && n > 0) payload.maxSessions = n; + } + if (typeof rawOffset === "string") { + const n = Number(rawOffset); + if (Number.isInteger(n) && n >= 0) payload.offset = n; + } + const result = await sdk.trigger({ + function_id: "mem::export", + payload, + }); + // mem::export refuses an oversized payload rather than serializing it; + // over HTTP that refusal is a 413, not a 200 carrying an error body. + if (isOversizedPayload(result)) return { status_code: 413, body: result }; + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::export", + config: { api_path: "/agentmemory/export", http_method: "GET" }, + }); + + sdk.registerFunction("api::import", + async ( + req: ApiRequest<{ + exportData: unknown; + strategy?: "merge" | "replace" | "skip"; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.exportData) { + return { status_code: 400, body: { error: "exportData is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::import", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::import", + config: { api_path: "/agentmemory/import", http_method: "POST" }, + }); + + sdk.registerFunction("api::relations", + async ( + req: ApiRequest<{ sourceId: string; targetId: string; type: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.sourceId || !req.body?.targetId || !req.body?.type) { + return { + status_code: 400, + body: { error: "sourceId, targetId, and type are required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::relate", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::relations", + config: { api_path: "/agentmemory/relations", http_method: "POST" }, + }); + + sdk.registerFunction("api::evolve", + async ( + req: ApiRequest<{ + memoryId: string; + newContent: string; + newTitle?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.memoryId || !req.body?.newContent) { + return { + status_code: 400, + body: { error: "memoryId and newContent are required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::evolve", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::evolve", + config: { api_path: "/agentmemory/evolve", http_method: "POST" }, + }); + + sdk.registerFunction("api::auto-forget", + async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const dryRun = + req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true; + const result = await sdk.trigger({ function_id: "mem::auto-forget", payload: { dryRun } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::auto-forget", + config: { api_path: "/agentmemory/auto-forget", http_method: "POST" }, + }); + + sdk.registerFunction("api::claude-bridge-read", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::claude-bridge-read", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { + status_code: 404, + body: { error: "Claude bridge not enabled" }, + }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::claude-bridge-read", + config: { api_path: "/agentmemory/claude-bridge/read", http_method: "GET" }, + }); + + sdk.registerFunction("api::claude-bridge-sync", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::claude-bridge-sync", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { + status_code: 404, + body: { error: "Claude bridge not enabled" }, + }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::claude-bridge-sync", + config: { + api_path: "/agentmemory/claude-bridge/sync", + http_method: "POST", + }, + }); + + sdk.registerFunction("api::graph-query", + async ( + req: ApiRequest<{ + startNodeId?: string; + nodeType?: string; + maxDepth?: number; + query?: string; + limit?: number; + offset?: number; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + // Whitelist payload fields explicitly; AGENTS.md security rule: + // REST endpoints never pass raw req.body through to sdk.trigger. + const payload = { + startNodeId: req.body?.startNodeId, + nodeType: req.body?.nodeType, + maxDepth: req.body?.maxDepth, + query: req.body?.query, + limit: req.body?.limit, + offset: req.body?.offset, + }; + try { + const result = await sdk.trigger({ function_id: "mem::graph-query", payload }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-query", + config: { api_path: "/agentmemory/graph/query", http_method: "POST" }, + }); + + sdk.registerFunction("api::graph-stats", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::graph-stats", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-stats", + config: { api_path: "/agentmemory/graph/stats", http_method: "GET" }, + }); + + // #814: explicit snapshot rebuild endpoint. Pays the full graph + // enumeration once and persists a top-degree subgraph + aggregate + // counts so subsequent /graph/query and /graph/stats calls skip the + // unbounded kv.list. Operator-grade endpoint exposed for the viewer + // banner action and CLI repair. + sdk.registerFunction("api::graph-snapshot-rebuild", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ + function_id: "mem::graph-snapshot-rebuild", + payload: {}, + }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-snapshot-rebuild", + config: { api_path: "/agentmemory/graph/snapshot-rebuild", http_method: "POST" }, + }); + + // #814 v2: clean-restart endpoint for legacy corpora too large for + // safe rebuild. Wipes graph state without touching observations, so + // recall + history stay intact while the graph rebuilds incrementally + // from new extracts (or a one-shot /graph/build replay). + sdk.registerFunction("api::graph-reset", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ + function_id: "mem::graph-reset", + payload: {}, + }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-reset", + config: { api_path: "/agentmemory/graph/reset", http_method: "POST" }, + }); + + sdk.registerFunction("api::graph-extract", + async (req: ApiRequest<{ observations: unknown[] }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if ( + !Array.isArray(req.body?.observations) || + req.body.observations.length === 0 + ) { + return { + status_code: 400, + body: { error: "observations array is required" }, + }; + } + try { + const result = await sdk.trigger({ function_id: "mem::graph-extract", payload: req.body }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-extract", + config: { api_path: "/agentmemory/graph/extract", http_method: "POST" }, + }); + + // Backfill the knowledge graph from existing compressed observations. + // Viewer calls this when the graph is empty (#666). Iterates every + // session, collects observations that have a `title` (compressed only), + // and feeds them through `mem::graph-extract` in batches. + sdk.registerFunction("api::graph-build", + async (req: ApiRequest<{ batchSize?: number }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const batchSize = Math.max( + 1, + Math.min(100, Number((req.body as { batchSize?: number })?.batchSize) || 25), + ); + try { + const sessions = await kv.list<Session>(KV.sessions); + let totalNodes = 0; + let totalEdges = 0; + let batchesRun = 0; + for (const session of sessions) { + const sid = session?.id; + if (typeof sid !== "string" || sid.length === 0) continue; + const observations = await kv.list<CompressedObservation>(KV.observations(sid)); + const compressed = observations.filter((o) => o && typeof o.title === "string" && o.title.length > 0); + if (compressed.length === 0) continue; + for (let i = 0; i < compressed.length; i += batchSize) { + const batch = compressed.slice(i, i + batchSize); + try { + const result = (await sdk.trigger({ + function_id: "mem::graph-extract", + payload: { observations: batch }, + })) as { success?: boolean; nodesAdded?: number; edgesAdded?: number }; + if (result?.success) { + totalNodes += Number(result.nodesAdded) || 0; + totalEdges += Number(result.edgesAdded) || 0; + } + batchesRun++; + } catch (err) { + logger.warn("graph-build batch failed", { + sessionId: sid, + batchIndex: Math.floor(i / batchSize), + error: err instanceof Error ? err.message : String(err), + }); + } + } + } + return { + status_code: 200, + body: { + success: true, + sessions: sessions.length, + batches: batchesRun, + nodes: totalNodes, + edges: totalEdges, + }, + }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-build", + config: { api_path: "/agentmemory/graph/build", http_method: "POST" }, + }); + + // Import graphify's structural graph (graphify-out/graph.json) into the + // memory graph. Deterministic, no LLM call; idempotent via the graph + // name-index upsert. + sdk.registerFunction("api::graph-import-graphify", + async (req: ApiRequest<{ path?: string; cwd?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const { path, cwd } = req.body ?? {}; + if ( + (path !== undefined && typeof path !== "string") || + (cwd !== undefined && typeof cwd !== "string") + ) { + return { + status_code: 400, + body: { error: "path and cwd must be strings when provided" }, + }; + } + try { + const result = await sdk.trigger({ + function_id: "mem::graph::import-graphify", + payload: { + ...(path !== undefined ? { path } : {}), + ...(cwd !== undefined ? { cwd } : {}), + }, + }); + return { status_code: 200, body: result }; + } catch { + return graphDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::graph-import-graphify", + config: { api_path: "/agentmemory/graph/import-graphify", http_method: "POST" }, + }); + + // Re-run compression for observations that a failed mem::compress left in + // raw shape - present in KV but in neither search index, so unretrievable. + // Two sources: mem:compress-pending (parked by the failure path, full raw + // preserved) and raw-shaped records in KV.observations (the historical + // orphans that predate that fix). Sequential and limit-bounded on purpose: + // this exists to be run after a provider outage, and firing hundreds of + // concurrent LLM calls at a provider that has just stopped returning 529s + // is how you cause the next one. + sdk.registerFunction("api::recompress-orphans", + async (req: ApiRequest<{ limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body || {}) as { limit?: number; dryRun?: boolean; requeueQuarantined?: boolean; graceBypassBefore?: string }; + const limit = Math.max(1, Math.min(1000, Number(body.limit) || 50)); + const dryRun = body.dryRun === true; + // Records captured before this instant skip the one-hour grace. The + // cutover passes its freeze timestamp: nothing captured before the + // freeze can still have a compression in flight on the new daemon. + const graceBypassBefore = typeof body.graceBypassBefore === "string" ? new Date(body.graceBypassBefore).getTime() : NaN; + if (typeof body.graceBypassBefore === "string" && !Number.isFinite(graceBypassBefore)) { + return { status_code: 400, body: { error: "graceBypassBefore must be an ISO timestamp" } }; + } + // Give quarantined entries (attempts >= MAX_ATTEMPTS) one more shot. + // Meant for after a compression-pipeline fix lands: what was a + // deterministic failure may compress cleanly under the new code. + const requeueQuarantined = body.requeueQuarantined === true; + const GRACE_MS = 60 * 60 * 1000; + const now = Date.now(); + + const MAX_ATTEMPTS = 5; + const targets: Array<{ observationId: string; sessionId: string; raw: unknown }> = []; + + // Raw-shaped orphans FIRST: they are the records no search can return, + // so the batch budget belongs to them. Parked entries are already + // findable as degraded synthetics - re-compressing them is a quality + // upgrade, not a rescue. (The first version of this endpoint did the + // opposite and starved the raw ones: every failed parked entry was + // re-parked, so the pending queue never shrank and always ate the + // whole budget.) + let rawOrphans = 0; + for (const session of await kv.list<Session>(KV.sessions)) { + const sid = session?.id; + if (typeof sid !== "string" || sid.length === 0) continue; + for (const o of await kv.list<Record<string, unknown>>(KV.observations(sid))) { + const oid = o?.["id"]; + if (typeof oid !== "string") continue; + if (typeof o["narrative"] === "string") continue; + if (typeof o["hookType"] !== "string") continue; + const ts = new Date(String(o["timestamp"])).getTime(); + const bypass = Number.isFinite(graceBypassBefore) && Number.isFinite(ts) && ts < graceBypassBefore; + if (Number.isFinite(ts) && now - ts < GRACE_MS && !bypass) continue; + rawOrphans++; + if (targets.length < limit) { + targets.push({ observationId: oid, sessionId: sid, raw: o }); + } + } + } + + const queued = new Set(targets.map((t) => t.observationId)); + let parked = 0; + let quarantined = 0; + for (const p of await kv.list<{ + observationId?: string; + sessionId?: string; + raw?: unknown; + attempts?: number; + }>(KV.compressPending)) { + if (typeof p?.observationId !== "string" || typeof p?.sessionId !== "string") continue; + if (queued.has(p.observationId)) continue; + if ((p.attempts ?? 0) >= MAX_ATTEMPTS) { + quarantined++; + if (!requeueQuarantined) continue; + } else { + parked++; + } + if (targets.length < limit) { + targets.push({ observationId: p.observationId, sessionId: p.sessionId, raw: p.raw }); + } + } + + if (dryRun) { + return { + status_code: 200, + body: { + success: true, + dryRun: true, + rawOrphans, + parked, + quarantined, + queued: targets.length, + limit, + }, + }; + } + + let recompressed = 0; + let stillFailing = 0; + for (const t of targets) { + try { + const result = (await sdk.trigger({ + function_id: "mem::compress", + payload: t, + })) as { success?: boolean } | null; + if (result?.success) recompressed++; + else stillFailing++; + } catch { + stillFailing++; + } + // Bail out rather than grind through hundreds of doomed calls when + // the provider is clearly still down. Not for requeueQuarantined + // batches: there every target is a known deterministic failure, so + // ten straight losses say nothing about the provider. + if (!requeueQuarantined && stillFailing >= 10 && recompressed === 0) { + logger.warn("recompress-orphans aborting: provider still failing", { + attempted: recompressed + stillFailing, + }); + break; + } + } + + logger.info("recompress-orphans finished", { + rawOrphans, + parked, + quarantined, + queued: targets.length, + recompressed, + stillFailing, + }); + return { + status_code: 200, + body: { + success: true, + rawOrphans, + parked, + quarantined, + queued: targets.length, + recompressed, + stillFailing, + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::recompress-orphans", + config: { api_path: "/agentmemory/recompress-orphans", http_method: "POST" }, + }); + + sdk.registerFunction("api::consolidate-pipeline", + async (req: ApiRequest<{ tier?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: req.body || {}, + }); + return { status_code: 200, body: result }; + } catch { + return consolidationDisabledResponse(); + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::consolidate-pipeline", + config: { + api_path: "/agentmemory/consolidate-pipeline", + http_method: "POST", + }, + }); + + sdk.registerFunction("api::team-share", + async ( + req: ApiRequest<{ itemId: string; itemType: string; project?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.itemId || !req.body?.itemType) { + return { + status_code: 400, + body: { error: "itemId and itemType are required" }, + }; + } + try { + const result = await sdk.trigger({ function_id: "mem::team-share", payload: req.body }); + return { status_code: 201, body: result }; + } catch { + return { status_code: 404, body: { error: "Team memory not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::team-share", + config: { api_path: "/agentmemory/team/share", http_method: "POST" }, + }); + + sdk.registerFunction("api::team-feed", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const limit = parsedLimit ?? 20; + const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { limit } }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Team memory not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::team-feed", + config: { api_path: "/agentmemory/team/feed", http_method: "GET" }, + }); + + sdk.registerFunction("api::team-profile", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::team-profile", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Team memory not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::team-profile", + config: { api_path: "/agentmemory/team/profile", http_method: "GET" }, + }); + + sdk.registerFunction("api::audit", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const entries = await sdk.trigger({ function_id: "mem::audit-query", payload: { + operation: req.query_params?.["operation"], + limit: parsedLimit ?? 50, + } }); + return { status_code: 200, body: { entries, success: true } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::audit", + config: { api_path: "/agentmemory/audit", http_method: "GET" }, + }); + + sdk.registerFunction("api::governance-delete", + async ( + req: ApiRequest<{ memoryIds: string[]; reason?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.memoryIds || !Array.isArray(req.body.memoryIds)) { + return { + status_code: 400, + body: { error: "memoryIds array is required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::governance-delete", + config: { + api_path: "/agentmemory/governance/memories", + http_method: "DELETE", + }, + }); + + sdk.registerFunction("api::governance-bulk", + async ( + req: ApiRequest<{ + type?: string[]; + dateFrom?: string; + dateTo?: string; + qualityBelow?: number; + dryRun?: boolean; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::governance-bulk", payload: req.body || {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::governance-bulk", + config: { + api_path: "/agentmemory/governance/bulk-delete", + http_method: "POST", + }, + }); + + sdk.registerFunction("api::snapshots", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-list", payload: {} }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Snapshots not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::snapshots", + config: { api_path: "/agentmemory/snapshots", http_method: "GET" }, + }); + + sdk.registerFunction("api::snapshot-create", + async (req: ApiRequest<{ message?: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: req.body || {}, + }); + return { status_code: 201, body: result }; + } catch { + return { status_code: 404, body: { error: "Snapshots not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::snapshot-create", + config: { api_path: "/agentmemory/snapshot/create", http_method: "POST" }, + }); + + sdk.registerFunction("api::snapshot-restore", + async (req: ApiRequest<{ commitHash: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.commitHash) { + return { status_code: 400, body: { error: "commitHash is required" } }; + } + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-restore", payload: req.body }); + return { status_code: 200, body: result }; + } catch { + return { status_code: 404, body: { error: "Snapshots not enabled" } }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::snapshot-restore", + config: { api_path: "/agentmemory/snapshot/restore", http_method: "POST" }, + }); + + sdk.registerFunction("api::memories", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const memories = await kv.list<import("../types.js").Memory>(KV.memories); + const latest = req.query_params?.["latest"] === "true"; + // agentId filter. Request param wins, env AGENT_ID (when + // scope=isolated) is the fallback. Shared mode keeps the tag but + // does not restrict the list endpoint. Pass agentId=* to opt out + // of the env scope entirely. includeOrphans=true surfaces + // pre-AGENT_ID memories whose agentId is undefined. + const normalizedAgentId = + typeof req.query_params?.["agentId"] === "string" + ? req.query_params["agentId"].trim() + : undefined; + const wildcardAgent = normalizedAgentId === "*"; + const explicitAgentId = + normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined; + const includeOrphans = + req.query_params?.["includeOrphans"] === "true"; + const filterAgentId = wildcardAgent + ? undefined + : explicitAgentId ?? (isAgentScopeIsolated() ? getAgentId() : undefined); + let filtered = latest ? memories.filter((m) => m.isLatest) : memories; + if (filterAgentId) { + filtered = filtered.filter( + (m) => + m.agentId === filterAgentId || + (includeOrphans && m.agentId === undefined), + ); + } + + // viewer + `agentmemory status` were hitting this endpoint to + // count memories. On a real corpus (8K+ memories) the unbounded + // response either timed out at the iii engine boundary ("Invocation + // stopped") or arrived too large for the viewer to render — so the + // UI showed 0 memories despite a healthy store. Two opt-in modes: + // ?count=true — totals only, no payload + // ?limit=N&offset=M — page slice (default unlimited for back-compat) + if (req.query_params?.["count"] === "true") { + // Match the SAME scope that the list path applies — returning + // unfiltered totals here would leak cross-agent counts to a + // caller that's blocked from the underlying rows. + return { + status_code: 200, + body: { + total: filtered.length, + latestCount: filtered.filter((m) => m.isLatest).length, + }, + }; + } + + const rawLimit = req.query_params?.["limit"]; + const rawOffset = req.query_params?.["offset"]; + const parsedLimit = + typeof rawLimit === "string" ? Number(rawLimit) : Number.NaN; + const parsedOffset = + typeof rawOffset === "string" ? Number(rawOffset) : Number.NaN; + const limit = + Number.isInteger(parsedLimit) && parsedLimit > 0 + ? Math.min(parsedLimit, 5000) + : undefined; + const offset = + Number.isInteger(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0; + const sliced = + limit !== undefined ? filtered.slice(offset, offset + limit) : filtered; + + return { + status_code: 200, + body: { + memories: sliced, + total: filtered.length, + offset, + limit: limit ?? null, + }, + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::memories", + config: { api_path: "/agentmemory/memories", http_method: "GET" }, + }); + + sdk.registerFunction("api::memory-by-id", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const id = req.path_params?.["id"]; + if (!id || typeof id !== "string") { + return { status_code: 400, body: { error: "id path parameter is required" } }; + } + const memory = await kv.get<import("../types.js").Memory>(KV.memories, id); + if (!memory) { + return { status_code: 404, body: { error: `memory not found: ${id}` } }; + } + return { status_code: 200, body: { memory } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::memory-by-id", + config: { api_path: "/agentmemory/memories/:id", http_method: "GET" }, + }); + + // The route an operator reaches for first. Without it, removing one + // memory means discovering either /agentmemory/forget or the + // governance bulk paths, and the filter-based one invites deleting by + // date window and hoping the window held only the target. + sdk.registerFunction("api::memory-delete", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const id = req.path_params?.["id"]; + if (!id || typeof id !== "string") { + return { status_code: 400, body: { error: "id path parameter is required" } }; + } + const result = await sdk.trigger({ + function_id: "mem::forget", + payload: { memoryId: id }, + }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::memory-delete", + config: { api_path: "/agentmemory/memories/:id", http_method: "DELETE" }, + }); + + sdk.registerFunction("api::semantic-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); + return { status_code: 200, body: { semantic } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::semantic-list", + config: { api_path: "/agentmemory/semantic", http_method: "GET" }, + }); + + sdk.registerFunction("api::procedural-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); + return { status_code: 200, body: { procedural } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::procedural-list", + config: { api_path: "/agentmemory/procedural", http_method: "GET" }, + }); + + sdk.registerFunction("api::relations-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); + return { status_code: 200, body: { relations } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::relations-list", + config: { api_path: "/agentmemory/relations", http_method: "GET" }, + }); + + sdk.registerFunction("api::vision-search", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const queryText = asNonEmptyString(body["queryText"]); + const queryImageRef = asNonEmptyString(body["queryImageRef"]); + const queryImageBase64 = asNonEmptyString(body["queryImageBase64"]); + const sessionId = asNonEmptyString(body["sessionId"]); + if (!queryText && !queryImageRef && !queryImageBase64) { + return { + status_code: 400, + body: { error: "queryText, queryImageRef, or queryImageBase64 required" }, + }; + } + const topKParsed = parseOptionalPositiveInt(body["topK"]); + if (topKParsed === null) { + return { status_code: 400, body: { error: "topK must be a positive integer" } }; + } + const payload: Record<string, unknown> = {}; + if (queryText) payload["queryText"] = queryText; + if (queryImageRef) payload["queryImageRef"] = queryImageRef; + if (queryImageBase64) payload["queryImageBase64"] = queryImageBase64; + if (sessionId) payload["sessionId"] = sessionId; + if (topKParsed !== undefined) payload["topK"] = Math.min(50, topKParsed); + const result = await sdk.trigger({ function_id: "mem::vision-search", payload }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::vision-search", + config: { api_path: "/agentmemory/vision-search", http_method: "POST" }, + }); + + sdk.registerFunction("api::vision-embed", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const body = (req.body ?? {}) as Record<string, unknown>; + const imageRef = asNonEmptyString(body["imageRef"]); + const sessionId = asNonEmptyString(body["sessionId"]); + const observationId = asNonEmptyString(body["observationId"]); + if (!imageRef) { + return { status_code: 400, body: { error: "imageRef is required" } }; + } + const payload: Record<string, unknown> = { imageRef }; + if (sessionId) payload["sessionId"] = sessionId; + if (observationId) payload["observationId"] = observationId; + const result = await sdk.trigger({ function_id: "mem::vision-embed", payload }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("disabled") ? 503 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::vision-embed", + config: { api_path: "/agentmemory/vision-embed", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-list", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-list", + config: { api_path: "/agentmemory/slots", http_method: "GET" }, + }); + + sdk.registerFunction("api::slot-get", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const label = asNonEmptyString(req.query_params?.["label"]); + if (!label) return { status_code: 400, body: { error: "label query param required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-get", + config: { api_path: "/agentmemory/slot", http_method: "GET" }, + }); + + sdk.registerFunction("api::slot-create", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const label = asNonEmptyString(body["label"]); + if (!label) return { status_code: 400, body: { error: "label required" } }; + // Reject malformed inputs instead of silently dropping them. + if (body["content"] !== undefined && typeof body["content"] !== "string") { + return { status_code: 400, body: { error: "content must be a string" } }; + } + if (body["description"] !== undefined && typeof body["description"] !== "string") { + return { status_code: 400, body: { error: "description must be a string" } }; + } + if (body["pinned"] !== undefined && typeof body["pinned"] !== "boolean") { + return { status_code: 400, body: { error: "pinned must be a boolean" } }; + } + if ( + body["scope"] !== undefined && + body["scope"] !== "project" && + body["scope"] !== "global" + ) { + return { status_code: 400, body: { error: "scope must be 'project' or 'global'" } }; + } + const sizeLimit = parseOptionalPositiveInt(body["sizeLimit"]); + if (sizeLimit === null) { + return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } }; + } + if (sizeLimit !== undefined && sizeLimit > 20000) { + return { status_code: 400, body: { error: "sizeLimit must be <= 20000" } }; + } + const payload: Record<string, unknown> = { label }; + if (typeof body["content"] === "string") payload["content"] = body["content"]; + if (typeof body["description"] === "string") payload["description"] = body["description"]; + if (sizeLimit !== undefined) payload["sizeLimit"] = sizeLimit; + if (typeof body["pinned"] === "boolean") payload["pinned"] = body["pinned"]; + if (body["scope"] === "project" || body["scope"] === "global") payload["scope"] = body["scope"]; + const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("exists") ? 409 : 400, body: resp }; + } + return { status_code: 201, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-create", + config: { api_path: "/agentmemory/slot", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-append", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const label = asNonEmptyString(body["label"]); + const text = typeof body["text"] === "string" ? body["text"] : null; + if (!label || !text) return { status_code: 400, body: { error: "label and text required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + const notFound = resp.error?.includes("not found"); + const overLimit = resp.error?.includes("exceed"); + return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-append", + config: { api_path: "/agentmemory/slot/append", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-replace", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const label = asNonEmptyString(body["label"]); + const content = body["content"]; + if (!label || typeof content !== "string") { + return { status_code: 400, body: { error: "label and content (string) required" } }; + } + const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + const notFound = resp.error?.includes("not found"); + const overLimit = resp.error?.includes("exceed"); + return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-replace", + config: { api_path: "/agentmemory/slot/replace", http_method: "POST" }, + }); + + sdk.registerFunction("api::slot-delete", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + const label = asNonEmptyString(req.query_params?.["label"]); + if (!label) return { status_code: 400, body: { error: "label query param required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false) { + return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-delete", + config: { api_path: "/agentmemory/slot", http_method: "DELETE" }, + }); + + sdk.registerFunction("api::slot-reflect", async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!isSlotsEnabled()) return slotsDisabledResponse(); + if (!isReflectEnabled()) return reflectDisabledResponse(); + const body = (req.body ?? {}) as Record<string, unknown>; + const sessionId = asNonEmptyString(body["sessionId"]); + if (!sessionId) return { status_code: 400, body: { error: "sessionId required" } }; + const maxObservations = parseOptionalPositiveInt(body["maxObservations"]); + if (maxObservations === null) return { status_code: 400, body: { error: "maxObservations must be a positive integer" } }; + const payload: Record<string, unknown> = { sessionId }; + if (maxObservations !== undefined) payload["maxObservations"] = maxObservations; + const result = await sdk.trigger({ function_id: "mem::slot-reflect", payload }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ + type: "http", + function_id: "api::slot-reflect", + config: { api_path: "/agentmemory/slot/reflect", http_method: "POST" }, + }); + + sdk.registerFunction("api::action-create", + async ( + req: ApiRequest<{ + title: string; + description?: string; + priority?: number; + createdBy?: string; + project?: string; + tags?: string[]; + parentId?: string; + edges?: Array<{ type: string; targetActionId: string }>; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.title) { + return { status_code: 400, body: { error: "title is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-create", + config: { api_path: "/agentmemory/actions", http_method: "POST" }, + }); + + sdk.registerFunction("api::action-update", + async ( + req: ApiRequest<{ + actionId: string; + status?: string; + title?: string; + description?: string; + priority?: number; + result?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId) { + return { status_code: 400, body: { error: "actionId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-update", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-update", + config: { api_path: "/agentmemory/actions/update", http_method: "POST" }, + }); + + sdk.registerFunction("api::action-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::action-list", payload: { + status: req.query_params?.["status"], + project: req.query_params?.["project"], + parentId: req.query_params?.["parentId"], + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-list", + config: { api_path: "/agentmemory/actions", http_method: "GET" }, + }); + + sdk.registerFunction("api::action-get", + async (req: ApiRequest<{ actionId: string }>): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const actionId = req.query_params?.["actionId"] as string; + if (!actionId) { + return { status_code: 400, body: { error: "actionId required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-get", payload: { actionId } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-get", + config: { api_path: "/agentmemory/actions/get", http_method: "GET" }, + }); + + sdk.registerFunction("api::action-edge", + async ( + req: ApiRequest<{ + sourceActionId: string; + targetActionId: string; + type: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) { + return { status_code: 400, body: { error: "sourceActionId, targetActionId, and type are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::action-edge-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::action-edge", + config: { api_path: "/agentmemory/actions/edges", http_method: "POST" }, + }); + + sdk.registerFunction("api::frontier", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const result = await sdk.trigger({ function_id: "mem::frontier", payload: { + project: req.query_params?.["project"], + agentId: req.query_params?.["agentId"], + limit: parsedLimit, + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::frontier", + config: { api_path: "/agentmemory/frontier", http_method: "GET" }, + }); + + sdk.registerFunction("api::next", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::next", payload: { + project: req.query_params?.["project"], + agentId: req.query_params?.["agentId"], + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::next", + config: { api_path: "/agentmemory/next", http_method: "GET" }, + }); + + sdk.registerFunction("api::lease-acquire", + async ( + req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId || !req.body?.agentId) { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lease-acquire", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::lease-acquire", + config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" }, + }); + + sdk.registerFunction("api::lease-release", + async ( + req: ApiRequest<{ actionId: string; agentId: string; result?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId || !req.body?.agentId) { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lease-release", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::lease-release", + config: { api_path: "/agentmemory/leases/release", http_method: "POST" }, + }); + + sdk.registerFunction("api::lease-renew", + async ( + req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.actionId || !req.body?.agentId) { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lease-renew", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::lease-renew", + config: { api_path: "/agentmemory/leases/renew", http_method: "POST" }, + }); + + sdk.registerFunction("api::routine-create", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.name || !req.body?.steps) { + return { + status_code: 400, + body: { error: "name and steps are required" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::routine-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-create", + config: { api_path: "/agentmemory/routines", http_method: "POST" }, + }); + + sdk.registerFunction("api::routine-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::routine-list", payload: { + frozen: req.query_params?.["frozen"] === "true" ? true : undefined, + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-list", + config: { api_path: "/agentmemory/routines", http_method: "GET" }, + }); + + sdk.registerFunction("api::routine-run", + async ( + req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.routineId) { + return { status_code: 400, body: { error: "routineId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::routine-run", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-run", + config: { api_path: "/agentmemory/routines/run", http_method: "POST" }, + }); + + sdk.registerFunction("api::routine-status", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const runId = req.query_params?.["runId"] as string; + if (!runId) { + return { status_code: 400, body: { error: "runId query param required" } }; + } + const result = await sdk.trigger({ function_id: "mem::routine-status", payload: { runId } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::routine-status", + config: { api_path: "/agentmemory/routines/status", http_method: "GET" }, + }); + + sdk.registerFunction("api::signal-send", + async ( + req: ApiRequest<{ + from: string; + to?: string; + content: string; + type?: string; + replyTo?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.from || !req.body?.content) { + return { status_code: 400, body: { error: "from and content are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::signal-send", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::signal-send", + config: { api_path: "/agentmemory/signals/send", http_method: "POST" }, + }); + + sdk.registerFunction("api::signal-read", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const agentId = req.query_params?.["agentId"] as string; + if (!agentId) { + return { status_code: 400, body: { error: "agentId query param required" } }; + } + const parsedLimit = parseOptionalInt(req.query_params?.["limit"]); + const result = await sdk.trigger({ function_id: "mem::signal-read", payload: { + agentId, + unreadOnly: req.query_params?.["unreadOnly"] === "true", + threadId: req.query_params?.["threadId"], + limit: parsedLimit, + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::signal-read", + config: { api_path: "/agentmemory/signals", http_method: "GET" }, + }); + + sdk.registerFunction("api::checkpoint-create", + async ( + req: ApiRequest<{ + name: string; + description?: string; + type?: string; + linkedActionIds?: string[]; + expiresInMs?: number; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.name) { + return { status_code: 400, body: { error: "name is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::checkpoint-create", + config: { api_path: "/agentmemory/checkpoints", http_method: "POST" }, + }); + + sdk.registerFunction("api::checkpoint-resolve", + async ( + req: ApiRequest<{ + checkpointId: string; + status: string; + resolvedBy?: string; + result?: unknown; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.checkpointId || !req.body?.status) { + return { status_code: 400, body: { error: "checkpointId and status are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: req.body }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::checkpoint-resolve", + config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" }, + }); + + sdk.registerFunction("api::checkpoint-list", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { + status: req.query_params?.["status"], + type: req.query_params?.["type"], + } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::checkpoint-list", + config: { api_path: "/agentmemory/checkpoints", http_method: "GET" }, + }); + + sdk.registerFunction("api::mesh-register", + async ( + req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>, + ): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + if (!req.body?.url || !req.body?.name) { + return { status_code: 400, body: { error: "url and name are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::mesh-register", payload: req.body }); + return { status_code: 201, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-register", + config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" }, + }); + + sdk.registerFunction("api::mesh-list", + async (req: ApiRequest): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::mesh-list", payload: {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-list", + config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" }, + }); + + sdk.registerFunction("api::mesh-sync", + async ( + req: ApiRequest<{ peerId?: string; direction?: string }>, + ): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::mesh-sync", payload: req.body || {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-sync", + config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" }, + }); + + sdk.registerFunction("api::mesh-receive", + async (req: ApiRequest): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const result = await sdk.trigger({ function_id: "mem::mesh-receive", payload: req.body || {} }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-receive", + config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" }, + }); + + sdk.registerFunction("api::mesh-export", + async (req: ApiRequest): Promise<Response> => { + const secretErr = requireConfiguredSecret(secret, "mesh"); + if (secretErr) return secretErr; + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const since = req.query_params?.["since"] as string; + if (since) { + const parsed = new Date(since).getTime(); + if (Number.isNaN(parsed)) { + return { status_code: 400, body: { error: "Invalid 'since' date format" } }; + } + } + const project = req.query_params?.["project"] as string | undefined; + const sinceTime = since ? new Date(since).getTime() : 0; + const df = <T>(items: T[], field: "updatedAt" | "createdAt") => + items.filter((i) => new Date((i as Record<string, unknown>)[field] as string).getTime() > sinceTime); + let memories = await kv.list<import("../types.js").Memory>(KV.memories); + let actions = await kv.list<import("../types.js").Action>(KV.actions); + if (project) { + memories = memories.filter((m) => m.project === project); + actions = actions.filter((a) => a.project === project); + } + const body: Record<string, unknown> = { + memories: df(memories, "updatedAt"), + actions: df(actions, "updatedAt"), + }; + if (!project) { + const semantic = await kv.list<import("../types.js").SemanticMemory>(KV.semantic); + const procedural = await kv.list<import("../types.js").ProceduralMemory>(KV.procedural); + const relations = await kv.list<import("../types.js").MemoryRelation>(KV.relations); + body.semantic = df(semantic, "updatedAt"); + body.procedural = df(procedural, "updatedAt"); + body.relations = df(relations, "createdAt"); + // B-mode: graph frozen — never enumerate the graph scope for the + // mesh-sync delta body. + if (!graphLegDisabled()) { + const graphNodes = await kv.list<import("../types.js").GraphNode>(KV.graphNodes); + const graphEdges = await kv.list<import("../types.js").GraphEdge>(KV.graphEdges); + body.graphNodes = graphNodes.filter( + (n) => new Date(n.updatedAt || n.createdAt).getTime() > sinceTime, + ); + body.graphEdges = df(graphEdges, "createdAt"); + } + } + // Fail an oversized export with 413 rather than on heap. + const oversized = checkPayloadSize( + body, + "use ?since to fetch only changes after a timestamp, or ?project to scope the export", + ); + if (oversized) return { status_code: 413, body: oversized }; + return { status_code: 200, body }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::mesh-export", + config: { api_path: "/agentmemory/mesh/export", http_method: "GET" }, + }); + + sdk.registerFunction("api::flow-compress", + async ( + req: ApiRequest<{ + runId?: string; + actionIds?: string[]; + project?: string; + }>, + ): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + try { + const result = await sdk.trigger({ function_id: "mem::flow-compress", payload: req.body || {} }); + return { status_code: 200, body: result }; + } catch { + return { + status_code: 404, + body: { error: "Flow compression requires a provider" }, + }; + } + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::flow-compress", + config: { api_path: "/agentmemory/flow/compress", http_method: "POST" }, + }); + + sdk.registerFunction("api::branch-detect", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); + const result = await sdk.trigger({ function_id: "mem::detect-worktree", payload: { cwd } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::branch-detect", + config: { api_path: "/agentmemory/branch/detect", http_method: "GET" }, + }); + + sdk.registerFunction("api::branch-worktrees", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); + const result = await sdk.trigger({ function_id: "mem::list-worktrees", payload: { cwd } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::branch-worktrees", + config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" }, + }); + + sdk.registerFunction("api::branch-sessions", + async (req: ApiRequest): Promise<Response> => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const cwd = (req.query_params?.["cwd"] as string) || process.cwd(); + const result = await sdk.trigger({ function_id: "mem::branch-sessions", payload: { cwd } }); + return { status_code: 200, body: result }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::branch-sessions", + config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" }, + }); + + sdk.registerFunction("api::viewer", + async (req: ApiRequest): Promise<Response> => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const rendered = renderViewerDocument(); + if (rendered.found) { + return { + status_code: 200, + headers: { + "Content-Type": "text/html", + "Content-Security-Policy": rendered.csp, + }, + body: rendered.html, + }; + } + return { + status_code: 404, + headers: { + "Content-Type": "text/html", + }, + body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>", + }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::viewer", + config: { api_path: "/agentmemory/viewer", http_method: "GET" }, + }); + + sdk.registerFunction("api::sentinel-create", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.name) return { status_code: 400, body: { error: "name is required" } }; + const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-trigger", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-check", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-cancel", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sentinel-cancel", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } }); + + sdk.registerFunction("api::sentinel-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const result = await sdk.trigger({ function_id: "mem::sentinel-list", payload: { status: params.status, type: params.type } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } }); + + sdk.registerFunction("api::sketch-create", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.title) return { status_code: 400, body: { error: "title is required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-add", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sketchId || !body?.title) return { status_code: 400, body: { error: "sketchId and title are required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-add", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-promote", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-discard", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } }; + const result = await sdk.trigger({ function_id: "mem::sketch-discard", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } }); + + sdk.registerFunction("api::sketch-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const result = await sdk.trigger({ function_id: "mem::sketch-list", payload: { status: params.status, project: params.project } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } }); + + sdk.registerFunction("api::sketch-gc", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } }); + + sdk.registerFunction("api::crystallize", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.actionIds) return { status_code: 400, body: { error: "actionIds is required" } }; + const result = await sdk.trigger({ function_id: "mem::crystallize", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } }); + + sdk.registerFunction("api::crystal-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const limit = parseOptionalPositiveInt(params.limit); + if (limit === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: limit" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { project: params.project, sessionId: params.sessionId, limit } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } }); + + sdk.registerFunction("api::auto-crystallize", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::auto-crystallize", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } }); + + sdk.registerFunction("api::diagnose", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::diagnose", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } }); + + sdk.registerFunction("api::heal", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::heal", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } }); + + sdk.registerFunction("api::facet-tag", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.targetId || !body?.dimension || !body?.value) return { status_code: 400, body: { error: "targetId, dimension, and value are required" } }; + const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } }); + + sdk.registerFunction("api::facet-untag", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.targetId || !body?.dimension) return { status_code: 400, body: { error: "targetId and dimension are required" } }; + const result = await sdk.trigger({ function_id: "mem::facet-untag", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } }); + + sdk.registerFunction("api::facet-query", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const result = await sdk.trigger({ function_id: "mem::facet-query", payload: body || {} }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } }); + + sdk.registerFunction("api::facet-get", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + if (!params.targetId) return { status_code: 400, body: { error: "targetId query param is required" } }; + const result = await sdk.trigger({ function_id: "mem::facet-get", payload: { targetId: params.targetId } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } }); + + sdk.registerFunction("api::facet-stats", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const result = await sdk.trigger({ function_id: "mem::facet-stats", payload: { targetType: params.targetType } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } }); + + sdk.registerFunction("api::verify", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.id || typeof body.id !== "string") return { status_code: 400, body: { error: "id is required" } }; + const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: body.id } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } }); + + sdk.registerFunction("api::cascade-update", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") { + return { status_code: 400, body: { error: "supersededMemoryId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::cascade-update", payload: { supersededMemoryId: body.supersededMemoryId } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-save", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.content || typeof body.content !== "string") return { status_code: 400, body: { error: "content is required" } }; + const tags = typeof body.tags === "string" ? (body.tags as string).split(",").map((t: string) => t.trim()).filter(Boolean) : Array.isArray(body.tags) ? body.tags : []; + const result = (await sdk.trigger({ + function_id: "mem::lesson-save", + payload: { + content: body.content, + context: body.context || "", + confidence: typeof body.confidence === "number" ? body.confidence : undefined, + project: typeof body.project === "string" ? body.project : undefined, + tags, + source: "manual", + }, + })) as { action?: string }; + const statusCode = result?.action === "created" ? 201 : 200; + return { status_code: statusCode, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const minConfidence = parseOptionalFiniteNumber(params.minConfidence); + if (minConfidence === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: minConfidence" }, + }; + } + const limit = parseOptionalPositiveInt(params.limit); + if (limit === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: limit" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: { + project: params.project, + source: params.source, + minConfidence, + limit, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } }); + + sdk.registerFunction("api::lesson-search", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; + const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: body }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-strengthen", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.lessonId || typeof body.lessonId !== "string") return { status_code: 400, body: { error: "lessonId is required" } }; + const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: body.lessonId } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } }); + + sdk.registerFunction("api::lesson-delete", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + const lessonId = typeof body?.lessonId === "string" ? body.lessonId.trim() : ""; + if (!lessonId) return { status_code: 400, body: { error: "lessonId is required" } }; + const result = await sdk.trigger({ function_id: "mem::lesson-delete", payload: { lessonId } }); + const resp = result as { success?: boolean; error?: string }; + if (resp?.success === false && resp.error === "lesson not found") { + return { status_code: 404, body: { error: "lesson not found" } }; + } + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::lesson-delete", config: { api_path: "/agentmemory/lessons/delete", http_method: "POST" } }); + + sdk.registerFunction("api::obsidian-export", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = (req.body as Record<string, unknown>) || {}; + const vaultDir = asNonEmptyString(body.vaultDir); + if (!vaultDir) { + return { + status_code: 400, + body: { error: "vaultDir must be a non-empty string" }, + }; + } + const types = typeof body.types === "string" ? body.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined; + const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir, types } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } }); + + sdk.registerFunction("api::reflect", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = (req.body as Record<string, unknown>) || {}; + const result = await sdk.trigger({ function_id: "mem::reflect", payload: { + project: typeof body.project === "string" ? body.project : undefined, + maxClusters: typeof body.maxClusters === "number" ? body.maxClusters : undefined, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } }); + + sdk.registerFunction("api::insight-list", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const params = req.query_params || {}; + const minConfidence = parseOptionalFiniteNumber(params.minConfidence); + if (minConfidence === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: minConfidence" }, + }; + } + const limit = parseOptionalPositiveInt(params.limit); + if (limit === null) { + return { + status_code: 400, + body: { error: "invalid numeric parameter: limit" }, + }; + } + const result = await sdk.trigger({ function_id: "mem::insight-list", payload: { + project: params.project, + minConfidence, + limit, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } }); + + sdk.registerFunction("api::insight-search", async (req: ApiRequest) => { + const denied = checkAuth(req, secret); + if (denied) return denied; + const body = req.body as Record<string, unknown>; + if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } }; + const result = await sdk.trigger({ function_id: "mem::insight-search", payload: { + query: body.query, + project: typeof body.project === "string" ? body.project : undefined, + minConfidence: typeof body.minConfidence === "number" ? body.minConfidence : undefined, + limit: typeof body.limit === "number" ? body.limit : undefined, + } }); + return { status_code: 200, body: result }; + }); + sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } }); +} diff --git a/src/types.ts b/src/types.ts index c4b5410e05..b68d417e64 100644 --- a/src/types.ts +++ b/src/types.ts @@ -147,6 +147,7 @@ export interface SessionSummary { filesModified: string[]; concepts: string[]; observationCount: number; + lastObservationId?: string; } export type HookType = diff --git a/test/openai-count-tokens.test.ts b/test/openai-count-tokens.test.ts index b1f3cbd487..3ff8b0e2cd 100644 --- a/test/openai-count-tokens.test.ts +++ b/test/openai-count-tokens.test.ts @@ -35,6 +35,31 @@ describe("OpenAIProvider.countTokens", () => { await expect(provider.countTokens("hello")).rejects.toThrow(/404/); }); + + it("asks a server that answered 404 only once", async () => { + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(jsonResponse(404, { error: "no such route" })); + const provider = new OpenAIProvider("key", "gpt-4o", 4096, "https://api.openai.com"); + + await expect(provider.countTokens("hello")).rejects.toThrow(/404/); + await expect(provider.countTokens("again")).rejects.toThrow(/unavailable/); + + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it("keeps asking after a non-404 failure", async () => { + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(jsonResponse(500, { error: "boom" })) + .mockResolvedValueOnce(jsonResponse(200, { tokens: [1, 2] })); + const provider = new OpenAIProvider("key", "general", 4096, "http://broker:4010/v1"); + + await expect(provider.countTokens("hello")).rejects.toThrow(/500/); + await expect(provider.countTokens("hello")).resolves.toBe(2); + + expect(fetchSpy).toHaveBeenCalledTimes(2); + }); }); describe("ResilientProvider.countTokens", () => { diff --git a/test/summarize.test.ts b/test/summarize.test.ts index cd4b6e813e..f25f8a7cac 100644 --- a/test/summarize.test.ts +++ b/test/summarize.test.ts @@ -84,11 +84,14 @@ function makeObs(i: number, sessionId: string): CompressedObservation { }; } -// Fake count: every Observation is TOKENS_PER_OBS tokens, so a budget of -// PROMPT_OVERHEAD + n * TOKENS_PER_OBS packs exactly n Observations per chunk. +// Fake count: every Observation is TOKENS_PER_OBS tokens plus the separator +// the prompt spends on it, so a budget of PROMPT_OVERHEAD + n * (TOKENS_PER_OBS +// + SEPARATOR) packs exactly n Observations per chunk. const TOKENS_PER_OBS = 10; +const SEPARATOR = 4; const PROMPT_OVERHEAD = 400; -const budgetFor = (obsPerChunk: number) => String(PROMPT_OVERHEAD + obsPerChunk * TOKENS_PER_OBS); +const budgetFor = (obsPerChunk: number) => + String(PROMPT_OVERHEAD + obsPerChunk * (TOKENS_PER_OBS + SEPARATOR)); function makeProvider(responses: string[]): MemoryProvider & { calls: Array<{ system: string; user: string }>; @@ -540,6 +543,22 @@ describe("mem::summarize chunking", () => { expect((provider as any).calls.length).toBeGreaterThanOrEqual(2); }); + it("measures every Observation once, even across the summarize retry", async () => { + let counted = 0; + const provider = makeProvider(["garbage", summaryXml({ title: "second-attempt" })]); + provider.countTokens = async () => { + counted += 1; + return TOKENS_PER_OBS; + }; + const { handler } = await setupHandler({ sessionId: "ses_once", obsCount: 5, provider }); + + const result: any = await handler({ sessionId: "ses_once" }); + + expect(result.success).toBe(true); + expect(provider.calls).toHaveLength(2); + expect(counted).toBe(5); + }); + it("returns parse_failed only after both attempts fail", async () => { const provider = makeProvider([ "garbage one", @@ -564,7 +583,12 @@ describe("mem::summarize Session Summary reuse", () => { process.env = { ...ORIGINAL_ENV }; }); - async function withStoredSummary(sessionId: string, obsCount: number, storedCount: number) { + async function withStoredSummary( + sessionId: string, + obsCount: number, + storedCount: number, + storedLastId: string | null = `obs_${storedCount - 1}`, + ) { const provider = makeProvider([summaryXml({ title: "fresh" })]); const { handler, kv } = await setupHandler({ sessionId, obsCount, provider }); await kv.set("summaries", sessionId, { @@ -577,11 +601,12 @@ describe("mem::summarize Session Summary reuse", () => { filesModified: [], concepts: [], observationCount: storedCount, + ...(storedLastId === null ? {} : { lastObservationId: storedLastId }), }); return { handler, kv, provider }; } - it("returns the stored summary without calling the provider when its Observation count matches", async () => { + it("returns the stored summary without calling the provider when count and last Observation match", async () => { const { handler, provider } = await withStoredSummary("ses_cur", 10, 10); const result: any = await handler({ sessionId: "ses_cur" }); @@ -600,7 +625,28 @@ describe("mem::summarize Session Summary reuse", () => { expect(result.success).toBe(true); expect(result.summary.title).toBe("fresh"); expect(provider.calls).toHaveLength(1); - expect((await kv.get("summaries", "ses_stale") as any).observationCount).toBe(12); + const stored: any = await kv.get("summaries", "ses_stale"); + expect(stored.observationCount).toBe(12); + expect(stored.lastObservationId).toBe("obs_11"); + }); + + it("reproduces the summary when the count matches but the last Observation changed", async () => { + const { handler, provider } = await withStoredSummary("ses_swap", 10, 10, "obs_deleted"); + + const result: any = await handler({ sessionId: "ses_swap" }); + + expect(result.summary.title).toBe("fresh"); + expect(result.reused).toBeUndefined(); + expect(provider.calls).toHaveLength(1); + }); + + it("reproduces a summary stored before the last Observation id was recorded", async () => { + const { handler, provider } = await withStoredSummary("ses_old", 10, 10, null); + + const result: any = await handler({ sessionId: "ses_old" }); + + expect(result.summary.title).toBe("fresh"); + expect(provider.calls).toHaveLength(1); }); it("force: true calls the provider even when the summary is current", async () => {