Skip to content

Latest commit

 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Code Memory

Symbol-level experience tracking for AI coding agents.

Record what went wrong (and what worked) at the function/class level. Next time you touch that symbol, past lessons get injected into the agent's context — so it doesn't repeat the same mistakes.

$ cm.py -p myproject fail AuthService.validate "JWT expiry not handled" --file auth/service.py
x 기록: AuthService.validate - "JWT expiry not handled" (누적 실패 4회)

$ cm.py -p myproject query AuthService.validate
  AuthService.validate
  실패: 4  성공: 1  위험도: 11.20 (주의)
  주의 - 실패 4회. 과거 교훈 주입 권장.

  experiences (5):
    x [2026-07-24] #12 JWT expiry not handled
      - check refresh_token before validate
    x [2026-07-23] #10 timezone-naive datetime comparison
    x [2026-07-22] #9 empty string token not guarded
    ok [2026-07-24] #13 passed after UTC normalization

Why

AI coding agents (Claude Code, Codex, Cursor, Hermes, etc.) are stateless between sessions. They fix the same bug, hit the same edge case, and re-learn the same project quirk every time.

Code Memory is a dead-simple persistent layer: one SQLite file, one Python script. No MCP server, no npm, no embeddings, no LLM calls for storage. The agent's own skill/prompt system handles injection.

If a function reaches risk_score >= 10, the agent should know before it touches it.


Design Principles

  1. SQLite file + Python script. Nothing else. No server, no daemon, no network.
  2. Not every log is an experience. Only record when there's a lesson.
  3. Memory must change behavior. Query results get injected into prompts — not just stored.
  4. Lightweight first. Add complexity only after data accumulates.

Quick Start

# Clone
git clone https://github.com/reezex0-ux/code-memory.git
cd code-memory

# No install needed — it's one file
python3 cm.py --help

Record a failure

python3 cm.py -p myproject fail Payment.process "race condition on double-charge" \
  --detail "add SELECT FOR UPDATE before INSERT" \
  --file "payment/processor.py"

Record a success

python3 cm.py -p myproject ok Payment.process "idempotency key solved double-charge"

Query before editing

python3 cm.py -p myproject query Payment.process

Generate an injection block

python3 cm.py -p myproject query Payment.process --file "payment/processor.py" --inject

JSON output

python3 cm.py -p myproject query Payment.process --json

See what's risky

python3 cm.py -p myproject query --top 10

Project stats

python3 cm.py -p myproject stats

CLI Reference

cm.py [-p PROJECT] [--json] COMMAND

Commands:
  query [SYMBOL]          Look up active experiences for a symbol (partial match).
                          Without SYMBOL: show top risky symbols (--top N).
  fail SYMBOL LESSON      Record a failure. Use --detail for context.
  ok SYMBOL [LESSON]      Record a success.
  resolve EXPERIENCE_ID   Mark a lesson resolved.
  deactivate EXPERIENCE_ID Mark a lesson inactive.
  stats [SYMBOL]          Show project summary or single symbol detail.

Options:
  -p, --project      Project name (default: "default")
  --json             JSON output. Available on every command.
  --detail, -d       Extra context for fail/ok
  --file             Source file path. Used with project+symbol as the identifier.
  --session          Session ID for traceability
  --top N            Number of top risky symbols to show (default: 10)
  --all              query only: include resolved/inactive lessons
  --inject           query only: print prompt-ready active lessons when risk_score >= 10

Data Model

Two tables. That's it.

symbols (
    project, file, name,      -- UNIQUE(project, file, name); file defaults to ""
    fail_count, success_count,
    last_fail, last_success,
    risk_score
)

experiences (
    symbol_id, type ('fail'|'success'),
    lesson,          -- one line
    detail,          -- optional context
    session_id,      -- traceability
    status,          -- 'active'|'resolved'|'inactive'
    created_at
)

SQLite is opened with WAL mode and a 5-second busy timeout. Migrations run in an explicit transaction and set PRAGMA user_version = 2 after a successful v0.3 upgrade.

--file values are normalized before lookup and storage: backslashes become slashes, ./ and ../ segments are collapsed, leading ./ is removed, and absolute paths are stored relative to the current working directory. For example, src/auth.py, ./src/auth.py, src\auth.py, and .\src\auth.py identify the same symbol file.

lesson and detail are automatically redacted for common API key/token patterns before storage.


Agent Integration

Code Memory is designed to be called by AI coding agents via their skill/prompt system.

Workflow

