{"_id":"@atul-labs/dmag","_rev":"3-4b2ceb13d5fea87fc08f41b650a0eadd","name":"@atul-labs/dmag","dist-tags":{"latest":"0.2.4"},"versions":{"0.2.1":{"name":"@atul-labs/dmag","version":"0.2.1","keywords":["ai","coding","companion","skills","reasoning","tdd","debugging","memory","context","design","efficiency","claude","codex","cursor","windsurf","gemini","antigravity","browser-audit","headless","cdp","developer-tools"],"author":{"url":"https://github.com/pulak-ranjan","name":"pulak-ranjan"},"license":"Apache-2.0","_id":"@atul-labs/dmag@0.2.1","maintainers":[{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"}],"homepage":"https://github.com/ATUL-Labs/dmag","bugs":{"url":"https://github.com/ATUL-Labs/dmag/issues"},"bin":{"dmag":"bin/dmag.js","dmag-mcp":"bin/dmag-mcp.js"},"dist":{"shasum":"8f836d024ae71a45f4678586261ace80a756cabc","tarball":"https://registry.npmjs.org/@atul-labs/dmag/-/dmag-0.2.1.tgz","fileCount":226,"integrity":"sha512-VEq5ptAnb3SPIbFvBFofTWoIqSmm4nUtzI5K6zs8GSyqTShxf+5P4rZVv6ohnzoy4ljtKYXZ8WUgHAA4IjWvrw==","signatures":[{"sig":"MEQCIAlF1/xtt23MgsNnrPZgHJ+d+KhORxbKMwtDAIBI46F1AiBDo31W9846HhKuxxyzVHcwU74Id28rBDi7LMcgaI1fTQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1263454},"engines":{"node":">=22.5.0"},"gitHead":"390cd016273d0e507921a70c4459ae1b0e2e29ab","scripts":{"lint":"eslint bin lib scripts tests","test":"node scripts/test-all.js","check":"node bin/dmag.js guard","setup":"node bin/dmag.js init","start":"node bin/dmag.js serve","test:fast":"node --test tests/*.test.js","test:viewer":"node scripts/verify-viewer.js","prepublishOnly":"npm test && npm run lint && npm run check"},"_npmUser":{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"},"repository":{"url":"git+https://github.com/ATUL-Labs/dmag.git","type":"git"},"_npmVersion":"11.6.0","description":"Universal coding companion - reasoning, efficient code, design intelligence, project memory, crash recovery. LTS release.","directories":{},"_nodeVersion":"22.19.0","dependencies":{"lmdb":"^3.5.6","minisearch":"^7.2.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.0.0"},"_npmOperationalInternal":{"tmp":"tmp/dmag_0.2.1_1785858419029_0.15394432100267452","host":"s3://npm-registry-packages-npm-production"}},"0.2.2":{"name":"@atul-labs/dmag","version":"0.2.2","keywords":["ai","coding","companion","skills","reasoning","tdd","debugging","memory","context","design","efficiency","claude","codex","cursor","windsurf","gemini","antigravity","browser-audit","headless","cdp","developer-tools"],"author":{"url":"https://github.com/pulak-ranjan","name":"pulak-ranjan"},"license":"Apache-2.0","_id":"@atul-labs/dmag@0.2.2","maintainers":[{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"}],"homepage":"https://github.com/ATUL-Labs/dmag","bugs":{"url":"https://github.com/ATUL-Labs/dmag/issues"},"bin":{"dmag":"bin/dmag.js","dmag-mcp":"bin/dmag-mcp.js"},"dist":{"shasum":"bd94455ed5a0b4662bdbb195bf67cf430cc01647","tarball":"https://registry.npmjs.org/@atul-labs/dmag/-/dmag-0.2.2.tgz","fileCount":226,"integrity":"sha512-boIIaetFt1CLHJWUwMwQVpZf5yNK6I1j0MIs1DzDfCs5zsQLSh8sKZMZggkQxbpqZe2KTePBu0n9VHXa1Ojp5g==","signatures":[{"sig":"MEYCIQCL4yAPDGXaGuQEchHkOreUeOaGhWuH0Phn2oMuCY5TDwIhANxNB0svs+QukIG6Bw46QIsDpV06JV/QpYVzats/Dc0O","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1261865},"engines":{"node":">=22.5.0"},"gitHead":"b2d07269c0165e9beda2613045ef73efe41c3ead","scripts":{"lint":"eslint bin lib scripts tests","test":"node scripts/test-all.js","check":"node bin/dmag.js guard","setup":"node bin/dmag.js init","start":"node bin/dmag.js serve","test:fast":"node --test tests/*.test.js","test:viewer":"node scripts/verify-viewer.js","prepublishOnly":"npm test && npm run lint && npm run check"},"_npmUser":{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"},"repository":{"url":"git+https://github.com/ATUL-Labs/dmag.git","type":"git"},"_npmVersion":"11.6.0","description":"Universal coding companion - reasoning, efficient code, design intelligence, project memory, crash recovery. LTS release.","directories":{},"_nodeVersion":"22.19.0","dependencies":{"lmdb":"^3.5.6","minisearch":"^7.2.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.0.0"},"_npmOperationalInternal":{"tmp":"tmp/dmag_0.2.2_1785868097495_0.01386357936761029","host":"s3://npm-registry-packages-npm-production"}},"0.2.4":{"name":"@atul-labs/dmag","version":"0.2.4","description":"Universal coding companion - reasoning, efficient code, design intelligence, project memory, crash recovery. LTS release.","author":{"name":"pulak-ranjan","url":"https://github.com/pulak-ranjan"},"license":"Apache-2.0","bin":{"dmag":"bin/dmag.js","dmag-mcp":"bin/dmag-mcp.js"},"engines":{"node":">=22.5.0"},"scripts":{"test":"node scripts/test-all.js","test:fast":"node --test tests/*.test.js","test:viewer":"node scripts/verify-viewer.js","lint":"eslint bin lib scripts tests","check":"node bin/dmag.js guard","start":"node bin/dmag.js serve","setup":"node bin/dmag.js init","prepublishOnly":"npm test && npm run lint && npm run check"},"publishConfig":{"access":"public"},"devDependencies":{"eslint":"^9.0.0"},"repository":{"type":"git","url":"git+https://github.com/ATUL-Labs/dmag.git"},"homepage":"https://github.com/ATUL-Labs/dmag","keywords":["ai","coding","companion","skills","reasoning","tdd","debugging","memory","context","design","efficiency","claude","codex","cursor","windsurf","gemini","antigravity","browser-audit","headless","cdp","developer-tools"],"dependencies":{"lmdb":"^3.5.6","minisearch":"^7.2.0"},"_id":"@atul-labs/dmag@0.2.4","gitHead":"88bdb9de6352f436c6209f829e5c69d519cbce12","bugs":{"url":"https://github.com/ATUL-Labs/dmag/issues"},"_nodeVersion":"22.19.0","_npmVersion":"11.6.0","dist":{"integrity":"sha512-xxMBgVu5ucJNTroxeq5ci21oeVqX7VVTdl99pP9rbGwlAPZxKFOb2eLq/LS4MVjbgqBKNrMh5Ihf2quCvpe/8g==","shasum":"1101eeb5ac959d7a327c3622099b9422d2d92e0a","tarball":"https://registry.npmjs.org/@atul-labs/dmag/-/dmag-0.2.4.tgz","fileCount":236,"unpackedSize":1453358,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIB6L5CDvloZbFsWErapHLO6E2ul8sY7nl/k3BnHzwW4YAiEAoKhfUiBREdsuGPXlRBNaCQOR6MUK7coOFiHKukjGQls="}]},"_npmUser":{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"},"directories":{},"maintainers":[{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/dmag_0.2.4_1786559804018_0.4956702518313554"},"_hasShrinkwrap":false}},"time":{"created":"2026-08-04T15:46:58.873Z","modified":"2026-08-12T18:36:44.445Z","0.2.1":"2026-08-04T15:46:59.238Z","0.2.2":"2026-08-04T18:28:17.669Z","0.2.4":"2026-08-12T18:36:44.245Z"},"bugs":{"url":"https://github.com/ATUL-Labs/dmag/issues"},"author":{"name":"pulak-ranjan","url":"https://github.com/pulak-ranjan"},"license":"Apache-2.0","homepage":"https://github.com/ATUL-Labs/dmag","keywords":["ai","coding","companion","skills","reasoning","tdd","debugging","memory","context","design","efficiency","claude","codex","cursor","windsurf","gemini","antigravity","browser-audit","headless","cdp","developer-tools"],"repository":{"type":"git","url":"git+https://github.com/ATUL-Labs/dmag.git"},"description":"Universal coding companion - reasoning, efficient code, design intelligence, project memory, crash recovery. LTS release.","maintainers":[{"name":"atul-labs","email":"pulakranjanmahata0910@gmail.com"}],"readme":"<div align=\"center\">\n\n<img src=\"docs/images/dmag-hero.svg\" alt=\"dmag - The shared brain for AI coding agents\" width=\"100%\">\n\n[![Tests](https://img.shields.io/badge/tests-837%20pass-brightgreen)](#)\n[![Version](https://img.shields.io/badge/version-0.2.4-blue)](#)\n[![GitHub](https://img.shields.io/badge/repo-ATUL--Labs%2Fdmag-blueviolet)](https://github.com/ATUL-Labs/dmag)\n[![by pulak-ranjan](https://img.shields.io/badge/by-pulak--ranjan-blue)](https://www.linkedin.com/in/pulak-ranjan/)\n[![Stability](https://img.shields.io/badge/stability-stable-blue)](#)\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)\n[![Node](https://img.shields.io/badge/node-%3E%3D22-green)](#)\n[![Dependencies](https://img.shields.io/badge/dependencies-zero-success)](#)\n[![Platforms](https://img.shields.io/badge/platforms-21-informational)](#platform-support)\n[![MCP Tools](https://img.shields.io/badge/MCP%20tools-38-blueviolet)](#mcp-tools)\n\n[Quick Start](#quick-start) &bull; [CLI](#cli) &bull; [Gateway](#gateway-zero-approval-commands) &bull; [Viewer](#viewer) &bull; [Skills](#skills) &bull; [Docs](#docs)\n\n</div>\n\n<br>\n\n## Stop re-explaining your project to every new AI agent\n\nYou're building a feature in Claude Code. You hit a usage limit mid-task. You open\nCursor, or Windsurf, or Devin - and now you're explaining everything again. What you\nwere doing. What you already tried. What broke last time. The new agent has no memory\nof the last one.\n\nMultiply that across three projects and it's a constant tax: re-explaining,\nre-discovering, occasionally re-breaking something that was already fixed.\n\n**dmag exists because the chat window was never the right place to keep a project's\nmemory.** The chat is disposable. `.dmag/` is not.\n\n### The 30-second pitch\n\n<table>\n<tr>\n<td width=\"33%\" align=\"center\" valign=\"top\">\n\n**Without dmag**\n\n```\nAgent: \"What's the auth setup?\"\nYou:  (explains for 5 min)\nAgent: (reads 8 files, 12K tokens)\nAgent: \"Oh, I need the DB schema too\"\nYou:  (explains for 3 min)\nAgent: (reads 5 more files, 8K tokens)\nAgent: (breaks something fixed last week)\n```\n\n</td>\n<td width=\"33%\" align=\"center\" valign=\"top\">\n\n**With dmag**\n\n```\nAgent: reads .dmag/status.md\nAgent: dmag search \"auth\" → 248 tokens\nAgent: dmag symbols auth.ts → 40 rows\nAgent: dmag memory \"auth\" → past mistakes\nAgent: \"I see the issue. Fixing now.\"\n```\n\n</td>\n<td width=\"33%\" align=\"center\" valign=\"top\">\n\n**The difference**\n\n| Metric | Without | With |\n|--------|---------|------|\n| Setup time | 8 min | 0 sec |\n| Tokens used | 20K+ | 248 |\n| Past mistakes | Repeated | Avoided |\n| Crash recovery | None | Auto |\n| Agent switching | Re-explain | Continue |\n\n</td>\n</tr>\n</table>\n\n### The test dmag is built to pass\n\n> Start a task in Claude Code. Close it mid-way. Open Cursor. Type \"continue\".\n> The agent picks up exactly where the last one left off - same knowledge, same\n> discipline, same taste, on a completely different tool, with zero re-explaining.\n\n---\n\n## What's new in 0.2.4\n\n| Feature | Description |\n|---------|-------------|\n| **LAN share server** | `dmag share start/join/stop/status` — sync `.dmag/pages/` across machines on the same network. Token-based auth, dedup merge, optional push support |\n| **Docs-first agent instruction** | MCP `initialize` now instructs agents to call `docs` tool BEFORE answering any library/framework API question. Auto-distills missing libraries, auto-refreshes stale docs (30-day TTL) |\n| **Version-specific doc distillation** | Pin exact package versions: `npm:react@18.2.0` gets its own index entry. Reads `package-lock.json` for pinned versions, falls back to latest |\n| **Structured branched docs** | Each library distilled into JSON branches: `api`, `examples`, `config`, `types`, `install`, `readme`, `faq`, `testing`, `changelog`, `meta`. O(1) hashmap index, hash-skip refresh, `dmag docs distill/refresh/sync-deps/map` CLI |\n| **Version-aware FTS IDs** | MiniSearch documents use version-aware IDs to avoid stale inverted-index entries after file updates. Automatic migration from old-format indexes |\n| **Automatic context packing** | Session + file context injected without manual `proactive`/`memory` calls. MCP init gets WIP + recent mistakes + proactive memories; `read`/`symbols` attach file-scoped packs; failed `guard`/`audit_code` auto-notes CRITICAL/HIGH to `mistakes.md` |\n| **MCP v2 (2026-07-28)** | Stateless protocol support — `server/discover` for capability discovery without handshake, `ttlMs`/`cacheScope` on `tools/list` for client-side caching. Backward compatible with all legacy versions |\n| **Multi-IDE support** | Multiple IDEs open the same repo simultaneously — zero lock conflicts. MCP stdio detects serve server, opens LMDB read-only, proxies read-heavy tools |\n| **Fast-path search** | 90%+ of searches now skip semantic expansion — literal FTS + symbols return in ~4–17ms (warm), beating filesystem grep by ~5–30x on this repo |\n| **LMDB compression** | MiniSearch index persisted as deflate-compressed LMDB blob — 30%+ smaller, automatic migration from legacy JSON |\n| **Memory feedback loop** | Tracks which proactive memories lead to successful outcomes. Success rate feeds back into scoring |\n| **Task classifier** | Classifies tasks by category (security, design, bugfix, test, performance) — filters and boosts proactive memories by relevance |\n| **Memory mutation engine** | Heuristic mutation generation for failing patterns, risk classification, approval workflow, experiment snapshots |\n| **Swarm multi-agent** | `dmag swarm create/list/status/remove` — git worktree management with shared `.dmag/` symlinks, cross-agent learning |\n| **Subconscious session modularization** | Passive capture writes to `.dmag/subconscious/YYYY-MM-DD/session-NNN.jsonl` — one file per session |\n| **API test history persistence** | Every HTTP request tested is saved to `.dmag/api-tests/YYYY-MM-DD.jsonl` with status, response time, security findings |\n| **`test_history` MCP tool** | Query past API test results without re-running tests |\n| **`devloop` MCP tool** | Run the dev-loop directly — discovers endpoints, tests each one, captures errors in one call |\n| **38 MCP tools** | Up from 25 — added `test_history`, `devloop`, `benchmark`, `detect_stack`, and more |\n\nFull changelog: [CHANGELOG.md](CHANGELOG.md)\n\n---\n\n## Key features at a glance\n\n<table>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n### Cross-agent memory\n\n`.dmag/` folder stores everything an agent needs: project state, knowledge pages,\npast mistakes, patterns, design decisions, session summaries. Any agent that can\nread a file gets the full picture — no re-explaining.\n\n**Automatic context packing:** MCP initialize injects session context (WIP, recent\nmistakes, proactive memories). `read` / `symbols` attach file-scoped packs. Failed\n`guard` / `audit_code` auto-notes CRITICAL/HIGH findings into `mistakes.md`.\n\n**Crash recovery:** `wip.md` checkpoints let the next agent resume exactly where\nthe last one left off. Switch from Claude Code to Cursor mid-task? Just type\n\"continue\".\n\n</td>\n<td width=\"50%\" valign=\"top\">\n\n### Semantic code search\n\nSelf-maintaining LMDB + MiniSearch index with 5 vectorless semantic layers: Porter\nstemmer, code synonym map, co-occurrence graph, import-graph similarity, multi-turn\ncontext. Fast path skips expansion when literal hits are enough.\n\n```bash\n$ dmag search \"auth middleware\"\n  src/middleware/auth.ts:42   function validateToken()\n  src/routes/api.ts:18        router.use('/api', authMiddleware)\n  tests/auth.test.ts:88       test('rejects expired tokens')\n  3 files, ~412 tokens. grep would return ~12,400.\n```\n\n</td>\n</tr>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n### 38 MCP tools\n\nSearch, symbols, refs, links, memory, recall, guard, audit, devloop, reasoning,\nand more — all accessible from any MCP-compatible IDE. Each tool description\nexplicitly says when to use it vs built-in grep/read.\n\n```bash\ndmag mcp install --all  # write configs for all 21 supported IDEs\n```\n\n</td>\n<td width=\"50%\" valign=\"top\">\n\n### Zero-approval gateway\n\nAgents run 30+ dmag commands via `write_to_file` — no `run_command` approval\nneeded, no shell quoting, no PowerShell escaping. Results auto-injected as\ncontext.\n\n```bash\nwrite_to_file('.dmag/in/r.json', 'search auth')\n# Result auto-injected. Zero user interaction.\n```\n\n</td>\n</tr>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n### Security & testing\n\n- **`dmag guard`** — scans for exposed secrets + DB anti-patterns before every commit\n- **`dmag audit`** — headless Chrome/Edge crawls all pages, captures console + network errors\n- **`dmag test`** — API endpoint security scanner (headers, SQL, XSS, info disclosure)\n- **`dmag devloop`** — tests all endpoints with smart categorization\n\n</td>\n<td width=\"50%\" valign=\"top\">\n\n### LAN share & docs\n\n- **`dmag share`** — sync `.dmag/pages/` across machines on the same network\n- **`dmag docs`** — distill library docs into structured JSON branches for agent consumption\n- **Docs-first instruction** — agents call `docs` tool before answering API questions\n- **Version-pinned distillation** — `npm:react@18.2.0` gets its own index entry\n\n</td>\n</tr>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n### Live viewer dashboard\n\n`dmag serve` opens a mission-control dashboard at `localhost:4747`:\n\n- App server status (auto-detects port)\n- Agent activity timeline\n- Full-text search + API link graph\n- Schema ERD (pannable canvas)\n- API tester + dev loop\n- Knowledge pages + session summaries\n\n</td>\n</tr>\n</table>\n\n---\n\n## Demo\n\n<table>\n  <tr>\n    <td align=\"center\"><b>Dark mode</b></td>\n    <td align=\"center\"><b>Light mode</b></td>\n  </tr>\n  <tr>\n    <td><img src=\"docs/images/viewer-dark.png\" alt=\"dmag viewer in dark mode\" width=\"480\"></td>\n    <td><img src=\"docs/images/viewer-light.png\" alt=\"dmag viewer in light mode\" width=\"480\"></td>\n  </tr>\n</table>\n\n<img src=\"docs/images/viewer-panels.png\" alt=\"dmag viewer with collapsible panels and schema canvas\" width=\"960\">\n\n```bash\n# Run the viewer\nnode bin/dmag.js serve\n\n# Catch secrets before they ship\nnode bin/dmag.js guard\n\n# Search without reading files\nnode bin/dmag.js search \"userTask overdue\"\n\n# Test all endpoints with smart categorization\nnode bin/dmag.js devloop\n```\n\n---\n\n## Why it saves 98% of your tokens\n\nThe usual way an agent \"understands\" a codebase is expensive: grep for a term, read\nthe whole file that matched, read three more files to find where something else is\ndefined, read every migration to piece together the database. Each read costs tokens,\nand most of a 500-line file is irrelevant to the one function you needed.\n\n**dmag replaces that pattern with a query:**\n\n```bash\ndmag search loadAgentConfig\n# → lib/indexer.js:42  function loadAgentConfig(root) {\n# → tests/indexer.test.js:88  test('loadAgentConfig returns defaults')\n# 2 files, ~248 tokens. grep would return ~4,880.\n```\n\nOn a 45K-file repo, a common query like `ocr` returns 224 tokens via dmag vs **6.7\nmillion tokens** via grep. That's not a savings - it's the difference between working\nand crashing.\n\nFull benchmarks: [docs/benchmarks.md](docs/benchmarks.md)\n\n---\n\n<br>\n\n## What dmag actually does\n\n<table>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n### Memory & Continuity\n\n**Dual-process memory** - conscious memory (curated `.dmag/pages/`, `status.md`, `wip.md`) + subconscious memory (passive capture of every tool call to `.dmag/subconscious/`). The `dreams` command distills subconscious into conscious, like sleep.\n\n**Continuity engine** - `wip.md` checkpoints, ~80% context flush, hooks. Sessions survive compaction, crashes, and handoffs.\n\n**Project memory** - `.dmag/` folder with knowledge pages, session summaries, audit trail. Any agent that can read a file gets the full picture.\n\n**Crash recovery** - the next agent resumes exactly where the last one left off.\n\n```bash\n$ dmag status\n# → .dmag/wip.md found - resuming task\n# → Step 3 of 5: implement auth middleware\n# → Last edit: src/auth.js (2m ago)\n```\n\n</td>\n<td width=\"50%\" valign=\"top\">\n\n### Code Intelligence\n\n**dmag-index** - self-maintaining SQLite index. Zero tokens to maintain.\n\n```bash\n$ dmag search validateToken\n# → lib/auth.js:42  function validateToken()\n# → tests/auth.test.js:88  test('rejects expired')\n# 2 files, ~248 tokens\n```\n\n**dmag guard** - scans for exposed secrets + DB anti-patterns before every commit.\n\n**Browser audit** - headless Chrome/Edge crawls all pages, captures console + network errors.\n\n**API tester** - `dmag test <url>` runs security scan: missing headers, SQL errors, XSS, info disclosure.\n\n**Dev loop** - `dmag devloop` tests all endpoints with smart categories: OK, auth-required, not-found, server-error.\n\n</td>\n</tr>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n### Agent Tools\n\n**Reasoning skills** - 16 skills: brainstorming, planning, TDD, debugging, verification, code review, and more. Each with a `HARD-GATE` - written answers required before proceeding.\n\n**Stack overlays** - PHP? Agent uses Xdebug. Rust? Agent uses `dbg!` and audits `unsafe`. 5 overlay packs auto-detect at `dmag init`.\n\n**Image converter** - `dmag convert hero.svg hero.png` - SVG to PNG/WebP/ICO via headless Chrome.\n\n</td>\n<td width=\"50%\" valign=\"top\">\n\n### Infrastructure\n\n**Gateway** - 30+ commands via `write_to_file` - zero user approval, zero shell quoting.\n\n```bash\n# Agent writes this:\nwrite_to_file('.dmag/in/r.json', 'search auth')\n# Result auto-injected as context. No approval needed.\n```\n\n**LAN share** - `dmag share start/join` syncs `.dmag/pages/` across machines on the same network. Token-based auth, dedup merge.\n\n**Structured docs** - `dmag docs distill/sync-deps/map` distills library docs into JSON branches. Agents call `docs` tool before answering API questions.\n\n**Live viewer** - `dmag serve` opens a mission-control dashboard: status, task list, knowledge, schema, search, agent activity, API tester.\n\n**Zero dependencies** - pure markdown + one small Node script. No build step, no server, nothing to update.\n\n</td>\n</tr>\n</table>\n\nOne plugin replaces the separate reasoning, style, and memory tools you'd otherwise\nstitch together - and it works identically on **21 platforms**.\n\n---\n\n<br>\n\n## Quick Start\n\n### 1. Install\n\n**One-line (npm global - recommended):**\n```bash\nnpm install -g @atul-labs/dmag\n```\nThen use `dmag` from anywhere:\n```bash\ndmag init          # initialize .dmag/ in your project\ndmag serve         # live viewer at http://localhost:4747\ndmag audit         # headless browser audit of your dev server\ndmag guard         # scan for exposed secrets before commit\ndmag subconscious stats  # see passive memory capture stats\ndmag dreams --apply      # promote subconscious → conscious memory\ndmag share start         # share .dmag/pages/ on your LAN\ndmag docs sync-deps      # distill library docs for agent use\n```\n\n**Update to the latest version:**\n```bash\nnpm update -g @atul-labs/dmag\n```\n\n**Or per-platform plugin:**\n\n**Claude Code:**\n```bash\nclaude plugin install github:ATUL-Labs/dmag\n```\n\n**Codex:**\n```bash\ncodex plugin install github:ATUL-Labs/dmag\n```\n\n**Gemini CLI:**\n```bash\ngemini extensions install github:ATUL-Labs/dmag\n```\n\n**Cursor / Windsurf / Devin:** Auto-detected from plugin manifests. No manual setup.\n\n**Every MCP IDE at once (Claude Code, Cursor, Windsurf, Devin, VS Code, Zed, Cline, Roo, Trae + 8 more):**\n```bash\ndmag mcp install        # auto-detects your IDEs and writes configs (npx transport - no absolute paths, works even before dmag is installed)\ndmag mcp install --all  # or write configs for all 21 known clients\n```\nRestart your IDE and the `dmag` tools appear. See [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md) for the full matrix.\n\n**Any agent:** If it can read files, dmag works. Point it at `skills/using-dmag/SKILL.md`. No MCP? Use the file-based gateway (`.dmag/in/` → `.dmag/out/`) — works with Aider, shell scripts, and CI bots.\n\n<details>\n<summary>More install options (per-project, clone, Trae, manual)</summary>\n\n#### Per-project (clone and link)\n```bash\ngit clone https://github.com/ATUL-Labs/dmag.git\ncd dmag && npm link   # makes `dmag` available globally\n```\n\n#### Per-project (drop into codebase)\n```bash\ncp -r dmag-plugin/skills/ .          # Skills folder - agents auto-discover\ncp dmag-plugin/CLAUDE.md .           # Claude Code / Cursor / Windsurf\ncp dmag-plugin/AGENTS.md .           # Codex / Copilot / Windsurf\ncp dmag-plugin/GEMINI.md .           # Gemini CLI\n```\n\n#### Trae (no plugin system)\n```bash\nmkdir -p .trae/rules\ncp <dmag-repo>/templates/platform/trae-rules.md .trae/rules/project_rules.md\n```\n</details>\n\n### 2. Initialize\n\nTell your agent:\n```\nInitialize dmag for this project\n```\n\nOr run directly:\n```bash\nnode <dmag-repo>/bin/dmag.js init\n```\n\nThis creates `.dmag/` with `status.md`, `INDEX.md`, knowledge pages, and detects your\nstack (PHP, Rust, Python, TypeScript, Go) to load the right overlays.\n\n### 3. Start working\n\nThe plugin activates automatically every session. The agent reads `.dmag/status.md`,\nchecks for `wip.md` (crash recovery), and loads only the knowledge pages relevant to\nthe current task.\n\n---\n\n<br>\n\n## CLI\n\nRequires Node 22+.\n\n```bash\nnode <dmag-repo>/bin/dmag.js init [dir]                # scaffold .dmag/ from templates\nnode <dmag-repo>/bin/dmag.js guard                      # scan for exposed secrets + DB anti-patterns\nnode <dmag-repo>/bin/dmag.js check                      # pre-flight: wip.md, index, guard\nnode <dmag-repo>/bin/dmag.js tokens                     # session token usage + context budget\nnode <dmag-repo>/bin/dmag.js search userTask overdue   # full-text, fuzzy + line numbers\nnode <dmag-repo>/bin/dmag.js grep \"TODO|FIXME\"         # regex search (patterns FTS can't do)\nnode <dmag-repo>/bin/dmag.js symbols src/App.tsx       # symbol list without reading the file\nnode <dmag-repo>/bin/dmag.js links dashboard/tasks     # route + every frontend consumer\nnode <dmag-repo>/bin/dmag.js recent 20                 # recently modified files from audit log\nnode <dmag-repo>/bin/dmag.js errors                    # console errors captured from browser\nnode <dmag-repo>/bin/dmag.js audit [urls...]           # headless browser audit (auto-detects dev server)\nnode <dmag-repo>/bin/dmag.js test <url> [method]       # send request + security scan (headers, SQL, XSS)\nnode <dmag-repo>/bin/dmag.js devloop [--diff]          # test all endpoints, categorize results\nnode <dmag-repo>/bin/dmag.js convert <in> <out>        # SVG to PNG/WebP/ICO, PNG to ICO\nnode <dmag-repo>/bin/dmag.js benchmark [term]           # compare dmag search vs grep timing + recommendations\nnode <dmag-repo>/bin/dmag.js mcp install [--all]        # install MCP server config to IDEs\nnode <dmag-repo>/bin/dmag.js migrate [--keep-old]       # migrate .lex -> .dmag (auto-runs on init)\nnode <dmag-repo>/bin/dmag.js patch <file> <mode> ...   # surgical edit by anchor (saves tokens)\nnode <dmag-repo>/bin/dmag.js ls [dir]                  # list files from index (instant)\nnode <dmag-repo>/bin/dmag.js read <file> [start-end]   # read file with line numbers\nnode <dmag-repo>/bin/dmag.js refresh                   # manual reindex (rarely needed)\nnode <dmag-repo>/bin/dmag.js watch [port]              # server + file watcher, instant search\nnode <dmag-repo>/bin/dmag.js serve [port]              # live viewer, defaults to 4747\nnode <dmag-repo>/bin/dmag.js subconscious [terms...]   # search passive memory capture\nnode <dmag-repo>/bin/dmag.js subconscious stats        # entry count, date range, top topics\nnode <dmag-repo>/bin/dmag.js dreams [--apply]          # consolidate subconscious → conscious memory\nnode <dmag-repo>/bin/dmag.js share start [--port] [--pages] [--allow-push]  # LAN memory sync server\nnode <dmag-repo>/bin/dmag.js share join <url> --token XXX                   # join a share server\nnode <dmag-repo>/bin/dmag.js share stop               # stop share server\nnode <dmag-repo>/bin/dmag.js share status             # show share server status\nnode <dmag-repo>/bin/dmag.js docs distill <source>    # distill library docs into structured JSON\nnode <dmag-repo>/bin/dmag.js docs refresh [source]    # re-fetch and re-distill (hash-skip if unchanged)\nnode <dmag-repo>/bin/dmag.js docs sync-deps           # distill all project dependencies from package.json\nnode <dmag-repo>/bin/dmag.js docs map                 # list all distilled libraries and branches\n```\n\n**`guard`** scans all source files for hardcoded API keys, passwords, tokens,\nconnection strings (CRITICAL - exits with code 1 if found), and database\nanti-patterns like 1-to-1 tables, EAV, and settings tables (IMPORTANT).\n**Run it before every commit.**\n\nSuppress false positives with `// dmag-ignore` on the flagged line (or the line\nabove it), or `// dmag-ignore-file` in the first 5 lines to skip a whole file\n(e.g. test fixtures with intentional vulnerable code). Minified files\n(`.min.js`, `.min.css`) are skipped automatically.\n\n**`watch`** starts the viewer server with a file watcher. Files are re-indexed\nautomatically on save (debounced 300ms). When `watch` is running, `dmag search`\nroutes through the server via HTTP - cutting latency from ~200ms to ~15ms.\n\nLarge legacy folders: list path prefixes in `.dmag/ignore` (one per line) to exclude\nthem from indexing.\n\n### `migrate` - upgrade from .lex\n\n```bash\n# Auto-detect and migrate (also runs automatically during `dmag init`)\ndmag migrate\n\n# Keep the old folder instead of deleting it\ndmag migrate --keep-old\n```\n\nMigrates legacy `.lex/` folders to `.dmag/`. Renames the directory,\ncreates any missing runtime files (`audit.log`, `errors.log`, `browser-errors.log`),\nand ensures the full `.dmag/` structure is in place. If the old folder is locked\n(e.g. index in use on Windows), it falls back gracefully and retries next run.\n\nAlso runs automatically when you open a project — `findRoot()` detects legacy\ndirectories and migrates them in place before the MCP server starts.\n\n### `patch` - surgical edits\n\n```bash\n# Insert after an anchor\ndmag patch src/app.js after \"const x = 1\" --insert \"const y = 2;\"\n\n# Replace an anchor\ndmag patch src/app.js replace \"oldFunction()\" --insert \"newFunction()\"\n\n# Compact pipe format (41% shorter than JSON)\necho 'src/app.js|after|const x = 1|const y = 2;' | dmag patch\n\n# JSON mode (for agents)\ndmag patch '{\"file\":\"src/app.js\",\"anchor\":\"const x = 1\",\"insertion\":\"const y = 2;\",\"mode\":\"after\"}'\n```\n\n**Smart features:** auto-anchor (shortest unique substring), fuzzy match (typo\ntolerance with similarity %), diff output on every patch, preview mode, multi-match\ncontext.\n\n**Safety:** `rm` moves files to `.dmag/trash/` with a timestamp prefix. `mv` backs up\nthe destination before overwriting. Both report the trash path for recovery.\n\n### `audit` - headless browser runtime check\n\n```bash\n# Auto-detect dev server, crawl all pages (default: depth 2, max 30 pages)\ndmag audit\n\n# Explicit URLs\ndmag audit http://localhost:3000 http://localhost:5173\n\n# Single page, no crawling\ndmag audit --no-crawl http://localhost:3000\n\n# Deep crawl (depth 4, up to 100 pages)\ndmag audit --depth=4 --max-pages=100\n\n# JSON output for agents\ndmag audit --json\n\n# Wait longer for slow pages\ndmag audit --wait=5000\n```\n\nLaunches your installed Chrome/Edge/Brave in headless mode, visits each URL,\nand captures:\n- **Console errors** - `console.error`, uncaught exceptions, unhandled rejections\n- **Network errors** - HTTP 4xx/5xx responses, failed resource loads\n- **Console warnings** - `console.warn`\n\n**Crawling**: By default, after each page loads, dmag extracts all `<a href>` links\non the same origin and visits them too (BFS, up to `--depth` and `--max-pages`).\nThis catches errors on every page - dashboard, settings, login, etc.\n\n**Login support**: Create `.dmag/audit.json` (gitignored - may contain credentials):\n\n```json\n{\n  \"login\": {\n    \"url\": \"/login\",\n    \"fields\": {\n      \"#email\": \"test@example.com\",\n      \"#password\": \"testpass123\"\n    },\n    \"submit\": \"button[type=submit]\"\n  },\n  \"crawl\": true,\n  \"maxDepth\": 3,\n  \"maxPages\": 50,\n  \"waitMs\": 3000\n}\n```\n\nDmag logs in first, gets the session cookie, then crawls all authenticated pages.\nA single browser tab is reused for the entire session so cookies persist.\n\nAuto-detects browser path on Windows, macOS, Linux, and WSL. Zero dependencies -\nuses Chrome DevTools Protocol over WebSocket (built into Node 22).\n\nVia gateway (no approval needed):\n```\nwrite_to_file('.dmag/in/audit.json', '', true)  # auto-detect URLs, crawl all pages\n```\n\n### `test` - API endpoint security scanner\n\n```bash\n# Test a single endpoint\ndmag test http://localhost:3000/api/users\ndmag test http://localhost:3000/api/users POST\n\n# XSS scan\ndmag test http://localhost:3000/search?q=test --xss\n```\n\nSends an HTTP request and runs a security scan on the response:\n- **Missing security headers** - CSP, X-Frame-Options, HSTS, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy, Permissions-Policy\n- **SQL error signatures** - SQLSTATE, PDOException, MySQL errors, SQLite errors, syntax errors\n- **Information disclosure** - stack traces, framework version leaks, debug mode, X-Powered-By\n- **XSS reflection** - injected parameters reflected without encoding\n\nVia gateway:\n```\nwrite_to_file('.dmag/in/r.json', 'test http://localhost:3000/api/users GET')\n```\n\n### `devloop` - test all endpoints at once\n\n```bash\n# Test all indexed endpoints\ndmag devloop\n\n# Compare to previous run (shows what changed)\ndmag devloop --diff\n\n# Test with authentication\ndmag devloop --cookie=\"session=abc123\"\ndmag devloop --token=\"Bearer eyJhbG...\"\n\n# Filter to endpoints from a specific file\ndmag devloop src/api/auth.js\n```\n\nTests every route and API consumer found in the index. Each endpoint gets a category:\n\n| Category | Meaning | Counts as |\n|----------|---------|-----------|\n| `pass` | 200-299 | OK |\n| `auth-required` | 302→/login, 401, 403, 419 | OK (expected) |\n| `redirect` | 302 to non-auth URL | OK |\n| `not-found` | 404 | Fail |\n| `method-not-allowed` | 405 | OK |\n| `server-error` | 500+ | Fail |\n| `connection-error` | ECONNREFUSED | Fail |\n\n**Smart summary** - instead of \"72 failed\", you get:\n```\n100 endpoints tested: 5 OK, 55 require auth, 38 not found, 2 method not allowed, 2 findings, 0 actionable errors\n```\n\n**Diff mode** - compares to the last run's `.dmag/devloop.json`:\n```\n3 changed, 0 new, 0 removed, -3 errors, +0 findings\n  get /research: 500 server-error -> 200 pass\n  post /journals: 419 csrf-required -> 200 pass\n```\n\n**Expected findings filter** - HSTS is suppressed on HTTP dev servers (only flagged on HTTPS).\n\n**Auto port detection** - reads `.dmag/pages/run.md`, `.dmag/agent.json`, `.env`, and `docker-compose.yml` to find the app's actual port. Probes both IPv4 and IPv6 localhost.\n\nVia gateway:\n```\nwrite_to_file('.dmag/in/r.json', 'devloop')\nwrite_to_file('.dmag/in/r.json', 'devloop --diff')\n```\n\n### `convert` - SVG to PNG/WebP/ICO\n\n```bash\n# SVG to PNG (2x retina)\ndmag convert hero.svg hero.png --width=1200 --height=630 --scale=2\n\n# SVG to WebP (17x smaller than PNG)\ndmag convert hero.svg hero.webp --width=1200 --height=630\n\n# SVG to single-size ICO (favicon)\ndmag convert logo.svg favicon.ico --size=32\n\n# SVG to multi-size ICO (16, 32, 48, 64, 128, 256)\ndmag convert logo.svg favicon.ico --multi\n\n# PNG to ICO\ndmag convert logo.png favicon.ico --multi\n```\n\nRenders SVG using headless Chrome/Edge via CDP (same zero-dependency approach as `dmag audit`). ICO encoder is pure JS - wraps PNG data in ICO container format. Multi-size ICO includes all standard favicon sizes in one file.\n\nVia gateway:\n```\nwrite_to_file('.dmag/in/r.json', 'convert hero.svg hero.png')\nwrite_to_file('.dmag/in/req.json', '{\"cmd\":\"convert\",\"args\":{\"input\":\"logo.svg\",\"output\":\"favicon.ico\",\"multi\":true}}')\n```\n\n### `share` - LAN memory sync\n\nShare `.dmag/pages/` (mistakes, patterns, design, approaches) across machines on the same local network:\n\n```bash\n# Host: start sharing\ndmag share start\n# → Share server running at http://192.168.1.42:4748\n# → Token: a1b2c3d4e5f6\n# → Pages: mistakes.md, patterns.md, design.md, approaches.md\n\n# Peer: join and merge\ndmag share join http://192.168.1.42:4748 --token a1b2c3d4e5f6\n# → joined 192.168.1.42:4748\n# → merged: 3 pages\n# → skipped: 1 pages (already in sync)\n\n# Check status\ndmag share status\n\n# Stop sharing\ndmag share stop\n```\n\nToken-based auth on all `/pages` endpoints. Health check is open (no token needed). Dedup merge skips pages already in sync, appends shared sections with a `<!-- shared from HOST -->` marker.\n\n`--allow-push` flag enables `POST /pages/:name` so peers can push notes back to the host. `--port` and `--pages` flags customize the server.\n\n### `docs` - structured library documentation\n\nDistill library docs into structured JSON for agent consumption:\n\n```bash\n# Distill a specific library\ndmag docs distill npm:react\ndmag docs distill npm:react@18.2.0    # pin exact version\n\n# Re-fetch and re-distill (skips if content hash unchanged)\ndmag docs refresh npm:react\n\n# Distill all project dependencies from package.json\ndmag docs sync-deps\n\n# List all distilled libraries and their branches\ndmag docs map\n```\n\nEach library is distilled into branches: `api`, `examples`, `config`, `types`, `install`, `readme`, `faq`, `testing`, `changelog`, `meta`. The MCP `docs` tool provides O(1) lookup by library name and branch. Docs auto-refresh after 30-day TTL.\n\n### Gateway: zero-approval commands\n\nThe gateway lets agents use dmag **without `run_command`** - no user approval,\nno shell quoting, no PowerShell escaping. The agent writes a request to\n`.dmag/in/` via `write_to_file` (a native tool), the PostToolUse hook processes\nit, and the result is auto-injected as `additionalContext`.\n\n**Three input formats** (pick the lightest):\n\n```\n# 1. Empty file = no-arg command (filename IS the command, 21% less overhead)\nwrite_to_file('.dmag/in/errors.json', '', true)\n\n# 2. Plain text = cmd + args (17% less overhead than JSON)\nwrite_to_file('.dmag/in/r.json', 'search ValidationError')\nwrite_to_file('.dmag/in/r.json', 'grep res\\\\.status|src/app.js')\n\n# 3. JSON = full control (backward compatible)\nwrite_to_file('.dmag/in/req.json', '{\"cmd\":\"search\",\"args\":[\"InputError\"]}')\n```\n\n**30+ commands available:** `search`, `memory`, `recall`, `episode`, `note`, `docs`,\n`proactive`, `symbols`, `grep`, `read`, `patch`, `insert`, `rename`, `delete`, `batch`,\n`chain`, `task`, `synth`, `check`, `diff`, `errors`, `audit`, `integrity`, `test`,\n`devloop`, `convert`, `undo`, `snapshot`, `refs`, `recent`, `links`, `guard`, `decay`, `assoc`.\n\n| Feature | Gateway (`write_to_file`) | CLI (`run_command`) |\n|---------|--------------------------|---------------------|\n| User approval | **Never** | Every call |\n| Shell quoting | None | Required (PowerShell) |\n| Output injection | Auto (`additionalContext`) | Manual (read stdout) |\n| Batch support | Yes (1 call, N commands) | No (N calls) |\n| Token overhead | 42-50 tokens | 24-28 tokens |\n\nGateway costs ~20 more raw tokens per call, but saves **all approval friction**\nand enables **batching** (2 commands in 1 call saves 24%).\n\n---\n\n<br>\n\n## Viewer\n\n```bash\nnode <dmag-repo>/bin/dmag.js serve        # http://127.0.0.1:4747\nnode <dmag-repo>/bin/dmag.js serve 3000   # specific port\n```\n\nA live mission-control dashboard for your project. Here's what you can do:\n\n**Monitor**\n- **App server status** - auto-detects your app's port from `run.md`, `.env`, `docker-compose.yml`. Live green/red indicator, polls every 10s\n- **Agent activity timeline** - see every file edit, search, and command your AI agent has run\n- **Current task list** - live view of `wip.md` steps and their status\n\n**Explore code**\n- **Full-text search** - search the entire codebase without opening files. Results show file, line number, and context\n- **API link graph** - visual graph of every API route and its frontend consumers. Filter by URL, color-coded by HTTP method\n- **Schema ERD** - tables, columns, foreign keys from real migrations. Fullscreen pannable/zoomable canvas\n- **Symbol browser** - list functions, classes, and exports in any file without reading it\n\n**Test & secure**\n- **API tester** - send requests to any endpoint, get security scan with findings categorized by severity (High/Medium/Low). URL auto-populates from detected app server\n- **Dev loop** - one click tests all indexed endpoints. Smart categories: OK, auth-required, not-found, server-error. Actionable summary instead of raw pass/fail\n- **Console errors** - captures `console.error`, uncaught exceptions, and network failures from your dev pages\n\n**Knowledge**\n- **Knowledge pages** - browse `.dmag/pages/` with rendered markdown (stack.md, mistakes.md, patterns.md, design.md, rules.md)\n- **Session summaries** - read past agent sessions to see what was done and why\n\nDark/light theme toggle. Collapsible panels - show only what you need. Read-only and localhost-bound - never modifies your project.\n\nFull details: [docs/viewer.md](docs/viewer.md)\n\n---\n\n<br>\n\n## Skills\n\n16 skills, each a standalone `SKILL.md` with a `HARD-GATE` - written answers required\nbefore proceeding. No gate, no code. Stack overlays (PHP, Rust, Python, TypeScript,\nGo) auto-detect at `dmag init` and add language-specific tooling guidance.\n\nFull skill catalog: [docs/skills.md](docs/skills.md)\n\n---\n\n<br>\n\n## How It Works\n\n<img src=\"docs/images/dmag-architecture.svg\" alt=\"dmag architecture: .dmag/ folder structure and agent flow\" width=\"100%\">\n\n### Two memory systems: conscious and subconscious\n\nDmag doesn't just store files — it has a **dual-process memory system**, modeled on\nhow human memory actually works:\n\n<table>\n<tr>\n<td width=\"50%\" valign=\"top\">\n\n#### Conscious memory\n\nThe explicit, curated knowledge an agent **actively reads and writes**:\n\n| File | Purpose |\n|------|---------|\n| `status.md` | Current project state (~30 lines, rewritten each session) |\n| `wip.md` | Active task checkpoint (exists only during work) |\n| `INDEX.md` | Knowledge table of contents |\n| `pages/mistakes.md` | What broke, why, never repeat |\n| `pages/patterns.md` | What works in this project |\n| `pages/design.md` | Design rules for this project |\n| `pages/rules.md` | Agent output rules |\n| `sessions/*.md` | Compressed conversation summaries |\n\n**How it's used:** The agent reads `status.md` at session start, loads relevant\npages for the task, checks `wip.md` for crash recovery, and writes new findings\nto pages after completing work. This is deliberate, agent-driven memory.\n\n**Total budget:** ~200 lines max per session. Not 2,000. Not 20,000.\n\n</td>\n<td width=\"50%\" valign=\"top\">\n\n#### Subconscious memory\n\nThe passive, automatic capture of **every tool call, search, and exchange** —\nwithout the agent doing anything:\n\n```\n.dmag/subconscious/\n  2026-08-04/\n    session-001.jsonl    ← today's MCP session\n    session-002.jsonl    ← second session today\n  2026-08-03/\n    session-001.jsonl    ← yesterday\n```\n\nEach entry captures: what was asked, what was returned, which tool was called,\nand the task context. The agent never explicitly writes to it — the MCP server\ncaptures it automatically after every tool call.\n\n**Search it:** `dmag subconscious \"auth\"` or `mcp0_subconscious_search`\n**Stats:** `dmag subconscious stats` — entry count, date range, top topics\n**Consolidate:** `dmag dreams --apply` — clusters past discussions by topic,\ngenerates semantic summaries, and promotes high-value clusters to\n`pages/subconscious.md` so they become searchable persistent memory.\n\n**The flow:**\n```\nsubconscious capture (automatic)\n    ↓\ndreams --apply (clustering + summarization)\n    ↓\npages/subconscious.md (promoted to conscious memory)\n```\n\n</td>\n</tr>\n</table>\n\n**Why both?** Conscious memory is high-signal but expensive (agent must decide\nwhat to write). Subconscious memory is cheap (automatic) but noisy. The `dreams`\ncommand bridges them — it distills raw subconscious entries into curated\nknowledge pages. Just like human sleep.\n\n### Crash recovery\n\n`wip.md` checkpoints let the next agent resume exactly where the last one left\noff — same knowledge, same discipline, on a completely different tool.\n\n### Enforcement\n\nPostToolUse hook warns if `wip.md` missing, auto-logs edits. Git pre-commit hook\nruns `dmag guard` and blocks on CRITICAL violations.\n\nFull architecture: [docs/how-it-works.md](docs/how-it-works.md)\n\n---\n\n<br>\n\n## Platform Support\n\n| Platform | How it activates | Install |\n|----------|-----------------|---------|\n| **Any CLI** | `dmag` global command | `npm install -g @atul-labs/dmag` |\n| **Claude Code** | Shell hook at session start | `claude plugin install github:ATUL-Labs/dmag` |\n| **Codex** | Shell hook at session start | `codex plugin install github:ATUL-Labs/dmag` |\n| **Cursor** | Auto-detected from manifest | Drop in project root |\n| **Windsurf** | `AGENTS.md` at session start | Auto-detected from `.windsurf/plugin.json` |\n| **Devin Desktop** | `AGENTS.md` at session start | Auto-detected from `.devin/mcp_config.json` |\n| **Copilot CLI** | Shares Claude Code mechanism | Same as Claude Code |\n| **Gemini CLI** | `GEMINI.md` as context file | `gemini extensions install github:ATUL-Labs/dmag` |\n| **Kimi Code** | Manifest at session start | `/plugins install github:ATUL-Labs/dmag` |\n| **Antigravity** | `ANTIGRAVITY.md` context file | `agy plugin install github:ATUL-Labs/dmag` |\n| **Any agent** | Reads `skills/using-dmag/SKILL.md` | Drop `skills/` in project root |\n\n---\n\n<br>\n\n## Optional: code graph upgrade\n\ndmag-index answers \"where is X used\" with text search. For true call-graphs,\ndead-code detection, and trace-paths on large codebases, add the MIT-licensed\n[codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp) (single\nstatic binary, zero dependencies, fully local):\n\n```bash\n# macOS / Linux\ncurl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash\n```\n\n```powershell\n# Windows\nInvoke-WebRequest -Uri https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.ps1 -OutFile install.ps1; .\\install.ps1\n```\n\ndmag works fully without it - skills prefer the graph when connected, fall back to\n`dmag search`, then grep.\n\n---\n\n<br>\n\n## MCP Tools\n\nDmag exposes 38 MCP tools for AI agents. Each tool description explicitly says when to use it vs built-in IDE tools.\n\n### When to use Dmag vs built-in tools\n\n| Scenario | Use Dmag | Use built-in grep/read |\n|----------|---------|----------------------|\n| Searching for a concept (auth, validation, middleware) | `mcp0_search` — semantic expansion finds related terms | grep only finds literal strings |\n| Searching for an exact string you know | — | grep is faster (~1ms vs ~50ms with MCP overhead) |\n| Listing functions/classes in a file | `mcp0_symbols` — returns structured kind, name, line | — |\n| Finding all references to a symbol | `mcp0_refs` — searches import graph + definitions | grep misses aliases and re-exports |\n| Tracing an API route to frontend consumers | `mcp0_links` — no grep equivalent | — |\n| Scanning for exposed secrets | `mcp0_guard` — 20+ secret patterns, exit code 1 | — |\n| Checking console errors | `mcp0_errors` — captures from running browser | — |\n| Reading past mistakes/patterns | `mcp0_memory` / `mcp0_recall` — cross-session | — |\n| Comparing tool performance | `mcp0_benchmark` — no built-in equivalent | — |\n| Reading a specific file | — | Use built-in `read_file` — Dmag's `read` is a fallback |\n| Regex pattern search | — | Use built-in `grep_search` — Dmag's `grep` is a fallback |\n\n### Quick benchmark\n\n```bash\ndmag benchmark authentication\n```\n\nOutput shows timing, result counts, and a recommendation. Run it once per project to calibrate your agent's tool choices.\n\n### Installing Dmag MCP in your IDE\n\n```bash\ndmag mcp install              # auto-detect installed IDEs\ndmag mcp install --all        # install to all 21 supported IDEs\ndmag mcp install --ide devin  # specific IDE only\ndmag mcp install --list       # show detected IDEs\n```\n\nSupports: VS Code, Cursor, Windsurf, Devin, Trae, Kilo Code, Grok Code, OpenCode, Continue, Roo Code, Cline, Zed, Claude Desktop, Claude Code, Antigravity, Gemini CLI, Copilot CLI, Kiro, Codex CLI, Augment, Command Code, and Codex.\n\n### Proxy MCP chaining\n\nChain other MCP servers through Dmag so agents see all tools from one connection:\n\n```bash\ndmag proxy add laravel-boost --command php --args artisan boost:mcp\ndmag proxy list\ndmag proxy remove laravel-boost\n```\n\n---\n\n<br>\n\n## Best Practices: Getting the Most from Dmag\n\n### For agents\n\n1. **Start every session with `dmag check`** — verifies index freshness, guard status, and config. Takes 50ms.\n\n2. **Use `dmag search` for concepts, grep for literals** — Run `dmag benchmark <term>` once to see which is faster for your codebase. As a rule of thumb:\n   - If grep returns nothing → use `dmag search` (semantic expansion will find more)\n   - If you know the exact string → use grep (faster, no MCP overhead)\n   - If you're exploring an unfamiliar codebase → use `dmag search` (clusters, proactive context, learnings)\n\n3. **Check `dmag memory` before implementing** — past mistakes and patterns are curated knowledge. A 10-token search can save a 1000-token debugging session.\n\n4. **Run `dmag guard` before every commit** — catches exposed secrets (CRITICAL) and DB anti-patterns (IMPORTANT). Git pre-commit hook enforces this automatically.\n\n5. **Use `dmag recall` for cross-session context** — searches both persistent memory (mistakes, patterns, design) and episodic memory (past sessions) in one call.\n\n6. **Prefer gateway over CLI** — `write_to_file('.dmag/in/r.json', 'search auth')` needs zero approvals vs `run_command` which interrupts the user every time.\n\n### For project setup\n\n1. **Run `dmag init` once per project** — scaffolds `.dmag/` with status, knowledge pages, skills, and stack detection.\n\n2. **Add large folders to `.dmag/ignore`** — `vendor/`, `node_modules/`, `dist/` etc. One path per line. Keeps the index lean.\n\n3. **Run `dmag config --detect` after setup changes** — updates the single source of truth for language, framework, database, commands, and paths.\n\n4. **Use `dmag serve` during development** — the viewer dashboard shows live status, search, schema, API tester, and agent activity. Read-only, localhost-bound.\n\n5. **Let `dmag watch` keep the index fresh** — file watcher re-indexes on save (debounced 300ms). Search routes through the server, cutting latency from ~200ms to ~15ms.\n\n### For large codebases (10K+ files)\n\n1. **Dmag search uses fast-path mode** when literal matches are sufficient (~5ms), and falls back to semantic expansion only when needed (~100ms on 37K files).\n\n2. **`dmag symbols` and `dmag refs` are always fast** (~1ms) — they query the structured index, not the FTS table.\n\n3. **`dmag benchmark` calibrates expectations** — run it once per project to see actual timings and recommendations.\n\n4. **Session history and proactive context are skipped in fast mode** — they add value but cost time. Semantic mode (when grep would fail) includes them automatically.\n\n---\n\n<br>\n\n## Docs\n\n- [benchmarks.md](docs/benchmarks.md) - speed, token savings, gateway overhead, benchmark command, test results\n- [best-practices.md](docs/best-practices.md) - usage guide: when to use Dmag vs built-in tools, large codebase tips, agent workflow\n- [skills.md](docs/skills.md) - full skill catalog, stack overlays\n- [how-it-works.md](docs/how-it-works.md) - `.dmag/` folder, crash recovery, enforcement, file structure\n- [viewer.md](docs/viewer.md) - panel details, API tester, dev loop, app server status, console error capture\n- [upgrading.md](docs/upgrading.md) - safe upgrade path, no data loss\n- [CHANGELOG.md](CHANGELOG.md) - version history\n\n---\n\n<br>\n\n## Acknowledgments\n\n- Cross-platform plugin delivery pattern inspired by [superpowers](https://github.com/obra/superpowers) by Jesse Vincent (MIT)\n- Efficient code ladder inspired by [ponytail](https://github.com/DietrichGebert/ponytail)\n- README design principles from [beautify-github-readme](https://github.com/oil-oil/beautify-github-readme)\n\nAll skill content is original.\n\n## Author\n\n**pulak-ranjan** - [LinkedIn](https://www.linkedin.com/in/pulak-ranjan/) | [GitHub](https://github.com/pulak-ranjan)\n\nBuilt by [ATUL AI](https://github.com/ATUL-Labs). Free for all developers.\n\n## License\n\nApache 2.0 - see [LICENSE](LICENSE) for details.\n\n---\n\n<div align=\"center\">\n\n### If dmag saved you from re-explaining your project to yet another AI agent...\n\n**[Star this repo](https://github.com/ATUL-Labs/dmag)** - it helps other developers discover it.\n\n[Report a bug](https://github.com/ATUL-Labs/dmag/issues) &bull; [Request a feature](https://github.com/ATUL-Labs/dmag/issues) &bull; [CHANGELOG](CHANGELOG.md)\n\n---\n\n<div align=\"center\">\n\n```\nnpm install -g @atul-labs/dmag    # 30 seconds to set up. 21 platforms. Zero dependencies.\n```\n\n</div>\n","readmeFilename":"README.md"}