@gorkemblm/agent-ctx
v1.0.2
Published
File-based autonomous memory protocol for AI coding assistants — minimizes token cost, prevents context bloat.
Maintainers
Readme
agent-ctx
File-based autonomous memory protocol for AI coding assistants.
Problem
AI assistants (Claude Code, Codex, DeepClaude) lose context across sessions. They re-read thousands of lines of source code to re-discover project structure, wasting tokens and increasing time-to-first-token. Active tasks, architectural decisions, and tooling knowledge evaporate when the context window compacts.
Solution
agent-ctx provides a local .ctx/ directory — RAM and hard disk for the AI. Six clean markdown files, managed by the AI (five) and the user (one):
architecture.md— tech stack, project map, code standardsplan.md— active tasks, blockers, current stateinstructions.md— user preferences and per-project rules (user-owned)history.md— completed features with decisions (stack-ordered, newest top, last ~15 entries)history-digest.md— compacted summaries of older history (one line per entry, read first)tools.md— run, test, and automation commands
The AI reads lazily, writes with Edit-only discipline, and auto-cleans completed work. Plan.md stays lean. History auto-compacts. Context never bloats.
Key features:
- Tool-specific rule files —
CLAUDE.mdfor Claude/DeepClaude,AGENTS.mdfor Codex (mapped viaTOOL_RULE_FILE) - User preference memory —
.ctx/instructions.mdfor per-project rules and preferences ("always write tests", "prefer async/await"). Read on every startup. AI proposes additions, user confirms — no auto-edit. .gitignoreintegration —.ctx/is automatically added to.gitignoreoninit,index, and daily (when auto-creating.ctx/)- Auto-launch indexing —
indexcommand writes the rule file and launches the tool in non-interactive mode, prompting it to index immediately - Proactive status on launch — daily driver and
initpass an initial status prompt as positional argument, so the AI reads plan.md and reports current tasks on first turn without waiting for user input .ctx/version tracking —.ctx/.versionfile enables future-proof migration; warns on mismatch and auto-upgrades- Tiered history compaction — history.md auto-compacts when it reaches 15 entries: oldest 5 are summarized to one-line digests in
history-digest.md, raw entries deleted. LLM reads digest first (~30 tokens/entry), drills into raw history only when needed - Rich
statuscommand — offline.ctx/overview: plan progress per group, recent history, architecture freshness, token estimates - Better error resilience — scanner skips unreadable log files and directories gracefully, reports specific paths
Requirements
- Node.js >= 18
- A supported AI tool installed: Claude Code, Codex, or DeepClaude
Install
npm (recommended):
npm install -g @gorkemblm/agent-ctxcurl:
curl -fsSL https://raw.githubusercontent.com/gorkemblm/agent-ctx/v1.0.2/install.sh -o install.sh
# inspect the script, then:
bash install.shFrom source:
git clone [email protected]:gorkemblm/agent-ctx.git
cd agent-ctx
npm link # makes 'agent-ctx' available globallyUsage
agent-ctx <tool> [command]Tools: claude | codex | deepclaude
Commands:
| Command | What it does |
|---------|--------------|
| (none) | Daily driver. Writes the rule file with the memory protocol and launches the tool interactively. If .ctx/ doesn't exist yet, auto-creates it (same as init). Use this every session — it figures out what's needed. |
| init | First-time setup. Creates .ctx/ with all 6 template files, adds .ctx/ to .gitignore, writes the rule file with the memory protocol, and launches the tool. |
| index | Project indexing. Like init but drops the AI into a one-shot indexing session. It reads every source file, config, and script to map the project into architecture.md and tools.md, then mines git log for past milestones to seed history.md. Non-interactive. Re-prompts if already indexed. The rule file auto-reverts to the daily protocol when the session ends. |
| usage | Token usage report. Scans local session logs (no API calls) and prints per-session token usage: input, output, cache reads, cache writes, and cache discard estimates. Includes per-session averages and peak session. |
| status | Project status. Reads .ctx/ locally (no AI launch) and prints a formatted summary: active plan tasks with progress, recent history entries, architecture doc age, .ctx/ version, and a one-line status. |
Claude Code note: agent-ctx launches Claude Code with
--permission-mode default. Claude Code's plan mode skips reading project rule files (includingCLAUDE.md), which would prevent.ctx/from being loaded at startup. The flag ensures the memory protocol always activates on every session.
Examples:
# First time in a project
agent-ctx claude init
# Every day after
agent-ctx claude
# Re-index after big refactors or when .ctx/ feels stale
agent-ctx claude index
# Check token spend
agent-ctx claude usage
# Quick project status
agent-ctx claude status
# Same flow, different tools
agent-ctx codex init
agent-ctx codex usageThe rule file written depends on the tool:
| Tool | Rule file |
|------|-----------|
| claude | CLAUDE.md |
| codex | AGENTS.md |
| deepclaude | CLAUDE.md |
Rule file ownership
agent-ctx takes full ownership of the rule file (CLAUDE.md or AGENTS.md). On first run (init, index, or daily), if the file already exists and does not contain the AGENT-CTX PROTOCOL marker, it is automatically backed up to <file>.bak and a notice is printed:
Existing CLAUDE.md backed up to CLAUDE.md.bak.
agent-ctx takes over CLAUDE.md — preferences in .ctx/instructions.md, project docs in .ctx/.If the file already contains our protocol, it is safely overwritten without a backup. This means:
- Before agent-ctx: your custom rule file → backed up to
.bak - After agent-ctx: rule file is managed by agent-ctx → your notes go in
.ctx/
The rule file works best when it contains only the agent-ctx protocol. Mixing custom instructions with the protocol can confuse the AI — it needs a single, clean source of truth for memory operations. Your project-specific preferences, conventions, and patterns belong in
.ctx/instructions.md. Project architecture and code standards belong in.ctx/architecture.md.
Protocol (what the AI sees)
A concise prompt (~1600 chars) injected as the tool's rule file governs all memory operations. The current date is dynamically prepended to the file on every write so the AI always has the right temporal context for research and tool/library decisions:
- Current date — today's date written at the top of the rule file on every launch; keeps the AI anchored to the present for API versions, library compatibility, and best practices
- Session startup — reads
plan.md,instructions.md,history.mdtop entry, andhistory-digest.mdtop 3; reports "Last session: X. Open: Y, Z. Next: [first incomplete task]" - Recovery — after compaction or context reset: re-read
plan.mdbefore doing anything else, resume from the first- [ ] - Priority-ordered plan — groups and tasks top-to-bottom; always first
- [ ]in first incomplete group; TaskCreate/TaskUpdate banned, all tasks inplan.md - Plan granularity — every task MUST have sub-tasks with concrete file-level actions and verify clauses ("Move X from A/ to B/ → verify: imports resolved, tests pass"); sub-tasks are the recovery map after compaction
- Doc sub-tasks — sub-tasks MUST include
.ctx/documentation updates when files are created, moved, renamed, or deleted. Doc entries are tracked sub-tasks, not afterthoughts. - Simplicity guard — no speculative features, single-use abstractions, or unrequested flexibility; if the implementation could be simpler, the AI surfaces it
- Tiered history —
history-digest.mdread first (one-line summaries, ~30 tokens/entry);history.mdonly when deeper context needed - History compaction — when
history.mdreaches 15 entries, the oldest 5 are auto-summarized tohistory-digest.mdand deleted from raw history (CLEANUP step 5) - Lazy read order —
plan.md, theninstructions.md(user preferences), then digest if historical context needed, others only when required - I/O discipline — always
Edit(exact match), neverWrite(overwrite risk); surgical: don't refactor adjacent code or improve unrelated formatting - Doc sync (UPDATE) — after creating, moving, renaming, or deleting any file, the AI checks UPDATE rules: new modules/deps →
architecture.md, new scripts/ports →tools.md. Both docs have equal weight with explicit sub-rules. - Stack-ordered history — newest entries prepended; never write directly (always via plan.md → CLEANUP)
- 3D history format — every entry captures
Built,Decisions, andFiles - Auto-cleanup with double-check — before a completed group is moved to history, two verifications run: (0) every
[x]sub-task is re-checked against its verify clause — if any check fails, it's unmarked and fixed; (1) doc audit ensures architecture.md and tools.md reflect all file changes. Only then does the group move to history.md. - User preferences —
instructions.mdis user-owned; AI reads on startup and follows the rules. When the user expresses a preference ("always X", "never Y"), the AI proposes adding it and waits for confirmation — no auto-edit - Bug-reopen flow — bugs on completed features re-open as
[Name] — Fix - User-visible signals — every
.ctx/modification emits a one-line[ctx]marker in the same turn, immediately after the edit, never batched:
[ctx] plan.md + "hash passwords with bcrypt 12 rounds"
[ctx] plan.md - "Fix login redirect" → history.md
[ctx] history.md + "Fix login redirect"
[ctx] architecture.md ~ "§2.5 Configuration"
[ctx] tools.md + "npm run migrate"
[ctx] instructions.md + "always write tests"Token usage
agent-ctx claude usage (or codex usage, agent-ctx deepclaude usage) scans local session logs and shows per-session token usage. No network, no API calls.
The scanner is provider-agnostic: claude reads Claude Code's per-project JSONL from ~/.claude/projects/, codex reads Codex's global event-driven JSONL from ~/.codex/sessions/. Each provider implements findProjectDir + parseLines. Adding a new tool means writing one provider file.
For parsing details, output columns, and cache semantics, see docs/token-usage.md.
.ctx/ token estimates
The status command estimates token counts from .ctx/ file sizes using tool-specific chars/token ratios. These differ because each model's tokenizer splits text differently:
| Tool | Ratio | Why |
|------|-------|-----|
| Claude Code | 3.5 | Claude tokenizer is slightly more token-hungry, especially on non-English text |
| Codex | 4.0 | GPT-4o o200k_base tokenizer is efficient for code and English |
| DeepClaude | 3.8 | DeepSeek tokenizer is code-optimized but slightly less efficient than GPT-4o |
These are conservative estimates for mixed code/English content. .ctx/ files written in Turkish or other agglutinative languages will consume more tokens than estimated — the ratios drop toward 2.5–3.2 for those languages.
Source structure
agent-ctx/
├── lib/
│ ├── agent-ctx.js — AgentCtx class: all logic, templates, protocol prompt
│ └── scanner/
│ ├── index.js — provider-agnostic token scanner (parse, dedup, aggregate)
│ ├── claude.js — Claude Code log provider (find directory, parse lines)
│ └── codex.js — Codex log provider (find directory, stateful parse lines)
├── bin/
│ └── agent-ctx.js — CLI entry point (init | index | usage | status | daily)
├── .github/
│ ├── workflows/ci.yml — CI: runs npm test on push/PR to master (Node 18)
│ └── copilot-instructions.md — Copilot code review guidelines
├── test/
│ └── agent-ctx.test.js — unit + CLI dispatch + usage tests
└── package.jsonTests
npm testUses Node.js built-in test runner (node:test). No extra dependencies.
Run with AGENT_CTX_NO_LAUNCH=1 to skip tool spawning during tests.
Supported tools
| Tool | Commands | Rule file |
|------|----------|-----------|
| Claude Code | agent-ctx claude [init\|index\|usage\|status] | CLAUDE.md |
| Codex | agent-ctx codex [init\|index\|usage\|status] | AGENTS.md |
| DeepClaude | agent-ctx deepclaude [init\|index\|usage\|status] | CLAUDE.md |
Feedback
agent-ctx is early and evolving. Found a rough edge? Have an idea? PRs and feedback are welcome — open an issue or drop a comment on the repo. Real-world usage is what sharpens this tool.
License
MIT
Co-authored-by: deepseek-v4-pro
