Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@
# -----------------------------------------------------------------------------

# AGENTMEMORY_AUTO_COMPRESS=true # Run LLM compression on every observation batch (requires a provider key). Default off — synthetic compression handles most cases.
# AGENTMEMORY_INJECT_CONTEXT=true # Inject recalled memories back into agent prompts (#143). Default off — hooks capture observations but do not modify conversation.
# AGENTMEMORY_INJECT_CONTEXT=true # Inject recalled memories at SessionStart and PreToolUse (#143). Default off.
# AGENTMEMORY_PROMPT_RECALL=true # Inject up to 5 compact memories on each UserPromptSubmit in Claude Code and Codex. Independent from AGENTMEMORY_INJECT_CONTEXT; default off.
# CONSOLIDATION_ENABLED=true # Run the 4-tier consolidation pipeline (memories → semantic → procedural). Default off — opt in once you've measured the LLM cost.
# CONSOLIDATION_DECAY_DAYS=30 # Age (days) after which non-reinforced memories decay during consolidation
# GRAPH_EXTRACTION_ENABLED=true # Extract concept-graph edges on remember; powers the graph-traversal recall path
Expand Down
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ case "memory_your_tool": {
### Hook Scripts
Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout:

- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time.
- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix.
- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`, and opt-in `prompt-submit`) write recalled context to stdout for the host to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time. `prompt-submit` may write only when `AGENTMEMORY_PROMPT_RECALL=true`; its observation POST remains concurrent and fail-open.
- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`, plus `prompt-submit` when prompt recall is disabled) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix.

## Coding Standards

Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1477,6 +1477,12 @@ Create `~/.agentmemory/.env`:
# log only per Claude Code docs)
# Observations are still captured via
# PostToolUse regardless of this flag.
# AGENTMEMORY_PROMPT_RECALL=false # OFF by default. When on, the
# UserPromptSubmit hook injects up to
# 5 compact memories into each Claude
# Code or Codex prompt. Independent
# from AGENTMEMORY_INJECT_CONTEXT, so
# prompt recall can be enabled alone.
# GRAPH_EXTRACTION_ENABLED=false
# CONSOLIDATION_ENABLED=false # on by default when an LLM provider is configured
# LESSON_DECAY_ENABLED=true
Expand Down
143 changes: 123 additions & 20 deletions plugin/scripts/prompt-submit.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,45 @@
#!/usr/bin/env node
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { basename, join } from "node:path";
import { execSync } from "node:child_process";
import { basename } from "node:path";
//#region src/hooks/_env.ts
let fileEnv;
function loadHookEnvFile() {
if (fileEnv) return fileEnv;
const vars = {};
const envPath = join(process.env["AGENTMEMORY_DATA_DIR"] || join(homedir(), ".agentmemory"), ".env");
if (!existsSync(envPath)) {
fileEnv = vars;
return vars;
}
try {
for (const line of readFileSync(envPath, "utf-8").split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIdx = trimmed.indexOf("=");
if (eqIdx === -1) continue;
const key = trimmed.slice(0, eqIdx).trim();
let value = trimmed.slice(eqIdx + 1).trim();
const quote = value[0] === "\"" || value[0] === "'" ? value[0] : "";
if (quote) {
const closeIdx = value.indexOf(quote, 1);
if (closeIdx !== -1) value = value.slice(1, closeIdx);
} else {
const commentIdx = value.indexOf(" #");
if (commentIdx !== -1) value = value.slice(0, commentIdx).trim();
}
vars[key] = value;
}
} catch {}
fileEnv = vars;
return vars;
}
/** Process env wins; hook subprocesses fall back to ~/.agentmemory/.env. */
function getHookEnv(key) {
return process.env[key] ?? loadHookEnvFile()[key];
}
//#endregion
//#region src/hooks/_project.ts
function resolveProject(cwd) {
const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
Expand All @@ -27,12 +66,68 @@ function isSdkChildContext(payload) {
if (!payload || typeof payload !== "object") return false;
return payload.entrypoint === "sdk-ts";
}
const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
const REST_URL = getHookEnv("AGENTMEMORY_URL") || "http://localhost:3111";
const SECRET = getHookEnv("AGENTMEMORY_SECRET") || "";
const PROMPT_RECALL_ENABLED = getHookEnv("AGENTMEMORY_PROMPT_RECALL") === "true";
const RECALL_LIMIT = 5;
const RECALL_TIMEOUT_MS = 500;
const MAX_TITLE_CHARS = 500;
const MAX_TYPE_CHARS = 80;
function authHeaders() {
const h = { "Content-Type": "application/json" };
if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
return h;
const headers = {
"Content-Type": "application/json",
"X-Agentmemory-Source": "prompt-hook"
};
if (SECRET) headers["Authorization"] = `Bearer ${SECRET}`;
return headers;
}
function sanitizeInline(value, maxChars) {
return value.replace(/[<>]/g, "").replace(/\s+/g, " ").trim().slice(0, maxChars);
}
async function recallContext(prompt, project, sessionId) {
if (!prompt.trim()) return "";
try {
const response = await fetch(`${REST_URL}/agentmemory/smart-search`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({
query: prompt,
limit: RECALL_LIMIT,
project,
includeLessons: false,
sessionId,
source: "prompt-hook"
}),
signal: AbortSignal.timeout(RECALL_TIMEOUT_MS)
});
if (!response.ok) return "";
const body = await response.json();
const lines = (Array.isArray(body.results) ? body.results.slice(0, RECALL_LIMIT) : []).flatMap((item) => {
if (typeof item.title !== "string") return [];
const title = sanitizeInline(item.title, MAX_TITLE_CHARS);
if (!title) return [];
const itemType = typeof item.type === "string" ? sanitizeInline(item.type, MAX_TYPE_CHARS) : "";
return [`-${itemType ? ` [${itemType}]` : ""} ${title}`];
});
if (lines.length === 0) return "";
return [
"<agentmemory-context>",
"Relevant memories recalled for this prompt:",
...lines,
"Use these as background context; verify details against the current workspace.",
"</agentmemory-context>"
].join("\n");
} catch {
return "";
}
}
function observePrompt(payload) {
fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify(payload),
signal: AbortSignal.timeout(3e3)
}).catch(() => {});
}
async function main() {
let input = "";
Expand All @@ -46,20 +141,28 @@ async function main() {
if (!data || typeof data !== "object") return;
if (isSdkChildContext(data)) return;
const sessionId = data.session_id || data.sessionId || "unknown";
fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({
hookType: "prompt_submit",
sessionId,
project: resolveProject(data.cwd),
cwd: data.cwd || process.cwd(),
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
data: { prompt: data.prompt ?? data.userPrompt }
}),
signal: AbortSignal.timeout(3e3)
}).catch(() => {});
setTimeout(() => process.exit(0), 500).unref();
const cwd = data.cwd || process.cwd();
const project = resolveProject(cwd);
const prompt = String(data.prompt ?? data.userPrompt ?? "");
observePrompt({
hookType: "prompt_submit",
sessionId,
project,
cwd,
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
data: { prompt }
});
const promptRecall = PROMPT_RECALL_ENABLED && process.env["COPILOT_PLUGIN_ROOT"] === void 0;
setTimeout(() => process.exit(0), promptRecall ? RECALL_TIMEOUT_MS + 250 : 500).unref();
if (!promptRecall) return;
const additionalContext = await recallContext(prompt, project, sessionId);
if (!additionalContext) return;
await new Promise((resolve) => {
process.stdout.write(JSON.stringify({ hookSpecificOutput: {
hookEventName: "UserPromptSubmit",
additionalContext
} }), () => resolve());
});
}
main().catch(() => process.exit(0));
//#endregion
Expand Down
3 changes: 2 additions & 1 deletion plugin/skills/agentmemory-config/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded.

