mirror of
https://github.com/rohitg00/agentmemory.git
synced 2026-09-14 20:16:33 +08:00
e8f410b537
* feat: v0.7.0 — lessons, tool visibility, auto-consolidation, obsidian export, npx bootstrap Five DX improvements based on competitive research against Mem0, Engram, CodeMem: 1. `npx agentmemory` zero-config startup - New CLI bootstrap (src/cli.ts) auto-detects and starts iii-engine - Tries `iii` binary first, falls back to `docker compose up -d` - Bundles iii-config.yaml and docker-compose.yml in dist/ 2. Simplified MCP tool surface (7 core tools by default) - AGENTMEMORY_TOOLS=all unlocks all 49 tools - Default: save, recall, consolidate, forget, sessions, diagnose, lesson_save - Call handler remains unfiltered — any tool callable by name 3. Auto-consolidation on session end - CONSOLIDATION_ENABLED defaults to true (was false) - Session-end hook: session/end → crystallize → consolidate → bridge sync - Consolidation pipeline always registered (timer gated by config) 4. First-class lesson memory type with confidence decay - Lesson interface: confidence (0-1), reinforcements, decayRate, source - 5 functions: lesson-save, lesson-recall, lesson-list, lesson-strengthen, lesson-decay-sweep - Dedup via SHA-256 fingerprint — duplicate saves strengthen existing - Crystal lessons auto-flow into lesson system at confidence 0.6 - Daily decay sweep with parallel KV writes 5. Obsidian-compatible Markdown export - Export to ~/.agentmemory/vault/ with YAML frontmatter + wikilinks - MOC.md (Map of Content) index file - Parallel KV reads, auto-export via OBSIDIAN_AUTO_EXPORT=true Stats: 49 MCP tools, 99 REST endpoints, 573 tests passing * docs: add AGENTS.md, fix tool/endpoint counts across README, plugin, cli - Create AGENTS.md with strict consistency rules for MCP tools, REST endpoints, versions, KV scopes, and audit operations - Fix MCP tool count: 38 → 41 across README.md (4 occurrences) - Fix REST endpoint count: 93/95 → 99 across README.md and index.ts - Fix plugin.json: version 0.6.1 → 0.7.0, tool count 5 → 41 - Fix cli.ts help text: 48+ → 41 MCP tools - Fix README api.ts path reference → triggers/api.ts * fix: address code review findings — consolidation guard, decay bug, async fs, export-import lessons Inline fixes: - Revert CONSOLIDATION_ENABLED to opt-in (=== "true"), matching original behavior - Add early-exit guard in consolidation-pipeline handler when disabled - Gate session-end crystallize+consolidation calls on CONSOLIDATION_ENABLED - Fix lesson decay over-decay bug: add lastDecayedAt to Lesson, compute incremental delta instead of reapplying full age every sweep run - Add LESSON_DECAY_ENABLED flag (default true) to gate the sweep timer Outside diff fixes: - Add lessons to export-import (export + import + replace cleanup) - Log warning instead of swallowing obsidian auto-export errors Nitpick fixes: - Switch obsidian-export to async fs/promises (mkdir, writeFile) - Add per-item try/catch in obsidian-export, return errors array - Replace governance_delete with smart_search in ESSENTIAL_TOOLS (non-destructive default) - Fix CLI whichBinary for Windows (uses "where" on win32) - Use dynamic port in CLI error message instead of hardcoded 3111 - Return 201 for newly created lessons, 200 for strengthened - Wrap lesson audit calls in try/catch so audit failure doesn't surface - Fix build script to not swallow tsdown failure - Remove exact tool count from test, use >=41 + uniqueness + required names - Add test/consistency.test.ts: validates version, tool count, README consistency - Add isConsolidationEnabled mock to consolidation-pipeline test 579 tests passing (573 original + 6 new consistency checks) * fix: guard remaining audit calls, correct endpoint count, add CI + npm publish Review fixes: - Wrap lesson_recall and lesson_strengthen audit calls in try/catch - Fix REST endpoint count: 99 → 100 (verified via grep) across index.ts, README.md, and AGENTS.md - Use regex in consistency test for README assertions (flexible phrasing) - Add consolidation gate tests: disabled returns early, force=true bypasses CI/CD: - Add .github/workflows/ci.yml — test on Node 18/20/22 - Add .github/workflows/publish.yml — auto-publish to npm on GitHub release (uses NPM_TOKEN secret + provenance) Nitpick: - Single-char term filter (t.length > 1) kept intentionally — prevents noise from single-letter matches; documented in AGENTS.md if needed 581 tests passing * fix(ci): add --legacy-peer-deps for zod v3/v4 peer conflict @anthropic-ai/claude-agent-sdk@0.2.56 requires zod@^4.0.0 as a peer dependency but the project uses zod@^3.23.0. The lock file resolves this locally but npm ci is strict about peer deps in CI. * fix(ci): drop Node 18 from matrix — tsdown requires Node 20+ tsdown/rolldown uses node:util.styleText which is only available in Node 20.12+. Updated engines field to >=20.0.0 to match. * fix(ci): add inlineOnly: false to tsdown config, target node20 tsdown errors on CI with "Consider adding inlineOnly option" when dependencies are bundled. Setting inlineOnly: false suppresses this. Also updated target from node18 to node20 to match engines field.
4.5 KiB
4.5 KiB
agentmemory — Agent Instructions
Architecture
agentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through registerFunction/registerTrigger/sdk.trigger() — never bypass iii-engine with standalone SQLite or in-process alternatives.
- Engine: iii-sdk (WebSocket to iii-engine on port 49134)
- State: File-based SQLite via iii-engine's StateModule (
./data/state_store.db) - Build: TypeScript → ESM via tsdown, output to
dist/ - Test: vitest (
npm testexcludes integration tests)
Consistency Rules
When adding or removing MCP tools, you MUST update ALL of the following:
src/mcp/tools-registry.ts— tool definition +getAllTools()arraysrc/mcp/server.ts— handler case in themcp::tools::callswitchsrc/triggers/api.ts— REST endpoint registrationsrc/index.ts— function registration + endpoint count in the log linetest/mcp-standalone.test.ts— tool count assertionREADME.md— tool counts (search for "MCP tools")plugin/.claude-plugin/plugin.json— tool count in description
When adding REST endpoints, you MUST update:
src/triggers/api.ts— endpoint registrationsrc/index.ts— endpoint count in the log lineREADME.md— endpoint count (search for "REST endpoints" and "endpoints on port")
When bumping version, you MUST update ALL of the following:
package.json— version fieldsrc/version.ts— VERSION constant and type unionsrc/types.ts— ExportData version unionsrc/functions/export-import.ts— supportedVersions settest/export-import.test.ts— version assertionplugin/.claude-plugin/plugin.json— version field
When adding new KV scopes:
src/state/schema.ts— add to the KV objectsrc/types.ts— add the corresponding interface
When adding new audit operations:
src/types.ts— add to AuditEntry.operation union type
Code Patterns
Function Registration
sdk.registerFunction(
{ id: "mem::your-function" },
async (data: { ... }) => {
// validate inputs
// do work via kv.get/kv.set/kv.list
// record audit via recordAudit()
return { success: true, ... };
},
);
REST Endpoint Registration
sdk.registerFunction({ id: "api::your-endpoint" }, async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
// validate + whitelist fields (never pass raw body to sdk.trigger)
const result = await sdk.trigger("mem::your-function", { ... });
return { status_code: 200, body: result };
});
sdk.registerTrigger({
type: "http",
function_id: "api::your-endpoint",
config: { api_path: "/agentmemory/your-path", http_method: "POST" },
});
MCP Tool Handler
case "memory_your_tool": {
// validate args with typeof checks
// parse CSV args: args.field.split(",").map(t => t.trim()).filter(Boolean)
const result = await sdk.trigger("mem::your-function", { ... });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };
}
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. Always use try/catch with AbortSignal.timeout() for best-effort calls.
Coding Standards
- TypeScript, ESM only (
"type": "module") - No code comments explaining WHAT — use clear naming instead
- Use
fingerprintId()for content-addressable dedup,generateId()for unique IDs - Parallel operations where possible (
Promise.allfor independent kv writes/reads) - Input validation at system boundaries (MCP handlers, REST endpoints)
- 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
Testing
- All tests must pass before PR:
npm test(573+ tests) - Mock pattern:
vi.mock("iii-sdk")with mocksdk.trigger,kv.get/set/list - Test files go in
test/with.test.tsextension - Follow existing patterns in
test/crystallize.test.tsfor function tests
Current Stats (v0.7.0)
- 41 MCP tools (7 visible by default,
AGENTMEMORY_TOOLS=allfor all) - 100 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 4 skills
- 50+ iii functions
- 573 tests