npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@atul-labs/dmag

v0.2.4

Published

Universal coding companion - reasoning, efficient code, design intelligence, project memory, crash recovery. LTS release.

Readme

Tests Version GitHub by pulak-ranjan Stability License Node Dependencies Platforms MCP Tools

Quick Start • CLI • Gateway • Viewer • Skills • Docs

Stop re-explaining your project to every new AI agent

You're building a feature in Claude Code. You hit a usage limit mid-task. You open Cursor, or Windsurf, or Devin - and now you're explaining everything again. What you were doing. What you already tried. What broke last time. The new agent has no memory of the last one.

Multiply that across three projects and it's a constant tax: re-explaining, re-discovering, occasionally re-breaking something that was already fixed.

dmag exists because the chat window was never the right place to keep a project's memory. The chat is disposable. .dmag/ is not.

The 30-second pitch

Without dmag

Agent: "What's the auth setup?"
You:  (explains for 5 min)
Agent: (reads 8 files, 12K tokens)
Agent: "Oh, I need the DB schema too"
You:  (explains for 3 min)
Agent: (reads 5 more files, 8K tokens)
Agent: (breaks something fixed last week)

With dmag

Agent: reads .dmag/status.md
Agent: dmag search "auth" → 248 tokens
Agent: dmag symbols auth.ts → 40 rows
Agent: dmag memory "auth" → past mistakes
Agent: "I see the issue. Fixing now."

The difference

| Metric | Without | With | |--------|---------|------| | Setup time | 8 min | 0 sec | | Tokens used | 20K+ | 248 | | Past mistakes | Repeated | Avoided | | Crash recovery | None | Auto | | Agent switching | Re-explain | Continue |

The test dmag is built to pass

Start a task in Claude Code. Close it mid-way. Open Cursor. Type "continue". The agent picks up exactly where the last one left off - same knowledge, same discipline, same taste, on a completely different tool, with zero re-explaining.


What's new in 0.2.4

| Feature | Description | |---------|-------------| | 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 | | 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) | | Version-specific doc distillation | Pin exact package versions: npm:[email protected] gets its own index entry. Reads package-lock.json for pinned versions, falls back to latest | | 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 | | 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 | | 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 | | 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 | | 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 | | 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 | | LMDB compression | MiniSearch index persisted as deflate-compressed LMDB blob — 30%+ smaller, automatic migration from legacy JSON | | Memory feedback loop | Tracks which proactive memories lead to successful outcomes. Success rate feeds back into scoring | | Task classifier | Classifies tasks by category (security, design, bugfix, test, performance) — filters and boosts proactive memories by relevance | | Memory mutation engine | Heuristic mutation generation for failing patterns, risk classification, approval workflow, experiment snapshots | | Swarm multi-agent | dmag swarm create/list/status/remove — git worktree management with shared .dmag/ symlinks, cross-agent learning | | Subconscious session modularization | Passive capture writes to .dmag/subconscious/YYYY-MM-DD/session-NNN.jsonl — one file per session | | API test history persistence | Every HTTP request tested is saved to .dmag/api-tests/YYYY-MM-DD.jsonl with status, response time, security findings | | test_history MCP tool | Query past API test results without re-running tests | | devloop MCP tool | Run the dev-loop directly — discovers endpoints, tests each one, captures errors in one call | | 38 MCP tools | Up from 25 — added test_history, devloop, benchmark, detect_stack, and more |

Full changelog: CHANGELOG.md


Key features at a glance

Cross-agent memory

.dmag/ folder stores everything an agent needs: project state, knowledge pages, past mistakes, patterns, design decisions, session summaries. Any agent that can read a file gets the full picture — no re-explaining.

Automatic context packing: MCP initialize injects session context (WIP, recent mistakes, proactive memories). read / symbols attach file-scoped packs. Failed guard / audit_code auto-notes CRITICAL/HIGH findings into mistakes.md.

Crash recovery: wip.md checkpoints let the next agent resume exactly where the last one left off. Switch from Claude Code to Cursor mid-task? Just type "continue".

Semantic code search

Self-maintaining LMDB + MiniSearch index with 5 vectorless semantic layers: Porter stemmer, code synonym map, co-occurrence graph, import-graph similarity, multi-turn context. Fast path skips expansion when literal hits are enough.

