agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

OpenClaw plugin: agent_end observe broken (missing project/cwd, raw-path project, zombie active sessions)

Open cbsincool opened this issue 4 months ago • 6 comments

Summary

The OpenClaw integration plugin (integrations/openclaw/plugin.mjs on main, agentmemory 0.9.27) has three related defects in its agent_end turn-capture path:

  1. The agent_end observe payload omits required project/cwd → server returns 400, silently swallowed → OpenClaw turns are never persisted.
  2. When project is supplied, it's the raw cwd path, not the git basename → cross-agent recall fragments (Claude Code writes basename).
  3. mem::observe itself creates an active session record when the sessionId is new, and the plugin has no close path → active sessions accumulate forever on the dashboard.

The Claude Code plugin (plugin/scripts/post-tool-use.mjs) does all of this correctly and is the reference. Local install verified byte-identical to main (217 lines), so this is upstream, not an install problem.


Defect 1 — agent_end observe omits project/cwd → 400 silently swallowed

plugin.mjs, agent_end hook:

await client.postJson("/agentmemory/observe", {
  hookType: "post_tool_use",
  sessionId,
  timestamp: new Date().toISOString(),
  data: { tool_name: "conversation", tool_input: ..., tool_output: ... },
});

Missing project and cwd. Server (mem::observe) requires both as non-empty strings:

400 {"error":"hookType, sessionId, project, cwd, and timestamp are required strings"}

And postJson swallows it:

if (!res.ok) {
  if (fallbackOnError) return null;   // ← 400 swallowed, no warn, no log
}

So the failure is invisible — turns never persist, no signal to the user.

Evidence:

# plugin's shape (no project/cwd) → 400
$ curl -X POST .../observe -d '{"hookType":"post_tool_use","sessionId":"s","timestamp":"...","data":{...}}'
{"error":"hookType, sessionId, project, cwd, and timestamp are required strings"}
# with project/cwd → 201
{"observationId":"obs_..."}

Defect 2 — project written as raw cwd path, not git basename → cross-agent recall fragments

Even after fixing #1, if project is the raw cwd path (e.g. D:\projects\claudecodetest), it won't match Claude Code's project value, which is the git toplevel basename (claudecodetest) via resolveProject(cwd). mem::context (the recall path Claude Code uses on session start) filters strictly:

// dist/index.mjs, registerContextFunction
const sessions = (await kv.list(KV.sessions))
  .filter(s => s.project === data.project && s.id !== data.sessionId)   // strict ===

So Claude Code (tag claudecodetest) never recalls OpenClaw turns tagged with the full path, and vice versa. AGENT_ID/AGENTMEMORY_AGENT_SCOPE does not help — that's an orthogonal (agent-role) dimension; mem::context filters only on project. Confirmed: store had the same project fragmented into claudecodetest (9 sessions, Claude Code) and D:\projects\claudecodetest (32, an agent using the raw path).

Defect 3 — mem::observe creates an active session; no close path → zombie accumulation

Server-side, mem::observe upserts a session when one doesn't yet exist for the sessionId:

// dist/index.mjs, mem::observe
const existingSession = await kv.get(KV.sessions, payload.sessionId);
if (existingSession) { /* update observationCount */ }
else if (project && cwd) {
  await kv.set(KV.sessions, payload.sessionId, {
    ..., status: "active", observationCount: 1, ...   // ← created as active
  });
}

Each OpenClaw run uses a new sessionId → observe creates a new active session. The OpenClaw plugin has no session_end to close it (see background), so they accumulate. Not a data-loss bug, but the dashboard fills with stale active sessions.


Background: OpenClaw's hook surface (why session_start/session_end don't help)

The README documents the design as just two hooks — before_agent_start (recall) + agent_end (capture turns) — and explicitly calls this "the working integration path." That's the intended design; session-lifecycle hooks are not part of it.

