docmancer
Work from the same local memory as every other coding agent on this machine. Recall prior decisions, preferences, instructions, and project conventions that Claude Code, Codex, Cursor, and other agents wrote here, with cited sources, fully local. Also searches a separate local technical-documentation index.
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
Its scripts were only partly scanned.
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/docmancer/docmancer 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/docmancer/docmancer'
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/docmancer-docmancer)HTML
<a href="/listings/docmancer-docmancer"><img src="/api/listings/docmancer-docmancer/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.
pipx install docmancer pipx ensurepath export PATH="$(pipx environment --value PIPX_BIN_DIR):$PATH" docmancer setup
`pipx ensurepath` makes the change persistent for future terminals. The `export` line makes Docmancer available in the current terminal immediately, which matters in an existing SSH session. If `docmancer` still reports `command not found`, reconnect over SSH and try again.
If you use uv, `uv tool install docmancer` installs it the same way.
`setup` finds every supported coding agent, shows you one complete plan and privacy warning, and waits for your confirmation before it changes anything. Then it indexes what it found, builds your canonical memory, installs the agent skills, and turns on automatic recall where the agent supports it.
Ask it something:
docmancer ask "Why did we choose Railway?"
You get a bounded, cited answer built from your own agents' evidence. Then open the app for the current project:
cd /path/to/your-project docmancer web
That is the whole first run. It takes about a minute, and `setup` does not modify the project you are standing in.
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.
SKILL.md · Manifest · 113 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- ---
- name: docmancer
- description: Work from the same local memory as every other coding agent on this machine. Recall prior decisions, preferences, instructions, and project conventions that Claude Code, Codex, Cursor, and other agents wrote here, with cited sources, fully local. Also searches a separate local technical-documentation index.
- version: 0.9.5
- author: docmancer
- license: MIT
- homepage: https://docmancer.dev
- repository: https://github.com/docmancer/docmancer
- tags:
- - agent-memory
- - local-first
- - claude-code
- - codex
- - cursor
- - mcp
- - shared-memory
- - rag
- - documentation
- - sqlite
- install: pipx install docmancer
- ---
- # docmancer
- An AI-agent memory harness: shared memory for coding agents.
- Work from the same local memory as every other coding agent on this machine, instead of making the user explain the project again. Claude Code, Codex, Cursor, Gemini, and other coding agents write memory, instructions, and rules all over the machine, each locked in its own silo. Docmancer discovers that evidence, combines the durable parts into one human-readable Shared Memory tree, and gives every agent grounded, cited recall over it: automatically through recall hooks (Claude Code and Codex), on demand through this skill and the CLI, and through MCP tools for everything else. The core memory path runs locally. Network access happens only when the user explicitly fetches online documentation, uses an external model, checks a package registry, or enables Cloud.
- ## Quick start
- ```bash
- pipx install docmancer
- pipx ensurepath
- export PATH="$(pipx environment --value PIPX_BIN_DIR):$PATH"
- docmancer setup # discovers agents, indexes their memory, installs skills and hooks
- docmancer ask "why did we pick Railway?" # grounded answer with citations from what your agents wrote
- ```
- The PATH export makes Docmancer available in the current terminal, including an existing SSH session. `pipx ensurepath` keeps it available in future terminals.
- If you use uv, `uv tool install docmancer` installs it the same way.
- The default profile uses SQLite FTS5, sqlite-vec, and bundled Model2Vec embeddings: no API keys, no daemon, no model download, offline at runtime. The optional scale profile uses FastEmbed, sparse retrieval, and Qdrant without changing memory authority or provenance semantics. Technical documentation remains a separate Library corpus, searched with `docmancer docs`.
- ## Workflow
- 1. Run `docmancer ask "<the task>"` when prior decisions, instructions, conventions, or preferences may matter.
- 2. Follow stable citations with `docmancer read <address>` when the full file or current content hash is needed.
- 3. When the user explicitly asks to manage durable memory, use `docmancer ask` to prepare one complete-file proposal. Apply it only with the user's confirmation or explicit `--apply`.
- 4. Keep memory and technical-documentation results separate.
- 5. Use `docmancer docs list` and `docmancer docs query` for libraries, APIs, and vendor documentation.
- Read-only Ask reads the latest committed local index. A configured generation provider semantically separates read and mutation intent, produces grounded prose for the read part, and prepares at most one validated proposal for the mutation part. A mixed request can return both an answer and a proposal. Applying a proposal re-reads the affected state and reports whether the requested outcome was verified. Use `--read-only` to suppress action planning, `--apply` only after explicit authorisation, `--no-answer` for evidence only, and `--fresh` when the question must first wait for changed agent sources to be indexed.
- ## Memory commands
- ```bash
- docmancer setup
- docmancer web
- docmancer ask "what deployment decisions apply?"
- docmancer ask "how did this policy change?" --history
- docmancer ask "return evidence only" --no-answer
- docmancer ask "remember that production releases require a smoke test"
- docmancer ask "update decisions/deployment.md to require two reviewers" --apply
- docmancer common
- docmancer delivery
- docmancer timeline
- docmancer memory canonical
- docmancer read docmancer://memory/<id>
- docmancer write "# Decision\n\nDeploy on Railway." --path decisions/deployment.md --scope project
- docmancer edit docmancer://memory/<id> - --expected-hash <hash>
- docmancer move docmancer://memory/<id> decisions/hosting.md --expected-hash <hash>
- docmancer import ./notes
- docmancer status --check
- ```
- Existing-file mutations require the current content hash. Conversational Ask proposals affect exactly one complete file and never apply because the user merely types “yes”. Imported and harvested sources remain read-only. Never trash, restore, connect Cloud, change capture installation, or publish Team memory without explicit user authorization.
- When the user explicitly authorizes Personal Sync, `docmancer cloud connect` is the normal entry point. The first connected machine creates and checks the recovery kit and starts the first encrypted transfer. A second machine displays a four-word pairing code for approval from a connected machine; `docmancer cloud connect --recover` is the fallback when no connected machine remains. `docmancer cloud sync` is an explicit retry or later push and pull, not an onboarding requirement.
- ## Documentation commands
- ```bash
- docmancer docs list
- docmancer docs add ./docs
- docmancer docs add https://docs.example.com
- docmancer docs query "how to authenticate"
- docmancer docs query "how to authenticate" --expand
- docmancer docs query "how to authenticate" --expand page
- docmancer docs query "how to authenticate" --format json
- docmancer docs query "how to authenticate" --allow-degraded
- docmancer docs sync
- docmancer docs remove <source>
- docmancer docs download <url> --output <dir>
- docmancer doctor
- ```
- Use `docs add` for local files, directories, documentation URLs, and GitHub repositories. Use root `import` only for Markdown intended for memory curation.
- ## Optional providers and scale profile
- ```bash
- docmancer providers list
- docmancer providers key <provider>
- docmancer providers set <provider> --default --model <model-id>
- docmancer providers test <provider>
- pipx install "docmancer[embeddings-heavy]"
- docmancer qdrant up
- docmancer setup --profile scale
- ```
- If you use uv, the install line becomes `uv tool install "docmancer[embeddings-heavy]"`. Local retrieval does not require a generation provider or Qdrant.
README.md · README · 303 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <!-- mcp-name: dev.docmancer/docmancer -->
- <div align="center">
- <img src="https://raw.githubusercontent.com/docmancer/docmancer/main/readme-assets/wizard-logo.png" alt="" width="72" />
- # Docmancer
- **Your AI coding environment, restored on every machine.**
- [](https://pypi.org/project/docmancer/)
- [](https://pypi.org/project/docmancer/)
- [](https://pypi.org/project/docmancer/)
- [](https://github.com/docmancer/docmancer/blob/main/LICENSE)
- [](https://github.com/docmancer/docmancer/stargazers)
- [**Website**](https://docmancer.dev) · [**Documentation**](https://docmancer.dev/docs/getting-started) · [**Blog**](https://docmancer.dev/blog) · [**Changelog**](https://github.com/docmancer/docmancer/blob/main/CHANGELOG.md) · [**Discussions**](https://github.com/docmancer/docmancer/discussions)
- <img src="https://raw.githubusercontent.com/docmancer/docmancer/main/readme-assets/web-readme.png" alt="The Docmancer local app showing agent memory, the Shared Memory file tree, and the Library" width="1000" />
- </div>
- ## Your coding agents remember what happened on one machine
- > Agent backup and restore are development-preview commands. Local encrypted archives are available now. Managed Cloud snapshots remain gated on migration and recovery acceptance.
- Docmancer securely restores their sessions, memory, and setup, then makes the useful project context available to every agent you use.
- Claude Code and Codex can search the files they already wrote on one machine. A normal dotfile tool can copy directories. Neither gives you an agent-aware, secret-stripped backup with structural verification, project mapping, conflict quarantine, and a reviewed path from raw history to shared project memory.
- Start by seeing what Docmancer can protect:
- ```bash
- docmancer backup --dry-run
- ```
- Create a free passphrase-encrypted local archive:
- ```bash
- docmancer backup --local --to ~/Backups/agents.dmbak
- ```
- On a new machine, close Claude Code and Codex and preview the restore:
- ```bash
- docmancer restore ~/Backups/agents.dmbak --dry-run
- docmancer restore ~/Backups/agents.dmbak
- ```
- Docmancer restores missing history, skips identical files, merges only safe configuration, and quarantines divergent sessions. It never copies authentication stores, `.env` files, literal MCP environment values, caches, logs, telemetry, or machine keys.
- After backup or restore, local consolidation finds durable decisions and constraints in the protected histories. Every proposal links to exact transcript evidence and waits for review:
- ```bash
- docmancer consolidate
- docmancer consolidate --review PROPOSAL_ID
- docmancer consolidate --approve PROPOSAL_ID
- ```
- ## Your agents already learned this. They just cannot tell each other.
- Claude Code knows why you moved off Railway. Codex learned your migration convention. Cursor is still following a rule you overruled two months ago. Each agent wrote something down, none of them agree, and none of it is anywhere you can read.
- That knowledge is real, and it is already on your disk. It is sitting in `CLAUDE.md` files, `AGENTS.md` files, Cursor rules, agent memory directories, and session history, in a different place and a different format for every tool you use.
- Docmancer is built around two questions, in this order:
- 1. **I re-explain my project to every coding agent. How do I get them all working from the same context?** Docmancer arranges the durable parts as plain local Markdown you can read and edit, then delivers the relevant files to every agent you connect, so a decision you record once reaches all of them.
- 2. **What do my coding agents already know about me and my working style?** Docmancer indexes the memory, instructions, and rules they wrote on this machine, and keeps the contributing source attached to every claim, so you can read the answer instead of guessing at it.
- Nothing leaves your machine unless you ask it to. There is no telemetry, no account, and no API key needed for the core product.
- ## Install
- ```bash
- pipx install docmancer
- pipx ensurepath
- export PATH="$(pipx environment --value PIPX_BIN_DIR):$PATH"
- docmancer setup
- ```
- `pipx ensurepath` makes the change persistent for future terminals. The `export` line makes Docmancer available in the current terminal immediately, which matters in an existing SSH session. If `docmancer` still reports `command not found`, reconnect over SSH and try again.
- If you use uv, `uv tool install docmancer` installs it the same way.
- `setup` finds every supported coding agent, shows you one complete plan and privacy warning, and waits for your confirmation before it changes anything. Then it indexes what it found, builds your canonical memory, installs the agent skills, and turns on automatic recall where the agent supports it.
- Ask it something:
- ```bash
- docmancer ask "Why did we choose Railway?"
- ```
- You get a bounded, cited answer built from your own agents' evidence. Then open the app for the current project:
- ```bash
- cd /path/to/your-project
- docmancer web
- ```
- That is the whole first run. It takes about a minute, and `setup` does not modify the project you are standing in.
- ## What you get
- **One memory instead of six.** Every supported agent reads from the same canonical Markdown, so a decision recorded once is available to Claude Code, Codex, Cursor, Gemini, and the rest without you copying it around.
- **Answers with receipts.** Recall returns the mandatory policy, the curated memory, and the supporting agent evidence with stable citations, so you can see which agent said what and when. The optional language model turns that evidence into prose but never chooses what goes into it.
- **Files you own, not a database.** Shared Memory is ordinary Markdown in ordinary directories. You can open it in your editor, commit it, grep it, or delete it. Stable `docmancer://memory/<id>` addresses keep working even after you move a file.
- **Local and offline by default.** The default profile uses SQLite FTS5, `sqlite-vec`, and a small vendored embedding model. No daemon, no model download, no network call, no key.
- **Edits that cannot clobber each other.** Changing or moving an existing memory file requires the content hash you last read, so one agent cannot silently overwrite a newer decision made by another.
- **Approval before anything is written.** When you ask Docmancer to remember or change something, it prepares one complete file proposal and shows you the diff. The default answer is no, and a later "yes" in conversation never applies a stored proposal.
- ## Take the same memory to a VPS or another machine
- The complete product above is free on one machine. Optional paid Personal Sync adds encrypted transport, managed revision history, devices, and recovery when you work across a laptop, VPS, or other machines.
- On the machine that already has your memory, run:
- ```bash
- docmancer cloud connect
- ```
- Sign in through the browser. Docmancer creates and checks a recovery kit, shows it once for offline storage, and starts the first encrypted upload automatically. The account page then asks for a payment method to start the 30-day trial. There is no separate recovery verification or first-sync command.
- On the VPS or second machine, install Docmancer and run:
- ```bash
- docmancer setup
- docmancer cloud connect
- ```
- The new machine shows a four-word pairing code. Run `docmancer cloud connect` on an already connected machine, confirm the same four words, and approve it. Then run the command once more on the new machine. Docmancer downloads the machine-wide Shared Memory tree and any project trees mapped on that machine. If every connected machine is unavailable, use `docmancer cloud connect --recover` and enter the offline recovery kit.
- The selected monthly or yearly subscription begins automatically after the trial unless you cancel. A failed renewal has a fixed 7-day upload grace period, followed by a 30-day read-only pull and export window before hosted ciphertext is scheduled for deletion. Local memory and every local feature keep working in every billing state. See the [Personal Sync guide](https://docmancer.dev/docs/personal-sync) for the full journey.
- ## See what each agent actually receives
- Run `docmancer web` and open **Shared Memory**. The left pane is the real file tree on disk, the middle pane reads the selected file with its provenance, and the right pane lists your connected agents. Select an agent to inspect the exact bounded projection it will receive, before it receives it.
- The scaffold is opinionated, but the files are yours:
- ```text
- ~/.docmancer/tree/ # machine-wide, follows you between projects
- ├── profile/
- │ ├── about.md
- │ └── preferences.md
- ├── principles/
- │ └── working-style.md
- ├── projects/
- │ └── active.md
- └── shared/
- <project>/.docmancer/tree/ # per project
- ├── overview.md
- ├── decisions/
- ├── constraints/
- ├── workflows/
- └── lessons/
- ```
- ## Connect your agents
- `docmancer setup` installs everything it detects. To manage one integration on its own:
- ```bash
- docmancer agent install claude-code --hooks
- docmancer agent install codex --hooks
- ```
- | Agent | Skill file | Automatic recall | Session capture | MCP |
- | --- | --- | --- | --- | --- |
- | Claude Code | Yes | Yes | Yes | Yes |
- | Codex (CLI, app, desktop) | Yes | Yes | Yes | Yes |
- | Cursor | Yes | | | |
- | Cline | Yes | | | |
- | Gemini CLI | Yes | | | |
- | OpenCode | Yes | | | |
- | GitHub Copilot | Yes | | | |
- | Claude Desktop | Manual upload | | | Yes |
- Installed skills teach an agent when to ask Docmancer for prior decisions and how to write deliberate memory when you explicitly request it, which is why every supported agent can use the same memory. Automatic recall and session capture need lifecycle hooks, and only Claude Code and Codex expose those today, so the other agents recall on demand through their skill file instead.
- MCP is an alternative transport over the same local services, not a second memory store:
- ```bash
- docmancer mcp install codex
- docmancer mcp doctor
- ```
- ## Record a decision on purpose
- Discovery finds what your agents already wrote. When you want something recorded deliberately:
- ```bash
- docmancer write $'# Deployment\n\nDeploy the API on Railway.' \
- --path decisions/deployment.md \
- --scope project
- ```
- Read it back later, from any agent or from your shell:
- ```bash
- docmancer read decisions/deployment.md
- ```
- Or let Ask do it, with an approval step:
- ```bash
- docmancer ask "Remember that production releases require a smoke test"
- docmancer ask "Update decisions/release.md to require two reviewers" --apply
- ```
- ## Everyday commands
- | Command | Purpose |
- | --- | --- |
- | `docmancer setup` | Discover agent memory and connect every supported agent. |
- | `docmancer ask "..."` | Recall evidence, answer a question, or propose one memory change. |
- | `docmancer web` | Open the local app for the current project. |
- | `docmancer common` | Show what several agents recorded independently. |
- | `docmancer delivery` | Show installed integrations, recall state, and recent use. |
- | `docmancer timeline` | Show how curated memory changed over time. |
- | `docmancer write ... --path file.md` | Write one deliberate Markdown memory file. |
- | `docmancer read <address-or-path>` | Read one memory file with its provenance. |
- | `docmancer edit ... --expected-hash <hash>` | Safely edit a memory file. |
- | `docmancer move ... --expected-hash <hash>` | Safely rename or move a memory file. |
- | `docmancer import ./notes` | Copy arbitrary Markdown into the project inbox. |
- | `docmancer docs query "..."` | Search the separate documentation Library. |
- | `docmancer status` | Show memory, source, security, integration, and Cloud health. |
- | `docmancer doctor` | Diagnose installation and configuration problems. |
- | `docmancer cloud connect` | Connect this machine, approve another machine by four-word code, and start encrypted sync. |
- | `docmancer cloud estimate` | Preview the next encrypted upload size, batching, and current plan limits without queueing or sending it. |
- Run `docmancer --help` or `docmancer <command> --help` for exact arguments, and see the [command reference](https://docmancer.dev/docs/cli-reference) for the full surface.
- ## Documentation is a separate Library
- Your decisions and a vendor's API reference answer different questions, so Docmancer keeps them apart. Library content is searchable but is never injected into your personal memory automatically.
- ```bash
- docmancer docs add https://docs.pytest.org
- docmancer docs query "How do I parametrize a fixture?"
- ```
- Use `ask` for your own decisions, preferences, and rules. Use `docs query` for libraries, APIs, and vendor documentation.
- ## Choose a retrieval profile
- The default needs no daemon and no large download:
- ```bash
- docmancer setup --profile local
- ```
- It runs SQLite FTS5, `sqlite-vec`, and the bundled Model2Vec model. For sustained ingestion and filtered vector search across roughly 50,000 to 100,000 documents, switch to the scale profile:
- ```bash
- pipx install "docmancer[embeddings-heavy]"
- docmancer qdrant up
- docmancer setup --profile scale
- ```
- If you use uv, the first line becomes `uv tool install "docmancer[embeddings-heavy]"`.
- Scale uses Qdrant, FastEmbed dense embeddings, sparse SPLADE retrieval, and reciprocal-rank fusion. It helps with vector filtering, concurrent writes, and operational headroom. It will not fix poor source coverage or weak evaluation, and both profiles implement identical memory semantics: switching changes storage and capacity, never authority, provenance, or what counts as Shared Memory.
- ## Privacy
- Your memory, credentials, indexes, and the local app stay on your machine, and Docmancer has no telemetry. It reaches the network only when you explicitly fetch online documentation, use an external model, check a package registry, or enable Cloud.
- Everything above is free and stays free. There are two problems the free single-machine product does not solve, and those are what the paid tiers exist for. The first is that your memory is built on one machine while you work on more than one, which optional paid Personal Sync answers by carrying the same canonical memory to every machine you approve, encrypted on the device before it leaves, with managed revision history and recovery. Its normal setup is one `docmancer cloud connect` command on each machine, followed by a four-word approval on a machine you already trust. The second is that the context your agents accumulated about a feature is stranded on one machine where the rest of your team cannot reach it, which is the problem Team Sync is being designed to solve. Team Sync is not available yet.
- The hosted service receives ciphertext, and it cannot read your plaintext memory or run anything on your machine. The [security architecture](https://docmancer.dev/security) describes exactly what metadata remains visible rather than claiming the server knows nothing.
- ## Where things live
- | Location | Contents |
- | --- | --- |
- | `~/.docmancer/tree/` | Machine-wide Markdown under `profile/`, `principles/`, `projects/`, `shared/`. |
- | `<project>/.docmancer/tree/` | Project memory under `decisions/`, `constraints/`, `workflows/`, `lessons/`. |
- | `<project>/.docmancer/inbox/` | Markdown you imported, waiting for optional curation. |
- | `<project>/.docmancer/trash/` | Recoverable deleted memory files. |
- | `<project>/.docmancer/state/decision-journal.jsonl` | Append-only history of curated files. |
- | `~/.docmancer/memory.db` | Rebuildable machine-wide index. |
- | `~/.docmancer/docmancer.yaml` | Local configuration. |
- ## Requirements
- Docmancer supports Python 3.11 and newer, including 3.14, so the install command does not need an interpreter pin. `pipx install docmancer` (or `uv tool install docmancer`) can use whichever recent Python your machine already provides. If pipx installs successfully but the shell cannot find `docmancer`, run `pipx ensurepath`, export the bin directory with `export PATH="$(pipx environment --value PIPX_BIN_DIR):$PATH"`, and try again. For problems after the command starts, `docmancer doctor` will tell you why.
- ## Contributing
- Issues and pull requests are welcome. Start with [CONTRIBUTING.md](https://github.com/docmancer/docmancer/blob/main/CONTRIBUTING.md) for project layout and extension points, and open a [discussion](https://github.com/docmancer/docmancer/discussions) if you want to talk through an idea first. Security reports have their own private channel, described in [SECURITY.md](https://github.com/docmancer/docmancer/blob/main/SECURITY.md).
- For architecture, supported sources, Cloud boundaries, and troubleshooting, see the [wiki](https://github.com/docmancer/docmancer/blob/main/wiki/Home.md) or the full [documentation](https://docmancer.dev/docs/getting-started).
- ## License
- MIT. See [LICENSE](https://github.com/docmancer/docmancer/blob/main/LICENSE).
docmancer/backup/archive.py · Bundled script · 373 lines · 1 finding marked
- """One encrypted snapshot format for local archives and hosted backup."""
- from __future__ import annotations
- import hashlib
- import hmac
- import io
- import json
- import os
- import tempfile
- import uuid
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- from collections.abc import Callable as CallableABC, Mapping
- from typing import Any, Callable
- from nacl import pwhash
- from nacl.signing import SigningKey
- from docmancer import __version__
- from docmancer.cloud.crypto import b64decode, b64encode, decrypt, encrypt, hkdf, sign, verify
- from docmancer.cloud.serialize import canonicalize
- from .chunking import CHUNKER_ID, compress, decompress, dictionary_id, iter_content_defined_chunks
- from .inventory import ensure_source_device_id
- from .models import InventoryResult, SNAPSHOT_SCHEMA_VERSION
- from .sanitize import prepare_artifact
- ARCHIVE_FORMAT = "docmancer-backup-v1"
- _MANIFEST_AAD = b"docmancer-backup-manifest-v1"
- def _derive(passphrase: str, salt: bytes, *, opslimit: int, memlimit: int) -> dict[str, bytes]:
- if not passphrase:
- raise ValueError("backup passphrase cannot be empty")
- master = pwhash.argon2id.kdf(
- 32,
- passphrase.encode("utf-8"),
- salt,
- opslimit=opslimit,
- memlimit=memlimit,
- )
- return {
- name: hkdf(master, salt=salt, info=f"docmancer-backup-v1/{name}".encode())
- for name in ("content", "manifest", "reference", "signing")
- }
- def _chunk_ref(reference_key: bytes, digest: bytes) -> str:
- return hmac.new(reference_key, digest, hashlib.sha256).hexdigest()
- def _chunk_aad(reference: str, digest: str) -> bytes:
- return canonicalize({"format": ARCHIVE_FORMAT, "ref": reference, "compressed_sha256": digest})
- def create_archive(
- result: InventoryResult,
- destination: Path,
- *,
- passphrase: str,
- include_attachments: bool = False,
- on_progress: Callable[[str, int, int], None] | None = None,
- ) -> dict[str, Any]:
- progress = on_progress or (lambda _stage, _current, _total: None)
- destination = Path(destination).expanduser().resolve()
- if destination.suffix != ".dmbak":
- destination = destination.with_suffix(destination.suffix + ".dmbak" if destination.suffix else ".dmbak")
- destination.parent.mkdir(parents=True, exist_ok=True)
- salt = os.urandom(pwhash.argon2id.SALTBYTES)
- opslimit = pwhash.argon2id.OPSLIMIT_MODERATE
- memlimit = pwhash.argon2id.MEMLIMIT_MODERATE
- keys = _derive(passphrase, salt, opslimit=opslimit, memlimit=memlimit)
- signing = SigningKey(keys["signing"])
- snapshot_id = str(uuid.uuid4())
- ensure_source_device_id(result.source_home or Path.home())
- source_device = result.source_device_id
- chunks: dict[str, dict[str, Any]] = {}
- artifacts = []
- transformed = 0
- source_bytes = 0
- portable_bytes = 0
- compressed_bytes = 0
- with tempfile.TemporaryDirectory(prefix="docmancer-backup-") as temp_name:
- temp_root = Path(temp_name)
- temporary_archive = destination.parent / f".{destination.name}.{uuid.uuid4().hex}.tmp"
- try:
- with zipfile.ZipFile(temporary_archive, "w", compression=zipfile.ZIP_STORED, allowZip64=True) as archive:
- for index, spec in enumerate(result.artifacts, start=1):
- progress("prepare", index, len(result.artifacts))
- prepared = prepare_artifact(spec, temp_root, include_attachments=include_attachments)
- source_bytes += prepared.source_size
- portable_bytes += prepared.portable_size
- transformed += int(bool(prepared.transformations))
- for raw_chunk in iter_content_defined_chunks(prepared.portable_path):
- packed = compress(raw_chunk)
- digest_bytes = hashlib.sha256(packed).digest()
- digest = digest_bytes.hex()
- reference = _chunk_ref(keys["reference"], digest_bytes)
- prepared.chunks.append(reference)
- if reference in chunks:
- continue
- aad = _chunk_aad(reference, digest)
- nonce, ciphertext = encrypt(packed, keys["content"], aad=aad)
- descriptor = {
- "ref": reference,
- "compressed_sha256": digest,
- "plaintext_size": len(raw_chunk),
- "compressed_size": len(packed),
- "ciphertext_size": len(ciphertext),
- "ciphertext_sha256": hashlib.sha256(ciphertext).hexdigest(),
- "nonce": b64encode(nonce),
- "algorithm": "xchacha20poly1305-ietf",
- "key_version": 1,
- }
- descriptor["signature"] = b64encode(sign(canonicalize(descriptor), bytes(signing)))
- chunks[reference] = descriptor
- compressed_bytes += len(packed)
- archive.writestr(f"chunks/{reference}.bin", ciphertext)
- artifacts.append(prepared.manifest_dict())
- manifest = {
- "schema_version": SNAPSHOT_SCHEMA_VERSION,
- "format": ARCHIVE_FORMAT,
- "snapshot_id": snapshot_id,
- "source_device_id": source_device,
- "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
- "client_version": __version__,
- "adapters": {
- agent: {
- "adapter_versions": sorted({item["adapter_version"] for item in artifacts if item["agent"] == agent}),
- "vendor_versions": sorted({item["vendor_version"] for item in artifacts if item["agent"] == agent}),
- }
- for agent in sorted({item["agent"] for item in artifacts})
- },
- "chunker": CHUNKER_ID,
- "compression": "zstd",
- "dictionary_id": dictionary_id(),
- "artifacts": artifacts,
- "chunks": chunks,
- "excluded": result.excluded,
- "totals": {
- "artifacts": len(artifacts),
- "transformed_artifacts": transformed,
- "source_bytes": source_bytes,
- "portable_bytes": portable_bytes,
- "compressed_unique_bytes": compressed_bytes,
- "unique_chunks": len(chunks),
- },
- }
- manifest_bytes = canonicalize(manifest)
- manifest_nonce, manifest_ciphertext = encrypt(manifest_bytes, keys["manifest"], aad=_MANIFEST_AAD)
- manifest_signature = sign(manifest_nonce + manifest_ciphertext, bytes(signing))
- header = {
- "format": ARCHIVE_FORMAT,
- "schema_version": SNAPSHOT_SCHEMA_VERSION,
- "key_wrap": "argon2id",
- "salt": b64encode(salt),
- "opslimit": opslimit,
- "memlimit": memlimit,
- "manifest_nonce": b64encode(manifest_nonce),
- "manifest_signature": b64encode(manifest_signature),
- "sign_public_key": b64encode(bytes(signing.verify_key)),
- }
- archive.writestr("manifest.enc", manifest_ciphertext)
- archive.writestr("header.json", json.dumps(header, sort_keys=True, separators=(",", ":")))
- os.chmod(temporary_archive, 0o600)
- os.replace(temporary_archive, destination)
- finally:
- temporary_archive.unlink(missing_ok=True)
- return {"path": str(destination), **manifest["totals"], "snapshot_id": snapshot_id}
- def _read_header(archive: zipfile.ZipFile) -> dict[str, Any]:
- try:
- header = json.loads(archive.read("header.json"))
- except (KeyError, json.JSONDecodeError, UnicodeDecodeError) as exc:
- raise ValueError("invalid Docmancer backup header") from exc
- if not isinstance(header, dict) or header.get("format") != ARCHIVE_FORMAT:
- raise ValueError("unsupported Docmancer backup format")
- if int(header.get("schema_version") or 0) != SNAPSHOT_SCHEMA_VERSION:
- raise ValueError(f"unsupported Docmancer backup schema: {header.get('schema_version')}")
- return header
- def open_archive(path: Path, *, passphrase: str) -> tuple[dict[str, Any], dict[str, bytes]]:
- with zipfile.ZipFile(Path(path).expanduser().resolve(), "r") as archive:
- header = _read_header(archive)
- keys = _derive(
- passphrase,
- b64decode(str(header["salt"])),
- opslimit=int(header["opslimit"]),
- memlimit=int(header["memlimit"]),
- )
- ciphertext = archive.read("manifest.enc")
- nonce = b64decode(str(header["manifest_nonce"]))
- try:
- verify(
- nonce + ciphertext,
- b64decode(str(header["manifest_signature"])),
- b64decode(str(header["sign_public_key"])),
- )
- plaintext = decrypt(ciphertext, keys["manifest"], nonce=nonce, aad=_MANIFEST_AAD)
- manifest = json.loads(plaintext)
- except Exception as exc:
- raise ValueError("backup passphrase is wrong or the archive is corrupt") from exc
- Note: Quoted as data in code: Asks you to extract a password-protected archive, the usual way malware droppers get past scanners
- Line 207 on GitHub
- if not isinstance(manifest, dict) or manifest.get("format") != ARCHIVE_FORMAT:
- raise ValueError("invalid encrypted backup manifest")
- if int(manifest.get("schema_version") or 0) != SNAPSHOT_SCHEMA_VERSION:
- raise ValueError(f"unsupported encrypted backup schema: {manifest.get('schema_version')}")
- return manifest, keys
- def inspect_archive(path: Path, *, passphrase: str) -> dict[str, Any]:
- manifest, _keys = open_archive(path, passphrase=passphrase)
- return manifest
- def materialize_artifact(
- archive: zipfile.ZipFile,
- artifact: dict[str, Any],
- manifest: dict[str, Any],
- keys: dict[str, bytes],
- ) -> bytes:
- output = io.BytesIO()
- _write_materialized_artifact(archive, artifact, manifest, keys, output)
- return output.getvalue()
- def materialize_artifact_to_path(
- archive: zipfile.ZipFile,
- artifact: dict[str, Any],
- manifest: dict[str, Any],
- keys: dict[str, bytes],
- destination: Path,
- ) -> dict[str, Any]:
- destination.parent.mkdir(parents=True, exist_ok=True)
- digest = hashlib.sha256()
- size = 0
- with destination.open("wb") as output:
- def write(value: bytes) -> None:
- nonlocal size
- output.write(value)
- digest.update(value)
- size += len(value)
- _write_materialized_artifact(archive, artifact, manifest, keys, write)
- if digest.hexdigest() != artifact["portable_hash"]:
- destination.unlink(missing_ok=True)
- raise ValueError(f"artifact {artifact.get('logical_path')} failed portable hash verification")
- return {"path": str(destination), "size": size, "hash": digest.hexdigest()}
- def _write_materialized_artifact(
- archive: zipfile.ZipFile,
- artifact: dict[str, Any],
- manifest: dict[str, Any],
- keys: dict[str, bytes],
- output: io.BytesIO | Callable[[bytes], None],
- ) -> None:
- descriptors = manifest.get("chunks") or {}
- public_key = b64decode(str(_read_header(archive)["sign_public_key"]))
- for reference in artifact.get("chunks") or []:
- descriptor = descriptors.get(reference)
- if not isinstance(descriptor, dict):
- raise ValueError(f"backup is missing descriptor for chunk {reference}")
- signed = {key: value for key, value in descriptor.items() if key != "signature"}
- verify(
- canonicalize(signed),
- b64decode(str(descriptor["signature"])),
- public_key,
- )
- ciphertext = archive.read(f"chunks/{reference}.bin")
- if hashlib.sha256(ciphertext).hexdigest() != descriptor["ciphertext_sha256"]:
- raise ValueError(f"backup chunk {reference} failed ciphertext verification")
- packed = decrypt(
- ciphertext,
- keys["content"],
- nonce=b64decode(str(descriptor["nonce"])),
- aad=_chunk_aad(reference, str(descriptor["compressed_sha256"])),
- )
- if hashlib.sha256(packed).hexdigest() != descriptor["compressed_sha256"]:
- raise ValueError(f"backup chunk {reference} failed content verification")
- value = decompress(packed, dictionary=str(manifest.get("dictionary_id") or ""))
- output.write(value) if isinstance(output, io.BytesIO) else output(value)
- if isinstance(output, io.BytesIO):
- value = output.getvalue()
- if hashlib.sha256(value).hexdigest() != artifact["portable_hash"]:
- raise ValueError(f"artifact {artifact.get('logical_path')} failed portable hash verification")
- __all__ = [
- "ARCHIVE_FORMAT", "create_archive", "inspect_archive", "materialize_artifact", "materialize_artifact_to_path", "open_archive",
- "write_local_archive_from_compressed_chunks",
- ]
- def write_local_archive_from_compressed_chunks(
- manifest: dict[str, Any],
- compressed_chunks: Mapping[str, bytes] | Callable[[str], bytes],
- destination: Path,
- *,
- passphrase: str,
- ) -> dict[str, Any]:
- """Rewrap a verified Cloud snapshot as the identical local archive format."""
- destination = Path(destination).expanduser().resolve()
- destination.parent.mkdir(parents=True, exist_ok=True)
- salt = os.urandom(pwhash.argon2id.SALTBYTES)
- opslimit = pwhash.argon2id.OPSLIMIT_MODERATE
- memlimit = pwhash.argon2id.MEMLIMIT_MODERATE
- keys = _derive(passphrase, salt, opslimit=opslimit, memlimit=memlimit)
- signing = SigningKey(keys["signing"])
- ref_map: dict[str, str] = {}
- descriptors: dict[str, dict[str, Any]] = {}
- temporary = destination.parent / f".{destination.name}.{uuid.uuid4().hex}.tmp"
- try:
- with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_STORED, allowZip64=True) as archive:
- source_descriptors = manifest.get("chunks") or {}
- if not isinstance(source_descriptors, dict):
- raise ValueError("Cloud backup has an invalid chunk descriptor table")
- for old_ref in source_descriptors:
- packed = (
- compressed_chunks(old_ref)
- if isinstance(compressed_chunks, CallableABC)
- else compressed_chunks[old_ref]
- )
- digest_bytes = hashlib.sha256(packed).digest()
- digest = digest_bytes.hex()
- reference = _chunk_ref(keys["reference"], digest_bytes)
- ref_map[old_ref] = reference
- nonce, ciphertext = encrypt(packed, keys["content"], aad=_chunk_aad(reference, digest))
- descriptor = {
- "ref": reference,
- "compressed_sha256": digest,
- "plaintext_size": 0,
- "compressed_size": len(packed),
- "ciphertext_size": len(ciphertext),
- "ciphertext_sha256": hashlib.sha256(ciphertext).hexdigest(),
- "nonce": b64encode(nonce),
- "algorithm": "xchacha20poly1305-ietf",
- "key_version": 1,
- }
- descriptor["signature"] = b64encode(sign(canonicalize(descriptor), bytes(signing)))
- descriptors[reference] = descriptor
- archive.writestr(f"chunks/{reference}.bin", ciphertext)
- local_manifest = json.loads(json.dumps(manifest))
- local_manifest.pop("backup_ref_key", None)
- local_manifest["format"] = ARCHIVE_FORMAT
- local_manifest["chunks"] = descriptors
- for artifact in local_manifest.get("artifacts") or []:
- artifact["chunks"] = [ref_map[reference] for reference in artifact.get("chunks") or []]
- manifest_nonce, manifest_ciphertext = encrypt(
- canonicalize(local_manifest), keys["manifest"], aad=_MANIFEST_AAD
- )
- header = {
- "format": ARCHIVE_FORMAT,
- "schema_version": SNAPSHOT_SCHEMA_VERSION,
- "key_wrap": "argon2id",
- "salt": b64encode(salt),
- "opslimit": opslimit,
- "memlimit": memlimit,
- "manifest_nonce": b64encode(manifest_nonce),
- "manifest_signature": b64encode(sign(manifest_nonce + manifest_ciphertext, bytes(signing))),
- "sign_public_key": b64encode(bytes(signing.verify_key)),
- }
- archive.writestr("manifest.enc", manifest_ciphertext)
- archive.writestr("header.json", json.dumps(header, sort_keys=True, separators=(",", ":")))
- os.chmod(temporary, 0o600)
- os.replace(temporary, destination)
- finally:
- temporary.unlink(missing_ok=True)
- return {"path": str(destination), "snapshot_id": local_manifest.get("snapshot_id"), **(local_manifest.get("totals") or {})}
docmancer/cli/backup_commands.py · Bundled script · 294 lines · 1 finding marked
- """Root backup and restore commands."""
- from __future__ import annotations
- import json
- import secrets
- import tempfile
- from datetime import datetime
- from pathlib import Path
- import click
- from docmancer.cli.help import DocmancerCommand, HELP_CONTEXT_SETTINGS
- def _project_values(values: tuple[str, ...]) -> set[str]:
- return {str(Path(value).expanduser().resolve()) if Path(value).expanduser().exists() else value for value in values}
- def _passphrase(*, confirm: bool) -> str:
- return click.prompt(
- "Backup passphrase",
- hide_input=True,
- confirmation_prompt=confirm,
- type=str,
- )
- @click.command("backup", cls=DocmancerCommand, context_settings=HELP_CONTEXT_SETTINGS, short_help="Protect Claude Code and Codex history in an encrypted snapshot.")
- @click.option("--to", "destination", type=click.Path(path_type=Path, dir_okay=False), default=None, help="Write a local .dmbak archive to this path.")
- @click.option("--local", "force_local", is_flag=True, help="Create a local archive even when Docmancer Cloud is connected.")
- @click.option("--agent", "agents", multiple=True, type=click.Choice(["claude-code", "codex"]), help="Protect only this agent. Repeatable.")
- @click.option("--project", "projects", multiple=True, help="Include only a project path, name, or portable project id. Repeatable.")
- @click.option("--exclude-project", "excluded_projects", multiple=True, help="Exclude a project path, name, or portable project id. Repeatable.")
- @click.option("--include-attachments", is_flag=True, help="Include known inline and out-of-band attachments.")
- @click.option("--dry-run", is_flag=True, help="Show inventory without reading portable content or creating a backup.")
- @click.option("--yes", is_flag=True, help="Skip the inventory confirmation.")
- @click.option("--allow-large-removal", is_flag=True, help="Allow replacing this device's Cloud snapshot after a drop greater than 20 percent.")
- @click.option("--json", "as_json", is_flag=True)
- @click.option("--home", type=click.Path(path_type=Path, file_okay=False), hidden=True, help="Use an isolated agent home for testing.")
- def backup_cmd(
- destination: Path | None,
- force_local: bool,
- agents: tuple[str, ...],
- projects: tuple[str, ...],
- excluded_projects: tuple[str, ...],
- include_attachments: bool,
- dry_run: bool,
- yes: bool,
- allow_large_removal: bool,
- as_json: bool,
- home: Path | None,
- ) -> None:
- """Create a passphrase-encrypted local snapshot after a bounded preview."""
- from docmancer.backup.archive import create_archive
- from docmancer.backup.cloud import cloud_backup_entitled, cloud_connected, upload_cloud_backup
- from docmancer.backup.inventory import inventory
- result = inventory(
- home=home,
- agents=set(agents),
- include_projects=_project_values(projects),
- exclude_projects=_project_values(excluded_projects),
- include_attachments=include_attachments,
- )
- summary = result.as_dict()
- if dry_run:
- click.echo(json.dumps(summary, indent=2, ensure_ascii=False) if as_json else _inventory_text(summary))
- return
- if not result.artifacts:
- raise click.ClickException("No supported Claude Code or Codex artifacts were found.")
- if not yes and not click.confirm(_inventory_text(summary) + "\nCreate this encrypted backup?", default=True):
- raise click.Abort()
- use_cloud = (
- destination is None
- and not force_local
- and cloud_connected()
- and cloud_backup_entitled()
- )
- passphrase = None if use_cloud else _passphrase(confirm=True)
- with click.progressbar(length=len(result.artifacts), label="Preparing encrypted backup") as bar:
- last = 0
- def progress(_stage: str, current: int, _total: int) -> None:
- nonlocal last
- if current > last:
- bar.update(current - last)
- last = current
- if use_cloud:
- created = upload_cloud_backup(
- result,
- include_attachments=include_attachments,
- allow_large_removal=allow_large_removal,
- on_progress=progress,
- )
- else:
- destination = destination or Path.cwd() / f"docmancer-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.dmbak"
- created = create_archive(
- result,
- destination,
- passphrase=str(passphrase),
- include_attachments=include_attachments,
- on_progress=progress,
- )
- created["consolidation"] = _consolidate_restored_history(
- home,
- session_paths={
- artifact.source_path
- for artifact in result.artifacts
- if artifact.category == "session"
- },
- )
- if as_json:
- click.echo(json.dumps(created, indent=2, ensure_ascii=False))
- return
- if use_cloud:
- snapshot = created.get("snapshot") or {}
- click.echo(f"Encrypted Cloud backup committed: {snapshot.get('snapshot_id', 'unknown')}")
- click.echo(f"Uploaded {created['uploaded_chunks']:,} chunks; reused {created['deduplicated_chunks']:,} encrypted chunks.")
- _print_consolidation(created["consolidation"])
- return
- click.echo(f"Encrypted backup created: {created['path']}")
- click.echo(f"Protected {created['artifacts']:,} artifacts in {created['unique_chunks']:,} unique chunks.")
- _print_consolidation(created["consolidation"])
- def _inventory_text(summary: dict) -> str:
- agents = ", ".join(f"{key}: {value}" for key, value in sorted(summary["by_agent"].items())) or "none"
- categories = ", ".join(
- f"{key}: {value}" for key, value in sorted(summary["by_category"].items())
- ) or "none"
- return (
- f"Found {summary['artifacts']:,} portable artifacts ({summary['source_bytes']:,} logical bytes; "
- f"an estimated {summary['compression_estimate_bytes']:,} compressed bytes).\n"
- f"Agents: {agents}. Categories: {categories}.\n"
- f"Machine-global setup: {summary['machine_global_artifacts']:,}. "
- f"Structured files requiring content inspection during backup: {summary['transformation_candidates']:,}. "
- f"Explicit exclusions: {len(summary['excluded']):,}."
- )
- def _mappings(values: tuple[str, ...]) -> dict[str, Path]:
- result: dict[str, Path] = {}
- for value in values:
- if "=" not in value:
- raise click.UsageError("--map must use SOURCE=DESTINATION")
- source, destination = value.split("=", 1)
- target = Path(destination).expanduser().resolve()
- if not target.is_dir():
- raise click.UsageError(f"mapped destination is not a directory: {target}")
- result[source] = target
- return result
- @click.command("restore", cls=DocmancerCommand, context_settings=HELP_CONTEXT_SETTINGS, short_help="Restore an encrypted agent snapshot without overwriting divergent history.")
- @click.argument("archive", required=False, type=click.Path(path_type=Path, dir_okay=False))
- @click.option("--source-device", default=None, help="Restore the latest Cloud snapshot from this approved device id.")
- @click.option("--rollback", "rollback_snapshot", default=None, help="Undo a completed restore using its snapshot id.")
- @click.option("--map", "mapping_values", multiple=True, help="Map a source project path or id to a destination using SOURCE=DESTINATION.")
- @click.option("--dry-run", is_flag=True, help="Verify and preview without writing.")
- @click.option("--yes", is_flag=True, help="Skip the restore confirmation.")
- @click.option("--json", "as_json", is_flag=True)
- @click.option("--root", "legacy_tree_root", default=None, hidden=True, help="Restore a legacy Shared Memory trash token under this tree root.")
- @click.option("--home", type=click.Path(path_type=Path, file_okay=False), hidden=True, help="Use an isolated agent home for testing.")
- def restore_cmd(
- archive: Path | None,
- source_device: str | None,
- rollback_snapshot: str | None,
- mapping_values: tuple[str, ...],
- dry_run: bool,
- yes: bool,
- as_json: bool,
- legacy_tree_root: str | None,
- home: Path | None,
- ) -> None:
- """Verify, preview, and restore a local .dmbak snapshot."""
- if rollback_snapshot:
- if archive is not None or source_device is not None or mapping_values:
- raise click.UsageError("--rollback cannot be combined with an archive, source device, or mapping")
- from docmancer.backup.restore import rollback_restore
- try:
- result = rollback_restore(rollback_snapshot, home=home)
- except (OSError, ValueError, RuntimeError) as exc:
- raise click.ClickException(str(exc)) from exc
- click.echo(json.dumps(result, indent=2) if as_json else f"Restore {rollback_snapshot} rolled back: {result['restored']} restored, {result['removed']} newly created files removed.")
- return
- if legacy_tree_root is not None:
- if archive is None:
- raise click.UsageError("a Shared Memory restore token is required with --root")
- from docmancer.cli.tree_commands import restore as restore_memory_file
- click.get_current_context().invoke(
- restore_memory_file,
- restore_token=str(archive),
- root=legacy_tree_root,
- as_json=as_json,
- )
- return
- if archive is not None and not archive.expanduser().is_file():
- raise click.UsageError(f"backup archive does not exist: {archive}")
- from docmancer.backup.restore import plan_restore, restore_archive
- from docmancer.backup.cloud import download_cloud_backup
- temporary = tempfile.TemporaryDirectory(prefix="docmancer-cloud-restore-") if archive is None else None
- try:
- if archive is None:
- archive = Path(temporary.name) / "cloud-snapshot.dmbak"
- passphrase = secrets.token_urlsafe(32)
- download_cloud_backup(
- archive,
- passphrase=passphrase,
- source_device_id=source_device,
- )
- else:
- passphrase = _passphrase(confirm=False)
- mappings = _mappings(mapping_values)
- plan = plan_restore(archive, passphrase=passphrase, home=home, mappings=mappings)
- Dismissed after review: Asks you to extract a password-protected archive, the usual way malware droppers get past scanners
- Line 219 on GitHub
- if dry_run:
- click.echo(json.dumps(plan, indent=2, ensure_ascii=False) if as_json else _restore_text(plan))
- return
- if plan["counts"]["unmapped"]:
- raise click.ClickException("Restore has unmapped projects. Add --map SOURCE=DESTINATION and retry.")
- if not yes and not click.confirm(_restore_text(plan) + "\nApply this restore?", default=False):
- raise click.Abort()
- result = restore_archive(
- archive,
- passphrase=passphrase,
- home=home,
- mappings=mappings,
- preview=plan,
- )
- restored_sessions = {
- Path(value)
- for value in result.pop("_restored_session_paths", [])
- }
- result["consolidation"] = _consolidate_restored_history(
- home,
- session_paths=restored_sessions,
- )
- except (OSError, ValueError, RuntimeError) as exc:
- raise click.ClickException(str(exc)) from exc
- finally:
- if temporary:
- temporary.cleanup()
- if as_json:
- click.echo(json.dumps(result, indent=2, ensure_ascii=False))
- return
- click.echo(f"Restore {result['status']}: {result['written']} written, {result['identical']} identical, {result['conflicts']} quarantined.")
- if result.get("quarantine"):
- click.echo(f"Conflicts: {result['quarantine']}")
- for item in result.get("reconfiguration") or []:
- click.echo(f"Manual reconfiguration required: {item}")
- click.echo("Claude Code histories are structurally valid until you confirm one session in its resume picker.")
- _print_consolidation(result["consolidation"])
- def _restore_text(plan: dict) -> str:
- counts = plan["counts"]
- return (
- f"Snapshot {plan['snapshot_id']}: {counts['create']} new, {counts['merge']} safe merges, "
- f"{counts['identical']} identical, {counts['conflict']} conflicts, {counts['unmapped']} unmapped."
- )
- def _consolidate_restored_history(
- home: Path | None,
- *,
- session_paths: set[Path],
- ) -> dict:
- try:
- from docmancer.transcripts import TranscriptConsolidator
- return TranscriptConsolidator(
- root=(home / ".docmancer") if home else None,
- home=home,
- ).scan(session_paths=session_paths)
- except Exception as exc: # noqa: BLE001 - a protected backup remains valid if indexing needs attention
- return {"error": str(exc), "proposals": 0, "items": []}
- def _print_consolidation(value: dict) -> None:
- if value.get("error"):
- click.echo(f"Memory consolidation needs attention: {value['error']}", err=True)
- return
- proposals = len(value.get("items") or [])
- click.echo(
- f"Memory consolidation: {proposals} reviewable proposal(s). "
- "Review with `docmancer consolidate`."
- )
- __all__ = ["backup_cmd", "restore_cmd"]
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.