$ dmag search "auth middleware"
  src/middleware/auth.ts:42   function validateToken()
  src/routes/api.ts:18        router.use('/api', authMiddleware)
  tests/auth.test.ts:88       test('rejects expired tokens')
  3 files, ~412 tokens. grep would return ~12,400.

38 MCP tools

Search, symbols, refs, links, memory, recall, guard, audit, devloop, reasoning, and more — all accessible from any MCP-compatible IDE. Each tool description explicitly says when to use it vs built-in grep/read.

dmag mcp install --all  # write configs for all 21 supported IDEs

Zero-approval gateway

Agents run 30+ dmag commands via write_to_file — no run_command approval needed, no shell quoting, no PowerShell escaping. Results auto-injected as context.

write_to_file('.dmag/in/r.json', 'search auth')
# Result auto-injected. Zero user interaction.

Security & testing

  • dmag guard — scans for exposed secrets + DB anti-patterns before every commit
  • dmag audit — headless Chrome/Edge crawls all pages, captures console + network errors
  • dmag test — API endpoint security scanner (headers, SQL, XSS, info disclosure)
  • dmag devloop — tests all endpoints with smart categorization

LAN share & docs

  • dmag share — sync .dmag/pages/ across machines on the same network
  • dmag docs — distill library docs into structured JSON branches for agent consumption
  • Docs-first instruction — agents call docs tool before answering API questions
  • Version-pinned distillation — npm:[email protected] gets its own index entry

Live viewer dashboard

dmag serve opens a mission-control dashboard at localhost:4747:

  • App server status (auto-detects port)
  • Agent activity timeline
  • Full-text search + API link graph
  • Schema ERD (pannable canvas)
  • API tester + dev loop
  • Knowledge pages + session summaries

Demo

# Run the viewer
node bin/dmag.js serve

# Catch secrets before they ship
node bin/dmag.js guard

# Search without reading files
node bin/dmag.js search "userTask overdue"

# Test all endpoints with smart categorization
node bin/dmag.js devloop

Why it saves 98% of your tokens

The usual way an agent "understands" a codebase is expensive: grep for a term, read the whole file that matched, read three more files to find where something else is defined, read every migration to piece together the database. Each read costs tokens, and most of a 500-line file is irrelevant to the one function you needed.

dmag replaces that pattern with a query:

dmag search loadAgentConfig
# → lib/indexer.js:42  function loadAgentConfig(root) {
# → tests/indexer.test.js:88  test('loadAgentConfig returns defaults')
# 2 files, ~248 tokens. grep would return ~4,880.

On a 45K-file repo, a common query like ocr returns 224 tokens via dmag vs 6.7 million tokens via grep. That's not a savings - it's the difference between working and crashing.

Full benchmarks: docs/benchmarks.md


What dmag actually does

Memory & Continuity

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.

Continuity engine - wip.md checkpoints, ~80% context flush, hooks. Sessions survive compaction, crashes, and handoffs.

Project memory - .dmag/ folder with knowledge pages, session summaries, audit trail. Any agent that can read a file gets the full picture.

Crash recovery - the next agent resumes exactly where the last one left off.

$ dmag status
# → .dmag/wip.md found - resuming task
# → Step 3 of 5: implement auth middleware
# → Last edit: src/auth.js (2m ago)

Code Intelligence

dmag-index - self-maintaining SQLite index. Zero tokens to maintain.

$ dmag search validateToken
# → lib/auth.js:42  function validateToken()
# → tests/auth.test.js:88  test('rejects expired')
# 2 files, ~248 tokens

dmag guard - scans for exposed secrets + DB anti-patterns before every commit.

Browser audit - headless Chrome/Edge crawls all pages, captures console + network errors.

API tester - dmag test <url> runs security scan: missing headers, SQL errors, XSS, info disclosure.

Dev loop - dmag devloop tests all endpoints with smart categories: OK, auth-required, not-found, server-error.

Agent Tools

Reasoning skills - 16 skills: brainstorming, planning, TDD, debugging, verification, code review, and more. Each with a HARD-GATE - written answers required before proceeding.

Stack overlays - PHP? Agent uses Xdebug. Rust? Agent uses dbg! and audits unsafe. 5 overlay packs auto-detect at dmag init.

Image converter - dmag convert hero.svg hero.png - SVG to PNG/WebP/ICO via headless Chrome.

Infrastructure

Gateway - 30+ commands via write_to_file - zero user approval, zero shell quoting.

# Agent writes this:
write_to_file('.dmag/in/r.json', 'search auth')
# Result auto-injected as context. No approval needed.