plugin.yaml declares four hooks (on_session_start/on_pre_llm_call/on_post_tool_use/on_session_end), but (a) plugin.mjs only implements two of them, and (b) the declared names use an on_ prefix that doesn't match the SDK's session_start/session_end (per PLUGIN_HOOK_NAMES in hook-types-*.d.ts), so the declaration is inert. The stale yaml should be fixed or removed regardless.

I also tested whether adding session_end/session_start hooks would close sessions: with debug markers, before_agent_start and agent_end fire every turn, but session_start and session_end never fire in local/CLI mode — not on launch, not on graceful exit. The shutdown drain in session-reset-service (SHUTDOWN_DRAIN_DEFAULT_TOTAL_TIMEOUT_MS = 2000, fire-and-forget runSessionEnd(...).catch(...)) doesn't reach plugin hooks in this mode. So a session_start/session_end-based fix does not work; the zombie cleanup has to ride on agent_end.


Suggested fix

1. agent_end observe: add project/cwd, resolve project as git basename (mirror Claude Code's resolveProject).

import { execSync } from "node:child_process";
import { basename } from "node:path";

function resolveProject(cwd) {
  const explicit = process.env.AGENTMEMORY_PROJECT_NAME;
  if (explicit && explicit.trim()) return explicit.trim();
  const dir = cwd && cwd.trim() ? cwd : process.cwd();
  try {
    const top = execSync("git rev-parse --show-toplevel", {
      cwd: dir, stdio: ["ignore", "pipe", "ignore"], timeout: 500,
    }).toString().trim();
    if (top) return basename(top);
  } catch {}
  return basename(dir) || dir;
}

// in agent_end:
const cwd = process.cwd();                    // agent_end event has no cwd field
const project = resolveProject();
await client.postJson("/agentmemory/observe", {
  hookType: "post_tool_use", sessionId, project, cwd,
  timestamp: new Date().toISOString(),
  data: { tool_name: "conversation", tool_input: ..., tool_output: ... },
});

Note: PluginHookAgentEndEvent carries only { runId, messages, success, error, durationMs } — no cwd/project. The cwd is on PluginHookAgentContext.workspaceDir (passed via ctx, not the event) and on the before_agent_finalize event. So agent_end must fall back to process.cwd() + git basename; it's only correct if OpenClaw is launched from the project root. Surfacing workspaceDir/cwd on the agent_end event upstream (in OpenClaw) would let plugins avoid the guess.

2. Scope caveat for any session_end handler: if one is added for modes that do dispatch it, it cannot reference baseUrl/secret/timeoutMs/fallbackOnError directly — those are locals inside createClient(cfg, api), and register(api) only has client. A handler written with the bare names throws ReferenceError: baseUrl is not defined on every fire; openclaw's runSessionEnd(...).catch() swallows it → silent zombie accumulation (the exact dashboard-fills-with-active symptom). Use client.postJson(path, body), which has all four in its closure.

3. Zombie cleanup on agent_end (since session_end isn't dispatched). Reap leftover active sessions whenever the sessionId changes (new session / restart), keeping the current one. Once per sessionId, not per turn:

let __lastReapedSid = null;  // resets each OpenClaw launch (fresh module import)
// in agent_end, after the observe:
if (sessionId !== __lastReapedSid) {
  __lastReapedSid = sessionId;
  try {
    const authH = process.env.AGENTMEMORY_SECRET ? { Authorization: `Bearer ${process.env.AGENTMEMORY_SECRET}` } : {};
    const res = await fetch(`${client.baseUrl}/agentmemory/sessions?limit=200`, {
      headers: authH, signal: AbortSignal.timeout(cfg.timeout_ms || 5000),
    });
    if (res.ok) {
      const data = await res.json();
      const sessions = Array.isArray(data) ? data : (data.sessions || data.data || []);
      const zombies = sessions.filter((s) => s && s.status === "active" && s.id && s.id !== sessionId);
      await Promise.all(zombies.map((s) => client.postJson("/agentmemory/session/end", { sessionId: s.id })));
    }
  } catch (e) { /* best-effort; never block the agent */ }
}

Verified: after this, restarting OpenClaw no longer accumulates active sessions — the first agent_end of each run reaps the previous run's leftover; the dashboard shows just the current session. Caveat: the current session stays active until the next run reaps it (no session_end to close it on exit) — at most 1 leftover, not unbounded growth.

4. plugin.yaml: fix the stale 4-hook declaration (drop the on_ prefix to match the SDK, or remove it entirely since only before_agent_start/agent_end are implemented by design).


Environment

  • agentmemory server: 0.9.27 (iii-engine 0.11.2), Docker
  • OpenClaw plugin: integrations/openclaw/plugin.mjs from main (217 lines, local == main)
  • mem::observe impl: dist/index.mjs ~line 3662; mem::context ~line 5113; api::session::end ~line 15914
  • Remote deployment (server on a LAN IP, AGENTMEMORY_SECRET set) — but the 400 and the zombie behavior reproduce identically against loopback; they're unconditional.

Happy to open a PR covering defects 1–3.

cbsincool avatar Jul 14 '26 02:07 cbsincool

Update — the project value matters too, not just presence.

After fixing the missing-field 400, I hit a second issue: how project is resolved. If the OpenClaw plugin (or any agent) writes project as the raw cwd path — e.g. D:\projects\claudecodetest — while the Claude Code plugin writes the git toplevel basename — claudecodetest — memories for the same project fragment into two tags. mem::context filters sessions strictly:

// dist/index.mjs, registerContextFunction
const sessions = (await kv.list(KV.sessions))
  .filter(s => s.project === data.project && s.id !== data.sessionId)   // strict ===

So Claude Code (tag claudecodetest) never recalls OpenClaw/Hermes turns tagged with the full path, and vice versa. AGENT_ID / AGENTMEMORY_AGENT_SCOPE does not help here — that's an orthogonal (agent-role) dimension; mem::context filters only on project.

Suggested resolution for project (mirror the Claude Code plugin):

import { execSync } from "node:child_process";
import { basename } from "node:path";

function resolveProject(cwd) {
  const explicit = process.env.AGENTMEMORY_PROJECT_NAME;
  if (explicit && explicit.trim()) return explicit.trim();
  const dir = cwd && cwd.trim() ? cwd : process.cwd();
  try {
    const top = execSync("git rev-parse --show-toplevel", {
      cwd: dir, stdio: ["ignore", "pipe", "ignore"], timeout: 500,
    }).toString().trim();
    if (top) return basename(top);
  } catch {}
  return basename(dir) || dir;
}

One wrinkle specific to OpenClaw: PluginHookAgentEndEvent carries only { runId, messages, success, error, durationMs } — no cwd/project field (confirmed in hook-types-*.d.ts). The cwd is on PluginHookAgentContext.workspaceDir (passed via ctx, not the event) and on the before_agent_finalize event. So agent_end must fall back to process.cwd() + git basename, which is only correct if OpenClaw is launched from the project root. A cleaner fix upstream would be to surface workspaceDir/cwd on the agent_end event so plugins don't have to guess.

Summary of what the patch needs: (1) add project + cwd to the observe payload (the original 400 fix), AND (2) resolve project via resolveProject() so the value is the git basename, matching Claude Code — otherwise multi-agent recall stays fragmented even after the 400 is fixed.

cbsincool avatar Jul 14 '26 03:07 cbsincool

Update 2 — session lifecycle hooks are unimplemented too; sessions linger as "active" forever.

Beyond the observe/project issues above, integrations/openclaw/plugin.mjs only registers two hooks:

api.on("before_agent_start", ...)   // recall
api.on("agent_end", ...)            // write turn

But plugin.yaml declares four:

hooks:
  - on_session_start
  - on_pre_llm_call
  - on_post_tool_use
  - on_session_end

So session_start and session_end are never implemented (and the declared names use the on_ prefix, which doesn't match the SDK's session_start/session_end in PLUGIN_HOOK_NAMES, so the yaml declaration is inert anyway). The Claude Code plugin has a session-end.mjs script and closes sessions cleanly; the OpenClaw plugin doesn't, so every OpenClaw run creates a session via the agent_end observe path but nothing ever marks it ended. They accumulate as status: "active" on the dashboard.

Concretely, after normal use I had 13 sessions stuck active in the store; manually calling POST /agentmemory/session/end {sessionId} on each cleared them.

The server side is fine — api::session::end (/agentmemory/session/end) exists and only needs sessionId. The plugin just never calls it.

Suggested fix — register a session_end hook (and ideally session_start to call /agentmemory/session/start, which also gates the mem::context recall path that OpenClaw currently bypasses by doing smart-search in before_agent_start):

api.on("session_end", async (event) => {
  if (!cfg.enabled) return;
  const sessionId = event?.sessionId || event?.sessionKey || event?.runId;
  if (!sessionId) return;
  try {
    await fetch(`${baseUrl}/agentmemory/session/end`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...(secret ? { Authorization: `Bearer ${secret}` } : {}) },
      body: JSON.stringify({ sessionId }),
      signal: AbortSignal.timeout(timeoutMs),
    });
  } catch (e) { if (!fallbackOnError) throw e; }
});

