Skip to content
Merged
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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Current Stats (v0.9.28)

- 53 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all)
- 128 REST endpoints
- 129 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 15 skills
- 260+ iii functions
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1498,7 +1498,7 @@ Create `~/.agentmemory/.env`:

<h2 id="api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-api.svg"><img src="assets/tags/section-api.svg" alt="API" height="32" /></picture></h2>

128 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.
129 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.

<details>
<summary>Key endpoints</summary>
Expand Down
9 changes: 9 additions & 0 deletions docs/recipes/pairings.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ Recipe with agentmemory:

This is the broadest sweep across artifacts that live alongside the code. agentmemory then captures everything the agent does while exploring that graph — the questions you asked, the conclusions, the decisions — so the next session opens with both the graph and the conversation history available.

agentmemory can also import the graph directly. With `GRAPH_EXTRACTION_ENABLED=true`:

```bash
curl -X POST localhost:3111/agentmemory/graph/import-graphify \
-H 'content-type: application/json' -d '{"cwd": "'"$PWD"'"}'
```

This merges Graphify's structural entities and relationships (with their EXTRACTED/INFERRED confidence carried over as edge weight) into agentmemory's knowledge graph, so graph retrieval and context injection see codebase structure the developer never touched in a session. Re-importing after `graphify update .` merges instead of duplicating.

## How the four projects line up

Four planes, four consumers, four update models. None of them try to do what the others do.
Expand Down
12 changes: 12 additions & 0 deletions integrations/filesystem-watcher/watcher.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,18 @@ export class FilesystemWatcher {
const failures = [];
for (const root of this.roots) {
try {
// Validate the root before handing it to fs.watch: on Linux with
// Node 24+, fs.watch on a nonexistent path no longer throws
// synchronously, so a missing root would otherwise count as
// "attached" and be watched-in-name-only. An explicit stat keeps
// the failure deterministic across Node versions and platforms.
const st = statSync(root, { throwIfNoEntry: false });
if (!st) {
throw new Error("no such directory");
}
if (!st.isDirectory()) {
throw new Error("not a directory");
}
const handle = watch(
root,
{ recursive: true, persistent: true },
Expand Down
17 changes: 0 additions & 17 deletions plugin/scripts/session-end.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,6 @@ async function main() {
body: JSON.stringify({ sessionId }),
signal: AbortSignal.timeout(3e4)
}).catch(() => {});
if (process.env["CONSOLIDATION_ENABLED"] === "true") {
fetch(`${REST_URL}/agentmemory/crystals/auto`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({ olderThanDays: 0 }),
signal: AbortSignal.timeout(6e4)
}).catch(() => {});
fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({
tier: "all",
force: true
}),
signal: AbortSignal.timeout(12e4)
}).catch(() => {});
}
if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, {
method: "POST",
headers: authHeaders(),
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,12 +3,13 @@
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`
- `AGENTMEMORY_AUTO_COMPRESS`
- `AGENTMEMORY_COMMIT_SHA`
- `AGENTMEMORY_CONSOLIDATION_COOLDOWN_MS`
- `AGENTMEMORY_COPILOT_MCP_BLOCK`
- `AGENTMEMORY_CWD`
- `AGENTMEMORY_DATA_DIR`
Expand Down
3 changes: 2 additions & 1 deletion plugin/skills/agentmemory-rest-api/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run `
<!-- AUTOGEN:rest START - generated by scripts/skills/generate.ts, do not edit by hand -->
The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). When `AGENTMEMORY_SECRET` is set, send `Authorization: Bearer $AGENTMEMORY_SECRET`; localhost is otherwise open.

117 registered endpoints:
118 registered endpoints:

| Method | Path |
| --- | --- |
Expand Down Expand Up @@ -52,6 +52,7 @@ The REST API is the primary surface. All paths are under `http://localhost:3111`
| DELETE | `/agentmemory/governance/memories` |
| POST | `/agentmemory/graph/build` |
| POST | `/agentmemory/graph/extract` |
| POST | `/agentmemory/graph/import-graphify` |
| POST | `/agentmemory/graph/query` |
| POST | `/agentmemory/graph/reset` |
| POST | `/agentmemory/graph/snapshot-rebuild` |
Expand Down
7 changes: 7 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import { renderSplash } from "./cli/splash.js";
import { isFirstRun, readPrefs, resetPrefs, writePrefs } from "./cli/preferences.js";
import { runOnboarding } from "./cli/onboarding.js";
import { setBootVerbose } from "./logger.js";
import { hydrateProcessEnvFromFile } from "./config.js";
import { VERSION } from "./version.js";
import { getAllTools, ESSENTIAL_TOOLS } from "./mcp/tools-registry.js";
import { knownAgents } from "./cli/connect/index.js";
Expand All @@ -83,6 +84,12 @@ setBootVerbose(IS_VERBOSE);

const IS_RESET = args.includes("--reset");

// Fold ~/.agentmemory/.env into process.env before any port/URL read
// (getRestPort/getBaseUrl/getStreamPort/getEnginePort) or the --port /
// --instance / --tools handlers below. Only-if-unset, so a real
// process.env value — including one just set by a CLI flag — still wins.
Comment on lines +87 to +90

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove explanatory implementation comments from TypeScript source files.

  • src/cli.ts#L87-L90: Remove the hydration-order implementation comment.
  • src/config.ts#L25-L30: Remove the cache implementation comment.
  • src/config.ts#L62-L65: Remove the test-hook implementation comment.
  • src/config.ts#L74-L79: Remove the hydration implementation comment.
  • src/config.ts#L348-L351: Remove the snapshot-timer implementation comment.
  • src/config.ts#L451-L455: Remove the consolidation-cooldown implementation comment.