LAN share - dmag share start/join syncs .dmag/pages/ across machines on the same network. Token-based auth, dedup merge.

Structured docs - dmag docs distill/sync-deps/map distills library docs into JSON branches. Agents call docs tool before answering API questions.

Live viewer - dmag serve opens a mission-control dashboard: status, task list, knowledge, schema, search, agent activity, API tester.

Zero dependencies - pure markdown + one small Node script. No build step, no server, nothing to update.

One plugin replaces the separate reasoning, style, and memory tools you'd otherwise stitch together - and it works identically on 21 platforms.


Quick Start

1. Install

One-line (npm global - recommended):

npm install -g @atul-labs/dmag

Then use dmag from anywhere:

dmag init          # initialize .dmag/ in your project
dmag serve         # live viewer at http://localhost:4747
dmag audit         # headless browser audit of your dev server
dmag guard         # scan for exposed secrets before commit
dmag subconscious stats  # see passive memory capture stats
dmag dreams --apply      # promote subconscious → conscious memory
dmag share start         # share .dmag/pages/ on your LAN
dmag docs sync-deps      # distill library docs for agent use

Update to the latest version:

npm update -g @atul-labs/dmag

Or per-platform plugin:

Claude Code:

claude plugin install github:ATUL-Labs/dmag

Codex:

codex plugin install github:ATUL-Labs/dmag

Gemini CLI:

gemini extensions install github:ATUL-Labs/dmag

Cursor / Windsurf / Devin: Auto-detected from plugin manifests. No manual setup.

Every MCP IDE at once (Claude Code, Cursor, Windsurf, Devin, VS Code, Zed, Cline, Roo, Trae + 8 more):

dmag mcp install        # auto-detects your IDEs and writes configs (npx transport - no absolute paths, works even before dmag is installed)
dmag mcp install --all  # or write configs for all 21 known clients

Restart your IDE and the dmag tools appear. See docs/COMPATIBILITY.md for the full matrix.

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.

Per-project (clone and link)

git clone https://github.com/ATUL-Labs/dmag.git
cd dmag && npm link   # makes `dmag` available globally

Per-project (drop into codebase)

cp -r dmag-plugin/skills/ .          # Skills folder - agents auto-discover
cp dmag-plugin/CLAUDE.md .           # Claude Code / Cursor / Windsurf
cp dmag-plugin/AGENTS.md .           # Codex / Copilot / Windsurf
cp dmag-plugin/GEMINI.md .           # Gemini CLI

Trae (no plugin system)

mkdir -p .trae/rules
cp <dmag-repo>/templates/platform/trae-rules.md .trae/rules/project_rules.md

2. Initialize

Tell your agent:

Initialize dmag for this project

Or run directly:

node <dmag-repo>/bin/dmag.js init

This creates .dmag/ with status.md, INDEX.md, knowledge pages, and detects your stack (PHP, Rust, Python, TypeScript, Go) to load the right overlays.

3. Start working

The plugin activates automatically every session. The agent reads .dmag/status.md, checks for wip.md (crash recovery), and loads only the knowledge pages relevant to the current task.


CLI

Requires Node 22+.