Summary of the full OpenClaw plugin gap (all in integrations/openclaw/plugin.mjs on main):

  1. agent_end observe omits required project/cwd → 400, silently swallowed (original issue).
  2. project written as raw cwd path, not git basename → fragments recall across agents that use basename (Claude Code).
  3. session_end unimplemented → zombie active sessions accumulate; session_start also missing.

Happy to open a PR covering all three.

cbsincool avatar Jul 14 '26 06:07 cbsincool

Update 3 (revised) — session_end needs the client's closure; openclaw doesn't actually dispatch session_start/session_end in local/CLI mode, so reap on agent_end instead.

Two practical notes for whoever implements session close upstream:

1. Watch the scope. The obvious api.on("session_end", ...) registered inside register(api) cannot reference baseUrl/secret/timeoutMs/fallbackOnError directly — those are locals inside createClient(cfg, api), and register(api) only has client (the { postJson, baseUrl } it returns). A handler written with the bare names throws ReferenceError: baseUrl is not defined on every fire; openclaw's runSessionEnd(...).catch() swallows it, so the session is never closed and you get silent zombie accumulation. Use client.postJson(path, body) instead, which already has all four in its closure.

2. openclaw does NOT dispatch session_start/session_end in local/CLI mode — so a session_start reaper won't run. (This revises my original Update 3 suggestion.) I tested this with debug markers: before_agent_start and agent_end fire every turn, but session_start and session_end never fire — neither on launch nor on graceful exit. The shutdown drain in session-reset-service (SHUTDOWN_DRAIN_DEFAULT_TOTAL_TIMEOUT_MS = 2000, fire-and-forget runSessionEnd(...).catch(...)) does not reach plugin hooks in this mode. So neither a session_start reaper nor a session_end closer actually runs. (A session_end handler is still worth including for the modes/gateway variants that do dispatch it, with the scope fix from #1.)

Corrected fix — reap on agent_end (fires every turn), once per process via a module-level flag:

let __reaped = false;  // resets each openclaw launch (fresh module import)
// inside agent_end, after the observe:
if (!__reaped) {
  __reaped = true;
  try {
    const authH = process.env.AGENTMEMORY_SECRET ? { Authorization: `Bearer ${process.env.AGENTMEMORY_SECRET}` } : {};
    const res = await fetch(`${client.baseUrl}/agentmemory/sessions?limit=200`, {
      headers: authH, signal: AbortSignal.timeout(cfg.timeout_ms || 5000),
    });
    if (res.ok) {
      const data = await res.json();
      const sessions = Array.isArray(data) ? data : (data.sessions || data.data || []);
      const zombies = sessions.filter((s) => s && s.status === "active" && s.id && s.id !== sessionId);
      await Promise.all(zombies.map((s) => client.postJson("/agentmemory/session/end", { sessionId: s.id })));
    }
  } catch (e) { /* best-effort; never block the agent */ }
}

Verified: after this, restarting openclaw no longer accumulates active sessions — the first agent_end of each launch reaps the previous run's leftover; the dashboard shows just the current session. Caveat: the current session stays active until the next launch reaps it (no session_end to close it on exit), which is acceptable — at most 1 leftover, not unbounded growth.