As per coding guidelines, **/*.{ts,tsx} must “avoid code comments that explain what the code does.”

📍 Affects 2 files
  • src/cli.ts#L87-L90 (this comment)
  • src/config.ts#L25-L30
  • src/config.ts#L62-L65
  • src/config.ts#L74-L79
  • src/config.ts#L348-L351
  • src/config.ts#L451-L455
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/cli.ts` around lines 87 - 90, Remove the explanatory implementation
comments at src/cli.ts lines 87-90 and src/config.ts lines 25-30, 62-65, 74-79,
348-351, and 451-455, while leaving the surrounding behavior and code unchanged.

Source: Coding guidelines

hydrateProcessEnvFromFile();

// --version / -V early exit. Print VERSION + exit before any side effects
// (engine boot, env load, dir mkdir). `-v` is taken by --verbose so we
// reserve `-V` (capital) for version per POSIX convention.
Expand Down
196 changes: 196 additions & 0 deletions src/cli/connect/guidelines.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";

// Activating memory for agents that have no auto-capture hooks: write a short
// "use the memory tools" guideline into each agent's native rules mechanism so
// the agent proactively calls memory_recall / memory_save. Paths + formats are
// verified against each agent's OFFICIAL docs (cited per entry below). Claude
// Code / Codex are omitted here: they already auto-capture via lifecycle hooks.

const START = "<!-- agentmemory:start -->";
const END = "<!-- agentmemory:end -->";

const GUIDELINE_BODY = `## Agent memory (agentmemory)

You have persistent long-term memory via the agentmemory MCP server. Tools: \`memory_recall\`, \`memory_smart_search\`, \`memory_save\`, \`memory_sessions\`.

- At the START of a task, call \`memory_recall\` (or \`memory_smart_search\`) with the task context to load relevant past decisions, fixes, and preferences before asking the user to repeat anything.
- When you learn something durable (a decision, a fix, a gotcha, a user preference, a project convention), call \`memory_save\` to persist it.
- Prefer recalling over re-deriving, and save concise reusable facts rather than transcripts.`;

// "block" -> upsert a marked block inside a shared instructions file
// "mdc" -> Cursor project rule: dedicated .mdc with alwaysApply frontmatter
// "steering" -> Kiro steering file: dedicated .md with inclusion:always frontmatter
// "rule" -> dedicated always-on markdown rule file (own file, safe to own)
type GuidelineFormat = "block" | "mdc" | "steering" | "rule";

type GuidelineTarget = {
// Preferred user-global rules file (absolute). Omitted when the agent has no
// clean global rules FILE (UI-only or project-scoped), forcing the project
// fallback. Global is preferred so memory activates across all repos.
globalPath?: string;
// Project fallback, relative to cwd.
projectPath: string;
format: GuidelineFormat;
scope: "global" | "project";
source: string; // official doc URL the path/format was verified against
};

export function guidelineTargets(
home: string = homedir(),
): Record<string, GuidelineTarget> {
return {
// No global rules FILE (User Rules are UI-only) -> project .cursor/rules/*.mdc
cursor: {
projectPath: join(".cursor", "rules", "agentmemory.mdc"),
format: "mdc",
scope: "project",
source: "https://cursor.com/docs/rules",
},
// Cline's global rules dir is a non-standard ~/Documents path; the dedicated
// project rule (no frontmatter = always active) is the verified stable form.
cline: {
projectPath: join(".clinerules", "agentmemory.md"),
format: "rule",
scope: "project",
source: "https://docs.cline.bot/customization/cline-rules",
},
// Continue does not auto-read AGENTS.md; rules live in .continue/rules/*.md.
continue: {
projectPath: join(".continue", "rules", "00-agentmemory.md"),
format: "rule",
scope: "project",
source: "https://docs.continue.dev/customize/deep-dives/rules",
},
zed: {
globalPath: join(home, ".config", "zed", "AGENTS.md"),
projectPath: "AGENTS.md",
format: "block",
scope: "global",
source: "https://zed.dev/docs/ai/instructions",
},
// Warp global Rules are UI-managed (no file path) -> project AGENTS.md.
warp: {
projectPath: "AGENTS.md",
format: "block",
scope: "project",
source: "https://docs.warp.dev/agent-platform/capabilities/rules",
},
kiro: {
globalPath: join(home, ".kiro", "steering", "agentmemory.md"),
projectPath: join(".kiro", "steering", "agentmemory.md"),
format: "steering",
scope: "global",
source: "https://kiro.dev/docs/steering",
},
"gemini-cli": {
globalPath: join(home, ".gemini", "GEMINI.md"),
projectPath: "GEMINI.md",
format: "block",
scope: "global",
source: "https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/gemini-md.md",
},
qwen: {
globalPath: join(home, ".qwen", "QWEN.md"),
projectPath: "QWEN.md",
format: "block",
scope: "global",
source: "https://github.com/QwenLM/qwen-code/blob/main/docs/users/features/memory.md",
},
opencode: {
globalPath: join(home, ".config", "opencode", "AGENTS.md"),
projectPath: "AGENTS.md",
format: "block",
scope: "global",
source: "https://opencode.ai/docs/rules",
},
droid: {
globalPath: join(home, ".factory", "AGENTS.md"),
projectPath: "AGENTS.md",
format: "block",
scope: "global",
source: "https://docs.factory.ai/cli/configuration/agents-md",
},
// Antigravity does NOT read AGENTS.md; global rules live in ~/.gemini/GEMINI.md.
antigravity: {
globalPath: join(home, ".gemini", "GEMINI.md"),
projectPath: join(".agents", "rules", "agentmemory.md"),
format: "block",
scope: "global",
source: "https://antigravity.google/docs/rules-workflows",
},
"copilot-cli": {
globalPath: join(home, ".copilot", "copilot-instructions.md"),
projectPath: join(".github", "copilot-instructions.md"),
format: "block",
scope: "global",
source:
"https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-custom-instructions",
},
};
}

function renderDedicated(format: GuidelineFormat): string {
if (format === "mdc") {
return `---\ndescription: agentmemory long-term memory usage\nalwaysApply: true\n---\n\n${GUIDELINE_BODY}\n`;
}
if (format === "steering") {
return `---\ninclusion: always\n---\n\n${GUIDELINE_BODY}\n`;
}
// plain dedicated rule (Cline / Continue)
return `${GUIDELINE_BODY}\n`;
}

// Insert or replace the marked block in a shared instructions file, preserving
// any surrounding user content. Idempotent: re-running updates only our block.
function upsertBlock(existing: string): string {
const block = `${START}\n${GUIDELINE_BODY}\n${END}`;
const startIdx = existing.indexOf(START);
const endIdx = existing.indexOf(END);
if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
return (
existing.slice(0, startIdx) + block + existing.slice(endIdx + END.length)
);
}
// Malformed marker state: a lone or reversed marker. Appending here would
// let a later run pair the orphan marker with the appended block's twin and
// cut the user's content between them. Leave the file untouched.
if (startIdx !== -1 || endIdx !== -1) {
return existing;
}
const sep = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
const lead = existing.length === 0 ? "" : "\n";
return `${existing}${sep}${lead}${block}\n`;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

export type GuidelineResult =
| { kind: "written"; path: string; scope: string; source: string }
| { kind: "unchanged"; path: string; scope: string }
| { kind: "would-write"; path: string; scope: string }
| { kind: "no-target" };

export function writeGuideline(
agentName: string,
opts: { cwd: string; home?: string; dryRun?: boolean } = { cwd: process.cwd() },
): GuidelineResult {
const home = opts.home ?? homedir();
const target = guidelineTargets(home)[agentName];
if (!target) return { kind: "no-target" };

const path = target.globalPath ?? join(opts.cwd, target.projectPath);
const dedicated = target.format !== "block";

const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
const next = dedicated ? renderDedicated(target.format) : upsertBlock(existing);

if (existing === next) {
return { kind: "unchanged", path, scope: target.scope };
}
if (opts.dryRun) {
return { kind: "would-write", path, scope: target.scope };
}
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, next, "utf8");
return { kind: "written", path, scope: target.scope, source: target.source };
Comment on lines +193 to +195

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 5 '\brecordAudit\s*\(' src
rg -n -C 4 '\b(writeFileSync|writeFile|renameSync|rename)\s*\(' src/cli

Repository: rohitg00/agentmemory

Length of output: 50376


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file outline =="
ast-grep outline src/cli/connect/guidelines.ts --view expanded || true

echo "== relevant file ranges =="
sed -n '1,260p' src/cli/connect/guidelines.ts
sed -n '260,420p' src/cli/connect/guidelines.ts

echo "== function references =="
rg -n -C 3 'function|const|async|export|recordAudit|guidelines|writeFileSync|mkdirSync|audit' src/cli/connect/guidelines.ts

Repository: rohitg00/agentmemory

Length of output: 11579


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== writes outside src/functions outside guidelines.ts =="
python3 - <<'PY'
import pathlib, re
root = pathlib.Path("src")
for p in sorted(root.rglob("*")):
    if p.is_file() and p.suffix in {".ts", ".tsx"}:
        if str(p) == "src/cli/connect/guidelines.ts":
            continue
        text = p.read_text(errors="replace")
        if any(expr in text for expr in ["writeFileSync", "writeFile(", "renameSync(", "rename("]):
            lines = text.splitlines()
            hits = [i for i,l in enumerate(lines,1) if any(expr in l for expr in ["writeFileSync", "writeFile(", "renameSync(", "rename("])]
            print(f"FILE {p}")
            for h in hits[:20]:
                # print context around first/write/rename occurrences
                lo=max(1,h-3); hi=min(len(lines),h+3)
                print(f"  line {h}:", lines[h-1].strip())
            print(f"  recordAudit count:", sum(1 for l in lines if re.search(r'\brecordAudit\s*\(', l)))
            print("  recordAudit present:", bool(re.search(r'\brecordAudit\s*\(', text)))
PY

echo "== file write calls in src/cli/connect/guidelines.ts =="
python3 - <<'PY'
import pathlib, re
p = pathlib.Path("src/cli/connect/guidelines.ts")
text = p.read_text(errors="replace")
for expr in ["writeFileSync", "writeFile(", "renameSync(", "rename("]:
    print(expr, expr in text)
print("recordAudit present:", bool(re.search(r'\brecordAudit\s*\(', text)))
PY

Repository: rohitg00/agentmemory

Length of output: 3544


Record the guideline file mutation.

writeGuideline() overwrites user rules files without logging after writeFileSync(). Add recordAudit() for successful guideline writes, or update the audit contract to explicitly exclude CLI configuration files.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/cli/connect/guidelines.ts` around lines 187 - 189, Update
writeGuideline() to call recordAudit() after writeFileSync() completes
successfully, recording the overwritten guideline file mutation while preserving
the existing return behavior; only revise the audit contract instead if CLI
configuration files are intentionally excluded.

Source: Coding guidelines

}
Loading