node <dmag-repo>/bin/dmag.js init [dir]                # scaffold .dmag/ from templates
node <dmag-repo>/bin/dmag.js guard                      # scan for exposed secrets + DB anti-patterns
node <dmag-repo>/bin/dmag.js check                      # pre-flight: wip.md, index, guard
node <dmag-repo>/bin/dmag.js tokens                     # session token usage + context budget
node <dmag-repo>/bin/dmag.js search userTask overdue   # full-text, fuzzy + line numbers
node <dmag-repo>/bin/dmag.js grep "TODO|FIXME"         # regex search (patterns FTS can't do)
node <dmag-repo>/bin/dmag.js symbols src/App.tsx       # symbol list without reading the file
node <dmag-repo>/bin/dmag.js links dashboard/tasks     # route + every frontend consumer
node <dmag-repo>/bin/dmag.js recent 20                 # recently modified files from audit log
node <dmag-repo>/bin/dmag.js errors                    # console errors captured from browser
node <dmag-repo>/bin/dmag.js audit [urls...]           # headless browser audit (auto-detects dev server)
node <dmag-repo>/bin/dmag.js test <url> [method]       # send request + security scan (headers, SQL, XSS)
node <dmag-repo>/bin/dmag.js devloop [--diff]          # test all endpoints, categorize results
node <dmag-repo>/bin/dmag.js convert <in> <out>        # SVG to PNG/WebP/ICO, PNG to ICO
node <dmag-repo>/bin/dmag.js benchmark [term]           # compare dmag search vs grep timing + recommendations
node <dmag-repo>/bin/dmag.js mcp install [--all]        # install MCP server config to IDEs
node <dmag-repo>/bin/dmag.js migrate [--keep-old]       # migrate .lex -> .dmag (auto-runs on init)
node <dmag-repo>/bin/dmag.js patch <file> <mode> ...   # surgical edit by anchor (saves tokens)
node <dmag-repo>/bin/dmag.js ls [dir]                  # list files from index (instant)
node <dmag-repo>/bin/dmag.js read <file> [start-end]   # read file with line numbers
node <dmag-repo>/bin/dmag.js refresh                   # manual reindex (rarely needed)
node <dmag-repo>/bin/dmag.js watch [port]              # server + file watcher, instant search
node <dmag-repo>/bin/dmag.js serve [port]              # live viewer, defaults to 4747
node <dmag-repo>/bin/dmag.js subconscious [terms...]   # search passive memory capture
node <dmag-repo>/bin/dmag.js subconscious stats        # entry count, date range, top topics
node <dmag-repo>/bin/dmag.js dreams [--apply]          # consolidate subconscious → conscious memory
node <dmag-repo>/bin/dmag.js share start [--port] [--pages] [--allow-push]  # LAN memory sync server
node <dmag-repo>/bin/dmag.js share join <url> --token XXX                   # join a share server
node <dmag-repo>/bin/dmag.js share stop               # stop share server
node <dmag-repo>/bin/dmag.js share status             # show share server status
node <dmag-repo>/bin/dmag.js docs distill <source>    # distill library docs into structured JSON
node <dmag-repo>/bin/dmag.js docs refresh [source]    # re-fetch and re-distill (hash-skip if unchanged)
node <dmag-repo>/bin/dmag.js docs sync-deps           # distill all project dependencies from package.json
node <dmag-repo>/bin/dmag.js docs map                 # list all distilled libraries and branches

guard scans all source files for hardcoded API keys, passwords, tokens, connection strings (CRITICAL - exits with code 1 if found), and database anti-patterns like 1-to-1 tables, EAV, and settings tables (IMPORTANT). Run it before every commit.

Suppress false positives with // dmag-ignore on the flagged line (or the line above it), or // dmag-ignore-file in the first 5 lines to skip a whole file (e.g. test fixtures with intentional vulnerable code). Minified files (.min.js, .min.css) are skipped automatically.

watch starts the viewer server with a file watcher. Files are re-indexed automatically on save (debounced 300ms). When watch is running, dmag search routes through the server via HTTP - cutting latency from ~200ms to ~15ms.

Large legacy folders: list path prefixes in .dmag/ignore (one per line) to exclude them from indexing.

migrate - upgrade from .lex

# Auto-detect and migrate (also runs automatically during `dmag init`)
dmag migrate

# Keep the old folder instead of deleting it
dmag migrate --keep-old

Migrates legacy .lex/ folders to .dmag/. Renames the directory, creates any missing runtime files (audit.log, errors.log, browser-errors.log), and ensures the full .dmag/ structure is in place. If the old folder is locked (e.g. index in use on Windows), it falls back gracefully and retries next run.

Also runs automatically when you open a project — findRoot() detects legacy directories and migrates them in place before the MCP server starts.

patch - surgical edits

# Insert after an anchor
dmag patch src/app.js after "const x = 1" --insert "const y = 2;"

# Replace an anchor
dmag patch src/app.js replace "oldFunction()" --insert "newFunction()"

# Compact pipe format (41% shorter than JSON)
echo 'src/app.js|after|const x = 1|const y = 2;' | dmag patch

# JSON mode (for agents)
dmag patch '{"file":"src/app.js","anchor":"const x = 1","insertion":"const y = 2;","mode":"after"}'

Smart features: auto-anchor (shortest unique substring), fuzzy match (typo tolerance with similarity %), diff output on every patch, preview mode, multi-match context.

Safety: rm moves files to .dmag/trash/ with a timestamp prefix. mv backs up the destination before overwriting. Both report the trash path for recovery.

audit - headless browser runtime check

# Auto-detect dev server, crawl all pages (default: depth 2, max 30 pages)
dmag audit

# Explicit URLs
dmag audit http://localhost:3000 http://localhost:5173

# Single page, no crawling
dmag audit --no-crawl http://localhost:3000

# Deep crawl (depth 4, up to 100 pages)
dmag audit --depth=4 --max-pages=100

# JSON output for agents
dmag audit --json

# Wait longer for slow pages
dmag audit --wait=5000

Launches your installed Chrome/Edge/Brave in headless mode, visits each URL, and captures:

  • Console errors - console.error, uncaught exceptions, unhandled rejections
  • Network errors - HTTP 4xx/5xx responses, failed resource loads
  • Console warnings - console.warn

Crawling: By default, after each page loads, dmag extracts all <a href> links on the same origin and visits them too (BFS, up to --depth and --max-pages). This catches errors on every page - dashboard, settings, login, etc.

Login support: Create .dmag/audit.json (gitignored - may contain credentials):

{
  "login": {
    "url": "/login",
    "fields": {
      "#email": "[email protected]",
      "#password": "testpass123"
    },
    "submit": "button[type=submit]"
  },
  "crawl": true,
  "maxDepth": 3,
  "maxPages": 50,
  "waitMs": 3000
}

Dmag logs in first, gets the session cookie, then crawls all authenticated pages. A single browser tab is reused for the entire session so cookies persist.

Auto-detects browser path on Windows, macOS, Linux, and WSL. Zero dependencies - uses Chrome DevTools Protocol over WebSocket (built into Node 22).

Via gateway (no approval needed):

write_to_file('.dmag/in/audit.json', '', true)  # auto-detect URLs, crawl all pages

test - API endpoint security scanner

# Test a single endpoint
dmag test http://localhost:3000/api/users
dmag test http://localhost:3000/api/users POST

# XSS scan
dmag test http://localhost:3000/search?q=test --xss

Sends an HTTP request and runs a security scan on the response:

  • Missing security headers - CSP, X-Frame-Options, HSTS, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy, Permissions-Policy
  • SQL error signatures - SQLSTATE, PDOException, MySQL errors, SQLite errors, syntax errors
  • Information disclosure - stack traces, framework version leaks, debug mode, X-Powered-By
  • XSS reflection - injected parameters reflected without encoding

Via gateway:

write_to_file('.dmag/in/r.json', 'test http://localhost:3000/api/users GET')

devloop - test all endpoints at once

# Test all indexed endpoints
dmag devloop

# Compare to previous run (shows what changed)
dmag devloop --diff

# Test with authentication
dmag devloop --cookie="session=abc123"
dmag devloop --token="Bearer eyJhbG..."

# Filter to endpoints from a specific file
dmag devloop src/api/auth.js

Tests every route and API consumer found in the index. Each endpoint gets a category:

| Category | Meaning | Counts as | |----------|---------|-----------| | pass | 200-299 | OK | | auth-required | 302→/login, 401, 403, 419 | OK (expected) | | redirect | 302 to non-auth URL | OK | | not-found | 404 | Fail | | method-not-allowed | 405 | OK | | server-error | 500+ | Fail | | connection-error | ECONNREFUSED | Fail |

Smart summary - instead of "72 failed", you get:

100 endpoints tested: 5 OK, 55 require auth, 38 not found, 2 method not allowed, 2 findings, 0 actionable errors

Diff mode - compares to the last run's .dmag/devloop.json:

3 changed, 0 new, 0 removed, -3 errors, +0 findings
  get /research: 500 server-error -> 200 pass
  post /journals: 419 csrf-required -> 200 pass

Expected findings filter - HSTS is suppressed on HTTP dev servers (only flagged on HTTPS).

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.

Via gateway:

write_to_file('.dmag/in/r.json', 'devloop')
write_to_file('.dmag/in/r.json', 'devloop --diff')

convert - SVG to PNG/WebP/ICO

# SVG to PNG (2x retina)
dmag convert hero.svg hero.png --width=1200 --height=630 --scale=2

# SVG to WebP (17x smaller than PNG)
dmag convert hero.svg hero.webp --width=1200 --height=630

# SVG to single-size ICO (favicon)
dmag convert logo.svg favicon.ico --size=32

# SVG to multi-size ICO (16, 32, 48, 64, 128, 256)
dmag convert logo.svg favicon.ico --multi

# PNG to ICO
dmag convert logo.png favicon.ico --multi

Renders 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.

Via gateway:

write_to_file('.dmag/in/r.json', 'convert hero.svg hero.png')
write_to_file('.dmag/in/req.json', '{"cmd":"convert","args":{"input":"logo.svg","output":"favicon.ico","multi":true}}')

share - LAN memory sync

Share .dmag/pages/ (mistakes, patterns, design, approaches) across machines on the same local network:

# Host: start sharing
dmag share start
# → Share server running at http://192.168.1.42:4748
# → Token: a1b2c3d4e5f6
# → Pages: mistakes.md, patterns.md, design.md, approaches.md

# Peer: join and merge
dmag share join http://192.168.1.42:4748 --token a1b2c3d4e5f6
# → joined 192.168.1.42:4748
# → merged: 3 pages
# → skipped: 1 pages (already in sync)

# Check status
dmag share status

# Stop sharing
dmag share stop

Token-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.

--allow-push flag enables POST /pages/:name so peers can push notes back to the host. --port and --pages flags customize the server.

docs - structured library documentation

Distill library docs into structured JSON for agent consumption:

# Distill a specific library
dmag docs distill npm:react
dmag docs distill npm:[email protected]    # pin exact version

# Re-fetch and re-distill (skips if content hash unchanged)
dmag docs refresh npm:react

# Distill all project dependencies from package.json
dmag docs sync-deps

# List all distilled libraries and their branches
dmag docs map

Each 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.

Gateway: zero-approval commands

The gateway lets agents use dmag without run_command - no user approval, no shell quoting, no PowerShell escaping. The agent writes a request to .dmag/in/ via write_to_file (a native tool), the PostToolUse hook processes it, and the result is auto-injected as additionalContext.

Three input formats (pick the lightest):

# 1. Empty file = no-arg command (filename IS the command, 21% less overhead)
write_to_file('.dmag/in/errors.json', '', true)

# 2. Plain text = cmd + args (17% less overhead than JSON)
write_to_file('.dmag/in/r.json', 'search ValidationError')
write_to_file('.dmag/in/r.json', 'grep res\\.status|src/app.js')

# 3. JSON = full control (backward compatible)
write_to_file('.dmag/in/req.json', '{"cmd":"search","args":["InputError"]}')

30+ commands available: search, memory, recall, episode, note, docs, proactive, symbols, grep, read, patch, insert, rename, delete, batch, chain, task, synth, check, diff, errors, audit, integrity, test, devloop, convert, undo, snapshot, refs, recent, links, guard, decay, assoc.

| Feature | Gateway (write_to_file) | CLI (run_command) | |---------|--------------------------|---------------------| | User approval | Never | Every call | | Shell quoting | None | Required (PowerShell) | | Output injection | Auto (additionalContext) | Manual (read stdout) | | Batch support | Yes (1 call, N commands) | No (N calls) | | Token overhead | 42-50 tokens | 24-28 tokens |

Gateway costs ~20 more raw tokens per call, but saves all approval friction and enables batching (2 commands in 1 call saves 24%).


Viewer

node <dmag-repo>/bin/dmag.js serve        # http://127.0.0.1:4747
node <dmag-repo>/bin/dmag.js serve 3000   # specific port

A live mission-control dashboard for your project. Here's what you can do:

Monitor

  • App server status - auto-detects your app's port from run.md, .env, docker-compose.yml. Live green/red indicator, polls every 10s
  • Agent activity timeline - see every file edit, search, and command your AI agent has run
  • Current task list - live view of wip.md steps and their status

Explore code

  • Full-text search - search the entire codebase without opening files. Results show file, line number, and context
  • API link graph - visual graph of every API route and its frontend consumers. Filter by URL, color-coded by HTTP method
  • Schema ERD - tables, columns, foreign keys from real migrations. Fullscreen pannable/zoomable canvas
  • Symbol browser - list functions, classes, and exports in any file without reading it

Test & secure

  • 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
  • Dev loop - one click tests all indexed endpoints. Smart categories: OK, auth-required, not-found, server-error. Actionable summary instead of raw pass/fail
  • Console errors - captures console.error, uncaught exceptions, and network failures from your dev pages

Knowledge

  • Knowledge pages - browse .dmag/pages/ with rendered markdown (stack.md, mistakes.md, patterns.md, design.md, rules.md)
  • Session summaries - read past agent sessions to see what was done and why

Dark/light theme toggle. Collapsible panels - show only what you need. Read-only and localhost-bound - never modifies your project.

Full details: docs/viewer.md


Skills

16 skills, each a standalone SKILL.md with a HARD-GATE - written answers required before proceeding. No gate, no code. Stack overlays (PHP, Rust, Python, TypeScript, Go) auto-detect at dmag init and add language-specific tooling guidance.

Full skill catalog: docs/skills.md


How It Works

Two memory systems: conscious and subconscious

Dmag doesn't just store files — it has a dual-process memory system, modeled on how human memory actually works:

Conscious memory

The explicit, curated knowledge an agent actively reads and writes:

| File | Purpose | |------|---------| | status.md | Current project state (~30 lines, rewritten each session) | | wip.md | Active task checkpoint (exists only during work) | | INDEX.md | Knowledge table of contents | | pages/mistakes.md | What broke, why, never repeat | | pages/patterns.md | What works in this project | | pages/design.md | Design rules for this project | | pages/rules.md | Agent output rules | | sessions/*.md | Compressed conversation summaries |

How it's used: The agent reads status.md at session start, loads relevant pages for the task, checks wip.md for crash recovery, and writes new findings to pages after completing work. This is deliberate, agent-driven memory.

Total budget: ~200 lines max per session. Not 2,000. Not 20,000.

Subconscious memory

The passive, automatic capture of every tool call, search, and exchange — without the agent doing anything:

.dmag/subconscious/
  2026-08-04/
    session-001.jsonl    ← today's MCP session
    session-002.jsonl    ← second session today
  2026-08-03/
    session-001.jsonl    ← yesterday

Each entry captures: what was asked, what was returned, which tool was called, and the task context. The agent never explicitly writes to it — the MCP server captures it automatically after every tool call.

Search it: dmag subconscious "auth" or mcp0_subconscious_search Stats: dmag subconscious stats — entry count, date range, top topics Consolidate: dmag dreams --apply — clusters past discussions by topic, generates semantic summaries, and promotes high-value clusters to pages/subconscious.md so they become searchable persistent memory.

The flow:

subconscious capture (automatic)
    ↓
dreams --apply (clustering + summarization)
    ↓
pages/subconscious.md (promoted to conscious memory)

Why both? Conscious memory is high-signal but expensive (agent must decide what to write). Subconscious memory is cheap (automatic) but noisy. The dreams command bridges them — it distills raw subconscious entries into curated knowledge pages. Just like human sleep.

Crash recovery

wip.md checkpoints let the next agent resume exactly where the last one left off — same knowledge, same discipline, on a completely different tool.

Enforcement

PostToolUse hook warns if wip.md missing, auto-logs edits. Git pre-commit hook runs dmag guard and blocks on CRITICAL violations.

Full architecture: docs/how-it-works.md


Platform Support

| Platform | How it activates | Install | |----------|-----------------|---------| | Any CLI | dmag global command | npm install -g @atul-labs/dmag | | Claude Code | Shell hook at session start | claude plugin install github:ATUL-Labs/dmag | | Codex | Shell hook at session start | codex plugin install github:ATUL-Labs/dmag | | Cursor | Auto-detected from manifest | Drop in project root | | Windsurf | AGENTS.md at session start | Auto-detected from .windsurf/plugin.json | | Devin Desktop | AGENTS.md at session start | Auto-detected from .devin/mcp_config.json | | Copilot CLI | Shares Claude Code mechanism | Same as Claude Code | | Gemini CLI | GEMINI.md as context file | gemini extensions install github:ATUL-Labs/dmag | | Kimi Code | Manifest at session start | /plugins install github:ATUL-Labs/dmag | | Antigravity | ANTIGRAVITY.md context file | agy plugin install github:ATUL-Labs/dmag | | Any agent | Reads skills/using-dmag/SKILL.md | Drop skills/ in project root |


Optional: code graph upgrade

dmag-index answers "where is X used" with text search. For true call-graphs, dead-code detection, and trace-paths on large codebases, add the MIT-licensed codebase-memory-mcp (single static binary, zero dependencies, fully local):

# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash
# Windows
Invoke-WebRequest -Uri https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.ps1 -OutFile install.ps1; .\install.ps1

dmag works fully without it - skills prefer the graph when connected, fall back to dmag search, then grep.


MCP Tools

Dmag exposes 38 MCP tools for AI agents. Each tool description explicitly says when to use it vs built-in IDE tools.

When to use Dmag vs built-in tools

| Scenario | Use Dmag | Use built-in grep/read | |----------|---------|----------------------| | Searching for a concept (auth, validation, middleware) | mcp0_search — semantic expansion finds related terms | grep only finds literal strings | | Searching for an exact string you know | — | grep is faster (~1ms vs ~50ms with MCP overhead) | | Listing functions/classes in a file | mcp0_symbols — returns structured kind, name, line | — | | Finding all references to a symbol | mcp0_refs — searches import graph + definitions | grep misses aliases and re-exports | | Tracing an API route to frontend consumers | mcp0_links — no grep equivalent | — | | Scanning for exposed secrets | mcp0_guard — 20+ secret patterns, exit code 1 | — | | Checking console errors | mcp0_errors — captures from running browser | — | | Reading past mistakes/patterns | mcp0_memory / mcp0_recall — cross-session | — | | Comparing tool performance | mcp0_benchmark — no built-in equivalent | — | | Reading a specific file | — | Use built-in read_file — Dmag's read is a fallback | | Regex pattern search | — | Use built-in grep_search — Dmag's grep is a fallback |

Quick benchmark

dmag benchmark authentication

Output shows timing, result counts, and a recommendation. Run it once per project to calibrate your agent's tool choices.

Installing Dmag MCP in your IDE

dmag mcp install              # auto-detect installed IDEs
dmag mcp install --all        # install to all 21 supported IDEs
dmag mcp install --ide devin  # specific IDE only
dmag mcp install --list       # show detected IDEs

Supports: 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.

Proxy MCP chaining

Chain other MCP servers through Dmag so agents see all tools from one connection:

dmag proxy add laravel-boost --command php --args artisan boost:mcp
dmag proxy list
dmag proxy remove laravel-boost

Best Practices: Getting the Most from Dmag

For agents

  1. Start every session with dmag check — verifies index freshness, guard status, and config. Takes 50ms.

  2. 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:

    • If grep returns nothing → use dmag search (semantic expansion will find more)
    • If you know the exact string → use grep (faster, no MCP overhead)
    • If you're exploring an unfamiliar codebase → use dmag search (clusters, proactive context, learnings)
  3. Check dmag memory before implementing — past mistakes and patterns are curated knowledge. A 10-token search can save a 1000-token debugging session.

  4. Run dmag guard before every commit — catches exposed secrets (CRITICAL) and DB anti-patterns (IMPORTANT). Git pre-commit hook enforces this automatically.

  5. Use dmag recall for cross-session context — searches both persistent memory (mistakes, patterns, design) and episodic memory (past sessions) in one call.

  6. 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.

For project setup

  1. Run dmag init once per project — scaffolds .dmag/ with status, knowledge pages, skills, and stack detection.

  2. Add large folders to .dmag/ignore — vendor/, node_modules/, dist/ etc. One path per line. Keeps the index lean.

  3. Run dmag config --detect after setup changes — updates the single source of truth for language, framework, database, commands, and paths.

  4. Use dmag serve during development — the viewer dashboard shows live status, search, schema, API tester, and agent activity. Read-only, localhost-bound.

  5. 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.

For large codebases (10K+ files)

  1. 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).

  2. dmag symbols and dmag refs are always fast (~1ms) — they query the structured index, not the FTS table.

  3. dmag benchmark calibrates expectations — run it once per project to see actual timings and recommendations.

  4. 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.


Docs

  • benchmarks.md - speed, token savings, gateway overhead, benchmark command, test results
  • best-practices.md - usage guide: when to use Dmag vs built-in tools, large codebase tips, agent workflow
  • skills.md - full skill catalog, stack overlays
  • how-it-works.md - .dmag/ folder, crash recovery, enforcement, file structure
  • viewer.md - panel details, API tester, dev loop, app server status, console error capture
  • upgrading.md - safe upgrade path, no data loss
  • CHANGELOG.md - version history

Acknowledgments

All skill content is original.

Author

pulak-ranjan - LinkedIn | GitHub

Built by ATUL AI. Free for all developers.

License

Apache 2.0 - see LICENSE for details.


If dmag saved you from re-explaining your project to yet another AI agent...

Star this repo - it helps other developers discover it.

Report a bug • Request a feature • CHANGELOG


npm install -g @atul-labs/dmag    # 30 seconds to set up. 21 platforms. Zero dependencies.