cbsincool avatar Jul 14 '26 07:07 cbsincool

Cross-reference: the Hermes plugin does this correctly — OpenClaw can't, due to its hook surface

For whoever fixes this upstream: the Hermes integration (integrations/hermes/__init__.py) is a complete, correct reference — it has the full session lifecycle that OpenClaw's plugin is missing. Comparing the three defects:

Lifecycle step Hermes plugin OpenClaw plugin
Session create initialize() → explicit POST /session/start with sessionId+project+cwd (none) — observe auto-creates an active session as a side effect
Turn capture sync_turn() → POST /observe with project+cwd ✓ agent_end → POST /observe missing project+cwd → 400 (Defect 1)
Session close on_session_end() → POST /session/end ✓ (none) → zombie accumulation (Defect 3)
project value os.path.basename(cwd) ✓ raw cwd path (Defect 2)

Hermes code, for reference:

def initialize(self, session_id, **kwargs):
    self._project = os.path.basename(kwargs.get("cwd") or os.getcwd())
    _api(self._base, "session/start", {
        "sessionId": session_id, "project": self._project, "cwd": self._project,
    })

def sync_turn(self, user, assistant, **kwargs):
    _api_bg(self._base, "observe", {
        "hookType": "post_tool_use", "sessionId": ..., "project": self._project, "cwd": self._project,
        "timestamp": ..., "data": {...},
    })

def on_session_end(self, messages, **kwargs):
    _api(self._base, "session/end", {"sessionId": kwargs.get("session_id", self._session_id)})

Why Hermes is fine and OpenClaw isn't — the plugin mechanism differs

  • Hermes is a Python memory provider plugin. The Hermes framework actively calls lifecycle callbacks at well-defined points: initialize (session start) → sync_turn (each turn) → on_session_end (session end). All three exist, the official plugin wires each to the matching agentmemory endpoint, so there's no 400, no zombie, no project fragmentation. (I only had to patch one line locally — os.path.basename(cwd) was already there in the official version; the official version actually uses os.path.basename already, good.)

    Correction/clarification: the official Hermes plugin already uses os.path.basename(kwargs.get("cwd") or os.getcwd()) for project — i.e. it already does the right thing. No patch needed on the Hermes side.

  • OpenClaw is a JS hook plugin. OpenClaw only dispatches before_agent_start + agent_end (the README states this is the intended design — "the working integration path"). There is no session-lifecycle callback in OpenClaw's plugin contract, so the official OpenClaw plugin has nowhere to call /session/start or /session/end. That's the structural reason for Defects 1 and 3 — not an oversight in one plugin file, but a gap between OpenClaw's hook surface and what a memory backend needs.

Implication for the fix