<!-- AUTOGEN:env START - generated by scripts/skills/generate.ts, do not edit by hand -->
Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 35 recognized variables:
Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 36 recognized variables:

- `AGENTMEMORY_AGENT_SCOPE`
- `AGENTMEMORY_ALLOW_AGENT_SDK`
Expand All @@ -27,6 +27,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_MCP_BLOCK`
- `AGENTMEMORY_PROBE_TIMEOUT_MS`
- `AGENTMEMORY_PROJECT_NAME`
- `AGENTMEMORY_PROMPT_RECALL`
- `AGENTMEMORY_PROVIDER`
- `AGENTMEMORY_REFLECT`
- `AGENTMEMORY_SDK_CHILD`
Expand Down
5 changes: 3 additions & 2 deletions plugin/skills/agentmemory-config/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ Enable richer memory and set a provider key in `~/.agentmemory/.env`:
```env
ANTHROPIC_API_KEY=sk-ant-...
AGENTMEMORY_AUTO_COMPRESS=true
AGENTMEMORY_INJECT_CONTEXT=true
AGENTMEMORY_PROMPT_RECALL=true
```

## Defaults worth knowing

- No API key is required. Without one, agentmemory runs zero-LLM with BM25 plus local embeddings.
- Token-spending features ship OFF on purpose: `AGENTMEMORY_AUTO_COMPRESS` (LLM summaries) and `AGENTMEMORY_INJECT_CONTEXT` (auto context injection) both cost tokens proportional to tool-use frequency.
- Token-spending features ship OFF on purpose: `AGENTMEMORY_AUTO_COMPRESS` (LLM summaries), `AGENTMEMORY_INJECT_CONTEXT` (SessionStart/PreToolUse injection), and `AGENTMEMORY_PROMPT_RECALL` (compact per-prompt recall for Claude Code/Codex).
- `AGENTMEMORY_PROMPT_RECALL=true` can be enabled alone; it injects at most 5 compact memories per `UserPromptSubmit` and does not enable the other injection hooks.
- Tool visibility: `AGENTMEMORY_TOOLS=all` (default) or `core` for the lean set.
- Auth: set `AGENTMEMORY_SECRET` to require `Authorization: Bearer` on the REST API.

Expand Down
4 changes: 2 additions & 2 deletions plugin/skills/agentmemory-hooks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ Watch observations land live at `http://localhost:3113`.

- Session start and end frame each unit of work and let `handoff` resume it.
- Tool-use hooks capture what changed and why, the raw material for `recall` and `recap`.
- Prompt-submit captures intent. Pre-compact preserves context before the host trims it.
- Prompt-submit captures intent. With `AGENTMEMORY_PROMPT_RECALL=true`, the same hook proactively injects up to 5 compact memories into each Claude Code or Codex prompt. Pre-compact preserves context before the host trims it.
- A post-commit hook links commits to sessions, which powers `commit-context` and `commit-history`.

## Important

- Capture is on by default and is zero-LLM. Turning observations into LLM summaries (`AGENTMEMORY_AUTO_COMPRESS`) and injecting them back into context (`AGENTMEMORY_INJECT_CONTEXT`) are separate opt-ins because they spend tokens.
- Capture is on by default and is zero-LLM. LLM summaries (`AGENTMEMORY_AUTO_COMPRESS`), SessionStart/PreToolUse injection (`AGENTMEMORY_INJECT_CONTEXT`), and proactive prompt recall (`AGENTMEMORY_PROMPT_RECALL`) are separate opt-ins because they spend tokens.
- If observations are missing, confirm the plugin is enabled and the server is running. See ../_shared/TROUBLESHOOTING.md.

## See also
Expand Down
7 changes: 7 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,13 @@ export function isContextInjectionEnabled(): boolean {
return getMergedEnv()["AGENTMEMORY_INJECT_CONTEXT"] === "true";
}

// Prompt-time recall is a separate, lower-volume injection mode for hosts
// that support UserPromptSubmit (Claude Code and Codex). It is OFF by default
// and can be enabled without SessionStart or PreToolUse injection.
export function isPromptRecallEnabled(): boolean {
return getMergedEnv()["AGENTMEMORY_PROMPT_RECALL"] === "true";
}

export function getConsolidationDecayDays(): number {
return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);
}
Expand Down
7 changes: 4 additions & 3 deletions src/functions/smart-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,16 +224,17 @@ export function registerSmartSearchFunction(
);

// #771: followup-rate diagnostic. Only fires for agent-initiated
// searches that carry a sessionId — viewer-originated searches
// (source === "viewer") and direct-sdk callers without a session
// anchor are skipped. The result-set comparison uses obsIds: a
// searches that carry a sessionId — viewer and automatic prompt-hook
// searches, plus direct-sdk callers without a session anchor, are
// skipped. The result-set comparison uses obsIds: a
// disjoint set under the window suggests the previous call's
// results were not used, which is our directional proxy for
// reader-failure-with-evidence.
if (
data.sessionId &&
typeof data.sessionId === "string" &&
data.source !== "viewer" &&
data.source !== "prompt-hook" &&
compact.length > 0
) {
// Skip detection when retrieval returned nothing: an empty
Expand Down
48 changes: 48 additions & 0 deletions src/hooks/_env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";

let fileEnv: Record<string, string> | undefined;

function loadHookEnvFile(): Record<string, string> {
if (fileEnv) return fileEnv;

const vars: Record<string, string> = {};
const dataDir = process.env["AGENTMEMORY_DATA_DIR"] || join(homedir(), ".agentmemory");
const envPath = join(dataDir, ".env");
if (!existsSync(envPath)) {
fileEnv = vars;
return vars;
}

try {
for (const line of readFileSync(envPath, "utf-8").split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIdx = trimmed.indexOf("=");
if (eqIdx === -1) continue;

const key = trimmed.slice(0, eqIdx).trim();
let value = trimmed.slice(eqIdx + 1).trim();
const quote = value[0] === '"' || value[0] === "'" ? value[0] : "";
if (quote) {
const closeIdx = value.indexOf(quote, 1);
if (closeIdx !== -1) value = value.slice(1, closeIdx);
} else {
const commentIdx = value.indexOf(" #");
if (commentIdx !== -1) value = value.slice(0, commentIdx).trim();
}
vars[key] = value;
}
} catch {
// Hooks must fail open when the optional env file cannot be read.
}

fileEnv = vars;
return vars;
}

/** Process env wins; hook subprocesses fall back to ~/.agentmemory/.env. */
export function getHookEnv(key: string): string | undefined {
return process.env[key] ?? loadHookEnvFile()[key];
}
Loading