Skip to content
Back to search

deja-vu

Memory for AI coding agents: search and auto-recall your own past sessions across every tool you use.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 16 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/vshulcz/deja-vu with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/vshulcz/deja-vu'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/vshulcz--deja-vu/badge.svg)](/listings/vshulcz--deja-vu)

HTML

<a href="/listings/vshulcz--deja-vu"><img src="/api/listings/vshulcz--deja-vu/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

`install.sh` places the `deja` binary in `~/.local/bin`, and `deja install --auto` wires MCP recall and hooks into every detected agent and builds the initial index (~10s).

Open a new session in any wired agent and it already knows what you solved in that repository — or ask it directly (`have we dealt with jwt refresh rotation before?`).

<details> <summary><b>Homebrew, Windows (Scoop / winget), npm, plugin marketplaces, and binary-only setup</b></summary>

`brew install deja-vu`, `nix run github:numtide/llm-agents.nix#deja-vu`, `go install github.com/vshulcz/deja-vu/cmd/deja@latest`, or `npx @vshulcz/deja-vu "query"` to try it without installing anything. Desktop apps that take MCP servers as bundles can open the `.mcpb` from the [latest release](https://github.com/vshulcz/deja-vu/releases/latest); it carries the binary.

Codex CLI, opencode, Claude Code, Qwen and OpenClaw can also install the plugin bundle directly from their own marketplaces or registries (see [Harnesses with a package of their own](#harnesses-with-a-package-of-their-own), plus [`cursor-plugin/`](cursor-plugin/) for Cursor and [`antigravity-plugin/`](antigravity-plugin/) for Antigravity). Copilot CLI installs the marketplace bundle too, though it takes only the skill there — use `deja install copilot-auto` for hooks and MCP:

codex plugin marketplace add https://github.com/vshulcz/deja-vu && codex plugin add deja-vu@deja-vu
opencode plugin add opencode-deja
claude plugin marketplace add vshulcz/deja-vu && claude plugin install deja-vu@deja-vu

On Windows the install script exits with `unsupported OS` — it is a shell script. Use Scoop, from the main bucket every Scoop install already has, or winget, which ships with Windows:

scoop install deja-vu
winget install vshulcz.deja-vu

Or take `deja-vu_<version>_windows_amd64.zip` from the [latest release](https://github.com/vshulcz/deja-vu/releases/latest) and put `deja.exe` on your `PATH`, e.g. in `%USERPROFILE%\.local\bin`.

The binary alone is a complete install for searching: index, search, `show`, `ctx`, `blame`, `--json` and redaction need nothing else. `deja install` is what wires MCP into your agents and turns on session-start recall — worth having, and optional. On a binary-only setup `deja doctor` reports every MCP target as `config missing`, or `not-wired` where the agent is installed, which is that setup working as intended. `deja warmup` also leaves a skill at `~/.agents/skills/deja-search/SKILL.md` that teaches an agent the CLI contract — `deja recall`, `ctx`, `blame`, how to read the recall page and ask for the next one — so it knows history is searchable without MCP. The copy in the repo is [`skills/deja-search/SKILL.md`](skills/deja-search/SKILL.md).

`deja install --all` is `--auto` without the session-start recall: agents answer from memory when they decide to call it, rather than starting each session with it. The [agent setup guide](https://vshulcz.github.io/deja-vu/guide/agents.html) covers what each harness supports, aider's read-only context file, and the Windows `cmd /c deja mcp` wrapper.

</details>

<details> <summary>What gets written into each agent's own guidance file</summary>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 17 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "deja-vu",
  4. "description": "Memory for AI coding agents: search and auto-recall your own past sessions across every tool you use.",
  5. "owner": {
  6. "name": "vshulcz",
  7. "url": "https://github.com/vshulcz"
  8. },
  9. "plugins": [
  10. {
  11. "name": "deja-vu",
  12. "description": "Your agent starts already knowing what you did before — recall across Claude Code, Codex, Cursor, opencode and forty-four more agents.",
  13. "source": "./claude-plugin",
  14. "category": "productivity"
  15. }
  16. ]
  17. }
README.md · README · 694 lines · 1 finding marked
  1. <p align="center">
  2. <picture>
  3. <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/logo-dark.svg">
  4. <img src="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/logo.svg" width="280" alt="deja-vu">
  5. </picture>
  6. </p>
  7. <p align="center"><b>Shared local memory, session history search, cross-agent handoff, and code recovery across 48 coding agents.</b><br>
  8. Claude Code, Codex, Cursor, OpenClaw, Gemini CLI, OpenCode, Hermes and 40 more agents already save every session to disk.<br>
  9. <b>deja-vu</b> (<code>deja</code>) indexes all of it locally in one Go binary — zero LLM calls, 0.7 ms in-process lookup, ~4% index footprint.</p>
  10. <p align="center">English | <a href="docs/readme/README.zh.md">简体中文</a> | <a href="docs/readme/README.zh-TW.md">繁體中文</a> | <a href="docs/readme/README.ja.md">日本語</a> | <a href="docs/readme/README.ko.md">한국어</a> | <a href="docs/readme/README.es.md">Español</a> | <a href="docs/readme/README.pt.md">Português</a> | <a href="docs/readme/README.fr.md">Français</a> | <a href="docs/readme/README.de.md">Deutsch</a> | <a href="docs/readme/README.ru.md">Русский</a> | <a href="docs/readme/README.tr.md">Türkçe</a> | <a href="docs/readme/README.hi.md">हिन्दी</a></p>
  11. <p align="center">
  12. <a href="https://github.com/vshulcz/deja-vu/stargazers"><img src="https://img.shields.io/github/stars/vshulcz/deja-vu?style=flat&color=f59e0b" alt="GitHub Stars"></a>
  13. <a href="https://github.com/vshulcz/deja-vu/actions/workflows/ci.yml"><img src="https://github.com/vshulcz/deja-vu/actions/workflows/ci.yml/badge.svg?branch=main&event=push" alt="CI"></a>
  14. <a href="https://github.com/vshulcz/deja-vu/actions/workflows/ci.yml"><img src="https://img.shields.io/badge/coverage-88%25-brightgreen" alt="Coverage"></a>
  15. <a href="https://github.com/vshulcz/deja-vu/releases"><img src="https://img.shields.io/github/v/release/vshulcz/deja-vu" alt="Release"></a>
  16. <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License"></a>
  17. &middot;
  18. <a href="https://vshulcz.github.io/deja-vu/"><b>Website</b></a> &middot; <a href="https://vshulcz.github.io/deja-vu/view/"><b>Live demo</b></a> &middot; <a href="https://vshulcz.github.io/deja-vu/guide/getting-started.html">Docs</a> &middot; <a href="https://vshulcz.github.io/deja-vu/guide/benchmarks.html">Benchmarks</a> &middot; <a href="https://vshulcz.github.io/deja-vu/guide/compare.html">Compare</a> &middot; <a href="docs/ARCHITECTURE.md">Architecture</a>
  19. </p>
  20. <p align="center"><img src="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/demo.gif" width="720" alt="The same question put to the same agent twice: without memory it has no record of it, with deja it answers with the decision from eight months earlier"></p>
  21. ```sh
  22. npx @vshulcz/deja-vu install --auto # 1-step cross-platform install + wire installed agents
  23. # or via shell / Homebrew:
  24. curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh && deja install --auto
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 29 on GitHub
  25. ```
  26. <p align="center"><sub>Homebrew: <code>brew install deja-vu &amp;&amp; deja install --auto</code> &middot; Claude Code: <code>claude plugin marketplace add vshulcz/deja-vu &amp;&amp; claude plugin install deja-vu@deja-vu</code> &middot; Skills: <code>npx skills add vshulcz/deja-vu</code><br><a href="#install">Windows (Scoop / winget), Codex, OpenCode, OpenClaw and more</a> &middot; Try without installing: <code>npx @vshulcz/deja-vu stats --no-index --card</code> or <code>npx @vshulcz/deja-vu audit</code></sub></p>
  27. ```sh
  28. $ deja "jwt refresh token" # lexical + structural search across all 47 agent stores
  29. $ deja handoff --to codex # continue the active session's goal & state in another agent
  30. $ deja restore internal/auth/jwt.go # recover code an agent overwrote before git commit
  31. $ deja blame internal/auth/jwt.go:42 # trace which agent session wrote or replaced a line
  32. $ deja audit # check retention risk, purged chats & index health across all 47 stores
  33. ```
  34. <table align="center">
  35. <tr>
  36. <td align="center" width="33%">Recall<br><b>97.2% R@5</b> on LongMemEval-S<br><sub>MemPalace publishes 96.6%, agentmemory 95.2%</sub></td>
  37. <td align="center" width="33%">Tokens<br><b>half the tokens</b> of agentmemory<br><sub>on a task this machine had already solved</sub></td>
  38. <td align="center" width="33%">Index &amp; lookup<br><b>13.6 s</b> / <b>0.7 ms</b> lookup<br><sub>19,195 sessions (next of 7 tools: 72 s)</sub></td>
  39. </tr>
  40. </table>
  41. <p align="center"><sub>Every driver, corpus and scoring rule is in this repository: <a href="https://vshulcz.github.io/deja-vu/guide/day-zero.html">head-to-head</a> &middot; <a href="https://vshulcz.github.io/deja-vu/guide/benchmarks.html">all benchmark runs</a></sub></p>
  42. ## Search it yourself
  43. `deja` with no arguments opens a terminal search across every agent's history — starting with
  44. the sessions behind your uncommitted changes, then recent work in the current project.
  45. <p align="center"><img src="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/tui.gif" width="720" alt="Typing a search in the deja screen, reading the session it found, and continuing that session in another agent"></p>
  46. - **Navigate:** `↑↓` picks a session, `↵` opens at the match, `/` searches inside a session, `]` `[` jump between turns, `^s` toggles date/relevance sort (`deja search --sort date`).
  47. - **Filter:** by agent (`codex:`), time (`today`, `yesterday`, `week`, `month`), or project (`in:<project>`).
  48. - **Resume or hand off:** `r` reopens the session in its native agent; `o` continues it in another agent with its goal, decisions and open work.
  49. - **Recover deleted chats:** `tab` switches between this project, all projects, and **Deleted** (sessions an agent purged that deja still holds); `R` restores one, `D` deletes (`deja delete <id>`), `?` lists all keys.
  50. Prefer a browser? `deja view` exports the store — sessions, the recall audit trail, and promoted notes — into one local HTML file ([try the live demo](https://vshulcz.github.io/deja-vu/view/)). With `DEJA_TUI=0` (or `deja brief`), `deja` prints a plain-text summary.
  51. ## Highlights
  52. - **Starts full on day one.** Months of existing transcripts across all [forty-eight agents](#supported-harnesses) are searchable immediately — fix a bug in Codex and Claude Code, Cursor or OpenCode recalls it.
  53. - **Survives `/compact` and context resets.** Over 43 measured compactions, summaries kept 77% of decisions and 0.2% of commands; deja hands back the exact commands, errors, and decisions ([how](docs/compaction.md)).
  54. - **Cross-agent handoff (`deja handoff`).** Hit a rate limit or get stuck in Claude Code? Hand the active session's goal, decisions, touched files, and open work straight into Codex, Cursor, or OpenCode.
  55. - **Undo overwritten code (`deja restore` & `deja blame`).** Indexes opened files, commands with exit codes, and exact `Edit` spans so `deja restore <path>` recovers code an agent clobbered even before `git commit` (`deja blame <file>:<line>`).
  56. - **Automatic recall via hooks & MCP.** Surfaces prior sessions at session start, before a file edit or command runs, and when a command fails.
  57. - **Tracks decision lifecycle & staleness.** `deja promote <id> --state rejected` marks a reverted approach so later hits warn why it was dropped (`--state accepted` takes the mark back), and hits report when files touched by a session have changed since.
  58. - **Travels with the repository.** `deja repo add` commits the decisions and dead ends you pick into `.deja/memory.jsonl`; a teammate's agent recalls them after a clone ([repo memory](#memory-in-the-repository)).
  59. - **Incremental local index.** Append-only `records.bin` plus token buckets in `~/.cache/deja`, with per-file watermarks in `manifest.gob` so repeat passes only read changed files (~50 ms freshness check; 4% index footprint on a 5.7 GB / 358k-message corpus). Zero LLM calls, no cloud account, and automatic credential redaction at index time ([architecture](docs/ARCHITECTURE.md), [privacy](#privacy)).
  60. ### Your own work, wrapped
  61. `deja stats --card` draws your yearly agent activity in the terminal or writes an SVG for your GitHub profile ([convert to PNG in browser](https://vshulcz.github.io/deja-vu/card/)). Before installing, run `npx @vshulcz/deja-vu stats --no-index --card` to scan local stores without writing an index.
  62. <p align="center"><img src="https://raw.githubusercontent.com/vshulcz/deja-vu/main/docs/assets/stats-card-demo.svg" width="600" alt="deja stats card: a year of agent sessions as a heatmap, the agents they came from, and the longest one"></p>
  63. ## Install
  64. `install.sh` places the `deja` binary in `~/.local/bin`, and `deja install --auto` wires MCP recall and hooks into every detected agent and builds the initial index (~10s).
  65. <p align="center"><img src="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/banner.png" width="700" alt="What deja prints after the first index: the mark, the agents it found, and a query taken from your own history"></p>
  66. Open a new session in any wired agent and it already knows what you solved in that repository — or ask it directly (`have we dealt with jwt refresh rotation before?`).
  67. <details>
  68. <summary><b>Homebrew, Windows (Scoop / winget), npm, plugin marketplaces, and binary-only setup</b></summary>
  69. `brew install deja-vu`, `nix run github:numtide/llm-agents.nix#deja-vu`, `go install github.com/vshulcz/deja-vu/cmd/deja@latest`,
  70. or `npx @vshulcz/deja-vu "query"` to try it without installing anything. Desktop apps that
  71. take MCP servers as bundles can open the `.mcpb` from the
  72. [latest release](https://github.com/vshulcz/deja-vu/releases/latest); it carries the binary.
  73. Codex CLI, opencode, Claude Code, Qwen and OpenClaw can also install the plugin
  74. bundle directly from their own marketplaces or registries (see
  75. [Harnesses with a package of their own](#harnesses-with-a-package-of-their-own),
  76. plus [`cursor-plugin/`](cursor-plugin/) for Cursor and [`antigravity-plugin/`](antigravity-plugin/) for Antigravity). Copilot CLI installs the
  77. marketplace bundle too, though it takes only the skill there — use
  78. `deja install copilot-auto` for hooks and MCP:
  79. ```sh
  80. codex plugin marketplace add https://github.com/vshulcz/deja-vu && codex plugin add deja-vu@deja-vu
  81. opencode plugin add opencode-deja
  82. claude plugin marketplace add vshulcz/deja-vu && claude plugin install deja-vu@deja-vu
  83. ```
  84. On Windows the install script exits with `unsupported OS` — it is a shell script. Use
  85. Scoop, from the main bucket every Scoop install already has, or winget, which ships with Windows:
  86. ```powershell
  87. scoop install deja-vu
  88. winget install vshulcz.deja-vu
  89. ```
  90. Or take `deja-vu_<version>_windows_amd64.zip` from the
  91. [latest release](https://github.com/vshulcz/deja-vu/releases/latest) and put `deja.exe` on
  92. your `PATH`, e.g. in `%USERPROFILE%\.local\bin`.
  93. The binary alone is a complete install for searching: index, search, `show`, `ctx`, `blame`,
  94. `--json` and redaction need nothing else. `deja install` is what wires MCP into your agents
  95. and turns on session-start recall — worth having, and optional. On a binary-only setup
  96. `deja doctor` reports every MCP target as `config missing`, or `not-wired` where the agent
  97. is installed, which is that setup working as intended. `deja warmup` also leaves a skill at `~/.agents/skills/deja-search/SKILL.md`
  98. that teaches an agent the CLI contract — `deja recall`, `ctx`, `blame`, how to read the
  99. recall page and ask for the next one — so it knows history is searchable without MCP. The copy in the repo is
  100. [`skills/deja-search/SKILL.md`](skills/deja-search/SKILL.md).
  101. `deja install --all` is `--auto` without the session-start recall: agents answer from memory
  102. when they decide to call it, rather than starting each session with it. The
  103. [agent setup guide](https://vshulcz.github.io/deja-vu/guide/agents.html) covers what each
  104. harness supports, aider's read-only context file, and the Windows `cmd /c deja mcp` wrapper.
  105. </details>
  106. <details>
  107. <summary>What gets written into each agent's own guidance file</summary>
  108. Install also writes user-level guidance for the harnesses it detects: Claude Code, Codex, opencode, Gemini CLI, Antigravity, Qwen, Kimi Code, pi, Senpi, Copilot, VS Code Copilot Chat, Goose, OpenClaw, Hermes, Roo Code, omp, Amp, prime-agent, DeepSeek Harness, Continue, Crush, CodeBuddy Code, WorkBuddy, Zed, TRAE CLI, TRAE IDE, Muse Code, CodeWhale, ZCode and Junie each get it in their own guidance file (or under the configured `XDG_CONFIG_HOME`). Re-run rewrites deja's skill or marked block without changing surrounding user content. Use `deja install --all --no-guidance` to opt out; Grok Build and Devin CLI get the shared skill in `~/.agents/skills`, which is what they read; the `~/.grok/GROK.md` written beside it is for the unrelated community CLI that shares that directory. Cursor has no user-level instructions file, so it gets the shared skill in `~/.agents/skills` — one of the four places Cursor reads skills from — read only when something looks relevant rather than every session. Kilo Code, gajae-code, Kimchi, Command Code, Cherry Studio and Reasonix get the skill, MiniMax Code gets it inside the plugin package, and Kiro the skill and a steering file, from their own install target.
  109. </details>
  110. ## Memory in the repository
  111. Sync moves history between your own machines. To hand the people you work with the
  112. few things your agents learned the hard way, put them in the repository:
  113. ```text
  114. $ deja repo candidates
  115. 4cd7e7bb9c rejected Reverted the retry with jitter: it broke idempotency because the sender re-signs each attempt with a new delivery id. (session s1, claude 2026-08-03)
  116. $ deja repo add 4cd7e7bb9c
  117. added 1 entry to .deja/memory.jsonl
  118. nothing is committed: review with `git diff .deja/` and commit it like code
  119. ```
  120. Candidates come from this project's history in every agent: promoted and remembered
  121. notes, reversals reported in a session, and what sessions settled. Nothing is written
  122. until you pick, every entry is redacted on the way in, and one that still matches a secret
  123. rule is refused. The file is JSON lines sorted by a content hash, with a
  124. `merge=union` attribute beside it, so parallel additions merge; deleting a line removes
  125. an entry. After a clone, the entries come back at session start and in recall, in any agent
  126. deja is wired into, marked as from the repository and framed as untrusted like the rest.
  127. `{"activations":{"auto":{"repo":false}}}` in the trust policy keeps them out of the hooks.
  128. [More](https://vshulcz.github.io/deja-vu/guide/repo-memory.html).
  129. ## Privacy
  130. Indexing and search are local. The network is used only by `deja update`, `deja sync ssh`,
  131. the version check in `deja doctor`, `deja embed` against an endpoint you configure (and,
  132. once it has built the semantic sidecar, each search, which sends the query to that
  133. endpoint), and a once-a-day look at the latest release from an interactive command. That look sends no
  134. session data; `DEJA_OFFLINE=1` turns it off, and so does `DEJA_NO_UPDATE_NOTICE` set to any
  135. value, which also hides the note a new version prints on its first run.
  136. Credentials are stripped as the index is built: cloud and provider keys, tokens and JWTs,
  137. PEM blocks, passwords in URLs or stated in prose. Each becomes `[redacted:<kind>]` and the
  138. text around it stays searchable. The source transcripts still hold them
  139. ([one machine had 84 in 42 sessions](https://vshulcz.github.io/deja-vu/guide/credentials-in-transcripts.html)):
  140. `deja secrets` names those sessions without printing a value, and `deja secrets --scrub`
  141. rewrites the ones it can, keeping the original beside the file.
  142. `deja forget` drops sessions and keeps them dropped across rebuilds. `~/.config/deja/exclude`
  143. skips a project per line, or a whole store with `harness:opencode`. The
  144. [security model](docs/SECURITY-MODEL.md) has the data flows and what redaction cannot catch.
  145. ## CLI
  146. Bare `deja` in a terminal opens [the search screen](#search-it-yourself). With a query,
  147. or any command below, it prints and exits:
  148. ```text
  149. $ deja "jwt refresh token"
  150. [claude] api · Jul 8 · 8f31c0a9 — 2 matches
  151. login started failing after refresh token rotation; jwt kid mismatch in tests
  152. fixed by reloading jwks cache after rotateKey and adding a clock-skew test
  153. [codex] web · Jul 1 · b77d91e2 — 1 match
  154. refresh token cookie needed SameSite=Lax in local callback flow
  155. ```
  156. **Ask your history**
  157. | Command | What it does |
  158. | --- | --- |
  159. | `deja <query>` | Search every history. Multi-word is AND and quoted phrases require contiguous text; a query with no exact match then tries word forms and close spellings, which is where a substring reaches its word (`code` finds `opencode`). `--sort date` lists the newest match first. |
  160. | `deja` | In a terminal, the full-screen search above. `deja brief` prints the text summary instead: today's sessions, what deja served, recent work and a search to try. |
  161. | `deja wip` | What the last session in this directory was doing: the task, what it settled, the files in flight, the last command and whether it failed — derived from the transcript, not from a note someone remembered to write. |
  162. | `deja blame <path>[:line]` | Which sessions discussed a file, what was decided, and why. With a line: the commit that last changed it, and the session that wrote that line or the text the commit replaced. `--attribution` prints the line answer alone, as JSON with `--json`, and `--git-note` records it in `refs/notes/deja`. |
  163. | `deja origin [rev\|range]` | Which session and user turn produced a commit or commit range, matched against recorded edit spans (`attributed`, `uncertain`, or `unknown`). |
  164. | `deja review [rev\|range]` | Prior sessions and settled notes (`.deja/notes.jsonl` and personal notes) for the files changed in a working-tree diff, commit, or range. |
  165. | `deja files <topic>` | The other direction: which files the work on a subject actually touched. |
  166. | `deja how <tool>` | How this machine actually runs a thing, with the real flags, from what agents ran before. |
  167. | `deja fix <error>` | What this machine ran after that same error before, when the error did not come back. Never a merge, a force push or a deletion. |
  168. | `deja friction` | Errors that hit three or more separate sessions, with the harnesses named. |
  169. When the first word of a bare query has at least four characters and is one
  170. edit from a command name, deja names that command on stderr and then searches
  171. as usual. `deja search <query>` skips the suggestion.
  172. <details>
  173. <summary>Using what it finds, and moving it between machines</summary>
  174. **Use what it finds**
  175. | Command | What it does |
  176. | --- | --- |
  177. | `deja ctx <query>` | Markdown digest of the best match, with the code it changed, ready to pipe into a prompt. |
  178. | `deja recall <words>` | The page the MCP recall tool gives an agent: about 4 KB, this project first (`DEJA_RECALL_GLOBAL=1` ranks every project the same). For skills and scripts that run deja through the shell. |
  179. | `deja resume <id>` | Reopen a found session in its native harness. `--app` opens a Codex session in the ChatGPT desktop app. |
  180. | `deja restore <path>` | Hand back a span an agent replaced, from the `old_string` its edit recorded. Never writes over the original. |
  181. | `deja promote <id>` | Distill a session into a curated note with provenance, tags and a lifecycle state (`--repo` writes to `<repo>/.deja/notes.jsonl` for the team). Notes outrank raw transcripts. |
  182. | `deja share <id>` | A sanitized session digest for a colleague, with secrets already scrubbed. |
  183. **Move it and check it**
  184. | Command | What it does |
  185. | --- | --- |
  186. | `deja sync export/import/ssh` | Move memory between machines. Watermarked, append-only, idempotent. |
  187. | `deja repo candidates`, `deja repo add <id>` | Move memory between people: write the decisions and dropped approaches you pick into the repository's `.deja/memory.jsonl`, redacted, for review and commit. Whoever clones it gets them in recall. |
  188. | `deja view` | Your whole memory as one local HTML file ([live demo](https://vshulcz.github.io/deja-vu/view/)). No server, and the file never leaves the machine. |
  189. | `deja stats` | Your agent work, wrapped. `--no-index` scans local stores before installing, `--card` draws it in the terminal or SVG, `--html` writes a browsable timeline. |
  190. | `deja secrets [--scrub]` | Which sessions' source transcripts carry credentials, and what kind. Never prints a value. `--scrub` rewrites the ones it can, original kept beside the file. |
  191. | `deja rules [sync]` | Keep your standing rules in `~/.config/deja/rules.md`; `sync` copies them as a marked block into every installed agent's global rules file. |
  192. | `deja rules candidates [--json] [--limit n] [--since 90d] [--project name] [--repo]` | The turns where you corrected an agent, across every tool (or scoped to `--repo` / `--project`), numbered with their session. Ask your agent to suggest rules and it groups them; nothing is written until you pick. |
  193. | `deja audit [--json]` | Read-only check of local agent stores, Claude Code `cleanupPeriodDays` transcript deletion risk, preserved deleted sessions, recoverable edit paths, and wiring state. |
  194. | `deja doctor [--deep]` | Self-diagnosis, and with `--deep`, proof of the index against the sources. |
  195. | `deja mcp` | The stdio MCP server, which is what `deja install` wires in. |
  196. </details>
  197. Full reference: [commands](https://vshulcz.github.io/deja-vu/guide/commands.html) and
  198. [JSON output](docs/json-output.md).
  199. ### MCP tools
  200. The server exposes one tool, `deja`, with a `mode`; `deja install` wires it in. One tool
  201. costs 477 tokens of definitions a turn, against 8,283 for the largest of the seven servers
  202. measured in [day zero](https://vshulcz.github.io/deja-vu/guide/day-zero.html). The six
  203. older tool names (`recall`, `recall_context`, `blame`, `fix`, `how`, `remember`) still answer.
  204. `deja mcp --context-search` is a separate server with a single `context_search` tool, for
  205. Qwen Code's External Context MCP Profile v1 ([Qwen page](docs/registry/qwen.md)).
  206. <details>
  207. <summary>Arguments and return shapes</summary>
  208. | Tool | Arguments | Returns |
  209. | --- | --- | --- |
  210. | `deja` | `mode`, `q`, `harness?`, `project?`, `limit?` | Depends on the mode, below. |
  211. `q` carries whatever the mode asks about. The per-mode names below are still
  212. accepted; they are no longer declared, because the schema is read every turn
  213. whether or not the tool is called.
  214. | Mode | `q` is | Also reads | Returns |
  215. | --- | --- | --- | --- |
  216. | `recall` | 1-3 exact terms: a file path, an error string, a flag or identifier | `harness?`, `limit?`, `offset?` | Dense matching snippets, capped at 4KB. |
  217. | `context` | the same as recall | `harness?` | Markdown digest of the best-matching session, with the code it changed. |
  218. | `blame` | a file path | `harness?`, `project?`, `since?`, `limit?`, `all?` | Sessions that discussed a file. |
  219. | `fix` | the failing output, verbatim | `limit?` | What this machine ran, or changed, after that same error before. |
  220. | `how` | the tool or target, e.g. `go test` | `project?`, `limit?` | The real invocation, from what agents ran here. |
  221. | `orient` | nothing — it asks about the project | `project?`, `limit?` | The commands past sessions ran here and the files they worked in. |
  222. | `remember` | one durable fact or decision | `project?`, `tags?` | Stores a durable decision for later recall. `project` `repo:` (or `repo:rejected`, `repo:gotcha`) writes it into this repository's `.deja/memory.jsonl` instead, uncommitted. |
  223. | `handoff` | a session id or harness name; empty for the newest session here | `harness?` | Another session's goal, standing instructions, latest conclusions, passed checks and where it stopped, to continue it. |
  224. </details>
  225. ## Supported harnesses
  226. <!-- matrix:start -->
  227. aider &middot; Amp &middot; Antigravity &middot; Cherry Studio &middot; Claude Code &middot; Claw Code &middot; Cline &middot; CodeArts Desktop &middot; CodeBuddy Code &middot; CodeWhale &middot; Codex CLI &middot; Command Code &middot; Continue &middot; Copilot CLI &middot; VS Code Copilot Chat &middot; Crush &middot; Cursor &middot; DeepSeek Harness &middot; Devin CLI &middot; Gemini CLI &middot; gajae-code &middot; Goose &middot; Grok Build &middot; Hermes &middot; JetBrains AI Assistant &middot; Junie &middot; Kilo Code &middot; Kimchi Coding &middot; Kimi Code &middot; Kiro &middot; MiniMax Code &middot; MiMo-Code &middot; Muse Code &middot; Omnigent &middot; omp (Oh My Pi) &middot; OpenClaw &middot; opencode &middot; Orca &middot; pi &middot; prime-agent (PrimeIntellect) &middot; Qwen Code &middot; Reasonix &middot; Roo Code &middot; Senpi &middot; TRAE CLI &middot; Windsurf / Devin Desktop &middot; ZCode &middot; Zed.
  228. <details>
  229. <summary>What each one supports</summary>
  230. | Harness | MCP recall | Auto-recall | Skill | Command | Resume | Handoff | Needs |
  231. | --- | :-: | :-: | :-: | :-: | :-: | :-: | --- |
  232. | aider | ⚠ | ✅ | ✕ | ⚠ | ✕ | ✅ | deja aider |
  233. | Amp | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | threads from 0.0.1774963753 on live on ampcode.com; deja reads those its plugin has written out, and older local ones |
  234. | Antigravity | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  235. | Cherry Studio | ✅ | ✅ | ✅ | ✕ | ✕ | paste | import the server once in Settings -> MCP; enable the skill for the agent |
  236. | Claude Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  237. | Claw Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  238. | Cline | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  239. | CodeArts Desktop | ⚠ | ⚠ | ⚠ | ⚠ | ✕ | paste | — |
  240. | CodeBuddy Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  241. | CodeWhale | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  242. | Codex CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  243. | Command Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  244. | Continue | ✅ | ⚠ | ✅ | ✅ | ✅ | ✅ | — |
  245. | Copilot CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  246. | VS Code Copilot Chat | ✅ | ✅ | ✅ | ✅ | ✕ | ✅ | — |
  247. | Crush | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
  248. | Cursor | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 (IDE chats, CLI tool output) |
  249. | DeepSeek Harness | ✅ | ✅ | ✅ | ✅ | ✕ | ✅ | zstd |
  250. | Devin CLI | ✅ | ✅ | ✅ | ✕ | ✅ | ✅ | sqlite3 |
  251. | Gemini CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  252. | gajae-code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  253. | Goose | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | deja goose |
  254. | Grok Build | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 (grok-dev store) |
  255. | Hermes | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
  256. | JetBrains AI Assistant | ✅ | ⚠ | ⚠ | ⚠ | ✕ | paste | none |
  257. | Junie | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  258. | Kilo Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 for the CLI store |
  259. | Kimchi Coding | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  260. | Kimi Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  261. | Kiro | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 for the CLI database |
  262. | MiniMax Code | ✅ | ✅ | ✅ | ✕ | ✅ | ✅ | the MiniMax Code CLI (`mcode`) for `deja resume` and `deja handoff --to mcode --exec`; `sqlite3` for the session's workspace |
  263. | MiMo-Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
  264. | Muse Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  265. | Omnigent | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
  266. | omp (Oh My Pi) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  267. | OpenClaw | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 (2026.8+ store); zstd for .zst archives and compressed events (2026.9.9+) |
  268. | opencode | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
  269. | Orca | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
  270. | pi | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  271. | prime-agent (PrimeIntellect) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  272. | Qwen Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
  273. | Reasonix | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | zstd for 1.x sessions |
  274. | Roo Code | ✅ | ✕ | ✅ | ✅ | ✅ | paste | roo CLI (editor tasks reopen in the editor) |
  275. | Senpi | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  276. | TRAE CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
  277. | Windsurf / Devin Desktop | ✅ | ⚠ | ✅ | ✅ | ✕ | paste | none |
  278. | ZCode | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 for the CLI database |
  279. | Zed | ✅ | ✕ | ✅ | ✅ | ✕ | paste | sqlite3 + zstd |
  280. ✅ works &middot; — possible, not built yet &middot; ✕ the harness has no such mechanism &middot; ⚠ waiting on the harness itself &middot; ? not investigated
  281. </details>
  282. <!-- matrix:end -->
  283. TRAE IDE is wired, not read: its chats are in an encrypted database. `deja install trae-ide`
  284. adds the MCP server and the skill, and `trae-ide-auto` adds hooks, which TRAE IDE runs only
  285. after you turn them on in Settings > Hooks.
  286. Custom store locations go through `DEJA_*_ROOT` variables, and each agent's own relocation
  287. variable is honored too. The
  288. [session format registry](https://vshulcz.github.io/deja-vu/registry/README.html) documents
  289. the observed paths, record schemas and role mapping per harness, with synthetic fixtures
  290. keeping those descriptions checked against the parsers.
  291. ### Harnesses with a package of their own
  292. `deja install --auto` wires every one of these like every other harness, and
  293. that stays the shortest path. They also have a package in their own ecosystem,
  294. for people who install extensions there rather than from a CLI:
  295. | Harness | Package | Install |
  296. | --- | --- | --- |
  297. | opencode | npm `opencode-deja` | `opencode plugin add opencode-deja` |
  298. | DeepSeek Harness | npm `dsh-deja` | `dsh plugin --profile web add dsh-deja` |
  299. | Zed | `deja-context-server` | Zed → Extensions → deja |
  300. | Kimi Code | plugin `deja` | `/plugins install https://github.com/vshulcz/deja-vu` |
  301. | Gemini CLI | extension `@vshulcz/deja`, in the [Gemini CLI Extensions Gallery](https://geminicli.com/extensions/) | `gemini extensions install https://github.com/vshulcz/deja-vu` |
  302. | Antigravity | plugin `deja-vu` ([`antigravity-plugin/`](antigravity-plugin/)) | `agy plugin install deja-vu` |
  303. | Codex CLI | plugin `deja-vu` | `codex plugin marketplace add https://github.com/vshulcz/deja-vu` then `codex plugin add deja-vu@deja-vu` |
  304. | Grok Build | plugin `deja` | `grok plugin marketplace add vshulcz/deja-vu` then `grok plugin install deja` |
  305. | OpenClaw | ClawHub and npm `@vshulcz/openclaw-deja` | `openclaw plugins install clawhub:@vshulcz/openclaw-deja` |
  306. | pi (and omp) | npm `@vshulcz/pi-deja` | `pi install npm:@vshulcz/pi-deja` |
  307. | Hermes | memory provider `deja-memory`, in the Hermes plugin catalog | `hermes plugins install deja-memory`, or from GitHub: `hermes plugins install vshulcz/deja-vu/extensions/hermes` |
  308. | Magpie | npm `@vshulcz/magpie-deja` | `magpie plugin add @vshulcz/magpie-deja` |
  309. | Orca | v2 `trusted-worker` plugin `deja` | `Orca → Plugins → extensions/orca` (and `deja install orca` for native MCP and hooks) |
  310. | CodeWhale | Claude-compatible bundle `deja-vu` | `/plugin install extensions/codewhale` (and `deja install codewhale` for native hooks) |
  311. | VS Code / Cursor / Windsurf | status bar extension `vshulcz.deja-status` | `code --install-extension vshulcz.deja-status` |
  312. | JetBrains IDEs | [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/35998-deja-vu-cross-agent-ai-session-memory) (`com.github.vshulcz.deja-vu`) | `idea installPlugins com.github.vshulcz.deja-vu` |
  313. | Neovim | `lazy.nvim` &amp; CodeCompanion plugin ([`extensions/nvim/`](extensions/nvim/)) | `{ "vshulcz/deja-vu", opts = {} }` |
  314. | tmux | [TPM](https://github.com/tmux-plugins/tpm) popup (`prefix + D`) &amp; `#{deja_status}` (`deja.tmux`) | `set -g @plugin 'vshulcz/deja-vu'` |
  315. | Raycast | Raycast extension `deja-vu` | `cd extensions/raycast && npm install && npx ray develop` |
  316. | CC Switch | 1-click MCP &amp; Skill Repo import (`ccswitch://`) | [Add MCP to CC Switch](ccswitch://v1/import?resource=mcp&apps=claude,codex,gemini,opencode&config=eyJtY3BTZXJ2ZXJzIjp7ImRlamEiOnsiY29tbWFuZCI6Im5weCIsImFyZ3MiOlsiLXkiLCJAdnNodWxjei9kZWphLXZ1Iiwic2VydmUiXX19fQ==) · [Switching guide](https://vshulcz.github.io/deja-vu/guide/switch-agents-without-losing-context.html) |
  317. Either path works alone, and both together double nothing: each package reads what
  318. `deja install` already wrote and uses the deja you already have.
  319. In a [Spec Kit](https://github.com/github/spec-kit) project, an extension adds
  320. `/speckit.deja-vu.recall`, which searches past sessions for the feature before you
  321. implement it:
  322. ```sh
  323. specify extension add deja-vu --from https://github.com/vshulcz/deja-vu/releases/latest/download/deja-spec-kit.zip
  324. ```
  325. The same search is also a skill, for any agent that loads a `SKILL.md`:
  326. ```sh
  327. npx skills add https://github.com/vshulcz/deja-vu --skill deja-search # skills CLI: Claude Code, Cursor, Goose, Copilot…
  328. openclaw skills install @vshulcz/deja-search # ClawHub
  329. hermes skills install vshulcz/deja-vu/skills/deja-search # Hermes
  330. ```
  331. The skill drives the `deja` binary from the install step above; it does not bundle one.
  332. ## Semantic recall (optional)
  333. Point `deja embed` at a local Ollama, LM Studio or OpenAI-compatible endpoint with
  334. `DEJA_EMBED_URL` and rephrased queries still hit. Without a reachable runtime, lexical
  335. search and MCP recall continue unchanged. OpenAI Platform works with its standard key:
  336. ```sh
  337. export OPENAI_API_KEY='sk-...'
  338. export DEJA_EMBED_URL='https://api.openai.com/v1/embeddings'
  339. export DEJA_EMBED_MODEL='text-embedding-3-small'
  340. deja embed
  341. ```
  342. <details>
  343. <summary>Local runtimes, other endpoints, and what vectors cost</summary>
  344. With no `DEJA_EMBED_URL` set, deja probes `localhost:11434` and `localhost:1234`,
  345. so a machine already running Ollama or LM Studio is picked up without being asked.
  346. `DEJA_EMBED_OFF=1`, or `DEJA_EMBED_URL=off`, turns that probe off — any other
  347. configured `DEJA_EMBED_URL` still wins.
  348. For another authenticated OpenAI-compatible endpoint, set `DEJA_EMBED_KEY` explicitly:
  349. ```sh
  350. export DEJA_EMBED_URL='https://example.com/v1/embeddings'
  351. export DEJA_EMBED_MODEL='embedding-model'
  352. export DEJA_EMBED_KEY='...'
  353. deja embed
  354. ```
  355. `DEJA_EMBED_KEY` takes precedence. `OPENAI_API_KEY` is used automatically only for an
  356. HTTPS `api.openai.com` URL; it is never implicitly sent to local or third-party endpoints.
  357. Models trained with instruction prefixes, such as the multilingual E5 family, need them on
  358. both sides. `DEJA_EMBED_QUERY_PREFIX` goes in front of every search query and
  359. `DEJA_EMBED_PASSAGE_PREFIX` in front of every indexed text; both are empty by default:
  360. ```sh
  361. export DEJA_EMBED_MODEL='multilingual-e5-small'
  362. export DEJA_EMBED_QUERY_PREFIX='query: '
  363. export DEJA_EMBED_PASSAGE_PREFIX='passage: '
  364. deja embed
  365. ```
  366. The passage prefix is part of the sidecar's model name, so changing it embeds everything
  367. again, and search ignores vectors made with another model or prefix (it says so once).
  368. The sidecar sits beside the index as `.vectors.bin`, not inside `index.db`. Float32 vectors
  369. cost roughly 4 MB per 1k messages for a 1,024 dimension model. A remote endpoint receives
  370. the redacted indexed text, truncated to about 2k characters, but never raw source files.
  371. With Ollama or LM Studio, embedding stays local and needs no key.
  372. </details>
  373. ## Proof
  374. Millisecond lookups, and on LongMemEval-S 88.9% hit@1 (470-question cleaned set) and 88.2% hit@1 on all 500 questions;
  375. on LoCoMo retrieval, 71.9% hit@1. On a task this machine had already solved, 58% fewer
  376. tokens: eleven runs an arm, 53,558 against 126,222 with nothing wired, and 52,815 against
  377. 103,443 on a later build with the arms alternated. Both retrieval harnesses ship in this repo
  378. and run on the public datasets in minutes: [benchmarks](https://vshulcz.github.io/deja-vu/guide/benchmarks.html) ·
  379. [what one task costs](https://vshulcz.github.io/deja-vu/guide/day-zero.html).
  380. The rest is measured by `deja bench`:
  381. ```sh
  382. deja bench recall # ranking floor: 100 queries, half Russian, CI fails if recall drops
  383. deja bench context # 30 seeded task chains plus five negative controls
  384. deja bench block # does the answer survive into what deja hands over
  385. deja bench prompt # what the per-prompt hook fires on, and what it fires on wrongly
  386. deja bench ingest # what an update costs: unchanged, a turn, a new transcript, a rename, a rewrite
  387. deja bench read # what it costs to read a database-backed store, and what one long value does to it
  388. ```
  389. <details>
  390. <summary>What the in-repo benches measure, and lookup cost on a real store</summary>
  391. `bench block` asks the question the others cannot: with the right session in
  392. hand, does the block carry what that session settled. Eight sessions discuss each
  393. subject and one of them settles it, in the middle of its own transcript rather
  394. than at the end — so the baseline arm, the newest turns of the top hit, scores
  395. zero and an arm above zero had to choose.
  396. | Arm | Carries the answer | Median tokens |
  397. |---|---|---|
  398. | `deja-block` (session-start block) | 1.00 | 665 |
  399. | `deja-digest` (context digest) | 1.00 | 1656 |
  400. | `newest-turn` (baseline) | 0.00 | 289 |
  401. | `cold` | 0.00 | 0 |
  402. The context experiment compares deja-recall against full-history, naive grep and cold
  403. context. With the default seed:
  404. | Arm | Median tokens | Median coverage | Negative-control tokens |
  405. | --- | ---: | ---: | ---: |
  406. | deja-recall | 1,096 | 1.00 | 0 |
  407. | full-history | 80,547 | 1.00 | 78,145 |
  408. | naive-grep | 273,238 | 1.00 | 0 |
  409. | cold | 0 | 0.00 | 0 |
  410. Same fact coverage as grepping the raw logs for about 250x fewer tokens, and about 70x
  411. fewer than replaying the matched sessions in full, while injecting nothing on the chains
  412. where no prior fact is relevant. The corpus generator and the relevance labels are
  413. ordinary reviewed Go. Audit what "relevant" means before trusting any figure, ours
  414. included.
  415. Measured on a real store of 2,419 sessions and 179k messages, 1.9 GB of
  416. transcripts:
  417. | Measurement | Result |
  418. | --- | --- |
  419. | Lookup, in process | **0.7–0.8 ms** median (`deja bench recall`, 100 queries, half of them Russian), ~15 ms on the LongMemEval-S haystacks |
  420. | `deja <query>`, end to end | ~0.2 s median on that store: process start, the freshness check over every store, ranking, printing |
  421. | Freshness check alone | ~50 ms when nothing changed |
  422. | Index size | 200 MB, ~10% of corpus |
  423. The same store has since grown to 2,754 sessions, 358k messages and 5.7 GB.
  424. A cold full build over it takes 71 s and writes a 232 MB index — 4% of the
  425. corpus, because the share falls as transcripts repeat themselves — and the
  426. end-to-end median is unchanged at 0.25 s. Since 0.23.2 records are compressed
  427. from 256 bytes, which takes a 19k-session index from 277 to 185 MB.
  428. The index is incremental. When a session file grows, only that file is re-read. When one is
  429. rewritten, its new records are appended and the old ones zeroed in place. On a
  430. 40,000-session store a pass over 20 rewritten transcripts takes 1.7 s and peaks under 1 GB,
  431. and a search for a word most sessions hold takes about a second.
  432. </details>
  433. ### How it compares
  434. | Capability | `deja-vu` | `claude-mem` | `MemPalace` |
  435. | --- | --- | --- | --- |
  436. | History before install ([day zero](https://vshulcz.github.io/deja-vu/guide/day-zero.html)) | Yes — indexes existing transcripts (`36/100` hit@1) | No — records from install onward (`0/100`) | Claude Code, Codex, Cursor (`16/100`) |
  437. | Agents shared | 48 harnesses | 9 (hooks) | 3 (CLI) |
  438. | LongMemEval-S R@5 | **97.2%** (88.9% hit@1) | — | 96.6% |
  439. | Runtime & dependencies | 1 Go binary | Bun worker + SQLite + Chroma | Python + 300 MB embedding model |
  440. | LLM calls / account required | None | Observer LLM calls | None |
  441. | Uncommitted file recovery | `deja restore <path>` | No | No |
  442. | Existing `claude-mem.db` | Reads `~/.claude-mem/claude-mem.db` directly | Native | No |
  443. Side-by-side notes: [all 15 tools compared](https://vshulcz.github.io/deja-vu/guide/compare.html) · [claude-mem alternative](https://vshulcz.github.io/deja-vu/guide/claude-mem-alternative.html) · [Mem0 alternative](https://vshulcz.github.io/deja-vu/guide/mem0-alternative.html) · [SpecStory alternative](https://vshulcz.github.io/deja-vu/guide/specstory-alternative.html) · [Basic Memory alternative](https://vshulcz.github.io/deja-vu/guide/basic-memory-alternative.html).
  444. ## How it works
  445. Local inverted index in `~/.cache/deja`: parse the JSONL and SQLite stores, redact
  446. credentials, write an append-only `records.bin` plus token buckets, and track per-file state in
  447. `manifest.gob` so repeat runs only ingest what changed. The MCP server, stats, share and
  448. sync all read that one index. Details in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
  449. ## FAQ
  450. <details>
  451. <summary><b>How is this different from the other memory tools?</b></summary>
  452. | | deja | Memory platforms<br>(Mem0, Letta, memU) | Session search<br>(cass) |
  453. | --- | :-: | :-: | :-: |
  454. | Knows work from before you installed it | yes | no | yes |
  455. | Capture step | none, the transcripts are the memory | the agent or your code writes facts | none |
  456. | Needs an LLM or embedding key | no | yes | optional |
  457. | Recalls without being asked | at session start and before a tool runs | no | no |
  458. [engram](https://github.com/Gentleman-Programming/engram) is the strongest of the
  459. record-forward tools and worth your time if that model fits you; it still starts empty and
  460. knows only what an agent chose to save. The
  461. [full comparison](https://vshulcz.github.io/deja-vu/guide/compare.html) covers 15 of them.
  462. </details>
  463. <details>
  464. <summary><b>Will it slow my agent down?</b></summary>
  465. A recall is a lexical lookup against a local index:
  466. 0.7–0.8 ms median, and nothing waits on a model. A hook adds the process start and a
  467. freshness check over your stores on top of that: about 0.2 s end to end on a 1.9 GB
  468. store. On an index of 19k sessions the per-prompt hook takes 107 ms at the median,
  469. and a recall through `deja mcp` 85 ms.
  470. </details>
  471. <details>
  472. <summary><b>Where is Claude Code session history stored, and can I search it?</b></summary>
  473. Under `~/.claude/projects`, one JSONL file per session; Codex keeps `~/.codex/sessions`, Cursor a
  474. SQLite `state.vscdb`. deja reads them all in place: bare `deja` opens a screen to search
  475. and read them, `deja search` does it from a script, `deja last` lists the recent
  476. sessions of every agent, and `deja view` opens the whole history as one local page. Paths
  477. for each agent: [where sessions are stored](https://vshulcz.github.io/deja-vu/guide/where-sessions-are-stored.html).
  478. </details>
  479. <details>
  480. <summary><b>My Claude Code session history disappeared. Is it gone?</b></summary>
  481. Claude Code deletes transcripts older than 30 days (`cleanupPeriodDays` in `~/.claude/settings.json`), and `claude --resume` lists
  482. only what is left. A session deja indexed before the cleanup stays searchable after the
  483. file is gone, and the weekly note at session start says how many it kept, with an id
  484. `deja resume <id> --write-back` puts back. Details: [session files on disk](https://vshulcz.github.io/deja-vu/guide/session-files-on-disk.html).
  485. </details>
  486. <details>
  487. <summary><b>What files live in ~/.config/deja, and what can I set in them?</b></summary>
  488. Under `~/.config/deja` (or `$XDG_CONFIG_HOME/deja`):
  489. - **`policy.json`** (`DEJA_POLICY_FILE` moves it) — JSON object with four optional keys:
  490. - `"activations"`: per-surface origin rules for `"search"`, `"mcp"` and `"auto"` (hooks), keyed by `"local"`, `"imported"`, `"imported:<group>"` or `"*"` (`true`/`false`). `DEJA_AUTORECALL_LOCAL_ONLY=1` sets `activations.auto.imported` to `false`.
  491. - `"ignore"`: array of shell globs matched against session path and project to exclude from recall and `sync` (default `["*/.claude/jobs/*"]`).
  492. - `"auto_index"`: `false` stops automatic index updates on search, MCP recall and hooks (same as `DEJA_NO_AUTO_INDEX=1`).
  493. - `"search_only"`: `true` skips mining fixes, commands and co-occurrence, saving ~20% of build CPU (same as `DEJA_SEARCH_ONLY=1`).
  494. - **`exclude`** — one project name or path pattern per line to skip at index time and `sync export`, or `harness:<name>` (e.g. `harness:opencode`) to skip a store (`DEJA_EXCLUDE_PROJECTS`, `DEJA_EXCLUDE_HARNESSES`).
  495. - **`projects`** — one `<path> = <name>` per line to group multiple checkouts or worktrees as one project.
  496. - **`rules.md`** — standing instructions copied into each installed agent's global rules file by `deja rules sync`.
  497. - **State files written by deja** — `peers.json` (`deja sync ssh`), `settled.json` (`deja friction --settle`), `tombstones` (`deja forget`), `wiring.json` and `bin/deja-hook` (`deja install`).
  498. Hook recall mode is set by `DEJA_RECALL`: `safe` (default, 2 KB cap and up to 3 sessions from the current project at session start), `aggressive` (4 KB cap and up to 6 sessions across projects), or `off` (silences all hooks). The `DEJA_INDEX_*` switches and full configuration table are in the [commands guide](https://vshulcz.github.io/deja-vu/guide/commands.html#configuration).
  499. </details>
  500. <details>
  501. <summary><b>One project is spread over several checkouts. Can recall treat them as one?</b></summary>
  502. List the trees in `~/.config/deja/projects`, one `<path> = <name>` per line:
  503. ```text
  504. ~/work/monorepo = work
  505. ~/work/worktrees = work
  506. ```
  507. Every directory under a listed path is then that project, for indexing, the hooks and recall alike; the longest matching path wins. Run `deja index --rebuild` to re-file existing transcripts under the new name. The exclude file still wins over project aliases.
  508. </details>
  509. <details>
  510. <summary><b>How do I wipe everything?</b></summary>
  511. ```sh
  512. deja uninstall --all
  513. rm -rf ~/.cache/deja ~/.local/share/deja ~/.config/deja
  514. ```
  515. The index is under `~/.cache/deja`, your `remember` and `promote` notes in
  516. `~/.local/share/deja`, and the rules, exclude list, project aliases and hook launcher in
  517. `~/.config/deja` (or under `XDG_DATA_HOME` and `XDG_CONFIG_HOME` when set; on
  518. Windows the notes are in `%AppData%\deja`).
  519. </details>
  520. ## Guides
  521. - **Context & recovery:** [Recovering overwritten uncommitted files](https://vshulcz.github.io/deja-vu/guide/recover-overwritten-files.html) · [Does your agent remember previous conversations?](https://vshulcz.github.io/deja-vu/guide/does-my-agent-remember.html) · [The agent lost the context you had](https://vshulcz.github.io/deja-vu/guide/lost-context.html) · [The context window is full](https://vshulcz.github.io/deja-vu/guide/context-window-full.html) · [What compaction drops](https://vshulcz.github.io/deja-vu/guide/after-compaction.html) · [Why agents forget between sessions](https://vshulcz.github.io/deja-vu/guide/forgetting.html)
  522. - **Resuming & finding:** [Claude Code usage-limit handoff](https://vshulcz.github.io/deja-vu/guide/claude-code-usage-limit-handoff.html) · [Resuming yesterday's session](https://vshulcz.github.io/deja-vu/guide/resume-a-session.html) · [Finding the session where you solved it](https://vshulcz.github.io/deja-vu/guide/find-a-session.html) · [The agent repeats a mistake you already fixed](https://vshulcz.github.io/deja-vu/guide/repeated-mistakes.html) · [Switching agents](https://vshulcz.github.io/deja-vu/guide/switching-agents.html)
  523. - **Session files & cleanup:** [Session files on disk](https://vshulcz.github.io/deja-vu/guide/session-files-on-disk.html) · [Where each agent keeps its history](https://vshulcz.github.io/deja-vu/guide/where-sessions-are-stored.html) · [Recovering a deleted Claude Code session](https://vshulcz.github.io/deja-vu/guide/recover-a-deleted-session.html) · [Claude Code: No conversation found with session ID](https://vshulcz.github.io/deja-vu/guide/no-conversation-found-claude-code.html) · [Cursor state.vscdb too large](https://vshulcz.github.io/deja-vu/guide/cursor-state-vscdb-too-large.html) · [Codex resume session](https://vshulcz.github.io/deja-vu/guide/codex-resume-session.html) · [Deleting old Claude Code sessions](https://vshulcz.github.io/deja-vu/guide/delete-old-claude-sessions.html)
  524. - **Comparisons & operations:** [What each memory tool knows the day you install it](https://vshulcz.github.io/deja-vu/guide/day-zero.html) · [Memory plugins compared](https://vshulcz.github.io/deja-vu/guide/compare.html) · [claude-mem alternative](https://vshulcz.github.io/deja-vu/guide/claude-mem-alternative.html) · [Mem0 alternative](https://vshulcz.github.io/deja-vu/guide/mem0-alternative.html) · [SpecStory alternative](https://vshulcz.github.io/deja-vu/guide/specstory-alternative.html) · [Basic Memory alternative](https://vshulcz.github.io/deja-vu/guide/basic-memory-alternative.html) · [What memory costs](https://vshulcz.github.io/deja-vu/guide/token-cost.html) · [Auditing an agent](https://vshulcz.github.io/deja-vu/guide/auditing-agents.html) · [Exporting a conversation](https://vshulcz.github.io/deja-vu/guide/export-conversations.html) · [Across machines](https://vshulcz.github.io/deja-vu/guide/sync-across-machines.html)
  525. <details>
  526. <summary><b>Per-harness setup guides (Claude Code, Codex, Cursor, OpenClaw, Hermes…)</b></summary>
  527. [Claude Code](https://vshulcz.github.io/deja-vu/guide/memory-for-claude-code.html) · [Codex](https://vshulcz.github.io/deja-vu/guide/memory-for-codex.html) · [Cursor](https://vshulcz.github.io/deja-vu/guide/memory-for-cursor.html) · [Windsurf](https://vshulcz.github.io/deja-vu/guide/memory-for-windsurf.html) · [opencode](https://vshulcz.github.io/deja-vu/guide/memory-for-opencode.html) · [DeepSeek Harness](https://vshulcz.github.io/deja-vu/guide/memory-for-dsh.html) · [Kimi Code](https://vshulcz.github.io/deja-vu/guide/memory-for-kimi.html) · [Zed](https://vshulcz.github.io/deja-vu/guide/memory-for-zed.html) · [Grok Build](https://vshulcz.github.io/deja-vu/guide/memory-for-grok.html) · [Gemini CLI](https://vshulcz.github.io/deja-vu/guide/memory-for-gemini.html) · [Qwen Code](https://vshulcz.github.io/deja-vu/guide/memory-for-qwen.html) · [OpenClaw](https://vshulcz.github.io/deja-vu/guide/memory-for-openclaw.html) · [Goose](https://vshulcz.github.io/deja-vu/guide/memory-for-goose.html) · [Cline](https://vshulcz.github.io/deja-vu/guide/memory-for-cline.html) · [pi](https://vshulcz.github.io/deja-vu/guide/memory-for-pi.html) · [Hermes](https://vshulcz.github.io/deja-vu/guide/memory-for-hermes.html) · [Copilot CLI](https://vshulcz.github.io/deja-vu/guide/memory-for-copilot.html) · [Copilot Chat](https://vshulcz.github.io/deja-vu/guide/memory-for-copilot-chat.html) · [aider](https://vshulcz.github.io/deja-vu/guide/memory-for-aider.html) · [Amp](https://vshulcz.github.io/deja-vu/guide/memory-for-amp.html) · [Antigravity](https://vshulcz.github.io/deja-vu/guide/memory-for-antigravity.html) · [Continue](https://vshulcz.github.io/deja-vu/guide/memory-for-continue.html) · [Crush](https://vshulcz.github.io/deja-vu/guide/memory-for-crush.html) · [Roo Code](https://vshulcz.github.io/deja-vu/guide/memory-for-roo.html) · [Kilo Code](https://vshulcz.github.io/deja-vu/guide/memory-for-kilocode.html) · [Kiro](https://vshulcz.github.io/deja-vu/guide/memory-for-kiro.html) · [Cherry Studio](https://vshulcz.github.io/deja-vu/guide/memory-for-cherrystudio.html) · [Oh My Pi](https://vshulcz.github.io/deja-vu/guide/memory-for-omp.html) · [prime-agent](https://vshulcz.github.io/deja-vu/guide/memory-for-prime.html) · [Senpi](https://vshulcz.github.io/deja-vu/guide/memory-for-senpi.html) · [Kimchi](https://vshulcz.github.io/deja-vu/guide/memory-for-kimchi.html) · [Command Code](https://vshulcz.github.io/deja-vu/guide/memory-for-commandcode.html) · [ZCode](https://vshulcz.github.io/deja-vu/guide/memory-for-zcode.html) · [gjc](https://vshulcz.github.io/deja-vu/guide/memory-for-gjc.html) · [CodeWhale](https://vshulcz.github.io/deja-vu/guide/memory-for-codewhale.html) · [Reasonix](https://vshulcz.github.io/deja-vu/guide/memory-for-reasonix.html) · [TRAE CLI](https://vshulcz.github.io/deja-vu/guide/memory-for-trae.html)
  528. </details>
  529. ## Contributing
  530. `make build test lint`, then [CONTRIBUTING.md](CONTRIBUTING.md). Adding a harness starts in
  531. the [parser registry](docs/ARCHITECTURE.md#source-parsers). Priorities and non-goals are in
  532. [ROADMAP.md](ROADMAP.md). Good first issues are labeled.
  533. ## Support
  534. Bugs and questions go to [issues](https://github.com/vshulcz/deja-vu/issues).
  535. Anything you think is exploitable goes through the private advisory link in
  536. [SECURITY.md](SECURITY.md) instead. What deja reads, what it never sends
  537. anywhere, and how to exclude a project or forget a session is under
  538. [Privacy](#privacy). Found it useful? [Star deja-vu on GitHub](https://github.com/vshulcz/deja-vu).
  539. ## License
  540. MIT © [Vladislav Shulcz](https://github.com/vshulcz)
docs/assets/guide.js · Bundled script · 383 lines · 2 findings marked
  1. (function(){
  2. var ORDER=[
  3. ['getting-started.html','Getting started'],
  4. ['agents.html','Agents & MCP'],
  5. ['search.html','Search'],
  6. ['commands.html','CLI reference'],
  7. ['harnesses.html','Harnesses'],
  8. ['privacy.html','Privacy'],
  9. ['benchmarks.html','Benchmarks'],
  10. ['compare.html','Compare']
  11. ];
  12. var art=document.querySelector('.doc article');
  13. if(!art)return;
  14. /* copy buttons on code blocks */
  15. art.querySelectorAll('pre').forEach(function(pre){
  16. var b=document.createElement('button');
  17. b.className='pre-copy';b.type='button';b.textContent='copy';
  18. b.addEventListener('click',function(){
  19. navigator.clipboard.writeText(pre.textContent.trim());
  20. b.textContent='copied';setTimeout(function(){b.textContent='copy'},1200);
  21. });
  22. /* a lid rather than a button floating over the code: a control that only
  23. appears on hover is a control most readers never learn about */
  24. var text=pre.textContent.trim();
  25. var what=/^[$#]|\bdeja\b|^curl|^brew|^go /.test(text)?'shell':
  26. /^[{[]/.test(text)?'json':'text';
  27. var lid=document.createElement('div');lid.className='pre-lid';
  28. lid.innerHTML='<span class="what">'+what+'</span>';
  29. lid.appendChild(b);
  30. var wrapEl=document.createElement('div');wrapEl.className='pre-wrap';
  31. pre.parentNode.insertBefore(wrapEl,pre);
  32. wrapEl.appendChild(lid);wrapEl.appendChild(pre);
  33. });
  34. /* anchors on h2 */
  35. art.querySelectorAll('h2').forEach(function(h){
  36. if(!h.id)h.id=h.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
  37. var a=document.createElement('a');
  38. a.className='hlink';a.href='#'+h.id;a.textContent=' #';a.setAttribute('aria-label','link to section');
  39. h.appendChild(a);
  40. });
  41. /* prev / next */
  42. var here=location.pathname.split('/').pop()||ORDER[0][0];
  43. var i=ORDER.findIndex(function(x){return x[0]===here});
  44. if(i>=0){
  45. var nav=document.createElement('div');nav.className='pn';
  46. var prev=i>0?ORDER[i-1]:null,next=i<ORDER.length-1?ORDER[i+1]:null;
  47. /* the name alone does not say which way it goes, and an arrow alone does
  48. not say where. Both, with the direction as the quiet half. */
  49. nav.innerHTML=(prev?'<a class="pv" href="'+prev[0]+'"><small>Previous</small>'+prev[1]+'</a>':'<span></span>')+
  50. (next?'<a class="nx" href="'+next[0]+'"><small>Next</small>'+next[1]+'</a>':'<span></span>');
  51. art.appendChild(nav);
  52. }
  53. /* ── how long the page takes ───────────────────────────────────────── */
  54. (function(){
  55. var slot=art.querySelector('[data-mins]');
  56. if(!slot)return;
  57. var words=art.textContent.trim().split(/\s+/).length;
  58. slot.textContent=Math.max(1,Math.round(words/220))+' min read';
  59. })();
  60. /* ── the sidebar remembers what you have read ──────────────────────────
  61. The same idea the home page greets you with. Of every documentation site
  62. that could do this, one about a memory tool has the most right to. */
  63. (function(){
  64. var KEY='deja.read';
  65. var here=location.pathname.split('/').pop()||ORDER[0][0];
  66. var read={};
  67. try{read=JSON.parse(localStorage.getItem(KEY)||'{}')}catch(e){}
  68. read[here]=1;
  69. try{localStorage.setItem(KEY,JSON.stringify(read))}catch(e){}
  70. var side=document.querySelector('.doc aside');
  71. if(!side)return;
  72. var n=0;
  73. ORDER.forEach(function(pair){
  74. var a=side.querySelector('a[href="'+pair[0]+'"]');
  75. if(!a)return;
  76. if(read[pair[0]]){a.classList.add('read');a.title='read';n++}
  77. });
  78. var grp=side.querySelector('.grp');
  79. if(grp&&n){
  80. var c=document.createElement('span');
  81. c.className='count';c.textContent=n+'/'+ORDER.length;
  82. grp.appendChild(c);
  83. }
  84. })();
  85. /* ── say that the guide can be searched ────────────────────────────── */
  86. var docLang=(document.documentElement.lang||'en').toLowerCase();
  87. var isRu=docLang.indexOf('ru')===0,isZh=docLang.indexOf('zh')===0;
  88. (function(){
  89. var nav=document.querySelector('nav .spacer');
  90. if(!nav)return;
  91. var hint=document.createElement('button');
  92. hint.className='searchhint';hint.type='button';
  93. hint.innerHTML='<span>'+(isRu?'поиск по документации':isZh?'搜索指南':'search the guide')+'</span><kbd>/</kbd>';
  94. hint.addEventListener('click',function(){
  95. document.dispatchEvent(new KeyboardEvent('keydown',{key:'/',bubbles:true}));
  96. });
  97. nav.parentNode.insertBefore(hint,nav.nextSibling);
  98. /* upgrade the top nav with a Demo link and a prominent ★ GitHub button */
  99. var gh=nav.parentNode.querySelector('a[href*="github.com/vshulcz/deja-vu"]');
  100. if(gh){
  101. gh.className='nav-cta';
  102. gh.innerHTML='<span class="star-ic" aria-hidden="true">★</span>GitHub';
  103. var homeLink=nav.parentNode.querySelector('a.brand');
  104. var rootPrefix=homeLink?homeLink.getAttribute('href'):'../';
  105. if(rootPrefix.slice(-1)!=='/')rootPrefix+='/';
  106. if(!nav.parentNode.querySelector('a[href*="view/"]')){
  107. var demo=document.createElement('a');
  108. demo.className='lnk';
  109. demo.href=rootPrefix+'view/';
  110. demo.textContent=isRu?'Демо':isZh?'演示':'Demo';
  111. nav.parentNode.insertBefore(demo,gh);
  112. }
  113. }
  114. })();
  115. /* ── enrich the closing star CTA with a 1-click install & live demo ─── */
  116. (function(){
  117. var cta=art.querySelector('.star-cta');
  118. if(!cta){
  119. cta=document.createElement('p');
  120. cta.className='star-cta';
  121. art.appendChild(cta);
  122. }
  123. var homeLink=document.querySelector('nav a.brand');
  124. var rootPrefix=homeLink?homeLink.getAttribute('href'):'../';
  125. if(rootPrefix.slice(-1)!=='/')rootPrefix+='/';
  126. var cmdText='curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh';
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 135 on GitHub
  127. var leadTxt=isRu?'Установка за 10 секунд, индекс за 10.':isZh?'十秒安装,十秒建索引。':'Ten seconds to install, ten to index.';
  128. var starTxt=isRu?'★ Поставить звезду на GitHub':isZh?'★ 在 GitHub 上点 Star':'★ Star deja-vu on GitHub';
  129. var demoTxt=isRu?'Живое демо в браузере →':isZh?'浏览器在线演示 →':'Try live browser demo →';
  130. cta.innerHTML=
  131. '<div class="cta-cmd"><span class="p">$</span><code>'+cmdText+'</code><button type="button">copy</button></div>'+
  132. '<div class="cta-row"><span>'+leadTxt+'</span>'+
  133. '<a class="cta-btn" href="https://github.com/vshulcz/deja-vu">'+starTxt+'</a>'+
  134. '<a class="cta-demo" href="'+rootPrefix+'view/">'+demoTxt+'</a></div>';
  135. var btn=cta.querySelector('button');
  136. if(btn){
  137. btn.addEventListener('click',function(){
  138. navigator.clipboard.writeText(cmdText);
  139. btn.textContent='copied';
  140. setTimeout(function(){btn.textContent='copy'},1200);
  141. });
  142. }
  143. var saveFirst=art.querySelector('.save-first');
  144. /* a page that names its own commands writes them into the callout; the
  145. copy buttons there only need wiring */
  146. if(saveFirst)saveFirst.querySelectorAll('.save-actions .save-cmd').forEach(function(row){
  147. var b=row.querySelector('button'),c=row.querySelector('code');
  148. if(!b||!c)return;
  149. b.addEventListener('click',function(){
  150. navigator.clipboard.writeText(c.textContent);
  151. b.textContent='copied';
  152. setTimeout(function(){b.textContent='copy'},1200);
  153. });
  154. });
  155. if(saveFirst&&!saveFirst.querySelector('.save-actions')){
  156. var saveCmd='curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh && deja index';
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 166 on GitHub
  157. var bar=document.createElement('div');
  158. bar.className='save-actions';
  159. bar.innerHTML=
  160. '<div class="save-cmd"><span class="p">$</span><code>'+saveCmd+'</code><button type="button">copy</button></div>'+
  161. '<a class="save-btn" href="https://github.com/vshulcz/deja-vu">'+starTxt+'</a>'+
  162. '<a class="save-demo" href="'+rootPrefix+'view/">'+demoTxt+'</a>';
  163. saveFirst.appendChild(bar);
  164. var sbtn=bar.querySelector('button');
  165. if(sbtn){
  166. sbtn.addEventListener('click',function(){
  167. navigator.clipboard.writeText(saveCmd);
  168. sbtn.textContent='copied';
  169. setTimeout(function(){sbtn.textContent='copy'},1200);
  170. });
  171. }
  172. }
  173. })();
  174. /* ── the sidebar folds on a phone ───────────────────────────────────────
  175. Eleven links and a cat above the article means scrolling past the whole
  176. guide to reach the page you opened. */
  177. (function(){
  178. var side=document.querySelector('.doc aside');
  179. if(!side||!matchMedia('(max-width:860px)').matches)return;
  180. var here=side.querySelector('a[aria-current]');
  181. var box=document.createElement('details');
  182. box.className='sidefold';
  183. var head=document.createElement('summary');
  184. /* "Codex" alone could be the delete page or the memory one */
  185. var grp=here&&here.closest('details.grpfold');
  186. var where=grp?grp.querySelector('summary').firstChild.textContent.trim()+' · ':'';
  187. head.innerHTML='<span>Guide</span><b>'+(here?where+here.textContent.trim():'contents')+'</b>';
  188. box.appendChild(head);
  189. while(side.firstChild)box.appendChild(side.firstChild);
  190. side.appendChild(box);
  191. /* opening it should not leave the reader somewhere else when it closes */
  192. box.addEventListener('toggle',function(){
  193. if(!box.open)side.scrollIntoView({block:'nearest'});
  194. });
  195. })();
  196. /* new page behaviour goes above this line, inside this closure */
  197. /* ── a hairline that fills as you read ─────────────────────────────── */
  198. (function(){
  199. if(matchMedia('(prefers-reduced-motion: reduce)').matches)return;
  200. var bar=document.createElement('div');bar.className='progress';
  201. document.body.appendChild(bar);
  202. addEventListener('scroll',function(){
  203. var h=document.documentElement.scrollHeight-innerHeight;
  204. bar.style.transform='scaleX('+(h>0?scrollY/h:0)+')';
  205. },{passive:true});
  206. })();
  207. /* ── contents, with the section you are in marked ──────────────────── */
  208. (function(){
  209. var heads=[].slice.call(art.querySelectorAll('h2'));
  210. if(heads.length<3)return; /* three sections is where a list starts earning its place */
  211. /* a div, not a nav: the stylesheet's nav rule is the page header — flex,
  212. sticky, padded — and it applied to this one too, laying the sections out
  213. in a row that ran off the side of the page */
  214. var toc=document.createElement('div');
  215. toc.className='toc';toc.setAttribute('role','navigation');
  216. toc.setAttribute('aria-label','on this page');
  217. toc.innerHTML='<div class="grp">On this page</div>'+heads.map(function(h){
  218. return '<a href="#'+h.id+'">'+h.firstChild.textContent.trim()+'</a>';
  219. }).join('');
  220. document.querySelector('.doc').appendChild(toc);
  221. var links=[].slice.call(toc.querySelectorAll('a'));
  222. var seen=new Map();
  223. var io=new IntersectionObserver(function(es){
  224. es.forEach(function(e){seen.set(e.target,e.isIntersecting)});
  225. /* the first visible heading wins, so scrolling up marks the one you are
  226. arriving at rather than the one you are leaving */
  227. var current=heads.find(function(h){return seen.get(h)})||null;
  228. links.forEach(function(a,i){
  229. a.classList.toggle('on',current?heads[i]===current:i===0);
  230. });
  231. },{rootMargin:'-72px 0px -70% 0px'});
  232. heads.forEach(function(h){io.observe(h)});
  233. })();
  234. /* ── the docs are searchable ───────────────────────────────────────────
  235. A tool for searching your own history whose own pages cannot be searched
  236. is arguing against itself. The index is built in the browser, on the first
  237. keystroke, from the pages themselves — no service, nothing sent. */
  238. (function(){
  239. var box=document.createElement('div');
  240. box.className='palette';box.id='palette';box.setAttribute('aria-hidden','true');
  241. box.innerHTML='<div class="pbox"><input id="pq" type="search" autocomplete="off" '+
  242. 'spellcheck="false" placeholder="search the guide…" aria-label="search the guide">'+
  243. '<div class="phits" id="phits"></div>'+
  244. '<div class="pfoot"><span><kbd>↑↓</kbd> move · <kbd>↵</kbd> open · <kbd>esc</kbd> close</span>'+
  245. '<span class="plocal">indexed in your browser</span></div></div>';
  246. document.body.appendChild(box);
  247. var input=box.querySelector('#pq'),hits=box.querySelector('#phits');
  248. var docs=null,loading=null,sel=0,rows=[];
  249. function load(){
  250. if(docs)return Promise.resolve(docs);
  251. if(loading)return loading;
  252. /* Index every sidebar link immediately so all 95 guide pages and 43
  253. coding agents are reachable on the first keystroke, not only the 8
  254. pages in ORDER. */
  255. var seenUrls={};
  256. ORDER.forEach(function(pair){seenUrls[pair[0]]=true});
  257. var sidePages=[];
  258. document.querySelectorAll('.doc aside a[href$=".html"]').forEach(function(a){
  259. var url=a.getAttribute('href');
  260. if(!url||url.indexOf('..')===0||url.indexOf('http')===0||seenUrls[url])return;
  261. seenUrls[url]=true;
  262. var grp=a.closest('details.grpfold');
  263. var cat=grp?grp.querySelector('summary').firstChild.textContent.trim():'Guide';
  264. var label=a.textContent.trim();
  265. sidePages.push({page:cat,url:url,title:label,body:cat+' '+label+' '+url.replace(/[-.]/g,' ')});
  266. });
  267. loading=Promise.all(ORDER.map(function(pair){
  268. return fetch(pair[0]).then(function(r){return r.text()}).then(function(html){
  269. var d=new DOMParser().parseFromString(html,'text/html');
  270. var a=d.querySelector('.doc article');
  271. if(!a)return [];
  272. return [].slice.call(a.querySelectorAll('h1,h2')).map(function(h){
  273. var body='',n=h.nextElementSibling;
  274. while(n&&!/^H[12]$/.test(n.tagName)){body+=' '+n.textContent;n=n.nextElementSibling}
  275. var id=h.id||h.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
  276. return {page:pair[1],url:pair[0]+(h.tagName==='H1'?'':'#'+id),
  277. title:h.textContent.replace(/\s*#$/,'').trim(),body:body.slice(0,600)};
  278. });
  279. }).catch(function(){return []});
  280. })).then(function(all){docs=[].concat.apply([],all).concat(sidePages);return docs});
  281. return loading;
  282. }
  283. function run(q){
  284. q=q.trim().toLowerCase();
  285. if(!q){hits.innerHTML='<p class="pnone">every page of the guide, searchable from here</p>';rows=[];return}
  286. load().then(function(all){
  287. var words=q.split(/\s+/);
  288. var scored=all.map(function(d){
  289. var t=d.title.toLowerCase(),b=d.body.toLowerCase(),score=0;
  290. words.forEach(function(w){
  291. if(t.indexOf(w)>=0)score+=8;
  292. if(b.indexOf(w)>=0)score+=1;
  293. });
  294. return {d:d,score:score};
  295. }).filter(function(x){return x.score>0})
  296. .sort(function(a,b){return b.score-a.score}).slice(0,7);
  297. rows=scored.map(function(x){return x.d});
  298. sel=0;
  299. hits.innerHTML=rows.length?rows.map(function(d,i){
  300. return '<a class="phit'+(i?'':' on')+'" href="'+d.url+'"><b>'+d.title+
  301. '</b><span>'+d.page+'</span></a>';
  302. }).join(''):'<p class="pnone">nothing here — try recall, mcp, redaction</p>';
  303. });
  304. }
  305. function open(){box.classList.add('on');box.setAttribute('aria-hidden','false');
  306. input.value='';run('');input.focus()}
  307. function close(){box.classList.remove('on');box.setAttribute('aria-hidden','true')}
  308. input.addEventListener('input',function(){run(input.value)});
  309. box.addEventListener('click',function(e){if(e.target===box)close()});
  310. addEventListener('keydown',function(e){
  311. var tag=(e.target.tagName||'').toLowerCase();
  312. if((e.key==='k'&&(e.metaKey||e.ctrlKey))||(e.key==='/'&&tag!=='input'&&tag!=='textarea')){
  313. e.preventDefault();box.classList.contains('on')?close():open();return;
  314. }
  315. if(!box.classList.contains('on'))return;
  316. if(e.key==='Escape')return close();
  317. if(e.key==='ArrowDown'||e.key==='ArrowUp'){
  318. e.preventDefault();
  319. var list=hits.querySelectorAll('.phit');
  320. if(!list.length)return;
  321. sel=(sel+(e.key==='ArrowDown'?1:list.length-1))%list.length;
  322. list.forEach(function(el,i){el.classList.toggle('on',i===sel)});
  323. }
  324. if(e.key==='Enter'&&rows[sel])location.href=rows[sel].url;
  325. });
  326. })();
  327. /* ── the cat knows where it is ─────────────────────────────────────── */
  328. (function(){
  329. var cat=document.querySelector('.sidecat');
  330. if(!cat)return;
  331. var says=['this page is indexed too','press / to search it','i was here in March',
  332. 'nothing left this machine','purr'];
  333. var i=0,label=cat.querySelector('span'),was=label?label.textContent:'';
  334. cat.addEventListener('click',function(e){
  335. e.preventDefault();
  336. if(!label)return;
  337. label.textContent=says[i++%says.length];
  338. clearTimeout(cat._t);
  339. cat._t=setTimeout(function(){label.textContent=was},2400);
  340. });
  341. })();
  342. })();
  343. /* Record the page for the home page's greeting. Same store, same rule as the
  344. tool itself: it stays in this browser. */
  345. (function(){
  346. var title=(document.querySelector('h1')||{}).textContent||'';
  347. title=title.replace(/^[$#\s]+/,'').trim();
  348. if(!title)return;
  349. try{
  350. var KEY='deja.visits';
  351. var s=JSON.parse(localStorage.getItem(KEY)||'null')||{n:0};
  352. s.page=title;
  353. localStorage.setItem(KEY,JSON.stringify(s));
  354. }catch(e){}
  355. })();
extensions/dsh/index.js · Bundled script · 711 lines · 1 finding marked
  1. // dsh-deja — the history you already have, inside DeepSeek Harness.
  2. //
  3. // dsh answers questions about its own sessions through the built-in
  4. // session-query subsystem. This plugin answers the other question: what you did
  5. // in Claude Code, Codex, Cursor, opencode and forty-four more agents, on this
  6. // machine, before dsh existed. The index is deja's; this file is the seam.
  7. import { installSearchRoute } from "./search.js";
  8. import { createRequire } from "node:module";
  9. import { execFile, execFileSync } from "node:child_process";
  10. import { randomUUID } from "node:crypto";
  11. import { existsSync } from "node:fs";
  12. import { homedir } from "node:os";
  13. import { join } from "node:path";
  14. import { argv, contributions, recallArgv, recallSilence, exitStatus, guarded, inert, newestEvents, noteBoard, resultText, splitHookReply } from "./lib.js";
  15. const require = createRequire(import.meta.url);
  16. // The tool registry lives in the host. A plugin that throws on a missing peer
  17. // takes the whole profile down with it, so this degrades: without dsh-tools the
  18. // command and automatic recall still work, only the model-facing tools are
  19. // skipped.
  20. let defineTool = null;
  21. try {
  22. ({ defineTool } = await import("@deepseek-ai/dsh-tools"));
  23. } catch {}
  24. const PLATFORM = process.platform === "win32" ? "windows" : process.platform;
  25. const ARCH = process.arch === "x64" ? "amd64" : process.arch;
  26. // resolveDeja picks the binary in the order a user would expect: what they
  27. // pointed at, then the deja they installed themselves and keep current with
  28. // `deja update` or a package manager, and only then the copy npm brought along
  29. // with this plugin. Each candidate is asked for its version rather than
  30. // trusted, because a name on PATH that does not run is worse than no name.
  31. function resolveDeja() {
  32. const exe = PLATFORM === "windows" ? "deja.exe" : "deja";
  33. const candidates = [process.env.DEJA_BIN, exe];
  34. try {
  35. candidates.push(require.resolve(`@vshulcz/deja-vu-${PLATFORM}-${ARCH}/bin/${exe}`));
  36. } catch {}
  37. for (const candidate of candidates) {
  38. if (!candidate) continue;
  39. try {
  40. execFileSync(candidate, ["version"], {
  41. windowsHide: true,
  42. encoding: "utf8",
  43. timeout: 5000,
  44. stdio: ["ignore", "pipe", "ignore"],
  45. });
  46. return candidate;
  47. } catch {}
  48. }
  49. // Nothing answered. Keep the plain name so the failure a user sees names the
  50. // thing that is missing.
  51. return exe;
  52. }
  53. const DEJA = resolveDeja();
  54. // run returns stdout, or "" when deja is missing or says nothing. Memory is
  55. // optional everywhere: a throw here would end the turn.
  56. function run(args, input, cwd) {
  57. try {
  58. return execFileSync(DEJA, args, {
  59. windowsHide: true,
  60. cwd,
  61. encoding: "utf8",
  62. timeout: 20000,
  63. maxBuffer: 8 * 1024 * 1024,
  64. input,
  65. stdio: [input === undefined ? "ignore" : "pipe", "pipe", "ignore"],
  66. }).trim();
  67. } catch {
  68. return "";
  69. }
  70. }
  71. const NOTHING = "Nothing in this machine's history matches that.";
  72. const MISSING =
  73. "deja is not installed on this machine, so there is no history to search. " +
  74. "Install it with: curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh";
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 84 on GitHub
  75. // installed answers whether the binary picked at load actually runs. Without
  76. // this every tool would report an empty history to a user who simply never
  77. // installed deja, which reads as "you have no past" rather than "nothing is
  78. // here to read it".
  79. const INSTALLED = run(["version"]) !== "";
  80. function answer(text) {
  81. if (INSTALLED) return text || NOTHING;
  82. return MISSING;
  83. }
  84. function tools(ctx) {
  85. if (!defineTool) return;
  86. // Every tool here answers with the text deja printed, so one output
  87. // declaration serves them all. Printed with --framed: ctx, blame, fix and
  88. // how write for a person (recall frames its own page), and without the frame a tag planted in a
  89. // transcript reached the model as though deja had closed its own block. The schema is plain JSON Schema — a
  90. // schemastery instance is rejected as "schema must be a value schema object",
  91. // because the host validates that this is an ordinary JSON record.
  92. const TEXT_OUTPUT = {
  93. schema: { type: "string" },
  94. render: (_args, value) => [{ type: "text", text: String(value) }],
  95. };
  96. guarded(() => ctx.tools.register(defineTool({
  97. name: "deja_recall",
  98. description:
  99. "Search this machine's own past AI coding sessions — every agent used on it, including months before deja was installed. Use before debugging an error, before any plan, review, or recommending an approach, before re-implementing anything that may already exist, before the first edit in a task, mid-task whenever concrete names surface (batch alongside reads), and before calling a change done or ready to merge. Match on the most specific token available: an exact error string, function name, file path or flag.",
  100. parameters: {
  101. query: {
  102. type: "string",
  103. required: true,
  104. description: "1-3 exact terms: a file path, an error string, a flag or identifier.",
  105. },
  106. limit: {
  107. type: "number",
  108. description: "How many sessions to return. Default 5.",
  109. },
  110. offset: {
  111. type: "number",
  112. description: "Sessions to skip, from the offset the previous page named. Default 0.",
  113. },
  114. },
  115. output: TEXT_OUTPUT,
  116. execute(args, exec) {
  117. // The page the MCP recall tool serves, framed and budgeted by deja. It
  118. // puts the project of its working directory first, so it runs in the
  119. // calling session's workspace rather than wherever dsh was launched.
  120. const call = recallArgv(args);
  121. const out = run(call, undefined, sessionCwd(exec && exec.agent));
  122. return Promise.resolve(answer(out || (INSTALLED ? recallSilence(call) : "")));
  123. },
  124. })));
  125. guarded(() => ctx.tools.register(defineTool({
  126. name: "deja_session",
  127. description:
  128. "A full digest of the single best-matching past session — what was tried, what was decided, what it cost. Use after deja_recall when the reasoning behind an earlier decision matters, not just that it happened.",
  129. parameters: {
  130. query: {
  131. type: "string",
  132. required: true,
  133. description: "A query, or a session id prefix returned by deja_recall.",
  134. },
  135. },
  136. output: TEXT_OUTPUT,
  137. execute(args) {
  138. return Promise.resolve(answer(run(["--framed", ...argv("ctx", [], args.query)])));
  139. },
  140. })));
  141. guarded(() => ctx.tools.register(defineTool({
  142. name: "deja_blame",
  143. description:
  144. "The past sessions that discussed a file, so you know why it is shaped the way it is before editing, refactoring or deleting it. Session history, not git authorship.",
  145. parameters: {
  146. path: {
  147. type: "string",
  148. required: true,
  149. description: "Path to the file, absolute or relative to the workspace.",
  150. },
  151. },
  152. output: TEXT_OUTPUT,
  153. execute(args) {
  154. return Promise.resolve(answer(run(["--framed", ...argv("blame", ["--json"], args.path)])));
  155. },
  156. })));
  157. guarded(() => ctx.tools.register(defineTool({
  158. name: "deja_fix",
  159. description:
  160. "What this machine ran after that same error before, in the sessions where the error did not come back. Paste the failing output verbatim rather than a paraphrase — the match is on the error's own words.",
  161. parameters: {
  162. error: {
  163. type: "string",
  164. required: true,
  165. description: "The failing output, copied as it was printed.",
  166. },
  167. },
  168. output: TEXT_OUTPUT,
  169. execute(args) {
  170. return Promise.resolve(answer(run(["--framed", ...argv("fix", [], args.error)])));
  171. },
  172. })));
  173. guarded(() => ctx.tools.register(defineTool({
  174. name: "deja_how",
  175. description:
  176. "The real invocation this machine uses for a build, test, deploy or script, with the flags it actually ran, ordered by how many sessions ran it. A guessed command is plausible and fails on this setup.",
  177. parameters: {
  178. what: {
  179. type: "string",
  180. required: true,
  181. description: "The thing to run: a tool, a task, a script name.",
  182. },
  183. },
  184. output: TEXT_OUTPUT,
  185. execute(args) {
  186. return Promise.resolve(answer(run(["--framed", ...argv("how", [], args.what)])));
  187. },
  188. })));
  189. guarded(() => ctx.tools.register(defineTool({
  190. name: "deja_remember",
  191. description:
  192. "Store one durable decision once it is settled, as a single self-contained fact that will make sense months later. Not transcripts, not a summary of the conversation, and not anything already obvious from the code.",
  193. parameters: {
  194. text: {
  195. type: "string",
  196. required: true,
  197. description: "The decision, in one or two sentences, with the reason it was taken.",
  198. },
  199. },
  200. output: TEXT_OUTPUT,
  201. execute(args) {
  202. const written = run(argv("remember", [], args.text));
  203. if (!INSTALLED) return Promise.resolve(MISSING);
  204. return Promise.resolve(written || "deja did not record that.");
  205. },
  206. })));
  207. }
  208. // `/deja --session <id> -- <query>` scopes the search to one conversation; the
  209. // composer shortcut writes exactly that. Anything else stays one plain query.
  210. // A line that starts with --session but does not parse is refused rather than
  211. // searched as those words: the person asked for one conversation, and a silent
  212. // full search would look like the scope worked.
  213. const SESSION_FLAG = /^--session\s+(\S+)(?:\s+--\s*([\s\S]*))?$/;
  214. function commandQuery(rawInput) {
  215. const text = String(rawInput || "").trim();
  216. const match = SESSION_FLAG.exec(text);
  217. if (match) return { session: bareSessionId(match[1]), query: (match[2] || "").trim(), scoped: true, malformed: false };
  218. return { session: "", query: text, scoped: false, malformed: /^--session(?:\s|$)/.test(text) };
  219. }
  220. function command(ctx, board) {
  221. guarded(() => ctx.commands.register({
  222. name: "deja",
  223. description: "Search this machine's past AI coding sessions",
  224. input: { hint: "what to look for" },
  225. async handler(invocation) {
  226. const { session, query, scoped, malformed } = commandQuery(invocation && invocation.rawInput);
  227. if (malformed) {
  228. return { kind: "error", text: "A scoped search looks like `/deja --session <id> -- <query>`." };
  229. }
  230. if (session && !/^[a-zA-Z0-9_-]+$/.test(session)) {
  231. return { kind: "error", text: "That session id is not one dsh writes — `/deja --session <id> -- <query>` searches one conversation." };
  232. }
  233. if (!query) {
  234. return { kind: "error", text: scoped
  235. ? "A scoped search needs a query — `/deja --session <id> -- <query>`."
  236. : "Say what to look for: /deja <error, file, or decision>" };
  237. }
  238. // Named, not handed over as deja's first word: the bare-query path
  239. // dispatches a word that happens to be a command, so `/deja version`
  240. // printed a version number and `/deja index` rebuilt the index, and one
  241. // of the words people most want history about is `install`.
  242. const out = run(argv("search", session ? ["--session", session] : [], query));
  243. if (!INSTALLED) return { kind: "error", text: MISSING };
  244. // Outside dsh web a person sees nothing the hooks print — the digest
  245. // goes to the model — so the reply to /deja is where deja's own notes
  246. // reach them. In dsh web the session's lines may still be waiting on the
  247. // board for a page that has not asked; they go here, once, instead.
  248. const waiting = board ? board.take(sessionId(invocation && invocation.agent)) : [];
  249. const notes = [...waiting, run(["hook-context", "--notes"])].filter(Boolean).join("\n");
  250. return { kind: "success", text: notes ? answer(out) + "\n\n" + notes : answer(out) };
  251. },
  252. }));
  253. }
  254. function userText(message) {
  255. const content = message && message.content;
  256. if (!Array.isArray(content)) return typeof content === "string" ? content.trim() : "";
  257. return content
  258. .filter((part) => part && part.type === "text" && typeof part.text === "string")
  259. .map((part) => part.text)
  260. .join("\n")
  261. .trim();
  262. }
  263. // autoRecall puts the answer in front of the model without anyone asking for
  264. // it, through the seam the host evaluates on every assembly. The obvious
  265. // alternative — splicing a message into the "agent/pre-step" waterfall — looks
  266. // like it works and does not: a later listener rebuilds its answer from the
  267. // payload, and the added message is dropped with nothing reported.
  268. //
  269. // The registration is guarded because the host throws "prompt context
  270. // deja:recall is already registered" on a second copy in the same profile, and
  271. // that failure is not local: the whole profile fails to load, so a duplicate
  272. // memory plugin costs the user their agent. One registration is all recall
  273. // needs. installedByCLI() below is the first line of defence; this is the one
  274. // that holds when the installer wrote to a different DSH_HOME than the profile
  275. // boots from.
  276. // autoDigest puts what this project settled in front of the model once at the
  277. // start of the session — the question-independent counterpart to autoRecall.
  278. // dsh's own agent/session-start is emit-only, its return reaches nothing, so
  279. // the digest rides the same assembly seam the recall does. deja_once keys the
  280. // one-shot on the session id in deja's ledger, which survives a resume in a new
  281. // process; the Map caches the opening digest across systemPrompt.refreshContext
  282. // re-resolutions during the first step (#5904) and clears it once the session
  283. // moves past its opening step.
  284. function autoDigest(ctx, board) {
  285. const digests = new Map();
  286. guarded(() =>
  287. ctx.systemPrompt.context({
  288. name: "deja:project",
  289. order: 110,
  290. interpolate: false,
  291. text: (assembly) => {
  292. const agent = assembly && assembly.agent;
  293. if (!agent) return "";
  294. const sid = sessionId(agent);
  295. if (pastOpeningStep(agent.session)) {
  296. if (sid) digests.set(sid, "");
  297. return "";
  298. }
  299. if (sid && digests.has(sid)) return digests.get(sid);
  300. const text = inert(askHook(
  301. ["hook-context", "--plain"],
  302. ["hook-context"],
  303. JSON.stringify({ session_id: sid, cwd: sessionCwd(agent), source: "startup", deja_once: true }),
  304. sid,
  305. board,
  306. ));
  307. if (sid) {
  308. digests.set(sid, text);
  309. while (digests.size > 64) digests.delete(digests.keys().next().value);
  310. }
  311. return text;
  312. },
  313. }),
  314. );
  315. }
  316. function pastOpeningStep(session) {
  317. let humanTurns = 0;
  318. for (const event of newestEvents(session)) {
  319. if (!event || typeof event.type !== "string") continue;
  320. if (event.type === "turn/start" && event.data && event.data.turn > 1) return true;
  321. if (event.type === "runtime-context" || event.type === "turn/end" || event.type === "step/end" || event.type.startsWith("assistant/")) {
  322. return true;
  323. }
  324. if (event.type === "user/message" && isHuman(event.data)) {
  325. if (++humanTurns > 1) return true;
  326. }
  327. if (event.type === "agent/inbox/spliced") {
  328. const inserted = event.data && event.data.inserted;
  329. if (Array.isArray(inserted) && inserted.some(isHuman) && ++humanTurns > 1) return true;
  330. }
  331. }
  332. return false;
  333. }
  334. // dsh names a session "session-<uuid>" and its log's folder the same; deja
  335. // indexes it by the uuid, so that is the id every hook is given.
  336. function bareSessionId(id) {
  337. return String(id || "").replace(/^session-/, "");
  338. }
  339. function sessionId(agent) {
  340. return bareSessionId((agent && (agent.sessionId || (agent.session && agent.session.id))) || "");
  341. }
  342. // The workspace a session belongs to. One web or tui process serves sessions
  343. // from every workspace and never changes directory, so process.cwd() is only
  344. // where dsh was launched; the session header carries the directory the session
  345. // was opened in.
  346. function sessionCwd(agent) {
  347. const header = agent && agent.session && agent.session.header;
  348. return (header && header.cwd) || process.cwd();
  349. }
  350. // askHook runs a hook once for both readers. Where a page will show the
  351. // person's lines, deja is asked for its JSON reply: additionalContext, the
  352. // text --plain prints, goes to the model and systemMessage waits on the board.
  353. // Anywhere else — tui, headless, sdk — it stays --plain. deja marks a note
  354. // shown when it prints it, so asking for notes nobody will read spends them,
  355. // and `/deja` and the next Claude Code session would not see them either.
  356. function askHook(plain, json, payload, sid, board) {
  357. if (!board.hasReader()) return run(plain, payload);
  358. const reply = splitHookReply(run(json, payload));
  359. board.push(sid, reply.notes);
  360. return reply.context;
  361. }
  362. function autoRecall(ctx, board) {
  363. let asked = "";
  364. let askedIn = "";
  365. let askedBy = "";
  366. let recalled = "";
  367. const compacted = new Set();
  368. watchCompaction(ctx, compacted);
  369. guarded(() =>
  370. ctx.systemPrompt.context({
  371. name: "deja:recall",
  372. order: 120,
  373. interpolate: false,
  374. text: (assembly) => {
  375. const agent = assembly && assembly.agent;
  376. if (!agent) return "";
  377. const prompt = lastHumanText(agent);
  378. if (!prompt) return "";
  379. const cwd = sessionCwd(agent);
  380. const sid = sessionId(agent);
  381. const afterCompaction = compacted.delete(sid);
  382. // The same question asked in another workspace is a different question,
  383. // and so is one asked again after its session compacted: deja then
  384. // answers with the recovery packet, which only a prompt naming the
  385. // session gets back.
  386. if (prompt !== asked || cwd !== askedIn || sid !== askedBy || afterCompaction) {
  387. asked = prompt;
  388. askedIn = cwd;
  389. askedBy = sid;
  390. recalled = inert(askHook(
  391. ["hook-prompt", "--plain"],
  392. ["hook-prompt"],
  393. JSON.stringify({ prompt, cwd, session_id: sid }),
  394. sid,
  395. board,
  396. ));
  397. }
  398. // Silence is the common case: this speaks only when the history answers.
  399. return recalled;
  400. },
  401. }),
  402. );
  403. }
  404. // The person's half. dsh shows nobody what a plugin hands the model, and has
  405. // no notice channel a host plugin can write to, so deja's lines wait on a board
  406. // and the browser half (client.js) asks for them under the composer. The route
  407. // rides dsh's own /api mount, which applies the same Host/Origin fence and
  408. // browser login as every other call the page makes. Only a profile that serves
  409. // that page — the connection service and a web server both — registers it;
  410. // headless, tui, sdk and an older dsh never do, and keep asking deja for
  411. // --plain. A second copy of the plugin finds the path taken and stands down.
  412. const NOTES_PATH = "/api/deja-notes";
  413. function notesRoute(ctx, board) {
  414. if (typeof ctx.inject !== "function") return;
  415. try {
  416. ctx.inject(["connection", "webServer"], (c) => {
  417. const registered = guarded(() =>
  418. c.connection.fetch.register({
  419. path: NOTES_PATH,
  420. methods: ["GET"],
  421. requestBody: "buffered",
  422. fetch: async (request) => {
  423. let sid = "";
  424. try {
  425. sid = bareSessionId(new URL(request.url).searchParams.get("session"));
  426. } catch {}
  427. return Response.json({ notes: sid ? board.take(sid) : [] }, { headers: { "cache-control": "no-store" } });
  428. },
  429. }),
  430. );
  431. if (registered) board.setReader();
  432. });
  433. } catch {}
  434. }
  435. // runAsync is run for a seam dsh awaits, so the event loop goes on while deja
  436. // answers. It never rejects.
  437. function runAsync(args, input) {
  438. return new Promise((resolve) => {
  439. try {
  440. const child = execFile(DEJA, args, { windowsHide: true, encoding: "utf8", timeout: 20000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout) =>
  441. resolve(err ? "" : String(stdout || "").trim()),
  442. );
  443. child.on("error", () => resolve(""));
  444. child.stdin.on("error", () => {});
  445. child.stdin.end(input);
  446. } catch {
  447. resolve("");
  448. }
  449. });
  450. }
  451. // Compaction shadows the turns it summarises but leaves them in the session
  452. // log, so deja reads the session there as compaction/start lands and keeps a
  453. // recovery packet: the task, each command with how it went, what was still
  454. // open. The log is written behind the session, so it is flushed first. dsh
  455. // assembles a step's context before its agent/pre-step waterfall, where the
  456. // compaction runs, so the step that compacts waits there for the capture and
  457. // the packet rides the recall of the next step, or of the next turn.
  458. function watchCompaction(ctx, compacted) {
  459. if (typeof ctx.on !== "function") return;
  460. const capturing = new Map();
  461. const listen = (c) =>
  462. c.on("session/event", (session, event) => {
  463. if (!session || !event || event.type !== "compaction/start") return;
  464. const sid = bareSessionId(session.id || (session.header && session.header.id));
  465. if (!sid) return;
  466. const cwd = (session.header && session.header.cwd) || process.cwd();
  467. // One compaction can follow another inside a step; two captures at once
  468. // contend for the index and the loser marks the packet unavailable, so
  469. // each waits for the one before it.
  470. const before = capturing.get(sid) || Promise.resolve();
  471. const capture = before.then(async () => {
  472. try {
  473. if (c.sessions && typeof c.sessions.flush === "function") await c.sessions.flush(session);
  474. } catch {}
  475. await runAsync(["hook-precompact"], JSON.stringify({ session_id: sid, cwd, harness: "deepseek" }));
  476. compacted.add(sid);
  477. });
  478. capturing.set(sid, capture);
  479. capture.then(() => {
  480. if (capturing.get(sid) === capture) capturing.delete(sid);
  481. });
  482. });
  483. try {
  484. if (typeof ctx.inject === "function") ctx.inject(["sessions"], listen);
  485. else listen(ctx);
  486. } catch {}
  487. try {
  488. ctx.on("agent/pre-step", async (step, next) => {
  489. const sid = sessionId(step && step.agent);
  490. if (capturing.has(sid)) await capturing.get(sid);
  491. const decision = await next();
  492. if (capturing.has(sid)) await capturing.get(sid);
  493. return decision;
  494. });
  495. } catch {}
  496. }
  497. // The point of action, as `deja install dsh-auto` wires it. tools/post-execute
  498. // runs on every tool result, and an accept decision's additionalContexts reach
  499. // the model on the next step: a read, edit or write gets what deja knows about
  500. // the file, a bash that exited non-zero gets the fix this machine found for
  501. // that error before. The before-seam, tools/execute, has no channel to the
  502. // model.
  503. function toolNotes(ctx) {
  504. if (typeof ctx.on !== "function") return;
  505. try {
  506. ctx.on("tools/post-execute", async (exec, result, next) => {
  507. const decision = await next();
  508. try {
  509. if (!decision || decision.kind !== "accept" || !exec) return decision;
  510. const note = await toolNote(exec, result);
  511. if (!note) return decision;
  512. return {
  513. ...decision,
  514. additionalContexts: [...(decision.additionalContexts || []), noteMessage(note)],
  515. };
  516. } catch {
  517. return decision;
  518. }
  519. });
  520. } catch {}
  521. }
  522. // A session is over when dsh disposes of it, or when the process goes: on
  523. // 0.1.1-rc.2 the headless profile exits without disposing anything, and only
  524. // process "exit" runs. The digest and the recall stamp a session live, which
  525. // keeps it out of its own MCP recall; dropping the stamp lets the next session
  526. // be answered with it now rather than twenty minutes from now.
  527. function sessionEnds(ctx) {
  528. if (typeof ctx.on !== "function") return;
  529. // Each live session with the directory it opened in: the end refreshes that
  530. // project's start digest, so the next session there sees this one.
  531. const live = new Map();
  532. const end = (sid) => {
  533. if (!sid || !live.has(sid)) return;
  534. const cwd = live.get(sid);
  535. live.delete(sid);
  536. run(["hook-session-end"], JSON.stringify({ session_id: sid, cwd }));
  537. };
  538. try {
  539. ctx.on("session/created", (session) => {
  540. const sid = bareSessionId(session && session.id);
  541. if (sid) live.set(sid, (session.header && session.header.cwd) || process.cwd());
  542. });
  543. ctx.on("session/disposed", (session) => end(bareSessionId(session && session.id)));
  544. process.on("exit", () => {
  545. for (const sid of [...live.keys()]) end(sid);
  546. });
  547. } catch {}
  548. }
  549. async function toolNote(exec, result) {
  550. const args = exec.arguments || {};
  551. const base = { session_id: sessionId(exec.agent), cwd: sessionCwd(exec.agent) };
  552. const editFields = {};
  553. if (args.old_string || args.old_str) editFields.old_string = String(args.old_string || args.old_str);
  554. if (args.new_string || args.new_str || args.content || args.file_text) editFields.new_string = String(args.new_string || args.new_str || args.content || args.file_text);
  555. if ((exec.name === "read" || exec.name === "edit" || exec.name === "write") && args.file_path) {
  556. return runAsync(["hook-tool", "--plain"], JSON.stringify({
  557. tool_name: exec.name,
  558. tool_input: { file_path: String(args.file_path), ...editFields },
  559. ...base,
  560. }));
  561. }
  562. // The profile's other editor names the file "path"; view is its read.
  563. if (exec.name === "str_replace_editor" && args.path) {
  564. return runAsync(["hook-tool", "--plain"], JSON.stringify({
  565. tool_name: args.command === "view" ? "read" : "edit",
  566. tool_input: { file_path: String(args.path), ...editFields },
  567. ...base,
  568. }));
  569. }
  570. // pwsh is the Windows shell, with the same markers.
  571. if (exec.name === "bash" || exec.name === "pwsh") {
  572. const status = exitStatus(resultText(result));
  573. if (!(result && result.isError) && !status.failed) return "";
  574. return runAsync(["hook-tool-after", "--plain"], JSON.stringify({
  575. tool_name: exec.name === "pwsh" ? "powershell" : "bash",
  576. tool_input: { command: String(args.command || "") },
  577. tool_response: status.body,
  578. ...base,
  579. }));
  580. }
  581. return "";
  582. }
  583. // A context message the way dsh's own plugins build one: user role, a
  584. // producer-owned source so it is not read back as something the person typed,
  585. // a fresh id, frozen. v4 session format refuses the bare "plugin" kind, so the
  586. // producer owns "plugin:deja" — the value dsh's own v3→v4 migration assigns an
  587. // unmapped plugin.
  588. function noteMessage(text) {
  589. const message = {
  590. role: "user",
  591. content: [{ type: "text", text }],
  592. source: { kind: "plugin:deja", form: "notice" },
  593. id: randomUUID(),
  594. };
  595. Object.freeze(message.content[0]);
  596. Object.freeze(message.content);
  597. Object.freeze(message.source);
  598. return Object.freeze(message);
  599. }
  600. // lastHumanText is the newest thing the person actually typed. At assembly
  601. // time the message has already left the inbox and has not been appended as a
  602. // "user/message" yet — the only durable record of it is the inbox splice that
  603. // carried it in, so both are read. Anything a plugin contributed is skipped:
  604. // those carry a source of their own.
  605. function lastHumanText(agent) {
  606. for (const event of newestEvents(agent && agent.session)) {
  607. if (!event) continue;
  608. if (event.type === "user/message" && isHuman(event.data)) return userText(event.data);
  609. if (event.type === "agent/inbox/spliced") {
  610. const inserted = event.data && event.data.inserted;
  611. if (!Array.isArray(inserted)) continue;
  612. for (let j = inserted.length - 1; j >= 0; j--) {
  613. if (isHuman(inserted[j])) return userText(inserted[j]);
  614. }
  615. }
  616. }
  617. return "";
  618. }
  619. function isHuman(message) {
  620. return Boolean(message) && (!message.source || message.source.kind === "user");
  621. }
  622. // `deja install dsh` writes plugins of its own into DSH_HOME and adds them to
  623. // the profile, so a user who ran the installer and then added this package has
  624. // both: two `/deja` commands, the same recall on the system prompt twice, and
  625. // deja's MCP server answering the same six questions the tools here do. What
  626. // the installer wrote wins — it is the copy `deja install` keeps current — and
  627. // this package contributes only the parts that are missing.
  628. //
  629. // The two halves are separate on purpose: `deja install dsh` writes command.js
  630. // and the MCP row, and only `deja install dsh-auto` adds auto.js. A profile can
  631. // have the command from the installer and still want recall from here.
  632. function cliPluginDir() {
  633. const home = process.env.DSH_HOME || join(homedir(), ".dsh");
  634. return join(home, "plugins", "deja");
  635. }
  636. function installedByCLI(file) {
  637. try {
  638. return existsSync(join(cliPluginDir(), file));
  639. } catch {
  640. return false;
  641. }
  642. }
  643. function apply(ctx, config) {
  644. const adds = contributions(
  645. { command: installedByCLI("command.js"), auto: installedByCLI("auto.js") },
  646. config,
  647. );
  648. const board = noteBoard();
  649. // User-initiated search remains available when automatic recall is disabled.
  650. installSearchRoute(ctx, DEJA);
  651. if (adds.tools) tools(ctx);
  652. if (adds.command) command(ctx, board);
  653. if (adds.recall) {
  654. autoDigest(ctx, board);
  655. autoRecall(ctx, board);
  656. notesRoute(ctx, board);
  657. toolNotes(ctx);
  658. sessionEnds(ctx);
  659. }
  660. }
  661. apply.inject = ["tools", "commands", "systemPrompt"];
  662. export default apply;
extensions/grok/bin/deja-mcp.mjs · Bundled script · 92 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. // The plugin's MCP server: `deja mcp` over stdio, with the binary resolved the
  3. // way the user expects rather than pinned to whatever this release bundled.
  4. //
  5. // A plugin server and the `[mcp_servers.deja]` entry `deja install grok` writes
  6. // are two servers to Grok, not one — both would run and the agent would see
  7. // every tool twice. When the installer has already wired it, this stands down
  8. // and says why: the CLI's copy is the one `deja install` keeps current.
  9. import { spawn } from "node:child_process"
  10. import { grokHome, installerOwns, resolveDeja } from "../lib.mjs"
  11. if (installerOwns("mcp")) {
  12. process.stderr.write(
  13. `deja is already an MCP server in ${grokHome()}/config.toml, from \`deja install grok\`. ` +
  14. "This plugin's copy stays out of the way so the tools are not listed twice — " +
  15. "run `deja uninstall grok` to let the plugin own it instead.\n",
  16. )
  17. standDown()
  18. } else {
  19. start()
  20. }
  21. // Standing down by exiting looks like a crash from the outside: Grok Build 1.0.5
  22. // reports `handshake failed: connection closed: initialize response` and the
  23. // server sits in the UI as broken. So answer the handshake and offer nothing —
  24. // the tools come from the CLI-wired copy, and this one is visibly idle rather
  25. // than visibly failing.
  26. function standDown() {
  27. let buf = ""
  28. process.stdin.setEncoding("utf8")
  29. process.stdin.on("data", (chunk) => {
  30. buf += chunk
  31. let i
  32. while ((i = buf.indexOf("\n")) >= 0) {
  33. const line = buf.slice(0, i)
  34. buf = buf.slice(i + 1)
  35. if (line.trim()) reply(line)
  36. }
  37. })
  38. process.stdin.on("end", () => process.exit(0))
  39. }
  40. function reply(line) {
  41. let msg
  42. try {
  43. msg = JSON.parse(line)
  44. } catch {
  45. return
  46. }
  47. if (msg.id === undefined) return // a notification wants no answer
  48. let result
  49. switch (msg.method) {
  50. case "initialize":
  51. result = {
  52. protocolVersion: msg.params?.protocolVersion ?? "2024-11-05",
  53. capabilities: { tools: {} },
  54. serverInfo: { name: "deja (plugin, standing down)", version: "0.1.0" },
  55. }
  56. break
  57. case "tools/list":
  58. result = { tools: [] }
  59. break
  60. case "resources/list":
  61. result = { resources: [] }
  62. break
  63. case "prompts/list":
  64. result = { prompts: [] }
  65. break
  66. case "ping":
  67. result = {}
  68. break
  69. default:
  70. process.stdout.write(
  71. JSON.stringify({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "not served: deja is wired through the CLI" } }) + "\n",
  72. )
  73. return
  74. }
  75. process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n")
  76. }
  77. function start() {
  78. const child = spawn(resolveDeja(), ["mcp"], { windowsHide: true, stdio: "inherit" })
  79. child.on("error", (err) => {
  80. process.stderr.write(
  81. `deja could not start: ${err.message}. Install it with: ` +
  82. "curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh\n",
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 87 on GitHub
  83. )
  84. process.exit(1)
  85. })
  86. child.on("close", (code) => process.exit(code ?? 0))
  87. }
extensions/kimi/bin/deja-mcp.mjs · Bundled script · 31 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. // The plugin's MCP server: `deja mcp` over stdio, with the binary resolved the
  3. // way the user expects rather than pinned to whatever this release bundled.
  4. //
  5. // Kimi registers a plugin's server as `plugin-<id>:<name>`, so it does not
  6. // merge with the `deja` entry `deja install kimi` writes into mcp.json — both
  7. // would run, and the agent would see every tool twice. When the installer has
  8. // already wired it, this stands down and says why: the CLI's copy is the one
  9. // `deja install` keeps current.
  10. import { spawn } from "node:child_process"
  11. import { installerOwns, kimiHome, resolveDeja } from "../lib.mjs"
  12. if (installerOwns("mcp")) {
  13. process.stderr.write(
  14. `deja is already an MCP server in ${kimiHome()}/mcp.json, from \`deja install kimi\`. ` +
  15. "This plugin's copy stays out of the way so the tools are not listed twice — " +
  16. "run `deja uninstall kimi` to let the plugin own it instead.\n",
  17. )
  18. process.exit(0)
  19. }
  20. const child = spawn(resolveDeja(), ["mcp"], { windowsHide: true, stdio: "inherit" })
  21. child.on("error", (err) => {
  22. process.stderr.write(
  23. `deja could not start: ${err.message}. Install it with: ` +
  24. "curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh\n",
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 27 on GitHub
  25. )
  26. process.exit(1)
  27. })
  28. child.on("close", (code) => process.exit(code ?? 0))
extensions/opencode/index.js · Bundled script · 539 lines · 1 finding marked
  1. // opencode-deja — the sessions you already have, inside opencode.
  2. //
  3. // opencode remembers its own sessions. This plugin answers the other question:
  4. // what you did in Claude Code, Codex, Cursor, Gemini and forty-four more agents on
  5. // this machine, including months before deja existed. The index is deja's; this
  6. // file is the seam: six tools the model can call, plus recall that arrives
  7. // without being asked for.
  8. //
  9. // This is the 1.x plugin. opencode 2.x loads server.js, which runs this same
  10. // function and wires its hooks to 2.x's seams.
  11. import { createRequire } from "node:module"
  12. import { execFile } from "node:child_process"
  13. import { promisify } from "node:util"
  14. import { homedir } from "node:os"
  15. import { join } from "node:path"
  16. import { accessSync, constants, existsSync, readFileSync } from "node:fs"
  17. import {
  18. argv,
  19. cliPluginPath,
  20. configPaths,
  21. contextText,
  22. contributions,
  23. mcpWired,
  24. recallArgv,
  25. recallSilence,
  26. settleRecall,
  27. TOOL_SPECS,
  28. trailingRecall,
  29. userTurns,
  30. zodTools,
  31. } from "./lib.js"
  32. const require = createRequire(import.meta.url)
  33. const run_ = promisify(execFile)
  34. const WINDOWS = process.platform === "win32"
  35. const PLATFORM = WINDOWS ? "windows" : process.platform
  36. const ARCH = process.arch === "x64" ? "amd64" : process.arch
  37. const EXE = WINDOWS ? "deja.exe" : "deja"
  38. // How many turns of a session will ask again after being answered with
  39. // nothing. Three covers the moments that pass — a locked index, a call that
  40. // timed out, an upgrade replacing the binary — without turning a store that
  41. // genuinely holds nothing into a shell-out on every turn.
  42. const emptyRetries = 3
  43. // The tool helper is a peer of the host, not of us: it is identity plus a zod
  44. // re-export. Without it the hooks still run and only the model-facing tools are
  45. // skipped — a missing peer must not take the plugin down.
  46. let tool = null
  47. try {
  48. ;({ tool } = await import("@opencode-ai/plugin"))
  49. } catch {}
  50. // wellKnown lists the places a user's own install lands. PATH is the normal
  51. // answer; these cover the case where opencode was started from a launcher with
  52. // a PATH that never sourced a shell profile.
  53. function wellKnown() {
  54. const home = homedir()
  55. if (WINDOWS) {
  56. const local = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
  57. return [join(local, "deja", "bin", EXE), join(home, ".local", "bin", EXE)]
  58. }
  59. return [
  60. join(home, ".local", "bin", EXE),
  61. "/usr/local/bin/deja",
  62. "/opt/homebrew/bin/deja",
  63. "/usr/bin/deja",
  64. ]
  65. }
  66. // resolveDeja picks the binary in the order a user would expect: what they
  67. // pointed at, then the deja they installed themselves and keep current with
  68. // `deja update` or brew, and only last the copy npm brought along with this
  69. // plugin. Pinning them to our bundled copy would freeze their memory at
  70. // whatever version this package was released against.
  71. function resolveDeja(setting) {
  72. const candidates = [setting, process.env.DEJA_BIN, EXE, ...wellKnown()]
  73. try {
  74. candidates.push(require.resolve(`@vshulcz/deja-vu-${PLATFORM}-${ARCH}/bin/${EXE}`))
  75. } catch {}
  76. for (const candidate of candidates) {
  77. if (!candidate) continue
  78. if (candidate.includes("/") || candidate.includes("\\")) {
  79. try {
  80. accessSync(candidate, constants.X_OK)
  81. } catch {
  82. continue
  83. }
  84. }
  85. return candidate
  86. }
  87. // Nothing to check further; keep the plain name so a failure names the thing
  88. // that is missing rather than a path nobody chose.
  89. return EXE
  90. }
  91. // deja is asked for text, never for control flow: memory is optional
  92. // everywhere, and a throw here would end someone's turn.
  93. async function run(bin, args, input, cwd, timeout = 20000) {
  94. try {
  95. const child = run_(bin, args, {
  96. windowsHide: true,
  97. encoding: "utf8",
  98. timeout,
  99. cwd,
  100. maxBuffer: 8 * 1024 * 1024,
  101. })
  102. if (input !== undefined) {
  103. // deja can exit before it reads stdin; unhandled, the EPIPE that
  104. // follows would take opencode down. The generated plugin does the same.
  105. child.child.stdin.on("error", () => {})
  106. child.child.stdin.end(input)
  107. }
  108. const { stdout } = await child
  109. return stdout.trim()
  110. } catch {
  111. return ""
  112. }
  113. }
  114. const NOTHING = "Nothing in this machine's history matches that."
  115. const MISSING =
  116. "deja is not installed on this machine, so there is no history to search. " +
  117. "Install it with: curl -fsSL https://raw.githubusercontent.com/vshulcz/deja-vu/main/install.sh | sh"
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 126 on GitHub
  118. // installerWiring reads what `deja install` left on disk for opencode: the MCP
  119. // server in the config, and the plugin file `--auto` writes. Both reads are
  120. // wrapped — a config we cannot read means "not wired", so the worst case is
  121. // this package doing the work twice rather than not at all.
  122. function installerWiring() {
  123. const wiring = { mcp: false, recall: false }
  124. try {
  125. wiring.recall = existsSync(cliPluginPath(process.env, homedir()))
  126. } catch {}
  127. try {
  128. for (const path of configPaths(process.env, homedir())) {
  129. if (!existsSync(path)) continue
  130. if (mcpWired(readFileSync(path, "utf8"))) {
  131. wiring.mcp = true
  132. break
  133. }
  134. }
  135. } catch {}
  136. return wiring
  137. }
  138. export const DejaPlugin = async ({ client, directory }, options = {}) => {
  139. const config = options || {}
  140. const bin = resolveDeja(typeof config.bin === "string" ? config.bin : "")
  141. const cwd = directory || process.cwd()
  142. // Every call runs in the session's own directory: deja ranks by project.
  143. const ask = (args, input, timeout) => run(bin, args, input, cwd, timeout)
  144. // Whether the binary answers at all is asked once. Without it every tool
  145. // would report an empty history to someone who simply never installed deja,
  146. // which reads as "you have no past" rather than "nothing is here to read it".
  147. const installed = (await ask(["version"], undefined, 5000)) !== ""
  148. const answer = (text) => (installed ? text || NOTHING : MISSING)
  149. // The toast is the one channel to the person: what the hooks return is model
  150. // context. A 2.x server plugin has none, and there deja is asked --strict so
  151. // it keeps its lines for a host that shows them rather than spend them here.
  152. const toasts = typeof client?.tui?.showToast === "function"
  153. const toast = (message) => (toasts ? client.tui.showToast({ body: { message, variant: "info", duration: 6000 } }) : undefined)
  154. const hook = (name) => (toasts ? [name] : [name, "--strict"])
  155. const digests = new Map()
  156. const told = new Set()
  157. // How many times this session has been answered with nothing. An empty
  158. // answer is cached so the plugin does not shell out every turn, but the
  159. // reasons for it are not alike: no history is permanent, while a locked
  160. // index, a timed-out call or a binary being replaced mid-`deja update` are
  161. // over by the next turn. Cached alike, one bad moment cost the session all
  162. // of its memory — every later turn read the emptiness rather than asking
  163. // again. Counted, so a store that really is empty is still only asked a few
  164. // times.
  165. const empties = new Map()
  166. // Sessions between their compacting hook and the summary request.
  167. const compacting = new Set()
  168. // Every session the per-prompt hook stamped live. opencode never says a
  169. // session ended, so without ending them here the stamp sat out its whole
  170. // window and the next session's MCP recall left a finished one out (#4546).
  171. const live = new Set()
  172. // The per-prompt recall each user message was given, by message.
  173. const recalled = new Map()
  174. const remember = (key, extra) => {
  175. recalled.set(key, extra)
  176. if (recalled.size > 1000) recalled.delete(recalled.keys().next().value)
  177. }
  178. const endSession = (id) => ask(["hook-session-end"], JSON.stringify({ session_id: id, cwd }), 5000)
  179. // The session that spawned each one, asked of opencode once. A task
  180. // sub-agent's digest and recall led with its parent, which is live and
  181. // asking through it (#4548).
  182. const parents = new Map()
  183. const parentOf = async (id) => {
  184. if (!id) return ""
  185. if (!parents.has(id)) {
  186. let parent = ""
  187. try {
  188. const res = await client?.session?.get?.({ path: { id } })
  189. parent = res?.data?.parentID || ""
  190. } catch {}
  191. parents.set(id, parent)
  192. }
  193. return parents.get(id)
  194. }
  195. const hooks = {}
  196. // What `deja install` already wired for opencode is not repeated here. It
  197. // writes an MCP server (the same six answers, under their own names) and,
  198. // with --auto, a plugin file of its own that opencode loads beside this
  199. // package — verified with `opencode debug config`, which resolves both into
  200. // one plugin list. Whatever the installer wrote wins, because that is the
  201. // copy `deja install` keeps current; this package fills the gaps.
  202. const adds = contributions(installerWiring(), config)
  203. // The six tools, described once. The ones that read history ask for
  204. // --framed output: what those commands print is written for a person, and
  205. // the model has to get it inside deja's untrusted-data frame. opencode 1.x takes them through its zod
  206. // helper and 2.x as JSON Schema (server.js), so the arguments are plain
  207. // data and each side builds its own.
  208. const specs = {
  209. deja_recall: {
  210. description:
  211. "Search this machine's own past AI coding sessions — every agent used on it, including months before deja was installed. Use before debugging an error, before any plan, review, or recommending an approach, before re-implementing anything that may already exist, before the first edit in a task, mid-task whenever concrete names surface (batch alongside reads), and before calling a change done or ready to merge. Match on the most specific token available: an exact error string, function name, file path or flag.",
  212. args: {
  213. query: { type: "string", description: "1-3 exact terms: a file path, an error string, a flag or identifier." },
  214. limit: { type: "number", optional: true, description: "How many sessions to return. Default 5." },
  215. offset: {
  216. type: "number",
  217. optional: true,
  218. description: "Sessions to skip, from the offset the previous page named. Default 0.",
  219. },
  220. },
  221. async execute(args) {
  222. // The page the MCP recall tool serves, framed and budgeted by deja.
  223. const call = recallArgv(args)
  224. const out = await ask(call)
  225. return answer(out || (installed ? recallSilence(call) : ""))
  226. },
  227. },
  228. deja_session: {
  229. description:
  230. "A full digest of the single best-matching past session — what was tried, what was decided, what it cost. Use after deja_recall when the reasoning behind an earlier decision matters, not just that it happened.",
  231. args: {
  232. query: { type: "string", description: "A query, or a session id prefix returned by deja_recall." },
  233. },
  234. async execute(args) {
  235. return answer(await ask(["--framed", ...argv("ctx", [], args.query)]))
  236. },
  237. },
  238. deja_blame: {
  239. description:
  240. "The past sessions that discussed a file, so you know why it is shaped the way it is before editing, refactoring or deleting it. Session history, not git authorship.",
  241. args: {
  242. path: { type: "string", description: "Path to the file, absolute or relative to the project." },
  243. },
  244. async execute(args) {
  245. return answer(await ask(["--framed", ...argv("blame", ["--json"], args.path)]))
  246. },
  247. },
  248. deja_fix: {
  249. description:
  250. "What this machine ran after that same error before, in the sessions where the error did not come back. Paste the failing output verbatim rather than a paraphrase — the match is on the error's own words.",
  251. args: {
  252. error: { type: "string", description: "The failing output, copied as it was printed." },
  253. },
  254. async execute(args) {
  255. return answer(await ask(["--framed", ...argv("fix", [], args.error)]))
  256. },
  257. },
  258. deja_how: {
  259. description:
  260. "The real invocation this machine uses for a build, test, deploy or script, with the flags it actually ran, ordered by how many sessions ran it. A guessed command is plausible and fails on this setup.",
  261. args: {
  262. what: { type: "string", description: "The thing to run: a tool, a task, a script name." },
  263. },
  264. async execute(args) {
  265. return answer(await ask(["--framed", ...argv("how", [], args.what)]))
  266. },
  267. },
  268. deja_remember: {
  269. description:
  270. "Store one durable decision once it is settled, as a single self-contained fact that will make sense months later. Not transcripts, not a summary of the conversation, and not anything already obvious from the code.",
  271. args: {
  272. text: { type: "string", description: "The decision, in one or two sentences, with the reason it was taken." },
  273. },
  274. async execute(args) {
  275. const written = await ask(argv("remember", [], args.text))
  276. if (!installed) return MISSING
  277. return written || "deja did not record that."
  278. },
  279. },
  280. }
  281. if (adds.tools) {
  282. // Under a symbol, so 1.x, which reads its hooks by name, never sees it.
  283. hooks[TOOL_SPECS] = specs
  284. if (tool) hooks.tool = zodTools(tool, specs)
  285. }
  286. if (!adds.recall) return hooks
  287. // opencode has no session-start hook. The system prompt is assembled on
  288. // every request, so the session digest is fetched once and pushed there —
  289. // the same place Claude Code's SessionStart output lands.
  290. hooks["experimental.chat.system.transform"] = async (input, output) => {
  291. try {
  292. // The summary request is the last one a compaction makes, and the digest
  293. // has no business in it: asked here, deja would hand the summariser the
  294. // recovery packet meant for the turn after.
  295. if (input?.sessionID && compacting.delete(input.sessionID)) return
  296. const key = input?.sessionID || "default"
  297. if (!digests.has(key)) {
  298. // The session id, as the plugin `deja install opencode-auto` writes
  299. // sends it: without it deja hands the session its own work back and
  300. // never reads the digest cached for it (#4273). The parent rides
  301. // along so the digest leaves it out too.
  302. const payload = { session_id: input?.sessionID || "", parent_session_id: await parentOf(input?.sessionID), cwd }
  303. const { context, receipt } = contextText(await ask(hook("hook-context"), JSON.stringify(payload), 30000))
  304. digests.set(key, context)
  305. // The receipt is the only sign the user gets that memory arrived. Once
  306. // per session: repeating it every turn is wallpaper.
  307. if (receipt && !told.has(key)) {
  308. told.add(key)
  309. await toast(receipt)
  310. }
  311. }
  312. const context = digests.get(key)
  313. if (context) {
  314. // Fold into the first system entry, as the generated plugin does.
  315. // opencode sends each entry as its own system message, and a backend
  316. // whose template allows one (vLLM or SGLang serving Qwen) rejects the
  317. // request: "System message must be at the beginning." (#4058)
  318. // After opencode's own prompt, not before it: that prompt is the same
  319. // in every session and is what the provider's prompt cache keeps.
  320. if (output.system.length) output.system[0] = output.system[0] + "\n\n" + context
  321. else output.system.push(context)
  322. return
  323. }
  324. // Nothing recalled: this machine has no history yet, the first index is
  325. // still building, or the call did not get through. The build is the only
  326. // one worth saying out loud, and saying it drops the empty answer so the
  327. // next turn asks again.
  328. const asks = (empties.get(key) || 0) + 1
  329. empties.set(key, asks)
  330. if (asks < emptyRetries) digests.delete(key)
  331. if (told.has(key)) return
  332. const status = await ask(["warmup-status"], undefined, 5000)
  333. if (!status) return
  334. told.add(key)
  335. digests.delete(key)
  336. await toast(status)
  337. } catch {
  338. // memory is optional: never break the session over it
  339. }
  340. }
  341. // Per-prompt recall, the relevance pass Claude Code gets on
  342. // UserPromptSubmit: the digest above is ranked by the project, this is ranked
  343. // by what the user just asked. Silent when nothing matches.
  344. hooks["experimental.chat.messages.transform"] = async (input, output) => {
  345. try {
  346. // The compaction's own request runs this transform right after the
  347. // compacting hook. Recall there would land in the summariser's input and
  348. // the recovery packet would count as delivered to a turn that never saw it.
  349. const owner = (output?.messages || []).find((m) => m?.info?.sessionID)?.info?.sessionID
  350. if (owner && compacting.has(owner)) return
  351. const users = userTurns(output?.messages)
  352. const last = users[users.length - 1]
  353. if (!last) return
  354. // Asked once per message. opencode builds every model call afresh from
  355. // its store, so text added to a message here lasts one call: once the
  356. // agent ran a tool the recall was gone, and deja, having shown it, would
  357. // not send it again (#4786).
  358. // A block already on the message came from another copy of this plugin
  359. // earlier in the same call, or from this one in a host that keeps the
  360. // message between calls. It is the answer: asked again, deja picks the
  361. // next pointer down and the message carried both (#5682).
  362. const present = trailingRecall(last.parts[last.parts.length - 1]?.text).blocks[0]
  363. if (!recalled.has(last.key) && present) remember(last.key, present)
  364. if (!recalled.has(last.key)) {
  365. // A turn with no text, an image alone, still goes to hook-prompt: that
  366. // call is what stamps the session live again after session.idle ended
  367. // it, and without it the turn's MCP recall could return the session
  368. // to itself (#4573).
  369. // The session id lets recall skip what it already showed this
  370. // session. Without it every message re-injects the same block —
  371. // measured on a real store, half of all injections were a
  372. // word-for-word repeat.
  373. const key = input?.sessionID || last.sessionID || ""
  374. if (key) live.add(key)
  375. // A task sub-agent's turns are written by the agent that spawned it,
  376. // which had this recall already. Asked with no prompt, deja only stamps
  377. // the session live: on a real store sub-agents took more per-prompt
  378. // blocks than the sessions people typed in (34 to 19 in 17 days).
  379. const parent = await parentOf(key)
  380. const prompt = parent ? "" : last.prompt
  381. const raw = await ask(hook("hook-prompt"), JSON.stringify({ prompt, session_id: key, parent_session_id: parent, cwd }))
  382. const reply = prompt && raw ? JSON.parse(raw) : {}
  383. remember(last.key, reply?.hookSpecificOutput?.additionalContext || "")
  384. // The "deja-vu — from Codex CLI, …" line is the person's, and what goes
  385. // into the message is the model's: without the toast it reached no one,
  386. // while deja counted it shown and held the next one back twenty minutes.
  387. if (reply?.systemMessage) await toast(reply.systemMessage)
  388. }
  389. // Every message gets back what it was given, in every call, the way
  390. // Claude Code keeps a prompt hook's text in its transcript. Once: the
  391. // block is put in place of any already there, never after it.
  392. for (const u of users) {
  393. const extra = recalled.get(u.key)
  394. if (extra) settleRecall(u.parts[u.parts.length - 1], extra)
  395. }
  396. } catch {
  397. // memory is optional: never break the session over it
  398. }
  399. }
  400. // Compaction is about to summarise the session away. The turns are still in
  401. // opencode's store, so deja reads them by the session id and keeps a
  402. // recovery packet — commands, how they went, what was open — for the next
  403. // turn, as Claude Code gets through PreCompact.
  404. hooks["experimental.session.compacting"] = async (input) => {
  405. try {
  406. const sessionID = input?.sessionID || ""
  407. if (sessionID) compacting.add(sessionID)
  408. recalled.clear()
  409. await ask(["hook-precompact"], JSON.stringify({ session_id: sessionID, cwd, harness: "opencode" }), 60000)
  410. } catch {
  411. // memory is optional: never break a compaction over it
  412. }
  413. }
  414. // A spawned agent's instructions are the one thing the parent hands it, and
  415. // deja decides whether recall goes in there. It leaves them as written where
  416. // the parent had recall of its own, opencode included (hook_spawn.go), and
  417. // the call still asks for a rebuild when the index is stale (#2567).
  418. hooks["tool.execute.before"] = async (input, output) => {
  419. try {
  420. if (input?.tool !== "task") return
  421. const args = output?.args
  422. if (!args?.prompt) return
  423. const payload = {
  424. hook_event_name: "PreToolUse",
  425. tool_name: "Task",
  426. tool_input: { prompt: args.prompt },
  427. session_id: input.sessionID || "",
  428. cwd,
  429. }
  430. const raw = await ask(["hook-tool"], JSON.stringify(payload))
  431. if (!raw) return
  432. const next = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.prompt
  433. if (next) args.prompt = next
  434. } catch {
  435. // memory is optional: never break a spawn over it
  436. }
  437. }
  438. // The moment a command fails is the one an agent never thinks to ask about,
  439. // and tool.execute.after is the only seam opencode gives for it. The hook
  440. // returns nothing to inject, so the line is folded into the tool output,
  441. // which the next request carries as the tool result.
  442. hooks["tool.execute.after"] = async (input, output) => {
  443. try {
  444. // A file's history, at the read before the edit. opencode has no seam
  445. // that can inject before a file action — tool.execute.before can only
  446. // rewrite the arguments — so the line goes out the way the failure line
  447. // does: appended to the tool's own output, which the next request
  448. // carries as the tool result. Without this, what deja knows at the
  449. // point of an action reached every harness except this one.
  450. //
  451. // Matched on the argument rather than the tool name: a tool carrying a
  452. // file path is a file action whatever this version calls it, and a name
  453. // deja does not recognise is answered with silence.
  454. const fpath = input?.args?.filePath || input?.args?.path || ""
  455. const patchText = input?.args?.patchText || input?.args?.patch || ""
  456. if ((fpath || patchText) && input?.tool !== "bash") {
  457. const ftext = output?.output
  458. if (!ftext) return
  459. const fpayload = {
  460. hook_event_name: "PostToolUse",
  461. tool_name: input?.tool || "read",
  462. tool_input: { ...(input?.args || {}), file_path: fpath, patchText },
  463. session_id: input.sessionID || "",
  464. cwd,
  465. }
  466. const fraw = await ask(["hook-tool"], JSON.stringify(fpayload))
  467. if (!fraw) return
  468. const fextra = JSON.parse(fraw)?.hookSpecificOutput?.additionalContext
  469. if (fextra) output.output = ftext + "\n\n" + fextra
  470. return
  471. }
  472. if (input?.tool !== "bash") return
  473. const text = output?.output
  474. if (!text) return
  475. const payload = {
  476. hook_event_name: "PostToolUse",
  477. tool_name: "bash",
  478. tool_input: { command: input?.args?.command || "" },
  479. tool_response: { output: text },
  480. session_id: input.sessionID || "",
  481. cwd,
  482. }
  483. const raw = await ask(["hook-tool-after"], JSON.stringify(payload))
  484. if (!raw) return
  485. const extra = JSON.parse(raw)?.hookSpecificOutput?.additionalContext
  486. if (extra) output.output = text + "\n\n" + extra
  487. } catch {
  488. // memory is optional: never break a tool call over it
  489. }
  490. }
  491. // A turn is over when opencode publishes session.idle, and the next prompt
  492. // stamps the session again before the model can ask anything, so the session
  493. // is history to everyone else in between.
  494. hooks.event = async ({ event }) => {
  495. try {
  496. const id = event?.type === "session.idle" ? event.properties?.sessionID : ""
  497. if (!id) return
  498. await endSession(id)
  499. // Ended, so dispose does not spawn deja for it again on the way out.
  500. live.delete(id)
  501. } catch {
  502. // memory is optional: never break the session over it
  503. }
  504. }
  505. // `opencode run` exits without waiting for the event above, and it does wait
  506. // for dispose: a one-shot run ends what it started here.
  507. hooks.dispose = async () => {
  508. for (const id of live) await endSession(id)
  509. live.clear()
  510. }
  511. return hooks
  512. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.