The cleanest upstream fix is the Hermes shape: OpenClaw would need session-lifecycle hooks (session_start/session_end, dispatched in local/CLI mode — currently they aren't) so the plugin can call /session/start + /session/end explicitly. plugin.yaml already declares on_session_start/on_session_end, but (a) the names don't match the SDK (session_start/session_end, no on_ prefix) and (b) OpenClaw doesn't dispatch them in local mode (tested with debug markers — they never fire). So either OpenClaw dispatches them, or the plugin falls back to the agent_end reap workaround in the issue body.

Either way, Defect 1 (observe missing project/cwd) and Defect 2 (project = raw path, not basename) are fixable in plugin.mjs today regardless of the hook-surface gap — those are the must-fix ones. Defect 3 (zombie) is best-effort until OpenClaw dispatches session lifecycle hooks.

cbsincool avatar Jul 14 '26 08:07 cbsincool

Confirming on OpenClaw 2026.7.2-beta.7 + @agentmemory/agentmemory 0.9.28 (npm), Linux/Node 22: every agent_end observe from the plugin 400s with

{"error":"hookType, sessionId, project, cwd, and timestamp are required strings"}

and because the plugin swallows errors (fallback_on_error), the store silently stays at observations: 0 with nothing in any log — the failure is only visible by curling /agentmemory/export or posting an observe by hand. Adding project + a per-agent cwd to the observe POST returns HTTP 201 and captures flow normally.

Related current-version reports: #1159 (REST shims also drop agentId on this same endpoint), #1161 (the recall half of the plugin never fires on current OpenClaw — before_agent_start isn't a typed plugin hook there).

benjaml4 avatar Aug 06 '26 10:08 benjaml4

Confirming all defects on server 0.9.29 + the bundled OpenClaw plugin (OpenClaw 2026.7.1, macOS, Node 22.9). Local install of the plugin was byte-identical to main — everything below reproduces upstream, not a fork.

Adding one finding on top of the issue body, plus a fix that worked better in practice than the "reap on sessionId change" approach suggested in defect 3.

The sessionId itself is the root cause of the zombie sessions

PluginHookAgentEndEvent carries no stable session identity at all — only runId, which is a fresh UUID per run. The plugin's fallback chain therefore resolves to event.runId, so:

  • every single agent turn creates a brand-new active session on the server (exactly the "each OpenClaw run uses a new sessionId" symptom from defect 3), and
  • each of those sessions holds exactly 1 observation.

The stable identity does exist: it's on the hook's second argument ctx: PluginHookAgentContext, as ctx.sessionKey (e.g. agent:main:octo:<bot>:direct:<userId> — constant for the whole conversation, matches what OpenClaw's own session/control UI shows) and ctx.sessionId.

Fix used (patched the plugin locally)

api.on("agent_end", async (event, ctx) => {
  // ...
  const sessionId =
    ctx?.sessionKey ||
    ctx?.sessionId ||
    event.sessionId ||
    event.sessionKey ||
    event.runId ||
    `openclaw-${Date.now()}`;
  await client.postJson("/agentmemory/observe", {
    hookType: "post_tool_use",
    sessionId,
    project: ctx?.agentId || "openclaw",   // short stable string, not a raw path
    cwd: ctx?.workspaceDir || process.cwd(),
    timestamp: new Date().toISOString(),
    data: { /* ... */ },
  });
});

For the close path, session_end is a typed OpenClaw plugin hook (contrary to the "session_end isn't dispatched" note in the issue — it fires with reasons new | reset | idle | daily | compaction | deleted | shutdown | restart):

api.on("session_end", async (event) => {
  if (event?.reason === "compaction") return; // compaction keeps the session running
  const sessionId = event?.sessionKey || event?.sessionId;
  if (!sessionId) return;
  await client.postJson("/agentmemory/session/end", { sessionId });
});

Why this beats reap-on-change

Keying captures on ctx.sessionKey means the server only ever sees one long-lived session per real conversation — no garbage sessions are created in the first place, so nothing needs reaping. session/end then legitimately fires on idle/daily/reset/shutdown, driving summarize + graph-extract + the consolidation pipeline (with its cooldown) as designed.

Verified end-to-end: after applying, the dashboard went from 17 single-observation sessions to exactly 1 active session (the real conversation), observations accumulating per turn, and session/end closing it cleanly on reset/shutdown.

One caveat worth noting upstream: POST /agentmemory/session/start is an upsert that resets observationCount to 0, so the plugin deliberately does NOT call session/start — observe's auto-create is the safer path, and a gateway restart that resumes an existing session would otherwise wipe its counter.

Happy to upstream this as a PR against integrations/openclaw/plugin.mjs if wanted.

a652 avatar Aug 25 '26 08:08 a652