┌─────────────────────────────────────────────────┐
│  Before editing                                  │
│  1. Identify target symbol (e.g. Class.method)  │
│  2. cm.py query <symbol> --file <path>          │
│  3. If risk_score >= 10: use --inject and paste │
│     the coding prompt / Codex task              │
├─────────────────────────────────────────────────┤
│  After editing                                   │
│  4. Run tests / verify result                   │
│  5. cm.py fail <symbol> "<cause>" (if failed)   │
│     cm.py ok <symbol> "<note>"   (if passed)    │
└─────────────────────────────────────────────────┘

Prompt injection format

When risk_score >= 10, query --inject prints active lessons in this format:

[PAST EXPERIENCE — AuthService.validate (risk: 11.20, 주의)]
- JWT expiry not handled
- timezone-naive datetime
- empty string token

Apply these lessons. Do not repeat these mistakes.

Hermes Agent Integration

A skill file is included for Hermes Agent integration. It instructs the agent to automatically query before code edits and record outcomes after.

The skill runs cm query before code work and records the result afterwards with cm fail or cm ok.

Option A: Copy to skills directory

mkdir -p ~/.hermes/skills/software-development/code-memory
cp skills/code-memory.md ~/.hermes/skills/software-development/code-memory/SKILL.md

Option B: Symlink

mkdir -p ~/.hermes/skills/software-development/code-memory
ln -s $(pwd)/skills/code-memory.md ~/.hermes/skills/software-development/code-memory/SKILL.md

For other agents such as Claude Code or Codex, manually add the workflow from skills/code-memory.md to CLAUDE.md, AGENTS.md, or the agent's equivalent project instructions.


When to Record (and When Not To)

Record

  • Test failure occurred
  • Same fix failed 2+ times
  • Root cause clearly identified
  • Regression bug
  • User explicitly said "wrong approach"
  • Verified solution passed
  • Discovered project-specific rule

Don't Record

  • Routine command execution logs
  • Transient network errors
  • LLM hallucinations / guesses
  • Trivial one-off fixes with no reusable lesson

Risk Levels

v0.3 (current)

Risk score is recalculated on every fail, ok, resolve, and deactivate:

risk_score = fail_count * 1.0
           + recency_weight * 1.5
           + consecutive_fails * 1.5
           - success_count * 0.3

fail_count, success_count, last_fail, last_success, and consecutive_fails are based on active experiences only. resolved and inactive experiences are excluded after resolve or deactivate, so a symbol's risk drops when old lessons stop applying.

recency_weight is 1.0 for an active failure within 7 days, 0.5 within 30 days, and 0.2 after that. consecutive_fails is the number of active fail experiences after the last active success, or all active failures if there has never been an active success. The score is floored at 0.

risk_score Level Action
0-4 낮음 No injection unless explicitly useful
5-9 보통 Read active lessons before editing
10-14 주의 Use query --inject before editing
15+ 높음 Treat as high-risk; inject lessons and verify carefully

v3 (planned, with code graph)

Add impact analysis (caller count, dependency depth) via CodeGraph integration.


Roadmap

Phase Scope Status
1 cm.py — query / fail / ok / stats. SQLite. Skill file. ✅ Done
2 JSON output, prompt injection, composite identifiers, lesson status, risk scoring, pytest coverage. ✅ Done
3 Transactional migration, path normalization, Hermes installation docs, concurrency tests. ✅ Done
4 CodeGraph integration (call graph → impact score). Multi-project dashboard. Planned

What This Is NOT

Not this Because
A code knowledge graph Use CodeGraph or Serena for that
A vector memory / RAG system No embeddings. Exact symbol match + SQL LIKE.
An MCP server It's a CLI. Your agent's skill system calls it.
A general agent memory Use agentmemory for session/preference memory
Automatic The agent (or you) calls cm.py explicitly. No watchers, no hooks.

Inspiration

  • ExpeRepair — Dual-memory (episodic + semantic) for LLM-based program repair. Code Memory's experiences table is the episodic layer; merged lessons become the semantic layer.
  • agentmemory — Consolidation and lesson decay patterns.
  • CodeGraph — Pre-indexed code knowledge graph. Future Phase 3 integration target for impact scoring.

Requirements

  • Python 3.9+ (stdlib only — sqlite3, argparse, json, datetime)
  • No pip install. No dependencies.

License

MIT

About

코드 심볼 단위 경험 학습 — 실패 기록→교훈 주입. SQLite 1개 + Python 스크립트 1개.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages