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.
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
Markdown
[](/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
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
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "deja-vu",
- "description": "Memory for AI coding agents: search and auto-recall your own past sessions across every tool you use.",
- "owner": {
- "name": "vshulcz",
- "url": "https://github.com/vshulcz"
- },
- "plugins": [
- {
- "name": "deja-vu",
- "description": "Your agent starts already knowing what you did before — recall across Claude Code, Codex, Cursor, opencode and forty-four more agents.",
- "source": "./claude-plugin",
- "category": "productivity"
- }
- ]
- }
README.md · README · 694 lines · 1 finding marked
- <p align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/logo-dark.svg">
- <img src="https://raw.githubusercontent.com/vshulcz/deja-vu/main/assets/logo.svg" width="280" alt="deja-vu">
- </picture>
- </p>
- <p align="center"><b>Shared local memory, session history search, cross-agent handoff, and code recovery across 48 coding agents.</b><br>
- Claude Code, Codex, Cursor, OpenClaw, Gemini CLI, OpenCode, Hermes and 40 more agents already save every session to disk.<br>
- <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>
- <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>
- <p align="center">
- <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>
- <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>
- <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>
- <a href="https://github.com/vshulcz/deja-vu/releases"><img src="https://img.shields.io/github/v/release/vshulcz/deja-vu" alt="Release"></a>
- <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License"></a>
- ·
- <a href="https://vshulcz.github.io/deja-vu/"><b>Website</b></a> · <a href="https://vshulcz.github.io/deja-vu/view/"><b>Live demo</b></a> · <a href="https://vshulcz.github.io/deja-vu/guide/getting-started.html">Docs</a> · <a href="https://vshulcz.github.io/deja-vu/guide/benchmarks.html">Benchmarks</a> · <a href="https://vshulcz.github.io/deja-vu/guide/compare.html">Compare</a> · <a href="docs/ARCHITECTURE.md">Architecture</a>
- </p>
- <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>
- ```sh
- npx @vshulcz/deja-vu install --auto # 1-step cross-platform install + wire installed agents
- # or via shell / Homebrew:
- 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
- ```
- <p align="center"><sub>Homebrew: <code>brew install deja-vu && deja install --auto</code> · Claude Code: <code>claude plugin marketplace add vshulcz/deja-vu && claude plugin install deja-vu@deja-vu</code> · Skills: <code>npx skills add vshulcz/deja-vu</code><br><a href="#install">Windows (Scoop / winget), Codex, OpenCode, OpenClaw and more</a> · Try without installing: <code>npx @vshulcz/deja-vu stats --no-index --card</code> or <code>npx @vshulcz/deja-vu audit</code></sub></p>
- ```sh
- $ deja "jwt refresh token" # lexical + structural search across all 47 agent stores
- $ deja handoff --to codex # continue the active session's goal & state in another agent
- $ deja restore internal/auth/jwt.go # recover code an agent overwrote before git commit
- $ deja blame internal/auth/jwt.go:42 # trace which agent session wrote or replaced a line
- $ deja audit # check retention risk, purged chats & index health across all 47 stores
- ```
- <table align="center">
- <tr>
- <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>
- <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>
- <td align="center" width="33%">Index & 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>
- </tr>
- </table>
- <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> · <a href="https://vshulcz.github.io/deja-vu/guide/benchmarks.html">all benchmark runs</a></sub></p>
- ## Search it yourself
- `deja` with no arguments opens a terminal search across every agent's history — starting with
- the sessions behind your uncommitted changes, then recent work in the current project.
- <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>
- - **Navigate:** `↑↓` picks a session, `↵` opens at the match, `/` searches inside a session, `]` `[` jump between turns, `^s` toggles date/relevance sort (`deja search --sort date`).
- - **Filter:** by agent (`codex:`), time (`today`, `yesterday`, `week`, `month`), or project (`in:<project>`).
- - **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.
- - **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.
- 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.
- ## Highlights
- - **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.
- - **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)).
- - **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.
- - **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>`).
- - **Automatic recall via hooks & MCP.** Surfaces prior sessions at session start, before a file edit or command runs, and when a command fails.
- - **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.
- - **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)).
- - **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)).
- ### Your own work, wrapped
- `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.
- <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>
- ## Install
- `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).
- <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>
- 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:
- ```sh
- 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:
- ```powershell
- 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>
- 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.
- </details>
- ## Memory in the repository
- Sync moves history between your own machines. To hand the people you work with the
- few things your agents learned the hard way, put them in the repository:
- ```text
- $ deja repo candidates
- 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)
- $ deja repo add 4cd7e7bb9c
- added 1 entry to .deja/memory.jsonl
- nothing is committed: review with `git diff .deja/` and commit it like code
- ```
- Candidates come from this project's history in every agent: promoted and remembered
- notes, reversals reported in a session, and what sessions settled. Nothing is written
- until you pick, every entry is redacted on the way in, and one that still matches a secret
- rule is refused. The file is JSON lines sorted by a content hash, with a
- `merge=union` attribute beside it, so parallel additions merge; deleting a line removes
- an entry. After a clone, the entries come back at session start and in recall, in any agent
- deja is wired into, marked as from the repository and framed as untrusted like the rest.
- `{"activations":{"auto":{"repo":false}}}` in the trust policy keeps them out of the hooks.
- [More](https://vshulcz.github.io/deja-vu/guide/repo-memory.html).
- ## Privacy
- Indexing and search are local. The network is used only by `deja update`, `deja sync ssh`,
- the version check in `deja doctor`, `deja embed` against an endpoint you configure (and,
- once it has built the semantic sidecar, each search, which sends the query to that
- endpoint), and a once-a-day look at the latest release from an interactive command. That look sends no
- session data; `DEJA_OFFLINE=1` turns it off, and so does `DEJA_NO_UPDATE_NOTICE` set to any
- value, which also hides the note a new version prints on its first run.
- Credentials are stripped as the index is built: cloud and provider keys, tokens and JWTs,
- PEM blocks, passwords in URLs or stated in prose. Each becomes `[redacted:<kind>]` and the
- text around it stays searchable. The source transcripts still hold them
- ([one machine had 84 in 42 sessions](https://vshulcz.github.io/deja-vu/guide/credentials-in-transcripts.html)):
- `deja secrets` names those sessions without printing a value, and `deja secrets --scrub`
- rewrites the ones it can, keeping the original beside the file.
- `deja forget` drops sessions and keeps them dropped across rebuilds. `~/.config/deja/exclude`
- skips a project per line, or a whole store with `harness:opencode`. The
- [security model](docs/SECURITY-MODEL.md) has the data flows and what redaction cannot catch.
- ## CLI
- Bare `deja` in a terminal opens [the search screen](#search-it-yourself). With a query,
- or any command below, it prints and exits:
- ```text
- $ deja "jwt refresh token"
- [claude] api · Jul 8 · 8f31c0a9 — 2 matches
- login started failing after refresh token rotation; jwt kid mismatch in tests
- fixed by reloading jwks cache after rotateKey and adding a clock-skew test
- [codex] web · Jul 1 · b77d91e2 — 1 match
- refresh token cookie needed SameSite=Lax in local callback flow
- ```
- **Ask your history**
- | Command | What it does |
- | --- | --- |
- | `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. |
- | `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. |
- | `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. |
- | `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`. |
- | `deja origin [rev\|range]` | Which session and user turn produced a commit or commit range, matched against recorded edit spans (`attributed`, `uncertain`, or `unknown`). |
- | `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. |
- | `deja files <topic>` | The other direction: which files the work on a subject actually touched. |
- | `deja how <tool>` | How this machine actually runs a thing, with the real flags, from what agents ran before. |
- | `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. |
- | `deja friction` | Errors that hit three or more separate sessions, with the harnesses named. |
- When the first word of a bare query has at least four characters and is one
- edit from a command name, deja names that command on stderr and then searches
- as usual. `deja search <query>` skips the suggestion.
- <details>
- <summary>Using what it finds, and moving it between machines</summary>
- **Use what it finds**
- | Command | What it does |
- | --- | --- |
- | `deja ctx <query>` | Markdown digest of the best match, with the code it changed, ready to pipe into a prompt. |
- | `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. |
- | `deja resume <id>` | Reopen a found session in its native harness. `--app` opens a Codex session in the ChatGPT desktop app. |
- | `deja restore <path>` | Hand back a span an agent replaced, from the `old_string` its edit recorded. Never writes over the original. |
- | `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. |
- | `deja share <id>` | A sanitized session digest for a colleague, with secrets already scrubbed. |
- **Move it and check it**
- | Command | What it does |
- | --- | --- |
- | `deja sync export/import/ssh` | Move memory between machines. Watermarked, append-only, idempotent. |
- | `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. |
- | `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. |
- | `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. |
- | `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. |
- | `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. |
- | `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. |
- | `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. |
- | `deja doctor [--deep]` | Self-diagnosis, and with `--deep`, proof of the index against the sources. |
- | `deja mcp` | The stdio MCP server, which is what `deja install` wires in. |
- </details>
- Full reference: [commands](https://vshulcz.github.io/deja-vu/guide/commands.html) and
- [JSON output](docs/json-output.md).
- ### MCP tools
- The server exposes one tool, `deja`, with a `mode`; `deja install` wires it in. One tool
- costs 477 tokens of definitions a turn, against 8,283 for the largest of the seven servers
- measured in [day zero](https://vshulcz.github.io/deja-vu/guide/day-zero.html). The six
- older tool names (`recall`, `recall_context`, `blame`, `fix`, `how`, `remember`) still answer.
- `deja mcp --context-search` is a separate server with a single `context_search` tool, for
- Qwen Code's External Context MCP Profile v1 ([Qwen page](docs/registry/qwen.md)).
- <details>
- <summary>Arguments and return shapes</summary>
- | Tool | Arguments | Returns |
- | --- | --- | --- |
- | `deja` | `mode`, `q`, `harness?`, `project?`, `limit?` | Depends on the mode, below. |
- `q` carries whatever the mode asks about. The per-mode names below are still
- accepted; they are no longer declared, because the schema is read every turn
- whether or not the tool is called.
- | Mode | `q` is | Also reads | Returns |
- | --- | --- | --- | --- |
- | `recall` | 1-3 exact terms: a file path, an error string, a flag or identifier | `harness?`, `limit?`, `offset?` | Dense matching snippets, capped at 4KB. |
- | `context` | the same as recall | `harness?` | Markdown digest of the best-matching session, with the code it changed. |
- | `blame` | a file path | `harness?`, `project?`, `since?`, `limit?`, `all?` | Sessions that discussed a file. |
- | `fix` | the failing output, verbatim | `limit?` | What this machine ran, or changed, after that same error before. |
- | `how` | the tool or target, e.g. `go test` | `project?`, `limit?` | The real invocation, from what agents ran here. |
- | `orient` | nothing — it asks about the project | `project?`, `limit?` | The commands past sessions ran here and the files they worked in. |
- | `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. |
- | `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. |
- </details>
- ## Supported harnesses
- <!-- matrix:start -->
- aider · Amp · Antigravity · Cherry Studio · Claude Code · Claw Code · Cline · CodeArts Desktop · CodeBuddy Code · CodeWhale · Codex CLI · Command Code · Continue · Copilot CLI · VS Code Copilot Chat · Crush · Cursor · DeepSeek Harness · Devin CLI · Gemini CLI · gajae-code · Goose · Grok Build · Hermes · JetBrains AI Assistant · Junie · Kilo Code · Kimchi Coding · Kimi Code · Kiro · MiniMax Code · MiMo-Code · Muse Code · Omnigent · omp (Oh My Pi) · OpenClaw · opencode · Orca · pi · prime-agent (PrimeIntellect) · Qwen Code · Reasonix · Roo Code · Senpi · TRAE CLI · Windsurf / Devin Desktop · ZCode · Zed.
- <details>
- <summary>What each one supports</summary>
- | Harness | MCP recall | Auto-recall | Skill | Command | Resume | Handoff | Needs |
- | --- | :-: | :-: | :-: | :-: | :-: | :-: | --- |
- | aider | ⚠ | ✅ | ✕ | ⚠ | ✕ | ✅ | deja aider |
- | Amp | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | threads from 0.0.1774963753 on live on ampcode.com; deja reads those its plugin has written out, and older local ones |
- | Antigravity | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | Cherry Studio | ✅ | ✅ | ✅ | ✕ | ✕ | paste | import the server once in Settings -> MCP; enable the skill for the agent |
- | Claude Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | Claw Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Cline | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | CodeArts Desktop | ⚠ | ⚠ | ⚠ | ⚠ | ✕ | paste | — |
- | CodeBuddy Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | CodeWhale | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Codex CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | Command Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Continue | ✅ | ⚠ | ✅ | ✅ | ✅ | ✅ | — |
- | Copilot CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | VS Code Copilot Chat | ✅ | ✅ | ✅ | ✅ | ✕ | ✅ | — |
- | Crush | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
- | Cursor | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 (IDE chats, CLI tool output) |
- | DeepSeek Harness | ✅ | ✅ | ✅ | ✅ | ✕ | ✅ | zstd |
- | Devin CLI | ✅ | ✅ | ✅ | ✕ | ✅ | ✅ | sqlite3 |
- | Gemini CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | gajae-code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Goose | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | deja goose |
- | Grok Build | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 (grok-dev store) |
- | Hermes | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
- | JetBrains AI Assistant | ✅ | ⚠ | ⚠ | ⚠ | ✕ | paste | none |
- | Junie | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Kilo Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 for the CLI store |
- | Kimchi Coding | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Kimi Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | Kiro | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 for the CLI database |
- | MiniMax Code | ✅ | ✅ | ✅ | ✕ | ✅ | ✅ | the MiniMax Code CLI (`mcode`) for `deja resume` and `deja handoff --to mcode --exec`; `sqlite3` for the session's workspace |
- | MiMo-Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
- | Muse Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Omnigent | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
- | omp (Oh My Pi) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | OpenClaw | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 (2026.8+ store); zstd for .zst archives and compressed events (2026.9.9+) |
- | opencode | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
- | Orca | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 |
- | pi | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | prime-agent (PrimeIntellect) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | Qwen Code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | — |
- | Reasonix | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | zstd for 1.x sessions |
- | Roo Code | ✅ | ✕ | ✅ | ✅ | ✅ | paste | roo CLI (editor tasks reopen in the editor) |
- | Senpi | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | TRAE CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | none |
- | Windsurf / Devin Desktop | ✅ | ⚠ | ✅ | ✅ | ✕ | paste | none |
- | ZCode | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | sqlite3 for the CLI database |
- | Zed | ✅ | ✕ | ✅ | ✅ | ✕ | paste | sqlite3 + zstd |
- ✅ works · — possible, not built yet · ✕ the harness has no such mechanism · ⚠ waiting on the harness itself · ? not investigated
- </details>
- <!-- matrix:end -->
- TRAE IDE is wired, not read: its chats are in an encrypted database. `deja install trae-ide`
- adds the MCP server and the skill, and `trae-ide-auto` adds hooks, which TRAE IDE runs only
- after you turn them on in Settings > Hooks.
- Custom store locations go through `DEJA_*_ROOT` variables, and each agent's own relocation
- variable is honored too. The
- [session format registry](https://vshulcz.github.io/deja-vu/registry/README.html) documents
- the observed paths, record schemas and role mapping per harness, with synthetic fixtures
- keeping those descriptions checked against the parsers.
- ### Harnesses with a package of their own
- `deja install --auto` wires every one of these like every other harness, and
- that stays the shortest path. They also have a package in their own ecosystem,
- for people who install extensions there rather than from a CLI:
- | Harness | Package | Install |
- | --- | --- | --- |
- | opencode | npm `opencode-deja` | `opencode plugin add opencode-deja` |
- | DeepSeek Harness | npm `dsh-deja` | `dsh plugin --profile web add dsh-deja` |
- | Zed | `deja-context-server` | Zed → Extensions → deja |
- | Kimi Code | plugin `deja` | `/plugins install https://github.com/vshulcz/deja-vu` |
- | Gemini CLI | extension `@vshulcz/deja`, in the [Gemini CLI Extensions Gallery](https://geminicli.com/extensions/) | `gemini extensions install https://github.com/vshulcz/deja-vu` |
- | Antigravity | plugin `deja-vu` ([`antigravity-plugin/`](antigravity-plugin/)) | `agy plugin install deja-vu` |
- | Codex CLI | plugin `deja-vu` | `codex plugin marketplace add https://github.com/vshulcz/deja-vu` then `codex plugin add deja-vu@deja-vu` |
- | Grok Build | plugin `deja` | `grok plugin marketplace add vshulcz/deja-vu` then `grok plugin install deja` |
- | OpenClaw | ClawHub and npm `@vshulcz/openclaw-deja` | `openclaw plugins install clawhub:@vshulcz/openclaw-deja` |
- | pi (and omp) | npm `@vshulcz/pi-deja` | `pi install npm:@vshulcz/pi-deja` |
- | 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` |
- | Magpie | npm `@vshulcz/magpie-deja` | `magpie plugin add @vshulcz/magpie-deja` |
- | Orca | v2 `trusted-worker` plugin `deja` | `Orca → Plugins → extensions/orca` (and `deja install orca` for native MCP and hooks) |
- | CodeWhale | Claude-compatible bundle `deja-vu` | `/plugin install extensions/codewhale` (and `deja install codewhale` for native hooks) |
- | VS Code / Cursor / Windsurf | status bar extension `vshulcz.deja-status` | `code --install-extension vshulcz.deja-status` |
- | 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` |
- | Neovim | `lazy.nvim` & CodeCompanion plugin ([`extensions/nvim/`](extensions/nvim/)) | `{ "vshulcz/deja-vu", opts = {} }` |
- | tmux | [TPM](https://github.com/tmux-plugins/tpm) popup (`prefix + D`) & `#{deja_status}` (`deja.tmux`) | `set -g @plugin 'vshulcz/deja-vu'` |
- | Raycast | Raycast extension `deja-vu` | `cd extensions/raycast && npm install && npx ray develop` |
- | CC Switch | 1-click MCP & 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) |
- Either path works alone, and both together double nothing: each package reads what
- `deja install` already wrote and uses the deja you already have.
- In a [Spec Kit](https://github.com/github/spec-kit) project, an extension adds
- `/speckit.deja-vu.recall`, which searches past sessions for the feature before you
- implement it:
- ```sh
- specify extension add deja-vu --from https://github.com/vshulcz/deja-vu/releases/latest/download/deja-spec-kit.zip
- ```
- The same search is also a skill, for any agent that loads a `SKILL.md`:
- ```sh
- npx skills add https://github.com/vshulcz/deja-vu --skill deja-search # skills CLI: Claude Code, Cursor, Goose, Copilot…
- openclaw skills install @vshulcz/deja-search # ClawHub
- hermes skills install vshulcz/deja-vu/skills/deja-search # Hermes
- ```
- The skill drives the `deja` binary from the install step above; it does not bundle one.
- ## Semantic recall (optional)
- Point `deja embed` at a local Ollama, LM Studio or OpenAI-compatible endpoint with
- `DEJA_EMBED_URL` and rephrased queries still hit. Without a reachable runtime, lexical
- search and MCP recall continue unchanged. OpenAI Platform works with its standard key:
- ```sh
- export OPENAI_API_KEY='sk-...'
- export DEJA_EMBED_URL='https://api.openai.com/v1/embeddings'
- export DEJA_EMBED_MODEL='text-embedding-3-small'
- deja embed
- ```
- <details>
- <summary>Local runtimes, other endpoints, and what vectors cost</summary>
- With no `DEJA_EMBED_URL` set, deja probes `localhost:11434` and `localhost:1234`,
- so a machine already running Ollama or LM Studio is picked up without being asked.
- `DEJA_EMBED_OFF=1`, or `DEJA_EMBED_URL=off`, turns that probe off — any other
- configured `DEJA_EMBED_URL` still wins.
- For another authenticated OpenAI-compatible endpoint, set `DEJA_EMBED_KEY` explicitly:
- ```sh
- export DEJA_EMBED_URL='https://example.com/v1/embeddings'
- export DEJA_EMBED_MODEL='embedding-model'
- export DEJA_EMBED_KEY='...'
- deja embed
- ```
- `DEJA_EMBED_KEY` takes precedence. `OPENAI_API_KEY` is used automatically only for an
- HTTPS `api.openai.com` URL; it is never implicitly sent to local or third-party endpoints.
- Models trained with instruction prefixes, such as the multilingual E5 family, need them on
- both sides. `DEJA_EMBED_QUERY_PREFIX` goes in front of every search query and
- `DEJA_EMBED_PASSAGE_PREFIX` in front of every indexed text; both are empty by default:
- ```sh
- export DEJA_EMBED_MODEL='multilingual-e5-small'
- export DEJA_EMBED_QUERY_PREFIX='query: '
- export DEJA_EMBED_PASSAGE_PREFIX='passage: '
- deja embed
- ```
- The passage prefix is part of the sidecar's model name, so changing it embeds everything
- again, and search ignores vectors made with another model or prefix (it says so once).
- The sidecar sits beside the index as `.vectors.bin`, not inside `index.db`. Float32 vectors
- cost roughly 4 MB per 1k messages for a 1,024 dimension model. A remote endpoint receives
- the redacted indexed text, truncated to about 2k characters, but never raw source files.
- With Ollama or LM Studio, embedding stays local and needs no key.
- </details>
- ## Proof
- Millisecond lookups, and on LongMemEval-S 88.9% hit@1 (470-question cleaned set) and 88.2% hit@1 on all 500 questions;
- on LoCoMo retrieval, 71.9% hit@1. On a task this machine had already solved, 58% fewer
- tokens: eleven runs an arm, 53,558 against 126,222 with nothing wired, and 52,815 against
- 103,443 on a later build with the arms alternated. Both retrieval harnesses ship in this repo
- and run on the public datasets in minutes: [benchmarks](https://vshulcz.github.io/deja-vu/guide/benchmarks.html) ·
- [what one task costs](https://vshulcz.github.io/deja-vu/guide/day-zero.html).
- The rest is measured by `deja bench`:
- ```sh
- deja bench recall # ranking floor: 100 queries, half Russian, CI fails if recall drops
- deja bench context # 30 seeded task chains plus five negative controls
- deja bench block # does the answer survive into what deja hands over
- deja bench prompt # what the per-prompt hook fires on, and what it fires on wrongly
- deja bench ingest # what an update costs: unchanged, a turn, a new transcript, a rename, a rewrite
- deja bench read # what it costs to read a database-backed store, and what one long value does to it
- ```
- <details>
- <summary>What the in-repo benches measure, and lookup cost on a real store</summary>
- `bench block` asks the question the others cannot: with the right session in
- hand, does the block carry what that session settled. Eight sessions discuss each
- subject and one of them settles it, in the middle of its own transcript rather
- than at the end — so the baseline arm, the newest turns of the top hit, scores
- zero and an arm above zero had to choose.
- | Arm | Carries the answer | Median tokens |
- |---|---|---|
- | `deja-block` (session-start block) | 1.00 | 665 |
- | `deja-digest` (context digest) | 1.00 | 1656 |
- | `newest-turn` (baseline) | 0.00 | 289 |
- | `cold` | 0.00 | 0 |
- The context experiment compares deja-recall against full-history, naive grep and cold
- context. With the default seed:
- | Arm | Median tokens | Median coverage | Negative-control tokens |
- | --- | ---: | ---: | ---: |
- | deja-recall | 1,096 | 1.00 | 0 |
- | full-history | 80,547 | 1.00 | 78,145 |
- | naive-grep | 273,238 | 1.00 | 0 |
- | cold | 0 | 0.00 | 0 |
- Same fact coverage as grepping the raw logs for about 250x fewer tokens, and about 70x
- fewer than replaying the matched sessions in full, while injecting nothing on the chains
- where no prior fact is relevant. The corpus generator and the relevance labels are
- ordinary reviewed Go. Audit what "relevant" means before trusting any figure, ours
- included.
- Measured on a real store of 2,419 sessions and 179k messages, 1.9 GB of
- transcripts:
- | Measurement | Result |
- | --- | --- |
- | 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 |
- | `deja <query>`, end to end | ~0.2 s median on that store: process start, the freshness check over every store, ranking, printing |
- | Freshness check alone | ~50 ms when nothing changed |
- | Index size | 200 MB, ~10% of corpus |
- The same store has since grown to 2,754 sessions, 358k messages and 5.7 GB.
- A cold full build over it takes 71 s and writes a 232 MB index — 4% of the
- corpus, because the share falls as transcripts repeat themselves — and the
- end-to-end median is unchanged at 0.25 s. Since 0.23.2 records are compressed
- from 256 bytes, which takes a 19k-session index from 277 to 185 MB.
- The index is incremental. When a session file grows, only that file is re-read. When one is
- rewritten, its new records are appended and the old ones zeroed in place. On a
- 40,000-session store a pass over 20 rewritten transcripts takes 1.7 s and peaks under 1 GB,
- and a search for a word most sessions hold takes about a second.
- </details>
- ### How it compares
- | Capability | `deja-vu` | `claude-mem` | `MemPalace` |
- | --- | --- | --- | --- |
- | 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`) |
- | Agents shared | 48 harnesses | 9 (hooks) | 3 (CLI) |
- | LongMemEval-S R@5 | **97.2%** (88.9% hit@1) | — | 96.6% |
- | Runtime & dependencies | 1 Go binary | Bun worker + SQLite + Chroma | Python + 300 MB embedding model |
- | LLM calls / account required | None | Observer LLM calls | None |
- | Uncommitted file recovery | `deja restore <path>` | No | No |
- | Existing `claude-mem.db` | Reads `~/.claude-mem/claude-mem.db` directly | Native | No |
- 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).
- ## How it works
- Local inverted index in `~/.cache/deja`: parse the JSONL and SQLite stores, redact
- credentials, write an append-only `records.bin` plus token buckets, and track per-file state in
- `manifest.gob` so repeat runs only ingest what changed. The MCP server, stats, share and
- sync all read that one index. Details in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
- ## FAQ
- <details>
- <summary><b>How is this different from the other memory tools?</b></summary>
- | | deja | Memory platforms<br>(Mem0, Letta, memU) | Session search<br>(cass) |
- | --- | :-: | :-: | :-: |
- | Knows work from before you installed it | yes | no | yes |
- | Capture step | none, the transcripts are the memory | the agent or your code writes facts | none |
- | Needs an LLM or embedding key | no | yes | optional |
- | Recalls without being asked | at session start and before a tool runs | no | no |
- [engram](https://github.com/Gentleman-Programming/engram) is the strongest of the
- record-forward tools and worth your time if that model fits you; it still starts empty and
- knows only what an agent chose to save. The
- [full comparison](https://vshulcz.github.io/deja-vu/guide/compare.html) covers 15 of them.
- </details>
- <details>
- <summary><b>Will it slow my agent down?</b></summary>
- A recall is a lexical lookup against a local index:
- 0.7–0.8 ms median, and nothing waits on a model. A hook adds the process start and a
- freshness check over your stores on top of that: about 0.2 s end to end on a 1.9 GB
- store. On an index of 19k sessions the per-prompt hook takes 107 ms at the median,
- and a recall through `deja mcp` 85 ms.
- </details>
- <details>
- <summary><b>Where is Claude Code session history stored, and can I search it?</b></summary>
- Under `~/.claude/projects`, one JSONL file per session; Codex keeps `~/.codex/sessions`, Cursor a
- SQLite `state.vscdb`. deja reads them all in place: bare `deja` opens a screen to search
- and read them, `deja search` does it from a script, `deja last` lists the recent
- sessions of every agent, and `deja view` opens the whole history as one local page. Paths
- for each agent: [where sessions are stored](https://vshulcz.github.io/deja-vu/guide/where-sessions-are-stored.html).
- </details>
- <details>
- <summary><b>My Claude Code session history disappeared. Is it gone?</b></summary>
- Claude Code deletes transcripts older than 30 days (`cleanupPeriodDays` in `~/.claude/settings.json`), and `claude --resume` lists
- only what is left. A session deja indexed before the cleanup stays searchable after the
- file is gone, and the weekly note at session start says how many it kept, with an id
- `deja resume <id> --write-back` puts back. Details: [session files on disk](https://vshulcz.github.io/deja-vu/guide/session-files-on-disk.html).
- </details>
- <details>
- <summary><b>What files live in ~/.config/deja, and what can I set in them?</b></summary>
- Under `~/.config/deja` (or `$XDG_CONFIG_HOME/deja`):
- - **`policy.json`** (`DEJA_POLICY_FILE` moves it) — JSON object with four optional keys:
- - `"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`.
- - `"ignore"`: array of shell globs matched against session path and project to exclude from recall and `sync` (default `["*/.claude/jobs/*"]`).
- - `"auto_index"`: `false` stops automatic index updates on search, MCP recall and hooks (same as `DEJA_NO_AUTO_INDEX=1`).
- - `"search_only"`: `true` skips mining fixes, commands and co-occurrence, saving ~20% of build CPU (same as `DEJA_SEARCH_ONLY=1`).
- - **`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`).
- - **`projects`** — one `<path> = <name>` per line to group multiple checkouts or worktrees as one project.
- - **`rules.md`** — standing instructions copied into each installed agent's global rules file by `deja rules sync`.
- - **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`).
- 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).
- </details>
- <details>
- <summary><b>One project is spread over several checkouts. Can recall treat them as one?</b></summary>
- List the trees in `~/.config/deja/projects`, one `<path> = <name>` per line:
- ```text
- ~/work/monorepo = work
- ~/work/worktrees = work
- ```
- 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.
- </details>
- <details>
- <summary><b>How do I wipe everything?</b></summary>
- ```sh
- deja uninstall --all
- rm -rf ~/.cache/deja ~/.local/share/deja ~/.config/deja
- ```
- The index is under `~/.cache/deja`, your `remember` and `promote` notes in
- `~/.local/share/deja`, and the rules, exclude list, project aliases and hook launcher in
- `~/.config/deja` (or under `XDG_DATA_HOME` and `XDG_CONFIG_HOME` when set; on
- Windows the notes are in `%AppData%\deja`).
- </details>
- ## Guides
- - **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)
- - **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)
- - **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)
- - **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)
- <details>
- <summary><b>Per-harness setup guides (Claude Code, Codex, Cursor, OpenClaw, Hermes…)</b></summary>
- [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)
- </details>
- ## Contributing
- `make build test lint`, then [CONTRIBUTING.md](CONTRIBUTING.md). Adding a harness starts in
- the [parser registry](docs/ARCHITECTURE.md#source-parsers). Priorities and non-goals are in
- [ROADMAP.md](ROADMAP.md). Good first issues are labeled.
- ## Support
- Bugs and questions go to [issues](https://github.com/vshulcz/deja-vu/issues).
- Anything you think is exploitable goes through the private advisory link in
- [SECURITY.md](SECURITY.md) instead. What deja reads, what it never sends
- anywhere, and how to exclude a project or forget a session is under
- [Privacy](#privacy). Found it useful? [Star deja-vu on GitHub](https://github.com/vshulcz/deja-vu).
- ## License
- MIT © [Vladislav Shulcz](https://github.com/vshulcz)
docs/assets/guide.js · Bundled script · 383 lines · 2 findings marked
- (function(){
- var ORDER=[
- ['getting-started.html','Getting started'],
- ['agents.html','Agents & MCP'],
- ['search.html','Search'],
- ['commands.html','CLI reference'],
- ['harnesses.html','Harnesses'],
- ['privacy.html','Privacy'],
- ['benchmarks.html','Benchmarks'],
- ['compare.html','Compare']
- ];
- var art=document.querySelector('.doc article');
- if(!art)return;
- /* copy buttons on code blocks */
- art.querySelectorAll('pre').forEach(function(pre){
- var b=document.createElement('button');
- b.className='pre-copy';b.type='button';b.textContent='copy';
- b.addEventListener('click',function(){
- navigator.clipboard.writeText(pre.textContent.trim());
- b.textContent='copied';setTimeout(function(){b.textContent='copy'},1200);
- });
- /* a lid rather than a button floating over the code: a control that only
- appears on hover is a control most readers never learn about */
- var text=pre.textContent.trim();
- var what=/^[$#]|\bdeja\b|^curl|^brew|^go /.test(text)?'shell':
- /^[{[]/.test(text)?'json':'text';
- var lid=document.createElement('div');lid.className='pre-lid';
- lid.innerHTML='<span class="what">'+what+'</span>';
- lid.appendChild(b);
- var wrapEl=document.createElement('div');wrapEl.className='pre-wrap';
- pre.parentNode.insertBefore(wrapEl,pre);
- wrapEl.appendChild(lid);wrapEl.appendChild(pre);
- });
- /* anchors on h2 */
- art.querySelectorAll('h2').forEach(function(h){
- if(!h.id)h.id=h.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
- var a=document.createElement('a');
- a.className='hlink';a.href='#'+h.id;a.textContent=' #';a.setAttribute('aria-label','link to section');
- h.appendChild(a);
- });
- /* prev / next */
- var here=location.pathname.split('/').pop()||ORDER[0][0];
- var i=ORDER.findIndex(function(x){return x[0]===here});
- if(i>=0){
- var nav=document.createElement('div');nav.className='pn';
- var prev=i>0?ORDER[i-1]:null,next=i<ORDER.length-1?ORDER[i+1]:null;
- /* the name alone does not say which way it goes, and an arrow alone does
- not say where. Both, with the direction as the quiet half. */
- nav.innerHTML=(prev?'<a class="pv" href="'+prev[0]+'"><small>Previous</small>'+prev[1]+'</a>':'<span></span>')+
- (next?'<a class="nx" href="'+next[0]+'"><small>Next</small>'+next[1]+'</a>':'<span></span>');
- art.appendChild(nav);
- }
- /* ── how long the page takes ───────────────────────────────────────── */
- (function(){
- var slot=art.querySelector('[data-mins]');
- if(!slot)return;
- var words=art.textContent.trim().split(/\s+/).length;
- slot.textContent=Math.max(1,Math.round(words/220))+' min read';
- })();
- /* ── the sidebar remembers what you have read ──────────────────────────
- The same idea the home page greets you with. Of every documentation site
- that could do this, one about a memory tool has the most right to. */
- (function(){
- var KEY='deja.read';
- var here=location.pathname.split('/').pop()||ORDER[0][0];
- var read={};
- try{read=JSON.parse(localStorage.getItem(KEY)||'{}')}catch(e){}
- read[here]=1;
- try{localStorage.setItem(KEY,JSON.stringify(read))}catch(e){}
- var side=document.querySelector('.doc aside');
- if(!side)return;
- var n=0;
- ORDER.forEach(function(pair){
- var a=side.querySelector('a[href="'+pair[0]+'"]');
- if(!a)return;
- if(read[pair[0]]){a.classList.add('read');a.title='read';n++}
- });
- var grp=side.querySelector('.grp');
- if(grp&&n){
- var c=document.createElement('span');
- c.className='count';c.textContent=n+'/'+ORDER.length;
- grp.appendChild(c);
- }
- })();
- /* ── say that the guide can be searched ────────────────────────────── */
- var docLang=(document.documentElement.lang||'en').toLowerCase();
- var isRu=docLang.indexOf('ru')===0,isZh=docLang.indexOf('zh')===0;
- (function(){
- var nav=document.querySelector('nav .spacer');
- if(!nav)return;
- var hint=document.createElement('button');
- hint.className='searchhint';hint.type='button';
- hint.innerHTML='<span>'+(isRu?'поиск по документации':isZh?'搜索指南':'search the guide')+'</span><kbd>/</kbd>';
- hint.addEventListener('click',function(){
- document.dispatchEvent(new KeyboardEvent('keydown',{key:'/',bubbles:true}));
- });
- nav.parentNode.insertBefore(hint,nav.nextSibling);
- /* upgrade the top nav with a Demo link and a prominent ★ GitHub button */
- var gh=nav.parentNode.querySelector('a[href*="github.com/vshulcz/deja-vu"]');
- if(gh){
- gh.className='nav-cta';
- gh.innerHTML='<span class="star-ic" aria-hidden="true">★</span>GitHub';
- var homeLink=nav.parentNode.querySelector('a.brand');
- var rootPrefix=homeLink?homeLink.getAttribute('href'):'../';
- if(rootPrefix.slice(-1)!=='/')rootPrefix+='/';
- if(!nav.parentNode.querySelector('a[href*="view/"]')){
- var demo=document.createElement('a');
- demo.className='lnk';
- demo.href=rootPrefix+'view/';
- demo.textContent=isRu?'Демо':isZh?'演示':'Demo';
- nav.parentNode.insertBefore(demo,gh);
- }
- }
- })();
- /* ── enrich the closing star CTA with a 1-click install & live demo ─── */
- (function(){
- var cta=art.querySelector('.star-cta');
- if(!cta){
- cta=document.createElement('p');
- cta.className='star-cta';
- art.appendChild(cta);
- }
- var homeLink=document.querySelector('nav a.brand');
- var rootPrefix=homeLink?homeLink.getAttribute('href'):'../';
- if(rootPrefix.slice(-1)!=='/')rootPrefix+='/';
- 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
- var leadTxt=isRu?'Установка за 10 секунд, индекс за 10.':isZh?'十秒安装,十秒建索引。':'Ten seconds to install, ten to index.';
- var starTxt=isRu?'★ Поставить звезду на GitHub':isZh?'★ 在 GitHub 上点 Star':'★ Star deja-vu on GitHub';
- var demoTxt=isRu?'Живое демо в браузере →':isZh?'浏览器在线演示 →':'Try live browser demo →';
- cta.innerHTML=
- '<div class="cta-cmd"><span class="p">$</span><code>'+cmdText+'</code><button type="button">copy</button></div>'+
- '<div class="cta-row"><span>'+leadTxt+'</span>'+
- '<a class="cta-btn" href="https://github.com/vshulcz/deja-vu">'+starTxt+'</a>'+
- '<a class="cta-demo" href="'+rootPrefix+'view/">'+demoTxt+'</a></div>';
- var btn=cta.querySelector('button');
- if(btn){
- btn.addEventListener('click',function(){
- navigator.clipboard.writeText(cmdText);
- btn.textContent='copied';
- setTimeout(function(){btn.textContent='copy'},1200);
- });
- }
- var saveFirst=art.querySelector('.save-first');
- /* a page that names its own commands writes them into the callout; the
- copy buttons there only need wiring */
- if(saveFirst)saveFirst.querySelectorAll('.save-actions .save-cmd').forEach(function(row){
- var b=row.querySelector('button'),c=row.querySelector('code');
- if(!b||!c)return;
- b.addEventListener('click',function(){
- navigator.clipboard.writeText(c.textContent);
- b.textContent='copied';
- setTimeout(function(){b.textContent='copy'},1200);
- });
- });
- if(saveFirst&&!saveFirst.querySelector('.save-actions')){
- 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
- var bar=document.createElement('div');
- bar.className='save-actions';
- bar.innerHTML=
- '<div class="save-cmd"><span class="p">$</span><code>'+saveCmd+'</code><button type="button">copy</button></div>'+
- '<a class="save-btn" href="https://github.com/vshulcz/deja-vu">'+starTxt+'</a>'+
- '<a class="save-demo" href="'+rootPrefix+'view/">'+demoTxt+'</a>';
- saveFirst.appendChild(bar);
- var sbtn=bar.querySelector('button');
- if(sbtn){
- sbtn.addEventListener('click',function(){
- navigator.clipboard.writeText(saveCmd);
- sbtn.textContent='copied';
- setTimeout(function(){sbtn.textContent='copy'},1200);
- });
- }
- }
- })();
- /* ── the sidebar folds on a phone ───────────────────────────────────────
- Eleven links and a cat above the article means scrolling past the whole
- guide to reach the page you opened. */
- (function(){
- var side=document.querySelector('.doc aside');
- if(!side||!matchMedia('(max-width:860px)').matches)return;
- var here=side.querySelector('a[aria-current]');
- var box=document.createElement('details');
- box.className='sidefold';
- var head=document.createElement('summary');
- /* "Codex" alone could be the delete page or the memory one */
- var grp=here&&here.closest('details.grpfold');
- var where=grp?grp.querySelector('summary').firstChild.textContent.trim()+' · ':'';
- head.innerHTML='<span>Guide</span><b>'+(here?where+here.textContent.trim():'contents')+'</b>';
- box.appendChild(head);
- while(side.firstChild)box.appendChild(side.firstChild);
- side.appendChild(box);
- /* opening it should not leave the reader somewhere else when it closes */
- box.addEventListener('toggle',function(){
- if(!box.open)side.scrollIntoView({block:'nearest'});
- });
- })();
- /* new page behaviour goes above this line, inside this closure */
- /* ── a hairline that fills as you read ─────────────────────────────── */
- (function(){
- if(matchMedia('(prefers-reduced-motion: reduce)').matches)return;
- var bar=document.createElement('div');bar.className='progress';
- document.body.appendChild(bar);
- addEventListener('scroll',function(){
- var h=document.documentElement.scrollHeight-innerHeight;
- bar.style.transform='scaleX('+(h>0?scrollY/h:0)+')';
- },{passive:true});
- })();
- /* ── contents, with the section you are in marked ──────────────────── */
- (function(){
- var heads=[].slice.call(art.querySelectorAll('h2'));
- if(heads.length<3)return; /* three sections is where a list starts earning its place */
- /* a div, not a nav: the stylesheet's nav rule is the page header — flex,
- sticky, padded — and it applied to this one too, laying the sections out
- in a row that ran off the side of the page */
- var toc=document.createElement('div');
- toc.className='toc';toc.setAttribute('role','navigation');
- toc.setAttribute('aria-label','on this page');
- toc.innerHTML='<div class="grp">On this page</div>'+heads.map(function(h){
- return '<a href="#'+h.id+'">'+h.firstChild.textContent.trim()+'</a>';
- }).join('');
- document.querySelector('.doc').appendChild(toc);
- var links=[].slice.call(toc.querySelectorAll('a'));
- var seen=new Map();
- var io=new IntersectionObserver(function(es){
- es.forEach(function(e){seen.set(e.target,e.isIntersecting)});
- /* the first visible heading wins, so scrolling up marks the one you are
- arriving at rather than the one you are leaving */
- var current=heads.find(function(h){return seen.get(h)})||null;
- links.forEach(function(a,i){
- a.classList.toggle('on',current?heads[i]===current:i===0);
- });
- },{rootMargin:'-72px 0px -70% 0px'});
- heads.forEach(function(h){io.observe(h)});
- })();
- /* ── the docs are searchable ───────────────────────────────────────────
- A tool for searching your own history whose own pages cannot be searched
- is arguing against itself. The index is built in the browser, on the first
- keystroke, from the pages themselves — no service, nothing sent. */
- (function(){
- var box=document.createElement('div');
- box.className='palette';box.id='palette';box.setAttribute('aria-hidden','true');
- box.innerHTML='<div class="pbox"><input id="pq" type="search" autocomplete="off" '+
- 'spellcheck="false" placeholder="search the guide…" aria-label="search the guide">'+
- '<div class="phits" id="phits"></div>'+
- '<div class="pfoot"><span><kbd>↑↓</kbd> move · <kbd>↵</kbd> open · <kbd>esc</kbd> close</span>'+
- '<span class="plocal">indexed in your browser</span></div></div>';
- document.body.appendChild(box);
- var input=box.querySelector('#pq'),hits=box.querySelector('#phits');
- var docs=null,loading=null,sel=0,rows=[];
- function load(){
- if(docs)return Promise.resolve(docs);
- if(loading)return loading;
- /* Index every sidebar link immediately so all 95 guide pages and 43
- coding agents are reachable on the first keystroke, not only the 8
- pages in ORDER. */
- var seenUrls={};
- ORDER.forEach(function(pair){seenUrls[pair[0]]=true});
- var sidePages=[];
- document.querySelectorAll('.doc aside a[href$=".html"]').forEach(function(a){
- var url=a.getAttribute('href');
- if(!url||url.indexOf('..')===0||url.indexOf('http')===0||seenUrls[url])return;
- seenUrls[url]=true;
- var grp=a.closest('details.grpfold');
- var cat=grp?grp.querySelector('summary').firstChild.textContent.trim():'Guide';
- var label=a.textContent.trim();
- sidePages.push({page:cat,url:url,title:label,body:cat+' '+label+' '+url.replace(/[-.]/g,' ')});
- });
- loading=Promise.all(ORDER.map(function(pair){
- return fetch(pair[0]).then(function(r){return r.text()}).then(function(html){
- var d=new DOMParser().parseFromString(html,'text/html');
- var a=d.querySelector('.doc article');
- if(!a)return [];
- return [].slice.call(a.querySelectorAll('h1,h2')).map(function(h){
- var body='',n=h.nextElementSibling;
- while(n&&!/^H[12]$/.test(n.tagName)){body+=' '+n.textContent;n=n.nextElementSibling}
- var id=h.id||h.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
- return {page:pair[1],url:pair[0]+(h.tagName==='H1'?'':'#'+id),
- title:h.textContent.replace(/\s*#$/,'').trim(),body:body.slice(0,600)};
- });
- }).catch(function(){return []});
- })).then(function(all){docs=[].concat.apply([],all).concat(sidePages);return docs});
- return loading;
- }
- function run(q){
- q=q.trim().toLowerCase();
- if(!q){hits.innerHTML='<p class="pnone">every page of the guide, searchable from here</p>';rows=[];return}
- load().then(function(all){
- var words=q.split(/\s+/);
- var scored=all.map(function(d){
- var t=d.title.toLowerCase(),b=d.body.toLowerCase(),score=0;
- words.forEach(function(w){
- if(t.indexOf(w)>=0)score+=8;
- if(b.indexOf(w)>=0)score+=1;
- });
- return {d:d,score:score};
- }).filter(function(x){return x.score>0})
- .sort(function(a,b){return b.score-a.score}).slice(0,7);
- rows=scored.map(function(x){return x.d});
- sel=0;
- hits.innerHTML=rows.length?rows.map(function(d,i){
- return '<a class="phit'+(i?'':' on')+'" href="'+d.url+'"><b>'+d.title+
- '</b><span>'+d.page+'</span></a>';
- }).join(''):'<p class="pnone">nothing here — try recall, mcp, redaction</p>';
- });
- }
- function open(){box.classList.add('on');box.setAttribute('aria-hidden','false');
- input.value='';run('');input.focus()}
- function close(){box.classList.remove('on');box.setAttribute('aria-hidden','true')}
- input.addEventListener('input',function(){run(input.value)});
- box.addEventListener('click',function(e){if(e.target===box)close()});
- addEventListener('keydown',function(e){
- var tag=(e.target.tagName||'').toLowerCase();
- if((e.key==='k'&&(e.metaKey||e.ctrlKey))||(e.key==='/'&&tag!=='input'&&tag!=='textarea')){
- e.preventDefault();box.classList.contains('on')?close():open();return;
- }
- if(!box.classList.contains('on'))return;
- if(e.key==='Escape')return close();
- if(e.key==='ArrowDown'||e.key==='ArrowUp'){
- e.preventDefault();
- var list=hits.querySelectorAll('.phit');
- if(!list.length)return;
- sel=(sel+(e.key==='ArrowDown'?1:list.length-1))%list.length;
- list.forEach(function(el,i){el.classList.toggle('on',i===sel)});
- }
- if(e.key==='Enter'&&rows[sel])location.href=rows[sel].url;
- });
- })();
- /* ── the cat knows where it is ─────────────────────────────────────── */
- (function(){
- var cat=document.querySelector('.sidecat');
- if(!cat)return;
- var says=['this page is indexed too','press / to search it','i was here in March',
- 'nothing left this machine','purr'];
- var i=0,label=cat.querySelector('span'),was=label?label.textContent:'';
- cat.addEventListener('click',function(e){
- e.preventDefault();
- if(!label)return;
- label.textContent=says[i++%says.length];
- clearTimeout(cat._t);
- cat._t=setTimeout(function(){label.textContent=was},2400);
- });
- })();
- })();
- /* Record the page for the home page's greeting. Same store, same rule as the
- tool itself: it stays in this browser. */
- (function(){
- var title=(document.querySelector('h1')||{}).textContent||'';
- title=title.replace(/^[$#\s]+/,'').trim();
- if(!title)return;
- try{
- var KEY='deja.visits';
- var s=JSON.parse(localStorage.getItem(KEY)||'null')||{n:0};
- s.page=title;
- localStorage.setItem(KEY,JSON.stringify(s));
- }catch(e){}
- })();
extensions/dsh/index.js · Bundled script · 711 lines · 1 finding marked
- // dsh-deja — the history you already have, inside DeepSeek Harness.
- //
- // dsh answers questions about its own sessions through the built-in
- // session-query subsystem. This plugin answers the other question: what you did
- // in Claude Code, Codex, Cursor, opencode and forty-four more agents, on this
- // machine, before dsh existed. The index is deja's; this file is the seam.
- import { installSearchRoute } from "./search.js";
- import { createRequire } from "node:module";
- import { execFile, execFileSync } from "node:child_process";
- import { randomUUID } from "node:crypto";
- import { existsSync } from "node:fs";
- import { homedir } from "node:os";
- import { join } from "node:path";
- import { argv, contributions, recallArgv, recallSilence, exitStatus, guarded, inert, newestEvents, noteBoard, resultText, splitHookReply } from "./lib.js";
- const require = createRequire(import.meta.url);
- // The tool registry lives in the host. A plugin that throws on a missing peer
- // takes the whole profile down with it, so this degrades: without dsh-tools the
- // command and automatic recall still work, only the model-facing tools are
- // skipped.
- let defineTool = null;
- try {
- ({ defineTool } = await import("@deepseek-ai/dsh-tools"));
- } catch {}
- const PLATFORM = process.platform === "win32" ? "windows" : process.platform;
- const ARCH = process.arch === "x64" ? "amd64" : process.arch;
- // resolveDeja picks the binary in the order a user would expect: what they
- // pointed at, then the deja they installed themselves and keep current with
- // `deja update` or a package manager, and only then the copy npm brought along
- // with this plugin. Each candidate is asked for its version rather than
- // trusted, because a name on PATH that does not run is worse than no name.
- function resolveDeja() {
- const exe = PLATFORM === "windows" ? "deja.exe" : "deja";
- const candidates = [process.env.DEJA_BIN, exe];
- try {
- candidates.push(require.resolve(`@vshulcz/deja-vu-${PLATFORM}-${ARCH}/bin/${exe}`));
- } catch {}
- for (const candidate of candidates) {
- if (!candidate) continue;
- try {
- execFileSync(candidate, ["version"], {
- windowsHide: true,
- encoding: "utf8",
- timeout: 5000,
- stdio: ["ignore", "pipe", "ignore"],
- });
- return candidate;
- } catch {}
- }
- // Nothing answered. Keep the plain name so the failure a user sees names the
- // thing that is missing.
- return exe;
- }
- const DEJA = resolveDeja();
- // run returns stdout, or "" when deja is missing or says nothing. Memory is
- // optional everywhere: a throw here would end the turn.
- function run(args, input, cwd) {
- try {
- return execFileSync(DEJA, args, {
- windowsHide: true,
- cwd,
- encoding: "utf8",
- timeout: 20000,
- maxBuffer: 8 * 1024 * 1024,
- input,
- stdio: [input === undefined ? "ignore" : "pipe", "pipe", "ignore"],
- }).trim();
- } catch {
- return "";
- }
- }
- const NOTHING = "Nothing in this machine's history matches that.";
- const MISSING =
- "deja is not installed on this machine, so there is no history to search. " +
- "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
- // installed answers whether the binary picked at load actually runs. Without
- // this every tool would report an empty history to a user who simply never
- // installed deja, which reads as "you have no past" rather than "nothing is
- // here to read it".
- const INSTALLED = run(["version"]) !== "";
- function answer(text) {
- if (INSTALLED) return text || NOTHING;
- return MISSING;
- }
- function tools(ctx) {
- if (!defineTool) return;
- // Every tool here answers with the text deja printed, so one output
- // declaration serves them all. Printed with --framed: ctx, blame, fix and
- // how write for a person (recall frames its own page), and without the frame a tag planted in a
- // transcript reached the model as though deja had closed its own block. The schema is plain JSON Schema — a
- // schemastery instance is rejected as "schema must be a value schema object",
- // because the host validates that this is an ordinary JSON record.
- const TEXT_OUTPUT = {
- schema: { type: "string" },
- render: (_args, value) => [{ type: "text", text: String(value) }],
- };
- guarded(() => ctx.tools.register(defineTool({
- name: "deja_recall",
- description:
- "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.",
- parameters: {
- query: {
- type: "string",
- required: true,
- description: "1-3 exact terms: a file path, an error string, a flag or identifier.",
- },
- limit: {
- type: "number",
- description: "How many sessions to return. Default 5.",
- },
- offset: {
- type: "number",
- description: "Sessions to skip, from the offset the previous page named. Default 0.",
- },
- },
- output: TEXT_OUTPUT,
- execute(args, exec) {
- // The page the MCP recall tool serves, framed and budgeted by deja. It
- // puts the project of its working directory first, so it runs in the
- // calling session's workspace rather than wherever dsh was launched.
- const call = recallArgv(args);
- const out = run(call, undefined, sessionCwd(exec && exec.agent));
- return Promise.resolve(answer(out || (INSTALLED ? recallSilence(call) : "")));
- },
- })));
- guarded(() => ctx.tools.register(defineTool({
- name: "deja_session",
- description:
- "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.",
- parameters: {
- query: {
- type: "string",
- required: true,
- description: "A query, or a session id prefix returned by deja_recall.",
- },
- },
- output: TEXT_OUTPUT,
- execute(args) {
- return Promise.resolve(answer(run(["--framed", ...argv("ctx", [], args.query)])));
- },
- })));
- guarded(() => ctx.tools.register(defineTool({
- name: "deja_blame",
- description:
- "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.",
- parameters: {
- path: {
- type: "string",
- required: true,
- description: "Path to the file, absolute or relative to the workspace.",
- },
- },
- output: TEXT_OUTPUT,
- execute(args) {
- return Promise.resolve(answer(run(["--framed", ...argv("blame", ["--json"], args.path)])));
- },
- })));
- guarded(() => ctx.tools.register(defineTool({
- name: "deja_fix",
- description:
- "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.",
- parameters: {
- error: {
- type: "string",
- required: true,
- description: "The failing output, copied as it was printed.",
- },
- },
- output: TEXT_OUTPUT,
- execute(args) {
- return Promise.resolve(answer(run(["--framed", ...argv("fix", [], args.error)])));
- },
- })));
- guarded(() => ctx.tools.register(defineTool({
- name: "deja_how",
- description:
- "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.",
- parameters: {
- what: {
- type: "string",
- required: true,
- description: "The thing to run: a tool, a task, a script name.",
- },
- },
- output: TEXT_OUTPUT,
- execute(args) {
- return Promise.resolve(answer(run(["--framed", ...argv("how", [], args.what)])));
- },
- })));
- guarded(() => ctx.tools.register(defineTool({
- name: "deja_remember",
- description:
- "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.",
- parameters: {
- text: {
- type: "string",
- required: true,
- description: "The decision, in one or two sentences, with the reason it was taken.",
- },
- },
- output: TEXT_OUTPUT,
- execute(args) {
- const written = run(argv("remember", [], args.text));
- if (!INSTALLED) return Promise.resolve(MISSING);
- return Promise.resolve(written || "deja did not record that.");
- },
- })));
- }
- // `/deja --session <id> -- <query>` scopes the search to one conversation; the
- // composer shortcut writes exactly that. Anything else stays one plain query.
- // A line that starts with --session but does not parse is refused rather than
- // searched as those words: the person asked for one conversation, and a silent
- // full search would look like the scope worked.
- const SESSION_FLAG = /^--session\s+(\S+)(?:\s+--\s*([\s\S]*))?$/;
- function commandQuery(rawInput) {
- const text = String(rawInput || "").trim();
- const match = SESSION_FLAG.exec(text);
- if (match) return { session: bareSessionId(match[1]), query: (match[2] || "").trim(), scoped: true, malformed: false };
- return { session: "", query: text, scoped: false, malformed: /^--session(?:\s|$)/.test(text) };
- }
- function command(ctx, board) {
- guarded(() => ctx.commands.register({
- name: "deja",
- description: "Search this machine's past AI coding sessions",
- input: { hint: "what to look for" },
- async handler(invocation) {
- const { session, query, scoped, malformed } = commandQuery(invocation && invocation.rawInput);
- if (malformed) {
- return { kind: "error", text: "A scoped search looks like `/deja --session <id> -- <query>`." };
- }
- if (session && !/^[a-zA-Z0-9_-]+$/.test(session)) {
- return { kind: "error", text: "That session id is not one dsh writes — `/deja --session <id> -- <query>` searches one conversation." };
- }
- if (!query) {
- return { kind: "error", text: scoped
- ? "A scoped search needs a query — `/deja --session <id> -- <query>`."
- : "Say what to look for: /deja <error, file, or decision>" };
- }
- // Named, not handed over as deja's first word: the bare-query path
- // dispatches a word that happens to be a command, so `/deja version`
- // printed a version number and `/deja index` rebuilt the index, and one
- // of the words people most want history about is `install`.
- const out = run(argv("search", session ? ["--session", session] : [], query));
- if (!INSTALLED) return { kind: "error", text: MISSING };
- // Outside dsh web a person sees nothing the hooks print — the digest
- // goes to the model — so the reply to /deja is where deja's own notes
- // reach them. In dsh web the session's lines may still be waiting on the
- // board for a page that has not asked; they go here, once, instead.
- const waiting = board ? board.take(sessionId(invocation && invocation.agent)) : [];
- const notes = [...waiting, run(["hook-context", "--notes"])].filter(Boolean).join("\n");
- return { kind: "success", text: notes ? answer(out) + "\n\n" + notes : answer(out) };
- },
- }));
- }
- function userText(message) {
- const content = message && message.content;
- if (!Array.isArray(content)) return typeof content === "string" ? content.trim() : "";
- return content
- .filter((part) => part && part.type === "text" && typeof part.text === "string")
- .map((part) => part.text)
- .join("\n")
- .trim();
- }
- // autoRecall puts the answer in front of the model without anyone asking for
- // it, through the seam the host evaluates on every assembly. The obvious
- // alternative — splicing a message into the "agent/pre-step" waterfall — looks
- // like it works and does not: a later listener rebuilds its answer from the
- // payload, and the added message is dropped with nothing reported.
- //
- // The registration is guarded because the host throws "prompt context
- // deja:recall is already registered" on a second copy in the same profile, and
- // that failure is not local: the whole profile fails to load, so a duplicate
- // memory plugin costs the user their agent. One registration is all recall
- // needs. installedByCLI() below is the first line of defence; this is the one
- // that holds when the installer wrote to a different DSH_HOME than the profile
- // boots from.
- // autoDigest puts what this project settled in front of the model once at the
- // start of the session — the question-independent counterpart to autoRecall.
- // dsh's own agent/session-start is emit-only, its return reaches nothing, so
- // the digest rides the same assembly seam the recall does. deja_once keys the
- // one-shot on the session id in deja's ledger, which survives a resume in a new
- // process; the Map caches the opening digest across systemPrompt.refreshContext
- // re-resolutions during the first step (#5904) and clears it once the session
- // moves past its opening step.
- function autoDigest(ctx, board) {
- const digests = new Map();
- guarded(() =>
- ctx.systemPrompt.context({
- name: "deja:project",
- order: 110,
- interpolate: false,
- text: (assembly) => {
- const agent = assembly && assembly.agent;
- if (!agent) return "";
- const sid = sessionId(agent);
- if (pastOpeningStep(agent.session)) {
- if (sid) digests.set(sid, "");
- return "";
- }
- if (sid && digests.has(sid)) return digests.get(sid);
- const text = inert(askHook(
- ["hook-context", "--plain"],
- ["hook-context"],
- JSON.stringify({ session_id: sid, cwd: sessionCwd(agent), source: "startup", deja_once: true }),
- sid,
- board,
- ));
- if (sid) {
- digests.set(sid, text);
- while (digests.size > 64) digests.delete(digests.keys().next().value);
- }
- return text;
- },
- }),
- );
- }
- function pastOpeningStep(session) {
- let humanTurns = 0;
- for (const event of newestEvents(session)) {
- if (!event || typeof event.type !== "string") continue;
- if (event.type === "turn/start" && event.data && event.data.turn > 1) return true;
- if (event.type === "runtime-context" || event.type === "turn/end" || event.type === "step/end" || event.type.startsWith("assistant/")) {
- return true;
- }
- if (event.type === "user/message" && isHuman(event.data)) {
- if (++humanTurns > 1) return true;
- }
- if (event.type === "agent/inbox/spliced") {
- const inserted = event.data && event.data.inserted;
- if (Array.isArray(inserted) && inserted.some(isHuman) && ++humanTurns > 1) return true;
- }
- }
- return false;
- }
- // dsh names a session "session-<uuid>" and its log's folder the same; deja
- // indexes it by the uuid, so that is the id every hook is given.
- function bareSessionId(id) {
- return String(id || "").replace(/^session-/, "");
- }
- function sessionId(agent) {
- return bareSessionId((agent && (agent.sessionId || (agent.session && agent.session.id))) || "");
- }
- // The workspace a session belongs to. One web or tui process serves sessions
- // from every workspace and never changes directory, so process.cwd() is only
- // where dsh was launched; the session header carries the directory the session
- // was opened in.
- function sessionCwd(agent) {
- const header = agent && agent.session && agent.session.header;
- return (header && header.cwd) || process.cwd();
- }
- // askHook runs a hook once for both readers. Where a page will show the
- // person's lines, deja is asked for its JSON reply: additionalContext, the
- // text --plain prints, goes to the model and systemMessage waits on the board.
- // Anywhere else — tui, headless, sdk — it stays --plain. deja marks a note
- // shown when it prints it, so asking for notes nobody will read spends them,
- // and `/deja` and the next Claude Code session would not see them either.
- function askHook(plain, json, payload, sid, board) {
- if (!board.hasReader()) return run(plain, payload);
- const reply = splitHookReply(run(json, payload));
- board.push(sid, reply.notes);
- return reply.context;
- }
- function autoRecall(ctx, board) {
- let asked = "";
- let askedIn = "";
- let askedBy = "";
- let recalled = "";
- const compacted = new Set();
- watchCompaction(ctx, compacted);
- guarded(() =>
- ctx.systemPrompt.context({
- name: "deja:recall",
- order: 120,
- interpolate: false,
- text: (assembly) => {
- const agent = assembly && assembly.agent;
- if (!agent) return "";
- const prompt = lastHumanText(agent);
- if (!prompt) return "";
- const cwd = sessionCwd(agent);
- const sid = sessionId(agent);
- const afterCompaction = compacted.delete(sid);
- // The same question asked in another workspace is a different question,
- // and so is one asked again after its session compacted: deja then
- // answers with the recovery packet, which only a prompt naming the
- // session gets back.
- if (prompt !== asked || cwd !== askedIn || sid !== askedBy || afterCompaction) {
- asked = prompt;
- askedIn = cwd;
- askedBy = sid;
- recalled = inert(askHook(
- ["hook-prompt", "--plain"],
- ["hook-prompt"],
- JSON.stringify({ prompt, cwd, session_id: sid }),
- sid,
- board,
- ));
- }
- // Silence is the common case: this speaks only when the history answers.
- return recalled;
- },
- }),
- );
- }
- // The person's half. dsh shows nobody what a plugin hands the model, and has
- // no notice channel a host plugin can write to, so deja's lines wait on a board
- // and the browser half (client.js) asks for them under the composer. The route
- // rides dsh's own /api mount, which applies the same Host/Origin fence and
- // browser login as every other call the page makes. Only a profile that serves
- // that page — the connection service and a web server both — registers it;
- // headless, tui, sdk and an older dsh never do, and keep asking deja for
- // --plain. A second copy of the plugin finds the path taken and stands down.
- const NOTES_PATH = "/api/deja-notes";
- function notesRoute(ctx, board) {
- if (typeof ctx.inject !== "function") return;
- try {
- ctx.inject(["connection", "webServer"], (c) => {
- const registered = guarded(() =>
- c.connection.fetch.register({
- path: NOTES_PATH,
- methods: ["GET"],
- requestBody: "buffered",
- fetch: async (request) => {
- let sid = "";
- try {
- sid = bareSessionId(new URL(request.url).searchParams.get("session"));
- } catch {}
- return Response.json({ notes: sid ? board.take(sid) : [] }, { headers: { "cache-control": "no-store" } });
- },
- }),
- );
- if (registered) board.setReader();
- });
- } catch {}
- }
- // runAsync is run for a seam dsh awaits, so the event loop goes on while deja
- // answers. It never rejects.
- function runAsync(args, input) {
- return new Promise((resolve) => {
- try {
- const child = execFile(DEJA, args, { windowsHide: true, encoding: "utf8", timeout: 20000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout) =>
- resolve(err ? "" : String(stdout || "").trim()),
- );
- child.on("error", () => resolve(""));
- child.stdin.on("error", () => {});
- child.stdin.end(input);
- } catch {
- resolve("");
- }
- });
- }
- // Compaction shadows the turns it summarises but leaves them in the session
- // log, so deja reads the session there as compaction/start lands and keeps a
- // recovery packet: the task, each command with how it went, what was still
- // open. The log is written behind the session, so it is flushed first. dsh
- // assembles a step's context before its agent/pre-step waterfall, where the
- // compaction runs, so the step that compacts waits there for the capture and
- // the packet rides the recall of the next step, or of the next turn.
- function watchCompaction(ctx, compacted) {
- if (typeof ctx.on !== "function") return;
- const capturing = new Map();
- const listen = (c) =>
- c.on("session/event", (session, event) => {
- if (!session || !event || event.type !== "compaction/start") return;
- const sid = bareSessionId(session.id || (session.header && session.header.id));
- if (!sid) return;
- const cwd = (session.header && session.header.cwd) || process.cwd();
- // One compaction can follow another inside a step; two captures at once
- // contend for the index and the loser marks the packet unavailable, so
- // each waits for the one before it.
- const before = capturing.get(sid) || Promise.resolve();
- const capture = before.then(async () => {
- try {
- if (c.sessions && typeof c.sessions.flush === "function") await c.sessions.flush(session);
- } catch {}
- await runAsync(["hook-precompact"], JSON.stringify({ session_id: sid, cwd, harness: "deepseek" }));
- compacted.add(sid);
- });
- capturing.set(sid, capture);
- capture.then(() => {
- if (capturing.get(sid) === capture) capturing.delete(sid);
- });
- });
- try {
- if (typeof ctx.inject === "function") ctx.inject(["sessions"], listen);
- else listen(ctx);
- } catch {}
- try {
- ctx.on("agent/pre-step", async (step, next) => {
- const sid = sessionId(step && step.agent);
- if (capturing.has(sid)) await capturing.get(sid);
- const decision = await next();
- if (capturing.has(sid)) await capturing.get(sid);
- return decision;
- });
- } catch {}
- }
- // The point of action, as `deja install dsh-auto` wires it. tools/post-execute
- // runs on every tool result, and an accept decision's additionalContexts reach
- // the model on the next step: a read, edit or write gets what deja knows about
- // the file, a bash that exited non-zero gets the fix this machine found for
- // that error before. The before-seam, tools/execute, has no channel to the
- // model.
- function toolNotes(ctx) {
- if (typeof ctx.on !== "function") return;
- try {
- ctx.on("tools/post-execute", async (exec, result, next) => {
- const decision = await next();
- try {
- if (!decision || decision.kind !== "accept" || !exec) return decision;
- const note = await toolNote(exec, result);
- if (!note) return decision;
- return {
- ...decision,
- additionalContexts: [...(decision.additionalContexts || []), noteMessage(note)],
- };
- } catch {
- return decision;
- }
- });
- } catch {}
- }
- // A session is over when dsh disposes of it, or when the process goes: on
- // 0.1.1-rc.2 the headless profile exits without disposing anything, and only
- // process "exit" runs. The digest and the recall stamp a session live, which
- // keeps it out of its own MCP recall; dropping the stamp lets the next session
- // be answered with it now rather than twenty minutes from now.
- function sessionEnds(ctx) {
- if (typeof ctx.on !== "function") return;
- // Each live session with the directory it opened in: the end refreshes that
- // project's start digest, so the next session there sees this one.
- const live = new Map();
- const end = (sid) => {
- if (!sid || !live.has(sid)) return;
- const cwd = live.get(sid);
- live.delete(sid);
- run(["hook-session-end"], JSON.stringify({ session_id: sid, cwd }));
- };
- try {
- ctx.on("session/created", (session) => {
- const sid = bareSessionId(session && session.id);
- if (sid) live.set(sid, (session.header && session.header.cwd) || process.cwd());
- });
- ctx.on("session/disposed", (session) => end(bareSessionId(session && session.id)));
- process.on("exit", () => {
- for (const sid of [...live.keys()]) end(sid);
- });
- } catch {}
- }
- async function toolNote(exec, result) {
- const args = exec.arguments || {};
- const base = { session_id: sessionId(exec.agent), cwd: sessionCwd(exec.agent) };
- const editFields = {};
- if (args.old_string || args.old_str) editFields.old_string = String(args.old_string || args.old_str);
- 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);
- if ((exec.name === "read" || exec.name === "edit" || exec.name === "write") && args.file_path) {
- return runAsync(["hook-tool", "--plain"], JSON.stringify({
- tool_name: exec.name,
- tool_input: { file_path: String(args.file_path), ...editFields },
- ...base,
- }));
- }
- // The profile's other editor names the file "path"; view is its read.
- if (exec.name === "str_replace_editor" && args.path) {
- return runAsync(["hook-tool", "--plain"], JSON.stringify({
- tool_name: args.command === "view" ? "read" : "edit",
- tool_input: { file_path: String(args.path), ...editFields },
- ...base,
- }));
- }
- // pwsh is the Windows shell, with the same markers.
- if (exec.name === "bash" || exec.name === "pwsh") {
- const status = exitStatus(resultText(result));
- if (!(result && result.isError) && !status.failed) return "";
- return runAsync(["hook-tool-after", "--plain"], JSON.stringify({
- tool_name: exec.name === "pwsh" ? "powershell" : "bash",
- tool_input: { command: String(args.command || "") },
- tool_response: status.body,
- ...base,
- }));
- }
- return "";
- }
- // A context message the way dsh's own plugins build one: user role, a
- // producer-owned source so it is not read back as something the person typed,
- // a fresh id, frozen. v4 session format refuses the bare "plugin" kind, so the
- // producer owns "plugin:deja" — the value dsh's own v3→v4 migration assigns an
- // unmapped plugin.
- function noteMessage(text) {
- const message = {
- role: "user",
- content: [{ type: "text", text }],
- source: { kind: "plugin:deja", form: "notice" },
- id: randomUUID(),
- };
- Object.freeze(message.content[0]);
- Object.freeze(message.content);
- Object.freeze(message.source);
- return Object.freeze(message);
- }
- // lastHumanText is the newest thing the person actually typed. At assembly
- // time the message has already left the inbox and has not been appended as a
- // "user/message" yet — the only durable record of it is the inbox splice that
- // carried it in, so both are read. Anything a plugin contributed is skipped:
- // those carry a source of their own.
- function lastHumanText(agent) {
- for (const event of newestEvents(agent && agent.session)) {
- if (!event) continue;
- if (event.type === "user/message" && isHuman(event.data)) return userText(event.data);
- if (event.type === "agent/inbox/spliced") {
- const inserted = event.data && event.data.inserted;
- if (!Array.isArray(inserted)) continue;
- for (let j = inserted.length - 1; j >= 0; j--) {
- if (isHuman(inserted[j])) return userText(inserted[j]);
- }
- }
- }
- return "";
- }
- function isHuman(message) {
- return Boolean(message) && (!message.source || message.source.kind === "user");
- }
- // `deja install dsh` writes plugins of its own into DSH_HOME and adds them to
- // the profile, so a user who ran the installer and then added this package has
- // both: two `/deja` commands, the same recall on the system prompt twice, and
- // deja's MCP server answering the same six questions the tools here do. What
- // the installer wrote wins — it is the copy `deja install` keeps current — and
- // this package contributes only the parts that are missing.
- //
- // The two halves are separate on purpose: `deja install dsh` writes command.js
- // and the MCP row, and only `deja install dsh-auto` adds auto.js. A profile can
- // have the command from the installer and still want recall from here.
- function cliPluginDir() {
- const home = process.env.DSH_HOME || join(homedir(), ".dsh");
- return join(home, "plugins", "deja");
- }
- function installedByCLI(file) {
- try {
- return existsSync(join(cliPluginDir(), file));
- } catch {
- return false;
- }
- }
- function apply(ctx, config) {
- const adds = contributions(
- { command: installedByCLI("command.js"), auto: installedByCLI("auto.js") },
- config,
- );
- const board = noteBoard();
- // User-initiated search remains available when automatic recall is disabled.
- installSearchRoute(ctx, DEJA);
- if (adds.tools) tools(ctx);
- if (adds.command) command(ctx, board);
- if (adds.recall) {
- autoDigest(ctx, board);
- autoRecall(ctx, board);
- notesRoute(ctx, board);
- toolNotes(ctx);
- sessionEnds(ctx);
- }
- }
- apply.inject = ["tools", "commands", "systemPrompt"];
- export default apply;
extensions/grok/bin/deja-mcp.mjs · Bundled script · 92 lines · 1 finding marked
- #!/usr/bin/env node
- // The plugin's MCP server: `deja mcp` over stdio, with the binary resolved the
- // way the user expects rather than pinned to whatever this release bundled.
- //
- // A plugin server and the `[mcp_servers.deja]` entry `deja install grok` writes
- // are two servers to Grok, not one — both would run and the agent would see
- // every tool twice. When the installer has already wired it, this stands down
- // and says why: the CLI's copy is the one `deja install` keeps current.
- import { spawn } from "node:child_process"
- import { grokHome, installerOwns, resolveDeja } from "../lib.mjs"
- if (installerOwns("mcp")) {
- process.stderr.write(
- `deja is already an MCP server in ${grokHome()}/config.toml, from \`deja install grok\`. ` +
- "This plugin's copy stays out of the way so the tools are not listed twice — " +
- "run `deja uninstall grok` to let the plugin own it instead.\n",
- )
- standDown()
- } else {
- start()
- }
- // Standing down by exiting looks like a crash from the outside: Grok Build 1.0.5
- // reports `handshake failed: connection closed: initialize response` and the
- // server sits in the UI as broken. So answer the handshake and offer nothing —
- // the tools come from the CLI-wired copy, and this one is visibly idle rather
- // than visibly failing.
- function standDown() {
- let buf = ""
- process.stdin.setEncoding("utf8")
- process.stdin.on("data", (chunk) => {
- buf += chunk
- let i
- while ((i = buf.indexOf("\n")) >= 0) {
- const line = buf.slice(0, i)
- buf = buf.slice(i + 1)
- if (line.trim()) reply(line)
- }
- })
- process.stdin.on("end", () => process.exit(0))
- }
- function reply(line) {
- let msg
- try {
- msg = JSON.parse(line)
- } catch {
- return
- }
- if (msg.id === undefined) return // a notification wants no answer
- let result
- switch (msg.method) {
- case "initialize":
- result = {
- protocolVersion: msg.params?.protocolVersion ?? "2024-11-05",
- capabilities: { tools: {} },
- serverInfo: { name: "deja (plugin, standing down)", version: "0.1.0" },
- }
- break
- case "tools/list":
- result = { tools: [] }
- break
- case "resources/list":
- result = { resources: [] }
- break
- case "prompts/list":
- result = { prompts: [] }
- break
- case "ping":
- result = {}
- break
- default:
- process.stdout.write(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "not served: deja is wired through the CLI" } }) + "\n",
- )
- return
- }
- process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n")
- }
- function start() {
- const child = spawn(resolveDeja(), ["mcp"], { windowsHide: true, stdio: "inherit" })
- child.on("error", (err) => {
- process.stderr.write(
- `deja could not start: ${err.message}. Install it with: ` +
- "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
- )
- process.exit(1)
- })
- child.on("close", (code) => process.exit(code ?? 0))
- }
extensions/kimi/bin/deja-mcp.mjs · Bundled script · 31 lines · 1 finding marked
- #!/usr/bin/env node
- // The plugin's MCP server: `deja mcp` over stdio, with the binary resolved the
- // way the user expects rather than pinned to whatever this release bundled.
- //
- // Kimi registers a plugin's server as `plugin-<id>:<name>`, so it does not
- // merge with the `deja` entry `deja install kimi` writes into mcp.json — both
- // would run, and the agent would see every tool twice. When the installer has
- // already wired it, this stands down and says why: the CLI's copy is the one
- // `deja install` keeps current.
- import { spawn } from "node:child_process"
- import { installerOwns, kimiHome, resolveDeja } from "../lib.mjs"
- if (installerOwns("mcp")) {
- process.stderr.write(
- `deja is already an MCP server in ${kimiHome()}/mcp.json, from \`deja install kimi\`. ` +
- "This plugin's copy stays out of the way so the tools are not listed twice — " +
- "run `deja uninstall kimi` to let the plugin own it instead.\n",
- )
- process.exit(0)
- }
- const child = spawn(resolveDeja(), ["mcp"], { windowsHide: true, stdio: "inherit" })
- child.on("error", (err) => {
- process.stderr.write(
- `deja could not start: ${err.message}. Install it with: ` +
- "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
- )
- process.exit(1)
- })
- child.on("close", (code) => process.exit(code ?? 0))
extensions/opencode/index.js · Bundled script · 539 lines · 1 finding marked
- // opencode-deja — the sessions you already have, inside opencode.
- //
- // opencode remembers its own sessions. This plugin answers the other question:
- // what you did in Claude Code, Codex, Cursor, Gemini and forty-four more agents on
- // this machine, including months before deja existed. The index is deja's; this
- // file is the seam: six tools the model can call, plus recall that arrives
- // without being asked for.
- //
- // This is the 1.x plugin. opencode 2.x loads server.js, which runs this same
- // function and wires its hooks to 2.x's seams.
- import { createRequire } from "node:module"
- import { execFile } from "node:child_process"
- import { promisify } from "node:util"
- import { homedir } from "node:os"
- import { join } from "node:path"
- import { accessSync, constants, existsSync, readFileSync } from "node:fs"
- import {
- argv,
- cliPluginPath,
- configPaths,
- contextText,
- contributions,
- mcpWired,
- recallArgv,
- recallSilence,
- settleRecall,
- TOOL_SPECS,
- trailingRecall,
- userTurns,
- zodTools,
- } from "./lib.js"
- const require = createRequire(import.meta.url)
- const run_ = promisify(execFile)
- const WINDOWS = process.platform === "win32"
- const PLATFORM = WINDOWS ? "windows" : process.platform
- const ARCH = process.arch === "x64" ? "amd64" : process.arch
- const EXE = WINDOWS ? "deja.exe" : "deja"
- // How many turns of a session will ask again after being answered with
- // nothing. Three covers the moments that pass — a locked index, a call that
- // timed out, an upgrade replacing the binary — without turning a store that
- // genuinely holds nothing into a shell-out on every turn.
- const emptyRetries = 3
- // The tool helper is a peer of the host, not of us: it is identity plus a zod
- // re-export. Without it the hooks still run and only the model-facing tools are
- // skipped — a missing peer must not take the plugin down.
- let tool = null
- try {
- ;({ tool } = await import("@opencode-ai/plugin"))
- } catch {}
- // wellKnown lists the places a user's own install lands. PATH is the normal
- // answer; these cover the case where opencode was started from a launcher with
- // a PATH that never sourced a shell profile.
- function wellKnown() {
- const home = homedir()
- if (WINDOWS) {
- const local = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
- return [join(local, "deja", "bin", EXE), join(home, ".local", "bin", EXE)]
- }
- return [
- join(home, ".local", "bin", EXE),
- "/usr/local/bin/deja",
- "/opt/homebrew/bin/deja",
- "/usr/bin/deja",
- ]
- }
- // resolveDeja picks the binary in the order a user would expect: what they
- // pointed at, then the deja they installed themselves and keep current with
- // `deja update` or brew, and only last the copy npm brought along with this
- // plugin. Pinning them to our bundled copy would freeze their memory at
- // whatever version this package was released against.
- function resolveDeja(setting) {
- const candidates = [setting, process.env.DEJA_BIN, EXE, ...wellKnown()]
- try {
- candidates.push(require.resolve(`@vshulcz/deja-vu-${PLATFORM}-${ARCH}/bin/${EXE}`))
- } catch {}
- for (const candidate of candidates) {
- if (!candidate) continue
- if (candidate.includes("/") || candidate.includes("\\")) {
- try {
- accessSync(candidate, constants.X_OK)
- } catch {
- continue
- }
- }
- return candidate
- }
- // Nothing to check further; keep the plain name so a failure names the thing
- // that is missing rather than a path nobody chose.
- return EXE
- }
- // deja is asked for text, never for control flow: memory is optional
- // everywhere, and a throw here would end someone's turn.
- async function run(bin, args, input, cwd, timeout = 20000) {
- try {
- const child = run_(bin, args, {
- windowsHide: true,
- encoding: "utf8",
- timeout,
- cwd,
- maxBuffer: 8 * 1024 * 1024,
- })
- if (input !== undefined) {
- // deja can exit before it reads stdin; unhandled, the EPIPE that
- // follows would take opencode down. The generated plugin does the same.
- child.child.stdin.on("error", () => {})
- child.child.stdin.end(input)
- }
- const { stdout } = await child
- return stdout.trim()
- } catch {
- return ""
- }
- }
- const NOTHING = "Nothing in this machine's history matches that."
- const MISSING =
- "deja is not installed on this machine, so there is no history to search. " +
- "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
- // installerWiring reads what `deja install` left on disk for opencode: the MCP
- // server in the config, and the plugin file `--auto` writes. Both reads are
- // wrapped — a config we cannot read means "not wired", so the worst case is
- // this package doing the work twice rather than not at all.
- function installerWiring() {
- const wiring = { mcp: false, recall: false }
- try {
- wiring.recall = existsSync(cliPluginPath(process.env, homedir()))
- } catch {}
- try {
- for (const path of configPaths(process.env, homedir())) {
- if (!existsSync(path)) continue
- if (mcpWired(readFileSync(path, "utf8"))) {
- wiring.mcp = true
- break
- }
- }
- } catch {}
- return wiring
- }
- export const DejaPlugin = async ({ client, directory }, options = {}) => {
- const config = options || {}
- const bin = resolveDeja(typeof config.bin === "string" ? config.bin : "")
- const cwd = directory || process.cwd()
- // Every call runs in the session's own directory: deja ranks by project.
- const ask = (args, input, timeout) => run(bin, args, input, cwd, timeout)
- // Whether the binary answers at all is asked once. Without it every tool
- // would report an empty history to someone who simply never installed deja,
- // which reads as "you have no past" rather than "nothing is here to read it".
- const installed = (await ask(["version"], undefined, 5000)) !== ""
- const answer = (text) => (installed ? text || NOTHING : MISSING)
- // The toast is the one channel to the person: what the hooks return is model
- // context. A 2.x server plugin has none, and there deja is asked --strict so
- // it keeps its lines for a host that shows them rather than spend them here.
- const toasts = typeof client?.tui?.showToast === "function"
- const toast = (message) => (toasts ? client.tui.showToast({ body: { message, variant: "info", duration: 6000 } }) : undefined)
- const hook = (name) => (toasts ? [name] : [name, "--strict"])
- const digests = new Map()
- const told = new Set()
- // How many times this session has been answered with nothing. An empty
- // answer is cached so the plugin does not shell out every turn, but the
- // reasons for it are not alike: no history is permanent, while a locked
- // index, a timed-out call or a binary being replaced mid-`deja update` are
- // over by the next turn. Cached alike, one bad moment cost the session all
- // of its memory — every later turn read the emptiness rather than asking
- // again. Counted, so a store that really is empty is still only asked a few
- // times.
- const empties = new Map()
- // Sessions between their compacting hook and the summary request.
- const compacting = new Set()
- // Every session the per-prompt hook stamped live. opencode never says a
- // session ended, so without ending them here the stamp sat out its whole
- // window and the next session's MCP recall left a finished one out (#4546).
- const live = new Set()
- // The per-prompt recall each user message was given, by message.
- const recalled = new Map()
- const remember = (key, extra) => {
- recalled.set(key, extra)
- if (recalled.size > 1000) recalled.delete(recalled.keys().next().value)
- }
- const endSession = (id) => ask(["hook-session-end"], JSON.stringify({ session_id: id, cwd }), 5000)
- // The session that spawned each one, asked of opencode once. A task
- // sub-agent's digest and recall led with its parent, which is live and
- // asking through it (#4548).
- const parents = new Map()
- const parentOf = async (id) => {
- if (!id) return ""
- if (!parents.has(id)) {
- let parent = ""
- try {
- const res = await client?.session?.get?.({ path: { id } })
- parent = res?.data?.parentID || ""
- } catch {}
- parents.set(id, parent)
- }
- return parents.get(id)
- }
- const hooks = {}
- // What `deja install` already wired for opencode is not repeated here. It
- // writes an MCP server (the same six answers, under their own names) and,
- // with --auto, a plugin file of its own that opencode loads beside this
- // package — verified with `opencode debug config`, which resolves both into
- // one plugin list. Whatever the installer wrote wins, because that is the
- // copy `deja install` keeps current; this package fills the gaps.
- const adds = contributions(installerWiring(), config)
- // The six tools, described once. The ones that read history ask for
- // --framed output: what those commands print is written for a person, and
- // the model has to get it inside deja's untrusted-data frame. opencode 1.x takes them through its zod
- // helper and 2.x as JSON Schema (server.js), so the arguments are plain
- // data and each side builds its own.
- const specs = {
- deja_recall: {
- description:
- "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.",
- args: {
- query: { type: "string", description: "1-3 exact terms: a file path, an error string, a flag or identifier." },
- limit: { type: "number", optional: true, description: "How many sessions to return. Default 5." },
- offset: {
- type: "number",
- optional: true,
- description: "Sessions to skip, from the offset the previous page named. Default 0.",
- },
- },
- async execute(args) {
- // The page the MCP recall tool serves, framed and budgeted by deja.
- const call = recallArgv(args)
- const out = await ask(call)
- return answer(out || (installed ? recallSilence(call) : ""))
- },
- },
- deja_session: {
- description:
- "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.",
- args: {
- query: { type: "string", description: "A query, or a session id prefix returned by deja_recall." },
- },
- async execute(args) {
- return answer(await ask(["--framed", ...argv("ctx", [], args.query)]))
- },
- },
- deja_blame: {
- description:
- "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.",
- args: {
- path: { type: "string", description: "Path to the file, absolute or relative to the project." },
- },
- async execute(args) {
- return answer(await ask(["--framed", ...argv("blame", ["--json"], args.path)]))
- },
- },
- deja_fix: {
- description:
- "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.",
- args: {
- error: { type: "string", description: "The failing output, copied as it was printed." },
- },
- async execute(args) {
- return answer(await ask(["--framed", ...argv("fix", [], args.error)]))
- },
- },
- deja_how: {
- description:
- "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.",
- args: {
- what: { type: "string", description: "The thing to run: a tool, a task, a script name." },
- },
- async execute(args) {
- return answer(await ask(["--framed", ...argv("how", [], args.what)]))
- },
- },
- deja_remember: {
- description:
- "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.",
- args: {
- text: { type: "string", description: "The decision, in one or two sentences, with the reason it was taken." },
- },
- async execute(args) {
- const written = await ask(argv("remember", [], args.text))
- if (!installed) return MISSING
- return written || "deja did not record that."
- },
- },
- }
- if (adds.tools) {
- // Under a symbol, so 1.x, which reads its hooks by name, never sees it.
- hooks[TOOL_SPECS] = specs
- if (tool) hooks.tool = zodTools(tool, specs)
- }
- if (!adds.recall) return hooks
- // opencode has no session-start hook. The system prompt is assembled on
- // every request, so the session digest is fetched once and pushed there —
- // the same place Claude Code's SessionStart output lands.
- hooks["experimental.chat.system.transform"] = async (input, output) => {
- try {
- // The summary request is the last one a compaction makes, and the digest
- // has no business in it: asked here, deja would hand the summariser the
- // recovery packet meant for the turn after.
- if (input?.sessionID && compacting.delete(input.sessionID)) return
- const key = input?.sessionID || "default"
- if (!digests.has(key)) {
- // The session id, as the plugin `deja install opencode-auto` writes
- // sends it: without it deja hands the session its own work back and
- // never reads the digest cached for it (#4273). The parent rides
- // along so the digest leaves it out too.
- const payload = { session_id: input?.sessionID || "", parent_session_id: await parentOf(input?.sessionID), cwd }
- const { context, receipt } = contextText(await ask(hook("hook-context"), JSON.stringify(payload), 30000))
- digests.set(key, context)
- // The receipt is the only sign the user gets that memory arrived. Once
- // per session: repeating it every turn is wallpaper.
- if (receipt && !told.has(key)) {
- told.add(key)
- await toast(receipt)
- }
- }
- const context = digests.get(key)
- if (context) {
- // Fold into the first system entry, as the generated plugin does.
- // opencode sends each entry as its own system message, and a backend
- // whose template allows one (vLLM or SGLang serving Qwen) rejects the
- // request: "System message must be at the beginning." (#4058)
- // After opencode's own prompt, not before it: that prompt is the same
- // in every session and is what the provider's prompt cache keeps.
- if (output.system.length) output.system[0] = output.system[0] + "\n\n" + context
- else output.system.push(context)
- return
- }
- // Nothing recalled: this machine has no history yet, the first index is
- // still building, or the call did not get through. The build is the only
- // one worth saying out loud, and saying it drops the empty answer so the
- // next turn asks again.
- const asks = (empties.get(key) || 0) + 1
- empties.set(key, asks)
- if (asks < emptyRetries) digests.delete(key)
- if (told.has(key)) return
- const status = await ask(["warmup-status"], undefined, 5000)
- if (!status) return
- told.add(key)
- digests.delete(key)
- await toast(status)
- } catch {
- // memory is optional: never break the session over it
- }
- }
- // Per-prompt recall, the relevance pass Claude Code gets on
- // UserPromptSubmit: the digest above is ranked by the project, this is ranked
- // by what the user just asked. Silent when nothing matches.
- hooks["experimental.chat.messages.transform"] = async (input, output) => {
- try {
- // The compaction's own request runs this transform right after the
- // compacting hook. Recall there would land in the summariser's input and
- // the recovery packet would count as delivered to a turn that never saw it.
- const owner = (output?.messages || []).find((m) => m?.info?.sessionID)?.info?.sessionID
- if (owner && compacting.has(owner)) return
- const users = userTurns(output?.messages)
- const last = users[users.length - 1]
- if (!last) return
- // Asked once per message. opencode builds every model call afresh from
- // its store, so text added to a message here lasts one call: once the
- // agent ran a tool the recall was gone, and deja, having shown it, would
- // not send it again (#4786).
- // A block already on the message came from another copy of this plugin
- // earlier in the same call, or from this one in a host that keeps the
- // message between calls. It is the answer: asked again, deja picks the
- // next pointer down and the message carried both (#5682).
- const present = trailingRecall(last.parts[last.parts.length - 1]?.text).blocks[0]
- if (!recalled.has(last.key) && present) remember(last.key, present)
- if (!recalled.has(last.key)) {
- // A turn with no text, an image alone, still goes to hook-prompt: that
- // call is what stamps the session live again after session.idle ended
- // it, and without it the turn's MCP recall could return the session
- // to itself (#4573).
- // The session id lets recall skip what it already showed this
- // session. Without it every message re-injects the same block —
- // measured on a real store, half of all injections were a
- // word-for-word repeat.
- const key = input?.sessionID || last.sessionID || ""
- if (key) live.add(key)
- // A task sub-agent's turns are written by the agent that spawned it,
- // which had this recall already. Asked with no prompt, deja only stamps
- // the session live: on a real store sub-agents took more per-prompt
- // blocks than the sessions people typed in (34 to 19 in 17 days).
- const parent = await parentOf(key)
- const prompt = parent ? "" : last.prompt
- const raw = await ask(hook("hook-prompt"), JSON.stringify({ prompt, session_id: key, parent_session_id: parent, cwd }))
- const reply = prompt && raw ? JSON.parse(raw) : {}
- remember(last.key, reply?.hookSpecificOutput?.additionalContext || "")
- // The "deja-vu — from Codex CLI, …" line is the person's, and what goes
- // into the message is the model's: without the toast it reached no one,
- // while deja counted it shown and held the next one back twenty minutes.
- if (reply?.systemMessage) await toast(reply.systemMessage)
- }
- // Every message gets back what it was given, in every call, the way
- // Claude Code keeps a prompt hook's text in its transcript. Once: the
- // block is put in place of any already there, never after it.
- for (const u of users) {
- const extra = recalled.get(u.key)
- if (extra) settleRecall(u.parts[u.parts.length - 1], extra)
- }
- } catch {
- // memory is optional: never break the session over it
- }
- }
- // Compaction is about to summarise the session away. The turns are still in
- // opencode's store, so deja reads them by the session id and keeps a
- // recovery packet — commands, how they went, what was open — for the next
- // turn, as Claude Code gets through PreCompact.
- hooks["experimental.session.compacting"] = async (input) => {
- try {
- const sessionID = input?.sessionID || ""
- if (sessionID) compacting.add(sessionID)
- recalled.clear()
- await ask(["hook-precompact"], JSON.stringify({ session_id: sessionID, cwd, harness: "opencode" }), 60000)
- } catch {
- // memory is optional: never break a compaction over it
- }
- }
- // A spawned agent's instructions are the one thing the parent hands it, and
- // deja decides whether recall goes in there. It leaves them as written where
- // the parent had recall of its own, opencode included (hook_spawn.go), and
- // the call still asks for a rebuild when the index is stale (#2567).
- hooks["tool.execute.before"] = async (input, output) => {
- try {
- if (input?.tool !== "task") return
- const args = output?.args
- if (!args?.prompt) return
- const payload = {
- hook_event_name: "PreToolUse",
- tool_name: "Task",
- tool_input: { prompt: args.prompt },
- session_id: input.sessionID || "",
- cwd,
- }
- const raw = await ask(["hook-tool"], JSON.stringify(payload))
- if (!raw) return
- const next = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.prompt
- if (next) args.prompt = next
- } catch {
- // memory is optional: never break a spawn over it
- }
- }
- // The moment a command fails is the one an agent never thinks to ask about,
- // and tool.execute.after is the only seam opencode gives for it. The hook
- // returns nothing to inject, so the line is folded into the tool output,
- // which the next request carries as the tool result.
- hooks["tool.execute.after"] = async (input, output) => {
- try {
- // A file's history, at the read before the edit. opencode has no seam
- // that can inject before a file action — tool.execute.before can only
- // rewrite the arguments — so the line goes out the way the failure line
- // does: appended to the tool's own output, which the next request
- // carries as the tool result. Without this, what deja knows at the
- // point of an action reached every harness except this one.
- //
- // Matched on the argument rather than the tool name: a tool carrying a
- // file path is a file action whatever this version calls it, and a name
- // deja does not recognise is answered with silence.
- const fpath = input?.args?.filePath || input?.args?.path || ""
- const patchText = input?.args?.patchText || input?.args?.patch || ""
- if ((fpath || patchText) && input?.tool !== "bash") {
- const ftext = output?.output
- if (!ftext) return
- const fpayload = {
- hook_event_name: "PostToolUse",
- tool_name: input?.tool || "read",
- tool_input: { ...(input?.args || {}), file_path: fpath, patchText },
- session_id: input.sessionID || "",
- cwd,
- }
- const fraw = await ask(["hook-tool"], JSON.stringify(fpayload))
- if (!fraw) return
- const fextra = JSON.parse(fraw)?.hookSpecificOutput?.additionalContext
- if (fextra) output.output = ftext + "\n\n" + fextra
- return
- }
- if (input?.tool !== "bash") return
- const text = output?.output
- if (!text) return
- const payload = {
- hook_event_name: "PostToolUse",
- tool_name: "bash",
- tool_input: { command: input?.args?.command || "" },
- tool_response: { output: text },
- session_id: input.sessionID || "",
- cwd,
- }
- const raw = await ask(["hook-tool-after"], JSON.stringify(payload))
- if (!raw) return
- const extra = JSON.parse(raw)?.hookSpecificOutput?.additionalContext
- if (extra) output.output = text + "\n\n" + extra
- } catch {
- // memory is optional: never break a tool call over it
- }
- }
- // A turn is over when opencode publishes session.idle, and the next prompt
- // stamps the session again before the model can ask anything, so the session
- // is history to everyone else in between.
- hooks.event = async ({ event }) => {
- try {
- const id = event?.type === "session.idle" ? event.properties?.sessionID : ""
- if (!id) return
- await endSession(id)
- // Ended, so dispose does not spawn deja for it again on the way out.
- live.delete(id)
- } catch {
- // memory is optional: never break the session over it
- }
- }
- // `opencode run` exits without waiting for the event above, and it does wait
- // for dispose: a one-shot run ends what it started here.
- hooks.dispose = async () => {
- for (const id of live) await endSession(id)
- live.clear()
- }
- return hooks
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.