Skip to content
Back to search

maxfreedompollard

Plugins by Max Freedom Pollard: Compartment, encrypted offline memory for Claude Code.

Safety scan

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

Checked today

Check it deeper on your machine

It has changed since its scan on 11 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/MaxFreedomPollard/Compartment 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/MaxFreedomPollard/Compartment'

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

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/maxfreedompollard--compartment/badge.svg)](/listings/maxfreedompollard--compartment)

HTML

<a href="/listings/maxfreedompollard--compartment"><img src="/api/listings/maxfreedompollard--compartment/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

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

**No command line needed.** On a Mac, download **Compartment-&lt;version&gt;.pkg** (Apple silicon) or **Compartment-&lt;version&gt;-intel.pkg** (Intel) from the [latest release](https://github.com/MaxFreedomPollard/Compartment/releases/latest) and open it. Python, the embedding model and every dependency are inside it. It asks you to choose a passphrase, creates the vault, and puts Compartment in your menu bar, where the **Connect an agent** buttons do the rest.

From the command line, on any system:

| | | |---|---| | **pipx** (recommended) | `pipx install compartment && compartment init` | | **uv** | `uv tool install compartment && compartment init` | | **pip** | `pip install compartment && compartment init` inside a virtual environment. Debian 12+, Ubuntu 23.04+, Fedora, Arch and Homebrew refuse a system-wide `pip install` with "externally-managed-environment"; pipx and uv avoid that. On Windows, `py -m pip install compartment` | | **Install script** | from a checkout: `bash install/install-linux.sh` (Linux, WSL, ChromeOS), `bash install/install-macos.sh`, or `powershell -ExecutionPolicy Bypass -File install\install-windows.ps1`. Each picks a Python that works on the machine, handles the externally-managed case, creates the vault and connects the agents it finds | | **Docker** | `docker build -t compartment .` from a checkout; see [Wiring each agent](#wiring-each-agent) |

Agents can also install it from their own stores - the Claude Desktop extension (`compartment-<version>.mcpb` on each release), the Claude Code and Codex plugin marketplaces, Gemini CLI extensions, Hermes Agent plugins and more. Each still needs the vault from `compartment init`, because the passphrase is typed by you. [docs/PLUGINS.md](docs/PLUGINS.md) lists every store and its install command.

Where it runs

| System | CPU | Python for pip / pipx / uv | The app | |---|---|---|---| | macOS 14 or newer | Apple silicon | 3.11 - 3.14 | menu bar; `.pkg` / `.dmg` | | macOS 13.4 or newer, and every Intel Mac | Apple silicon, Intel | 3.11 - 3.13 | menu bar; `-intel.pkg` / `-intel.dmg` on Intel | | Windows 10 / 11 | x64 | 3.11 - 3.14 | tray icon | | Windows 11 on ARM | ARM64 | 3.12 - 3.14 | tray icon | | Linux with glibc 2.28+ (Ubuntu 20.04+, Debian 11+, Fedora, RHEL 8+, Arch, openSUSE), WSL 2, ChromeOS Linux | x86_64, aarch64 (incl. Raspberry Pi 5) | 3.11 - 3.14 | a window (needs Tk: `python3-tk` or your distro's equivalent) | | Docker | amd64, arm64 | in the image | headless |

The limits come from onnxruntime, the one dependency without wheels everywhere: its macOS builds need macOS 14 from 1.24 on, and its last Intel Mac build (1.23.2) stops at Python 3.13. CI runs the suite on every row and checks the whole matrix for a dependency that would have to be compiled (`tools/wheel_coverage.py`). On Windows, onnxruntime also needs the [Microsoft Visual C++ runtime](https://aka.ms/vs/17/release/vc_redist.x64.exe) ([ARM64](https://aka.ms/vs/17/release/vc_redist.arm64.exe)); Compartment says so if it is missing.

**Elsewhere, with the system's onnxruntime.** Alpine (musl), FreeBSD and Android (Termux) package onnxruntime themselves; install it from the system and give Compartment a virtual environment that can see it. The install script does this for you.

# Alpine
apk add python3 py3-onnxruntime
# FreeBSD (default Python 3.12; the compiled dependencies come from packages)
pkg install py312-onnxruntime py312-tokenizers py312-pydantic-core py312-pynacl py312-argon2-cffi py312-numpy py312-cryptography
# Termux
pkg install python onnxruntime python-numpy rust

# then, on any of them
python3 -m venv --system-site-packages ~/.compartment-venv
~/.compartment-venv/bin/pip install compartment && ~/.compartment-venv/bin/compartment init

On Termux there is no shared memory for the unlock-until-restart credential, so set `COMPARTMENT_PASSPHRASE` or use `compartment unlock --once`. A glibc older than 2.28, 32-bit systems, armv7

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 · 19 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "maxfreedompollard",
  4. "description": "Plugins by Max Freedom Pollard: Compartment, encrypted offline memory for Claude Code.",
  5. "owner": {
  6. "name": "Max Freedom Pollard",
  7. "url": "https://github.com/MaxFreedomPollard"
  8. },
  9. "plugins": [
  10. {
  11. "name": "compartment",
  12. "description": "Encrypted, fully offline memory for Claude Code. One vault on your machine, shared with Claude Desktop, Cursor, Hermes and any other MCP client; 14 memory tools plus the compartmentalize skill. Requires `pip install compartment && compartment init` first.",
  13. "author": { "name": "Max Freedom Pollard" },
  14. "category": "productivity",
  15. "source": "./",
  16. "homepage": "https://github.com/MaxFreedomPollard/Compartment"
  17. }
  18. ]
  19. }
README.md · README · 872 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Compartment
  2. **Encrypted, fully offline memory for AI agents.** One vault on your own
  3. computer, read and written by Claude Code, Claude Desktop, Hermes Agent,
  4. OpenClaw, AntiGravity, Cursor, Codex and any other MCP client. No API key, no account, no
  5. network, no telemetry.
  6. [![PyPI](https://img.shields.io/pypi/v/compartment)](https://pypi.org/project/compartment/)
  7. [![Downloads](https://static.pepy.tech/badge/compartment)](https://pepy.tech/project/compartment)
  8. [![CI](https://github.com/MaxFreedomPollard/Compartment/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MaxFreedomPollard/Compartment/actions/workflows/ci.yml)
  9. [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
  10. [![MCP Toplist](https://mcptoplist.com/badge/io.github.MaxFreedomPollard%2Fcompartment.svg)](https://mcptoplist.com/server/io.github.MaxFreedomPollard%2Fcompartment)
  11. [![Cursor Directory](https://img.shields.io/badge/Cursor_Directory-listed-111111)](https://cursor.directory/plugins/compartment)
  12. [![Glama](https://img.shields.io/badge/Glama-listed-2ea44f)](https://glama.ai/mcp/servers/MaxFreedomPollard/Compartment)
  13. [![MCP Market](https://img.shields.io/badge/MCP_Market-listed-0ea5e9)](https://mcpmarket.com/server/compartment)
  14. [![mcpservers.org](https://img.shields.io/badge/mcpservers.org-listed-8b5cf6)](https://mcpservers.org/servers/maxfreedompollard/compartment)
  15. [![LobeHub](https://lobehub.com/badge/mcp/maxfreedompollard-compartment)](https://lobehub.com/mcp/maxfreedompollard-compartment)
  16. **One-click install** (after [installing](#install) and running `compartment init`):
  17. <p>
  18. <a href="https://cursor.com/install-mcp?name=compartment&config=eyJjb21tYW5kIjoiY29tcGFydG1lbnQiLCJhcmdzIjpbIi0tY2FsbGVyIiwiY3Vyc29yIiwic2VydmUiXX0="><img src="https://cursor.com/deeplink/mcp-install-dark.svg" alt="Add to Cursor" height="32"></a>
  19. <a href="https://vscode.dev/redirect/mcp/install?name=compartment&config=%7B%22command%22%3A%22compartment%22%2C%22args%22%3A%5B%22--caller%22%2C%22vscode%22%2C%22serve%22%5D%7D"><img src="https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=for-the-badge&logo=visualstudiocode&logoColor=white" alt="Install in VS Code" height="32"></a>
  20. <a href="https://insiders.vscode.dev/redirect/mcp/install?name=compartment&config=%7B%22command%22%3A%22compartment%22%2C%22args%22%3A%5B%22--caller%22%2C%22vscode%22%2C%22serve%22%5D%7D&quality=insiders"><img src="https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=for-the-badge&logo=visualstudiocode&logoColor=white" alt="Install in VS Code Insiders" height="32"></a>
  21. <a href="https://maxfreedompollard.github.io/Compartment/add/lmstudio"><img src="https://files.lmstudio.ai/deeplink/mcp-install-dark.svg" alt="Add to LM Studio" height="32"></a>
  22. <a href="https://maxfreedompollard.github.io/Compartment/add/goose"><img src="https://img.shields.io/badge/goose-Install_Extension-1f1f1f?style=for-the-badge" alt="Install in goose" height="32"></a>
  23. <a href="https://kiro.dev/launch/mcp/add?name=compartment&config=%7B%22command%22%3A%22compartment%22%2C%22args%22%3A%5B%22--caller%22%2C%22kiro%22%2C%22serve%22%5D%7D"><img src="https://kiro.dev/images/add-to-kiro.svg" alt="Add to Kiro" height="32"></a>
  24. </p>
  25. Claude Code, Claude Desktop, Hermes Agent, OpenClaw, AntiGravity and Codex are
  26. wired by one command (or the app's **Connect an agent** buttons) instead:
  27. `compartment integrate claude`, `hermes`, `openclaw`, `antigravity` or `codex`.
  28. Compartment is persistent memory for AI agents, stored on your own computer.
  29. What an agent learns in one session is available in every later session, in
  30. every project, to every agent on the machine, and nothing leaves the machine.
  31. Each memory is a single claim, recorded with its source and the date it was
  32. learned. Memories can expire: set `expires` and the memory is removed after
  33. that date. When a preference changes, the new one replaces the old one.
  34. Recall is a hybrid vector and keyword search over an in-memory index. It
  35. answers in about 12 ms and returns only what is relevant.
  36. The embedding model is included in the package. Everything on disk is
  37. encrypted, including the embedding vectors, and only your passphrase opens
  38. it. A new vault comes with about 6,700 reference facts about hardware,
  39. operating systems, ports, encodings and shell tools. They are ordinary
  40. memories, and one switch removes them from search.
  41. ## How it compares with other memory servers
  42. Where each server keeps memory and what protects it, as documented by each
  43. project on 2 September 2026. Sources and the full table are in
  44. [docs/COMPARISON.md](docs/COMPARISON.md); corrections are welcome as a PR
  45. against that file.
  46. | | Memory at rest | Encrypted | Account / API key | Network at runtime |
  47. |---|---|---|---|---|
  48. | **Compartment** | one encrypted file; index in RAM | **yes, vectors too** | none | none, CI-enforced |
  49. | `@modelcontextprotocol/server-memory` | plaintext `memory.jsonl`, substring search | no | none | none |
  50. | mem0 (open source) | vector store + LLM-extracted facts; its MCP server is hosted only | not documented | LLM key | LLM calls; telemetry on by default |
  51. | Graphiti (Zep) / Letta | Neo4j / server + database | not documented | LLM key | LLM calls; telemetry on by default |
  52. | claude-mem | local SQLite + Chroma | not documented | sign-in required | account + provider calls; telemetry on by default |
  53. | basic-memory (AGPL) | Markdown + SQLite | not documented | none | telemetry on by default |
  54. | Hindsight (Vectorize) | one container with embedded PostgreSQL | not documented | LLM key (local models configurable) | LLM calls; vendor states no telemetry |
  55. | Supermemory | cloud service, or a self-hosted prebuilt binary | not documented | account (cloud) or LLM key (self-host) | cloud calls; self-host: vendor states no telemetry |
  56. | Cognee | SQLite + LanceDB + Kuzu locally, or cloud | not documented | LLM key | LLM calls; telemetry on by default |
  57. | MemOS | Neo4j + Qdrant self-hosted, or cloud | not documented | LLM key | LLM calls; telemetry on by default |
  58. ## The memory logic
  59. **Almost everything is stored.** Only empty turns are dropped. A bare "OK" is
  60. a decision, not noise: when the agent asks *"Want me to send this reply to
  61. the client now?"* and the user answers *"OK"*, Compartment stores the
  62. decision together with the question it answered. Small talk is kept but
  63. ranked last.
  64. **Importance is assigned by fixed tiers.** Decisions and consent 0.90,
  65. personal facts and preferences 0.80, the user's machine and configuration
  66. 0.75, other substantive statements 0.55, small talk 0.20. Importance
  67. multiplies a match score rather than adding to it, so it breaks near-ties in
  68. favour of what matters and can never surface a memory that did not match the
  69. question.
  70. **One claim per memory, enforced.** The store rejects anything longer than
  71. 200 characters (the `max_memory_chars` setting), and anything containing
  72. lists, headings or paragraphs, with an error that says how to split it.
  73. Instructions alone did not work: on a real vault, the median memory written
  74. by an agent was 1,938 characters of bulleted session log. `memory_store_many`
  75. stores a batch in one call. `compartment atomize` splits over-limit memories
  76. in an existing vault; each piece keeps the original's dates, and the original
  77. is marked superseded but stays readable by id.
  78. **Every memory records its source and date.** `source` is required: "from
  79. chat", "read from pyproject.toml", "web search". `discovered` is the date the
  80. fact was learned, separate from the date it was saved. Both are appended to
  81. the text as a short clause, for example `[web search, 2026-08-01]`.
  82. **Memories can expire.** For a fact that stops being true on a known date,
  83. such as a sale price, a booking or a door code, set `expires` to that date
  84. (`2026-09-03`) or to a duration (`14d`, `2w`, `3m`, `1y`). The memory is
  85. removed after that date. `compartment expire` runs the sweep by hand;
  86. `expire_memories` turns it off. Most facts should not expire; a wrong expiry
  87. deletes a memory the user wanted.
  88. **Facts accumulate; opinions update.** A new fact is added beside the
  89. others: the door code changed, a script lives at a path, a release shipped.
  90. An opinion replaces one. When a preference is stored with `kind="opinion"`,
  91. the vault looks for a similar live opinion first. If it finds one, it returns
  92. the old record instead of inserting, and the caller resends with
  93. `supersedes=[old id]` to replace it, or `supersedes=[]` to keep both.
  94. Restating a live opinion refreshes its date instead of storing a copy.
  95. Superseded records are removed from search but kept in the audit chain and
  96. readable by id, with a pointer to their replacement. `supersedes` also works
  97. on facts, for corrections. Opinion ranking carries a recency bonus that
  98. fact ranking does not, so the newest opinion wins. `compartment opinions
  99. audit` finds overlapping live opinions in older vaults and keeps the
  100. newest, or reports them for manual merging.
  101. **Capture does not depend on the model.** A host that declares its own
  102. memory in its system prompt can override any tool instruction. So
  103. `integrate claude` installs a `PostToolUse` hook that writes each memory
  104. file Claude Code saves into the vault, whether or not the model calls the
  105. tool. The hook leaves your other hooks untouched, backs up `settings.json`
  106. first, always exits successfully so it can never break your editor, and does
  107. nothing while the vault is locked. `compartment hook status | install |
  108. uninstall`, or `integrate claude --no-hooks`. `compartment import-claude`
  109. imports anything the hook missed.
  110. **Search returns what is relevant, not a fixed number.** Compartment returns
  111. every memory whose score holds up against the best result for the same
  112. question, up to a generous cap. The cut is relative because scores are not
  113. comparable between questions: on a real vault, the nonsense query "how to
  114. bake sourdough bread" scored higher than the real query "what did Max decide
  115. about Airtable". A question the vault knows nothing about returns nothing.
  116. Pass `top_k` to get exactly that many.
  117. **Tags are kept current.** What a memory is about never changes; what it is
  118. relevant to does. Suppose that while working on a project called Northwind
  119. you learn that the client wants figures before conclusions. The agent tags
  120. the memory `northwind`. Two years later the same client, now called Harbour,
  121. hires you again, and the agent searches with the tag `harbour`. The memory
  122. is still true, but a tag filter cannot find it. So a background pass gives
  123. every memory the tags its nearest neighbours in embedding space were stored
  124. with, weighted by similarity: as Harbour memories accumulate near that old one, it
  125. picks up the `harbour` tag. Two more signals run alongside: tags that almost
  126. always occur together imply each other, and an existing tag whose phrase
  127. appears in a memory's text is attached. The pass writes only tags, never
  128. text, dates or embeddings. It only adds tags unless you pass `--prune`,
  129. `tags_origin` preserves the original tags, and `compartment retag --dry-run`
  130. shows what would change.
  131. **A graph as well as a list.** `memory_link` records a relation: subject,
  132. predicate, object, optionally tied to a memory and to a validity window.
  133. `memory_relations` answers by entity, by predicate, or as of a date.
  134. Compartment stores and matches relations deterministically; the host model
  135. decides what to link.
  136. **Memories are data, not instructions.** Recalled memories are wrapped with
  137. a notice that they are stored data. Content from an untrusted source can be
  138. marked `quarantined`, which adds a warning to every recall of it. The host
  139. agent must still treat memory as data.
  140. **One embedding model per vault.** The model's SHA-256 is recorded in the
  141. vault and checked on open, so similarity scores stay comparable. To change
  142. model, run `compartment reindex --re-embed`.
  143. **No LLM inside.** Embeddings run locally with a bundled 384-dimension int8
  144. ONNX model, in one shared process of about 70 MB that every agent on the
  145. machine uses. The host model decides what to store and
  146. forget; Compartment captures, encrypts and recalls. That split keeps the
  147. offline guarantee absolute and every decision reproducible. With an offline
  148. LLM, the whole agent runs with no network.
  149. **See what it learned.** `compartment recent` lists the newest memories,
  150. hiding the reference facts so your own memories are visible.
  151. `compartment status` reports `organic_records` beside the total.
  152. `memory_recent` is the same view over MCP.
  153. ## The app and the dashboard
  154. <p align="center">
  155. <img src="docs/images/menubar-panel.png" width="360" alt="The macOS panel: vault state, settings, connected agents, the last five memories">
  156. </p>
  157. The same panel on each system: the **menu bar** on macOS, the
  158. **notification area** on Windows, and an ordinary window on **Linux**, listed
  159. in the applications menu. Linux gets a window on purpose: a tray icon may
  160. never appear on GNOME or Wayland, and the control that unlocks your memories
  161. must not fail silently.
  162. The panel shows whether the vault is open, how many memories it holds and how
  163. many you stored, the three settings worth changing (capture hook, whether
  164. reference facts appear in search, auto-lock), which agents are connected with
  165. buttons to connect Claude, Hermes Agent, OpenClaw, AntiGravity or Codex, and the last five
  166. memories. You can unlock, lock and change your passphrase there without a
  167. terminal. The panel opens instantly with what it last read and refreshes in
  168. the background, only when something actually changed. While you use it, one
  169. helper process keeps the vault open read-only and reads just the new memories
  170. as agents add them; after ten idle minutes it exits, so an idle app holds no
  171. vault and no key. Looking never locks, unlocks or rewrites the vault. It is
  172. meant to be one of the many apps on your
  173. computer, not something you have to learn: every function is a button or a
  174. switch, and the defaults were chosen by measurement.
  175. The **Dashboard** button opens the whole vault in your browser: growth over
  176. time, the relation graph with every entity named, tags, per-agent counts and
  177. live search. It is served from RAM on 127.0.0.1 only, read-only, with no
  178. outbound requests.
  179. <p align="center">
  180. <img src="docs/images/dashboard-tables.png" width="820" alt="compartment dash: namespaces, memories per agent, relation types, top tags and search">
  181. </p>
  182. <p align="center">
  183. <img src="docs/images/dashboard.png" width="820" alt="compartment dash on a 51,000-memory vault: growth over time and the relation graph">
  184. </p>
  185. ## The mathematics
  186. Everything below is in one file,
  187. [`src/compartment/ranking.py`](src/compartment/ranking.py), used by the
  188. vault, the dashboard and the benchmark. A benchmark score therefore measures
  189. the product itself.
  190. ### Storage: long memories are embedded in windows
  191. The encoder reads 512 tokens. Text past that is not seen at all, so a long
  192. memory used to be searchable only by its opening. On a real 6,705-memory
  193. vault, 40% of records exceeded the window and **57.6% of the text was
  194. invisible to semantic search**.
  195. So each record is embedded as overlapping windows of `W = 448` tokens with a
  196. stride of `S = 384`, giving 64 tokens of overlap so no fact is cut in half,
  197. and the record is scored by its best window:
  198. ```
  199. windows(d) = ceil( max(0, tokens(d) - W) / S ) + 1 capped at 64
  200. s_vec(d) = max over windows w of d : cos(q, w)
  201. ```
  202. Max, not average: a memory is relevant if any part of it is, and an average
  203. would penalise a long memory for its other parts. With one window per record
  204. this is identical to the old behaviour, so short memories are unaffected.
  205. Most memories are short: 6,705 records produced 6,785 windows. Windows are
  206. measured in model tokens, not characters, because a character budget is off
  207. by a factor of three between prose and a hex digest.
  208. ### Recall: two channels, combined as evidence
  209. Two indexes answer different questions. The vector index answers what a
  210. memory means; the keyword index answers what it says. Their scores are not on
  211. the same scale, and combining them is the whole problem.
  212. Until 4.7, Compartment added them. Adding lets a merely-good semantic match
  213. outvote conclusive literal evidence: searching a real vault for a commit SHA
  214. that appears in exactly one memory returned that memory **below ten
  215. paraphrases of it**, because the sum buried a first-place keyword hit.
  216. The two channels are alternatives, not addends: either one alone can
  217. establish relevance. That is a soft OR over independent evidence,
  218. ```
  219. P(relevant) = 1 - (1 - p_vec)(1 - p_lex)
  220. ```
  221. and the score is its logarithm, which ranks identically but keeps spreading
  222. results near the top instead of saturating at 1:
  223. ```
  224. score(d) = - w_vec · log(1 - p_vec(d)) - w_lex · log(1 - p_lex(d))
  225. w_vec = 0.75 w_lex = 0.25
  226. ```
  227. Either channel near certainty carries the memory alone; neither can veto the
  228. other.
  229. **Turning a cosine into a probability.** An L2-normalized encoder gives
  230. cosines that are comparable across queries, so fixed bounds map them.
  231. Per-query min-max normalization would rescale the best hit of a hopeless
  232. query up to 1.0 and throw that information away.
  233. ```
  234. p_vec(d) = clamp( (cos(q, d) - 0.25) / (0.85 - 0.25), 0, 0.88 )
  235. ```
  236. The 0.88 ceiling matters. A cosine is a similarity, never an identity: an
  237. encoder can say *this is about the same thing*, never *this is the record you
  238. named*. A literal match on a string unique to one memory can. So the semantic
  239. channel is capped below what the literal channel can reach, and the cap is
  240. forced by the weights: the literal channel tops out at
  241. `0.25 · -log(1 - 0.999) = 1.727`, so `0.75 · -log(1 - cap) < 1.727`, giving
  242. `cap < 0.90`.
  243. **Turning a keyword hit into a probability, without BM25.** BM25 measures
  244. how well a document matches, which does not settle a contest against a
  245. semantic hit. What settles it is how unlikely the match was by chance. Each
  246. query term carries its self-information over the vault, and a memory scores
  247. the fraction of the query's information it accounts for:
  248. ```
  249. I(t) = log( N / (1 + df(t)) ) N = records in the vault
  250. p_lex(d) = ( Σ I(t) for query terms t present in d ) / ( Σ I(t) for all t )
  251. ```
  252. A term unique to one memory is near-conclusive; a term in a tenth of the
  253. vault is almost nothing, whatever its BM25. This is what makes literal and
  254. semantic hits comparable.
  255. The keyword index is queried as AND first, because an exact phrase is the
  256. strongest signal. FTS5's implicit AND requires a nine-word question to appear
  257. word for word, so when AND finds nothing it falls back to OR over the
  258. informative terms only: anything in more than 10% of records is dropped. That
  259. threshold is measured from the vault, not taken from an English stopword
  260. list, so it works the same for code, names or other languages.
  261. A small rank-agreement term is added, the one thing reciprocal-rank fusion
  262. does well, sized to break ties:
  263. ```
  264. + w_rrf · k · [ 1/(k + rank_vec) + 1/(k + rank_lex) ] w_rrf = 0.10, k = 20
  265. ```
  266. ### Importance and recency reorder the score
  267. ```
  268. evidence(d) = aged( vec term, q(d) ) + lex term + rank residue
  269. final(d) = evidence(d) · ( 1 + w_imp · (2·importance(d) - 1) + w_op )
  270. aged(s, q) = log( 1 + 2^( -q / half_life_share ) · (e^s - 1) )
  271. q(d) = share of the vault's own memories written after this one
  272. half_life_share = 0.5, so the median memory is worth half the odds
  273. w_imp = 0.15, for facts and opinions alike
  274. w_op = 0.30 · 2^( -age_days / 30 ) for an opinion, from the last
  275. re-affirmation (`affirmed`); 0 for a fact
  276. ```
  277. **Multiplicative, so a prior can only reorder memories that already
  278. matched.** An additive prior would let an important memory surface for an
  279. unrelated question. A memory that matched nothing scores zero and stays
  280. there.
  281. **Centred on the 0.5 default**, hence `2·importance - 1`. Every unweighted
  282. memory carries 0.5, including the thousands of reference facts, so without
  283. centring they would all get the same boost and importance would do nothing.
  284. Centred, an unweighted memory is neutral and only a deliberate weight moves
  285. it.
  286. **A memory's age is counted in memories, not in days.** A fact does not get
  287. less true in six months; what makes an old memory the wrong answer is that
  288. the vault has moved on, and how far it has moved is a question about how
  289. much was written. So a memory is as old as the share of the vault written
  290. after it. Two memories added in a fortnight leaves a fortnight-old memory
  291. untouched; five hundred added in the same fortnight halves the odds behind
  292. its semantic evidence. The population counted is the vault's own live
  293. memories in the namespaces being searched: not the reference facts and not
  294. an installed pack, which arrive in their thousands at one instant and have
  295. no age in this sense.
  296. The shift is applied to the semantic channel only, and in odds, so a strong
  297. match is nudged and a faint one is scaled away. A literal identifier is left
  298. alone: a commit SHA that appears in exactly one memory names that memory
  299. whether it was written yesterday or last year. And the relevance floors read
  300. the unaged score, so recency chooses the ORDER of the results and never
  301. which ones come back. One consequence: a returned memory's reported `score`
  302. is the aged one and can sit below the absolute floor it passed, so the floor
  303. is a cut the vault makes and not a property of the number it hands back.
  304. An opinion carries a second prior on top of that, and that one is on the
  305. clock: it halves every 30 days from when it was last re-affirmed, heavily
  306. enough that the newest opinion on a subject wins.
  307. ### Retrieval order
  308. Namespace, tag, date and reference-fact filters run after ranking, so a pool
  309. sized to the requested number of results could be emptied by them while
  310. matching memories sit just past the cut. The pool starts at 200 per channel
  311. and widens up to three times when filtering leaves too few. Below 20,000
  312. records the vector search is exact (SIMD matrix math, recall 1.0); above
  313. that, HNSW at about 99% recall, unless usearch can use no SIMD on the
  314. machine - an agent's sandbox can hide the CPU features it probes - in which
  315. case the exact index stays, because rebuilding HNSW without SIMD on every
  316. open cost from 50 seconds at 25,000 records.
  317. ## Security and the lock model
  318. The primitives: XChaCha20-Poly1305 encryption on everything at rest,
  319. including embedding vectors, because vectors can be inverted back to text ·
  320. Argon2id key slots, LUKS-style · a key per record, so `forget --shred`
  321. destroys the key and the content is unrecoverable rather than marked deleted
  322. · an fsync'd sealed journal, atomic compaction, and tested kill -9 recovery ·
  323. a hash-chained audit log (`compartment audit verify`) · signed vault
  324. manifests and packs · stdio transport with no open ports; the one local
  325. socket is the shared embedding process's Unix socket, in the same private
  326. directory as the unlock credential, carrying text in and vectors out and
  327. never a key · a runtime guard that aborts on any network socket attempt
  328. (`--assert-offline`), with CI running the whole suite under it on Linux,
  329. macOS and Windows. The full threat model,
  330. including what Compartment cannot protect against, is in
  331. [SECURITY.md](SECURITY.md).
  332. ### From the app
  333. Everything you do day to day is a button. **Unlock** asks for your
  334. passphrase; **Lock** closes the vault and clears every stored credential;
  335. **Change password** rekeys it; **Auto-lock** chooses 15, 30 or 60 idle
  336. minutes, or never. Compartment never generates a password, seed or recovery
  337. phrase, and holds no credential you do not.
  338. After an unlock the vault stays open across processes, logouts and logins
  339. for as long as you leave it, until a restart or power loss, until the
  340. auto-lock timer fires, or until you lock it. A restart or power loss always
  341. locks it: the unlock credential is the master key wrapped with a random
  342. per-boot secret that lives only in kernel memory and is never written to
  343. disk, so a new boot cannot open it. A copy of the credential file on its own
  344. is useless.
  345. ### From the command line
  346. The same controls, plus two that only exist here:
  347. - **`compartment unlock`** and **`compartment lock`** do what the buttons do.
  348. Agents can lock with the `memory_lock` tool. (Vaults from older versions
  349. that were issued a recovery phrase still accept it.)
  350. - **`compartment 2fa enable`** adds a second factor: your passphrase plus a
  351. keyfile, for example on a USB stick. Both feed Argon2id together, so the
  352. requirement is enforced by the cryptography, not by a setting; a stolen
  353. vault file plus your passphrase opens nothing without the keyfile. The
  354. keyfile's location is remembered, so unlocking feels the same while it is
  355. present.
  356. - **`compartment unlock --keychain`** on macOS is an explicit opt-in that
  357. survives reboots.
  358. The `memory_unlock` MCP tool exists but is off by default, because enabling
  359. it puts the passphrase in the model's context.
  360. ## One vault, many agents, any machine
  361. ### Without the command line
  362. Every agent on the machine uses the same vault, and none of that needs
  363. setting up: the app's **Connect an agent** buttons wire Claude, Hermes Agent,
  364. OpenClaw, AntiGravity and Codex, and what one agent stores the others recall. Claude, Hermes
  365. Agent, Cursor and the CLI can use the vault at the same time: writes are
  366. serialised by a file lock, every process notices writes by others and
  367. reloads, and each agent has its own identity and namespace. Their servers
  368. share one embedding process too, so ten agents cost one model in RAM, and
  369. it leaves a few minutes after the last of them does.
  370. A locked vault is one file, `memory.vault` in the `.compartment` folder of
  371. your home directory. To move to another machine, lock the vault, copy the
  372. file there, install Compartment and unlock it in the app with your
  373. passphrase.
  374. ### From the command line
  375. The same move, signed so the recipient can check it, plus the escape
  376. hatches:
  377. ```bash
  378. compartment lock --sign
  379. scp ~/.compartment/memory.vault other-machine:
  380. compartment --vault memory.vault unlock # your passphrase (+ keyfile if 2FA)
  381. ```
  382. `lock --sign` adds an Ed25519 manifest that the recipient can check with
  383. `compartment verify` and no credential. `export --plaintext` writes the vault
  384. as JSONL and `import` reads it back, so you are never locked in.
  385. [FORMAT.md](FORMAT.md) specifies the `.vault` and `.mpack` files byte by
  386. byte. Per-agent namespaces take `rw`, `ro` or `none` grants in the settings
  387. file, so a scratch agent can read without writing.
  388. **Memory packs** are signed, read-only bundles of curated memories
  389. (`compartment pack build | install | remove | list | export`). They install
  390. under `packs/<name>`, read-only for every caller, and
  391. `include_packs_in_search` toggles them. A pack's signature is checked against
  392. a key you trust, never against the key inside the pack. The reference facts
  393. are the one pack that lives in `main` as ordinary memories.
  394. [PACKS.md](PACKS.md) covers authoring.
  395. `compartment setup airgap-bundle` prepares an install for a machine with no
  396. network; `setup download-model` and `setup download-longmemeval` fetch what
  397. the optional benchmarks need.
  398. ## Measured, on an 8 GB baseline laptop
  399. Every number below is reproducible on your machine with `compartment
  400. selftest` and `compartment bench` (`--longmemeval` runs the retrieval
  401. benchmark); `compartment embed-daemon status` reports the shared process's
  402. own size.
  403. | Metric | Measured |
  404. |---|---|
  405. | Fresh install → open vault, offline | seconds, zero network |
  406. | Vector search, 20k records (HNSW) | p95 0.68 ms |
  407. | Full hybrid search (embed + windows + keywords + evidence fusion) | median 11.6 ms, p95 14.7 ms |
  408. | Shared embedding process, model loaded, once per machine | 68 MB resident |
  409. | The same after two batches of 64 long text windows | 71 MB; before 4.9.6 every agent's server kept 1.5 GB, then 3 GB |
  410. | An MCP server process with its model in the shared daemon | 60 MB, plus its vault and index |
  411. | Store one memory (embed + encrypt + fsync journal) | ~40 ms |
  412. | Wheel size, model included | ~30 MB |
  413. | Test suite (crypto, tamper, crash, offline, concurrency, 2FA, graph, dash, ranking) | 800+ tests, offline guard active |
  414. ## Install
  415. **No command line needed.** On a Mac, download **Compartment-&lt;version&gt;.pkg**
  416. (Apple silicon) or **Compartment-&lt;version&gt;-intel.pkg** (Intel) from the
  417. [latest release](https://github.com/MaxFreedomPollard/Compartment/releases/latest)
  418. and open it. Python, the embedding model and every dependency are inside it.
  419. It asks you to choose a passphrase, creates the vault, and puts Compartment
  420. in your menu bar, where the **Connect an agent** buttons do the rest.
  421. From the command line, on any system:
  422. | | |
  423. |---|---|
  424. | **pipx** (recommended) | `pipx install compartment && compartment init` |
  425. | **uv** | `uv tool install compartment && compartment init` |
  426. | **pip** | `pip install compartment && compartment init` inside a virtual environment. Debian 12+, Ubuntu 23.04+, Fedora, Arch and Homebrew refuse a system-wide `pip install` with "externally-managed-environment"; pipx and uv avoid that. On Windows, `py -m pip install compartment` |
  427. | **Install script** | from a checkout: `bash install/install-linux.sh` (Linux, WSL, ChromeOS), `bash install/install-macos.sh`, or `powershell -ExecutionPolicy Bypass -File install\install-windows.ps1`. Each picks a Python that works on the machine, handles the externally-managed case, creates the vault and connects the agents it finds |
  428. | **Docker** | `docker build -t compartment .` from a checkout; see [Wiring each agent](#wiring-each-agent) |
  429. Agents can also install it from their own stores - the Claude Desktop
  430. extension (`compartment-<version>.mcpb` on each release), the Claude Code and
  431. Codex plugin marketplaces, Gemini CLI extensions, Hermes Agent plugins and
  432. more. Each still needs the vault from `compartment init`, because the
  433. passphrase is typed by you. [docs/PLUGINS.md](docs/PLUGINS.md) lists every
  434. store and its install command.
  435. ### Where it runs
  436. | System | CPU | Python for pip / pipx / uv | The app |
  437. |---|---|---|---|
  438. | macOS 14 or newer | Apple silicon | 3.11 - 3.14 | menu bar; `.pkg` / `.dmg` |
  439. | macOS 13.4 or newer, and every Intel Mac | Apple silicon, Intel | 3.11 - 3.13 | menu bar; `-intel.pkg` / `-intel.dmg` on Intel |
  440. | Windows 10 / 11 | x64 | 3.11 - 3.14 | tray icon |
  441. | Windows 11 on ARM | ARM64 | 3.12 - 3.14 | tray icon |
  442. | Linux with glibc 2.28+ (Ubuntu 20.04+, Debian 11+, Fedora, RHEL 8+, Arch, openSUSE), WSL 2, ChromeOS Linux | x86_64, aarch64 (incl. Raspberry Pi 5) | 3.11 - 3.14 | a window (needs Tk: `python3-tk` or your distro's equivalent) |
  443. | Docker | amd64, arm64 | in the image | headless |
  444. The limits come from onnxruntime, the one dependency without wheels
  445. everywhere: its macOS builds need macOS 14 from 1.24 on, and its last Intel
  446. Mac build (1.23.2) stops at Python 3.13. CI runs the suite on every row and
  447. checks the whole matrix for a dependency that would have to be compiled
  448. (`tools/wheel_coverage.py`). On Windows, onnxruntime also needs the
  449. [Microsoft Visual C++ runtime](https://aka.ms/vs/17/release/vc_redist.x64.exe)
  450. ([ARM64](https://aka.ms/vs/17/release/vc_redist.arm64.exe)); Compartment says
  451. so if it is missing.
  452. **Elsewhere, with the system's onnxruntime.** Alpine (musl), FreeBSD and
  453. Android (Termux) package onnxruntime themselves; install it from the system
  454. and give Compartment a virtual environment that can see it. The install
  455. script does this for you.
  456. ```bash
  457. # Alpine
  458. apk add python3 py3-onnxruntime
  459. # FreeBSD (default Python 3.12; the compiled dependencies come from packages)
  460. pkg install py312-onnxruntime py312-tokenizers py312-pydantic-core py312-pynacl py312-argon2-cffi py312-numpy py312-cryptography
  461. # Termux
  462. pkg install python onnxruntime python-numpy rust
  463. # then, on any of them
  464. python3 -m venv --system-site-packages ~/.compartment-venv
  465. ~/.compartment-venv/bin/pip install compartment && ~/.compartment-venv/bin/compartment init
  466. ```
  467. On Termux there is no shared memory for the
  468. unlock-until-restart credential, so set `COMPARTMENT_PASSPHRASE` or use
  469. `compartment unlock --once`. A glibc older than 2.28, 32-bit systems, armv7
  470. and riscv64 are not supported. On WSL 2, the VM shutting down after it has
  471. been idle clears the unlock credential, so the vault relocks between
  472. sessions.
  473. `init` asks you to choose a passphrase, creates the vault, loads the
  474. reference facts, connects Claude, Hermes Agent, OpenClaw, AntiGravity or Codex if they are
  475. installed, and starts the app: a menu bar item on macOS, a tray icon on
  476. Windows, a window on Linux. Restart your agent and it has a memory.
  477. To connect an agent later, or any other client:
  478. ```bash
  479. compartment integrate claude # Claude Code + Claude Desktop
  480. compartment integrate hermes # Hermes Agent
  481. compartment integrate openclaw # OpenClaw
  482. compartment integrate antigravity # AntiGravity
  483. compartment integrate codex # Codex CLI
  484. compartment integrate --list # the 34 MCP clients it can wire: AntiGravity, Cursor, VS Code, Windsurf, Cline, Roo Code, Kilo Code, Zed, OpenCode, Codex CLI, Gemini CLI, Kiro, Amazon Q, Junie, Goose, LM Studio, Continue ...
  485. compartment integrate --all # every one of them that is installed here
  486. ```
  487. `claude`, `hermes`, `openclaw`, `antigravity` and `codex` also get the **`/compartmentalize`** skill
  488. installed in their skills directories. Any other MCP client uses this block
  489. (stdio transport, no environment variables):
  490. ```json
  491. { "mcpServers": { "compartment": { "command": "compartment", "args": ["serve"] } } }
  492. ```
  493. An app started from the Dock, Finder or the Start menu does not see your
  494. shell's PATH, so a bare `compartment` can fail there with "spawn compartment
  495. ENOENT". Use the full path that `which compartment` (`where compartment` on
  496. Windows) prints; `integrate` always writes that full path.
  497. ## Wiring each agent
  498. None of this needs a terminal: the **Connect an agent** buttons in the app
  499. run the same steps for Claude, Hermes Agent, OpenClaw, AntiGravity and Codex. The commands below
  500. are for people who prefer them, and for wiring a client the app does not
  501. list. On Windows, run them in PowerShell with `py -m pip install compartment`
  502. in place of `pip install compartment`.
  503. **Claude (Code + Desktop)**
  504. ```bash
  505. pip install compartment && compartment init && compartment integrate claude
  506. ```
  507. Registers the MCP server with the Claude Code CLI (user scope, all
  508. projects), imports the memories Claude Code has already written to its
  509. memory files (copy-only and repeatable; `--no-import` skips it), installs the
  510. capture hook (`--no-hooks` skips it), installs the `/compartmentalize` skill,
  511. writes a managed block into `CLAUDE.md`, and, when Claude Desktop is
  512. installed, registers the server in Claude Desktop's config file, backed up
  513. first. The server also describes itself in the MCP handshake, telling the
  514. model to recall before answering and to store durable facts, credentials,
  515. names and decisions, so Claude uses Compartment as its memory without any
  516. manual instruction.
  517. **Hermes Agent**
  518. ```bash
  519. pip install compartment && compartment init && compartment integrate hermes
  520. ```
  521. Installs the provider plugin into the Hermes environment and runs
  522. `hermes memory setup compartment`; verify with `hermes memory status`.
  523. Hermes Agent 0.20.0 and newer also read the portable
  524. [Agent Plugins](https://agent-plugins.org) format, and this repository is
  525. one. That route installs the MCP server and the `/compartmentalize` skill
  526. from GitHub:
  527. ```bash
  528. pip install compartment && compartment init
  529. hermes plugins install MaxFreedomPollard/Compartment
  530. hermes plugins enable compartment
  531. ```
  532. The provider is the fuller integration, because it recalls and stores on
  533. every turn; the portable package works only when the model calls its tools.
  534. On macOS and Windows both install to the same plugin directory name, so use
  535. one or the other.
  536. **OpenClaw**
  537. ```bash
  538. pip install compartment && compartment init && compartment integrate openclaw
  539. ```
  540. Writes the `mcpServers` entry into `~/.openclaw/openclaw.json`, with a
  541. backup. Then run `openclaw gateway restart` and check with
  542. `openclaw mcp list`.
  543. **Any MCP client**
  544. `compartment integrate <client>` wires any of the 34 clients in `--list`.
  545. Each config write takes a byte-exact backup first, merges rather than
  546. replaces, writes atomically, and refuses to touch a file it cannot parse (it
  547. prints the block to paste instead). To do it by hand, use the block in
  548. [Install](#install); VS Code uses the key `servers` with `"type": "stdio"`,
  549. Zed uses `context_servers`, Codex uses TOML under
  550. `[mcp_servers.compartment]`. `--vault` and `--caller` are optional; the
  551. defaults are `~/.compartment/memory.vault` and caller `user`.
  552. Client-by-client walkthroughs are in
  553. [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md).
  554. **Docker**
  555. `docker build -t compartment .` from a checkout builds a headless image
  556. (amd64 and arm64): stdio only, no port, unprivileged user, the offline guard
  557. on, vault on a bind mount at `/data`. Create the vault on the host first
  558. with `compartment init`, because that step prompts for the passphrase, then
  559. give the client this command:
  560. ```bash
  561. docker run -i --rm --network none --user "$(id -u):$(id -g)" \
  562. -v "$HOME/.compartment:/data" -e COMPARTMENT_PASSPHRASE compartment
  563. ```
  564. `--user` lets the container read your 0600 vault on a Linux host; Docker
  565. Desktop on macOS and Windows does not need it.
  566. ## Configuration
  567. Nothing here is required. Compartment installs configured; this is the whole
  568. surface if you want to change something.
  569. ### In the app
  570. The panel behind the icon: **Unlock** and **Lock**, **Change password**,
  571. **Create memories automatically** (the capture hook), **Search starter
  572. facts**, **Auto-lock** (15, 30, 60 minutes or never), the **CONNECT AN
  573. AGENT** buttons for Claude, Hermes Agent, OpenClaw, AntiGravity and Codex, **Refresh** and
  574. **Quit**.
  575. ### Commands
  576. Global flags, before the command: `--vault PATH`, `--caller NAME`,
  577. `--keyfile PATH`, `--assert-offline`, `--version`.
  578. | Command | What it does |
  579. |---|---|
  580. | `init` | create the vault. `--passphrase`, `--creator`, `--keychain`, `--no-session`, `--no-app` |
  581. | `unlock` / `lock` | open or close it. `--passphrase-stdin`, `--keyfile`, `--keychain`, `--once`; `lock --sign --identity` |
  582. | `status` / `verify` / `selftest` | what is in it, is it intact, does it work |
  583. | `store` / `get` / `forget` | one memory. `--source` (required), `--discovered`, `--expires`, `--namespace`, `--tag`, `--importance`, `--kind fact\|opinion`, `--supersedes ID`, `--keep-both`, `--quarantined`, `--raw`; `forget --shred` |
  584. | `search` / `recent` | find things. `--namespace`, `--tag`, `--top-k`, `--limit`, `--all`, `--json` |
  585. | `expire` | remove expired memories |
  586. | `atomize` | list over-limit blob memories as JSONL (`--out` + `--plaintext`), apply an agent-written split plan (`--apply`) |
  587. | `opinions audit` | backfill `kind` on opinion-shaped records, cluster overlapping live opinions, resolve with `--keep-newest`. `--threshold`, `--no-backfill`, `--json` |
  588. | `link` / `relations` / `unlink` | the relation graph, with validity windows (`--from`, `--to`, `--as-of`) |
  589. | `panel` (`menubar`, `tray`) | the app. `--show`, `--self-check`, `--render`, `--login` |
  590. | `integrate <agent>` | wire claude, hermes, openclaw or any listed client, and install `/compartmentalize`. `--list`, `--all`, `--no-import`, `--no-hooks`; `integrate --refresh` updates the instructions an earlier install wrote into agent files and nothing else |
  591. | `hook` | the Claude Code capture hook: `install --pin-vault`, `uninstall`, `status`, `capture` |
  592. | `import-claude` | pull in what Claude Code already wrote. `--dir`, `--namespace`, `--dry-run` |
  593. | `serve` | the MCP server, over stdio |
  594. | `embed-daemon` | the shared embedding process every agent uses: `status`, `stop`, `run` |
  595. | `dash` | read the vault in a browser: 127.0.0.1, one-time token, GET only |
  596. | `export` / `import` | `export --plaintext` writes it unencrypted; `import` reads it back |
  597. | `rekey` | change the passphrase. `--new-passphrase-stdin` |
  598. | `2fa` | `enable`, `disable`, `status`: a keyfile as a second factor |
  599. | `audit` | `verify`, `repair` the hash-chained history |
  600. | `retag` | recompute tags from the current vault (`--dry-run`, `--prune`); never changes memory text |
  601. | `reindex` | rebuild the index, and give long records the embedding windows they are missing. `--int8`, `--f32`, `--re-embed`, `--model` |
  602. | `pack` | `build`, `install`, `remove`, `list`, `export` signed memory packs (`--trusted-key`) |
  603. | `bench` | `--records`, `--longmemeval`, `--variant`, `--limit` |
  604. | `setup` | `download-model`, `download-longmemeval`, `airgap-bundle` |
  605. | `update` | upgrade in place, then refresh the instructions in agent files. `--source` takes GitHub main, `--no-app` skips the restart |
  606. | `uninstall` | remove it. The vault is kept unless you pass `--purge` |
  607. `compartment panel --login on | off | status` controls starting at login (on
  608. Linux, the applications menu entry). `init --no-app` skips the app on
  609. headless machines and in CI.
  610. `compartment dash` is the Dashboard button from the terminal: the whole vault
  611. in your browser, growth over time, the relation graph with every entity
  612. named, tags, per-agent counts, live search. It serves from RAM on 127.0.0.1
  613. only, behind a random URL token, read-only, with no outbound requests and no
  614. configuration. Ctrl-C closes it.
  615. ### The /compartmentalize skill
  616. `compartment integrate <agent>` writes one file into that agent's own skills
  617. directory, and `compartment uninstall` takes it back:
  618. | Agent | Path |
  619. |---|---|
  620. | Claude Code | `~/.claude/skills/compartmentalize/SKILL.md` |
  621. | Hermes Agent | `$HERMES_HOME` or `~/.hermes/skills/compartmentalize/SKILL.md` |
  622. | OpenClaw | `$OPENCLAW_HOME` or `~/.openclaw/skills/compartmentalize/SKILL.md` |
  623. | AntiGravity | `~/.gemini/config/skills/compartmentalize/SKILL.md` |
  624. | Codex | `$CODEX_HOME` or `~/.codex/skills/compartmentalize/SKILL.md` |
  625. All five use the Agent Skills layout (`SKILL.md` inside `skills/compartmentalize/`). Only the user
  626. runs it. Type it before compacting, or at any time, and the agent stores the
  627. whole conversation in the vault: people and contacts, credentials and where
  628. they live, URLs and hosts, decisions and the reasons for them, and a record
  629. of the session itself. It makes many `memory_store` calls. You can edit your
  630. copy; a later install backs up a changed copy rather than overwriting it.
  631. ### Settings file
  632. `<vault>.config.json`, beside the vault, holding grants per caller and:
  633. | Setting | Default | Meaning |
  634. |---|---|---|
  635. | `auto_lock_minutes` | `30` | idle time before it locks. `0` never locks |
  636. | `search_starter_facts` | `true` | whether the seeded facts join search results |
  637. | `include_packs_in_search` | `true` | the same, for installed packs |
  638. | `recency_half_life_share` | `0.5` | how much of the vault has to be newer than a memory before its semantic evidence is worth half the odds. `0` turns the recency prior off |
  639. | `expire_memories` | `true` | remove expired memories automatically |
  640. | `duplicate_threshold` | `0.97` | cosine similarity at which a store is a duplicate |
  641. | `max_memory_chars` | `200` | the one-claim length limit for authored memories. `0` disables the length and layout checks |
  642. | `opinion_update_threshold` | `0.80` | similarity at which a new opinion is an update of a live one and needs a supersedes decision |
  643. | `opinion_reaffirm_threshold` | `0.97` | similarity at which a restated opinion re-affirms the live record instead of storing |
  644. | `retag_interval_hours` | `6` | how often the background pass recomputes tags. `0` turns it off |
  645. | `retag_prune` | `false` | whether that pass may also remove tags |
  646. | `index_precision` | `"f32"` | `"int8"` uses a quarter of the RAM |
  647. | `embed_daemon` | `true` | ask the machine's shared embedding process for vectors instead of loading the model in this process |
  648. | `unlock_tool_enabled` | `false` | lets an agent unlock the vault. Off because the passphrase would cross the model's context |
  649. ### Environment
  650. `COMPARTMENT_VAULT` which vault to use, `COMPARTMENT_PASSPHRASE` for scripts
  651. and CI, `COMPARTMENT_SESSION_DIR` where the unlock credential lives,
  652. `COMPARTMENT_UI_SCALE` panel scale, `COMPARTMENT_ASSERT_OFFLINE` abort on any
  653. network attempt. `COMPARTMENT_EMBED_DAEMON=0` keeps the embedding model
  654. inside each process instead of the shared one, `COMPARTMENT_EMBED_SOCKET`
  655. moves that process's socket, `COMPARTMENT_EMBED_IDLE` is how many seconds it
  656. outlives its last client (300). `HERMES_HOME`, `OPENCLAW_HOME` and `XDG_DATA_HOME` are read
  657. where they apply. Anything exported as `ENGRAM_*` still works.
  658. ### MCP tools
  659. Every tool has a title and a read-only or destructive annotation, so a
  660. client can tell the seven read-only tools from the ones that write before
  661. calling anything. `memory_search`, `memory_store`, `memory_store_many`,
  662. `memory_get`, `memory_recent`, `memory_forget`, `memory_link`,
  663. `memory_relations`, `memory_unlink`, `memory_list_namespaces`,
  664. `memory_status`, `memory_lock`, `memory_selftest`. `memory_unlock` exists but
  665. is off unless you turn it on above.
  666. ## Documentation
  667. | | |
  668. |---|---|
  669. | [docs/MEMORY.md](docs/MEMORY.md) | how memory is stored, what gets remembered, and the ranking design |
  670. | [docs/PLUGINS.md](docs/PLUGINS.md) | every plugin store and listing: how users install from it, what the maintainer does |
  671. | [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md) | selecting Compartment in Hermes Agent, OpenClaw, Claude, everything else |
  672. | [docs/COMPARISON.md](docs/COMPARISON.md) | other memory servers, with sources |
  673. | [SECURITY.md](SECURITY.md) | the full threat model and its limits |
  674. | [FORMAT.md](FORMAT.md) | byte-level `.vault` and `.mpack` specs (language-agnostic) |
  675. | [PACKS.md](PACKS.md) | authoring and shipping signed memory packs |
  676. | [CONTRIBUTING.md](CONTRIBUTING.md) | setup, good issues, and the guarantees to keep |
  677. | [RELEASING.md](RELEASING.md) | how a release is cut |
  678. ## Privacy Policy
  679. Compartment collects no data: no telemetry, no analytics, no account, and no
  680. network at runtime. Memories are stored only on your machine, AEAD-encrypted
  681. at rest with a passphrase that never leaves it, and nothing is shared with
  682. anyone. The full policy, covering collection, storage, network access,
  683. third-party sharing, retention, and contact, is at
  684. <https://maxfreedompollard.github.io/Compartment/privacy>.
  685. ## Where to find it
  686. Compartment is listed on [PyPI](https://pypi.org/project/compartment/), the
  687. [official MCP registry](https://maxfreedompollard.github.io/Compartment/registry),
  688. the [Cursor Directory](https://cursor.directory/plugins/compartment),
  689. [Glama](https://glama.ai/mcp/servers/MaxFreedomPollard/Compartment),
  690. [LobeHub](https://lobehub.com/mcp/maxfreedompollard-compartment),
  691. [MCP Toplist](https://mcptoplist.com/server/io.github.MaxFreedomPollard%2Fcompartment),
  692. [MCP Market](https://mcpmarket.com/server/compartment),
  693. [mcpservers.org](https://mcpservers.org/servers/maxfreedompollard/compartment),
  694. [TensorBlock](https://www.tensorblock.co/mcp/servers/github-maxfreedompollard-compartment-4ab11161),
  695. the [toolsdk.ai registry](https://github.com/toolsdk-ai/toolsdk-mcp-registry/blob/main/packages/knowledge-memory/compartment.json),
  696. [Libraries.io](https://libraries.io/pypi/compartment),
  697. [Snyk Advisor](https://snyk.io/advisor/python/compartment) and
  698. [deps.dev](https://deps.dev/pypi/compartment), and in the curated lists
  699. [abordage/awesome-mcp](https://github.com/abordage/awesome-mcp),
  700. [TensorBlock/awesome-mcp-servers](https://github.com/TensorBlock/awesome-mcp-servers/blob/main/docs/knowledge-management--memory.md)
  701. and [Jenqyang/Awesome-AI-Agents](https://github.com/Jenqyang/Awesome-AI-Agents).
  702. [![MCP Toplist](https://mcptoplist.com/badge/io.github.MaxFreedomPollard%2Fcompartment.svg)](https://mcptoplist.com/server/io.github.MaxFreedomPollard%2Fcompartment)
  703. [![LobeHub](https://lobehub.com/badge/mcp/maxfreedompollard-compartment)](https://lobehub.com/mcp/maxfreedompollard-compartment)
  704. <a href="https://glama.ai/mcp/servers/MaxFreedomPollard/Compartment"><img width="380" height="200" src="https://glama.ai/mcp/servers/MaxFreedomPollard/Compartment/badge" alt="Compartment MCP server" /></a>
  705. Bugs and feature requests: [Issues](https://github.com/MaxFreedomPollard/Compartment/issues).
  706. Support and questions: [Discussions](https://github.com/MaxFreedomPollard/Compartment/discussions);
  707. security reports: [SECURITY.md](SECURITY.md).
  708. Questions and ideas: [Discussions](https://github.com/MaxFreedomPollard/Compartment/discussions).
  709. ---
  710. mcp-name: io.github.MaxFreedomPollard/compartment
install/install-windows.ps1 · Bundled script · 237 lines · 2 findings marked
  1. # Compartment installer - Windows (Windows PowerShell 5.1 or PowerShell 7)
  2. #
  3. # Installs the package, creates and unlocks a vault, connects the agents it
  4. # finds, and puts Compartment in the tray. Fully offline after this script.
  5. #
  6. # powershell -ExecutionPolicy Bypass -File install\install-windows.ps1
  7. #
  8. # -ExecutionPolicy Bypass applies to this one run: Windows' default policy
  9. # refuses unsigned scripts, and changing it for good is the user's call.
  10. # Set $env:PYTHON to a python.exe to choose the interpreter. Running it again
  11. # upgrades Compartment and leaves an existing vault alone.
  12. $ErrorActionPreference = "Stop"
  13. Write-Host "Compartment installer (Windows)"
  14. function Stop-Install([string]$message) {
  15. Write-Host ""
  16. Write-Host $message
  17. # `exit` would close the PowerShell window of someone who ran this as
  18. # `irm ... | iex`, where there is no script file to exit from.
  19. if ($PSCommandPath) { exit 1 } else { throw "Compartment was not installed." }
  20. }
  21. # --- 1. A Python that can run Compartment ------------------------------------
  22. #
  23. # Compartment's compiled dependencies publish Windows wheels for 64-bit
  24. # Python 3.11 to 3.14 on x64, and 3.12 to 3.14 on ARM64 (no pyyaml wheel for
  25. # 3.11 there); tools/wheel_coverage.py checks that matrix in CI. 32-bit
  26. # Python has no onnxruntime build at all. An x64 Python on an ARM64 machine
  27. # runs under emulation and takes the x64 wheels. Anything else fails in pip
  28. # with a bare "No matching distribution found", so each candidate is probed
  29. # first and the first one inside the matrix is used.
  30. #
  31. # The probe is a file rather than `-c`: Windows PowerShell 5.1 passes an
  32. # argument with double quotes in it to a native program mangled.
  33. $probe = @'
  34. import sys, sysconfig
  35. v = sys.version_info[:2]
  36. plat = sysconfig.get_platform()
  37. if plat == 'win32':
  38. print('32-bit Python %d.%d' % v)
  39. sys.exit(2)
  40. low = (3, 12) if plat == 'win-arm64' else (3, 11)
  41. if not (low <= v <= (3, 14)):
  42. print('Python %d.%d (%s)' % (v[0], v[1], plat))
  43. sys.exit(1)
  44. print('ok')
  45. '@
  46. $probeFile = Join-Path ([System.IO.Path]::GetTempPath()) "compartment-probe-$PID.py"
  47. Set-Content -LiteralPath $probeFile -Value $probe -Encoding ASCII
  48. function Invoke-Probe($cand) {
  49. # Local to this function: a candidate that is missing, or the Microsoft
  50. # Store's python.exe stand-in, writes to stderr, and Windows PowerShell
  51. # turns redirected stderr into a terminating error under "Stop".
  52. $ErrorActionPreference = "Continue"
  53. if (-not (Get-Command $cand.Exe -ErrorAction SilentlyContinue)) { return $null }
  54. try {
  55. $a = $cand.Args
  56. $out = & $cand.Exe @a $probeFile 2>$null
  57. return @{ Code = $LASTEXITCODE; Out = ((@($out) -join " ").Trim()) }
  58. } catch {
  59. return $null
  60. }
  61. }
  62. $os = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
  63. $candidates = @()
  64. if ($env:PYTHON) {
  65. $candidates += @{ Exe = $env:PYTHON; Args = @() }
  66. } else {
  67. if ($os -eq "ARM64") {
  68. foreach ($v in "3.14", "3.13", "3.12") { $candidates += @{ Exe = "py"; Args = @("-$v-arm64") } }
  69. }
  70. foreach ($v in "3", "3.14", "3.13", "3.12", "3.11") { $candidates += @{ Exe = "py"; Args = @("-$v") } }
  71. $candidates += @{ Exe = "python"; Args = @() }
  72. $candidates += @{ Exe = "python3"; Args = @() }
  73. }
  74. $exe = $null
  75. $pyArgs = @()
  76. $found = @()
  77. try {
  78. foreach ($cand in $candidates) {
  79. $r = Invoke-Probe $cand
  80. if ($null -eq $r) { continue }
  81. $label = (@($cand.Exe) + $cand.Args) -join " "
  82. if ($r.Code -eq 0) { $exe = $cand.Exe; $pyArgs = $cand.Args; break }
  83. $found += "$label is $(if ($r.Out) { $r.Out } else { 'not runnable' })"
  84. }
  85. } finally {
  86. Remove-Item -LiteralPath $probeFile -ErrorAction SilentlyContinue
  87. }
  88. if (-not $exe) {
  89. $range = if ($os -eq "ARM64") { "3.12 to 3.14 (ARM64), or 3.11 to 3.14 (x64)" } else { "3.11 to 3.14" }
  90. $what = if ($found.Count) { "Found: " + ($found -join "; ") + "." } else { "None was found." }
  91. Stop-Install ("Compartment needs 64-bit Python $range. $what`n" +
  92. "Install it from python.org, or: winget install Python.Python.3.13`n" +
  93. "then run this script again, or name it with `$env:PYTHON.")
  94. }
  95. Write-Host "Using $((@($exe) + $pyArgs) -join ' ')"
  96. function Get-PyText([string]$code) {
  97. # UTF-8 both ways, so a profile path with a non-ASCII user name (C:\Users\
  98. # José) comes back as itself rather than in the console's OEM code page.
  99. $saved = $null
  100. try { $saved = [Console]::OutputEncoding; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
  101. try {
  102. $out = & $exe @pyArgs -X utf8 -c $code
  103. } finally {
  104. if ($saved) { try { [Console]::OutputEncoding = $saved } catch { } }
  105. }
  106. return ((@($out) -join "`n").Trim())
  107. }
  108. # --- 2. Install ---------------------------------------------------------------
  109. #
  110. # This checkout when the script is run from one, otherwise the release on
  111. # PyPI. Run as `irm ... | iex` there is no script file and $PSScriptRoot is
  112. # empty, which Split-Path refused, ending the script under "Stop".
  113. $src = "compartment"
  114. if ($PSScriptRoot) {
  115. $repoRoot = Split-Path -Parent $PSScriptRoot
  116. $pyproject = Join-Path $repoRoot "pyproject.toml"
  117. if ((Test-Path -LiteralPath $pyproject) -and
  118. (Select-String -LiteralPath $pyproject -Pattern '^name = "compartment"$' -Quiet)) {
  119. $src = $repoRoot
  120. }
  121. }
  122. # pip refuses --user inside a virtualenv, so an activated one is installed
  123. # into directly; otherwise --user, as before. Windows Pythons are not
  124. # externally managed.
  125. $kind = Get-PyText "import sys; print('venv' if sys.prefix != sys.base_prefix else 'plain')"
  126. $pipArgs = @("-m", "pip", "install", "--upgrade")
  127. if ($kind -ne "venv") { $pipArgs += "--user" }
  128. & $exe @pyArgs @pipArgs $src
  129. if ($LASTEXITCODE -ne 0) {
  130. Stop-Install "pip could not install Compartment (exit code $LASTEXITCODE); its reason is above."
  131. }
  132. # `pip install --user` puts compartment.exe in the interpreter's own user
  133. # Scripts directory (%APPDATA%\Python\PythonXY\Scripts), which is not on PATH
  134. # on a clean machine. Ask the interpreter where that is and use it, so the
  135. # rest of this script runs instead of dying on "compartment is not
  136. # recognized".
  137. if ($kind -eq "venv") {
  138. $userBin = Get-PyText "import sysconfig; print(sysconfig.get_path('scripts'))"
  139. } else {
  140. $userBin = Get-PyText "import sysconfig; print(sysconfig.get_path('scripts', scheme='nt_user'))"
  141. }
  142. $onPathAlready = [bool](Get-Command compartment -ErrorAction SilentlyContinue)
  143. if ($userBin -and (Test-Path -LiteralPath $userBin)) {
  144. $env:Path = "$userBin;$env:Path"
  145. }
  146. $compartment = $null
  147. if ($userBin -and (Test-Path -LiteralPath (Join-Path $userBin "compartment.exe"))) {
  148. $compartment = Join-Path $userBin "compartment.exe"
  149. } elseif (Get-Command compartment -ErrorAction SilentlyContinue) {
  150. $compartment = (Get-Command compartment).Source
  151. } else {
  152. # No console script on PATH, but the module may be importable. Windows
  153. # PowerShell turns a native command's redirected stderr into an error
  154. # under "Stop", which here means only that the import failed.
  155. try {
  156. & $exe @pyArgs -c "import compartment.cli" *> $null
  157. $importable = ($LASTEXITCODE -eq 0)
  158. } catch {
  159. $importable = $false
  160. }
  161. if (-not $importable) {
  162. Stop-Install "compartment was installed but cannot be found. Expected the command in: $userBin"
  163. }
  164. }
  165. function Invoke-Compartment {
  166. if ($compartment) { & $compartment @args } else { & $exe @pyArgs -m compartment.cli @args }
  167. }
  168. # --- 3. The vault ---------------------------------------------------------------
  169. #
  170. # Where `compartment` looks by default (home.py): COMPARTMENT_VAULT, then
  171. # the legacy ENGRAM_VAULT, then memory.vault in %USERPROFILE%\.compartment,
  172. # or in .engram when only that exists. A vault that is there is never
  173. # touched: `init` refuses to overwrite one, and a re-run should not fail on
  174. # that.
  175. $profileDir = $env:USERPROFILE
  176. if ($env:COMPARTMENT_VAULT) {
  177. $vault = $env:COMPARTMENT_VAULT
  178. } elseif ($env:ENGRAM_VAULT) {
  179. $vault = $env:ENGRAM_VAULT
  180. } elseif (-not (Test-Path -LiteralPath (Join-Path $profileDir ".compartment")) -and
  181. (Test-Path -LiteralPath (Join-Path $profileDir ".engram"))) {
  182. $vault = Join-Path $profileDir ".engram\memory.vault"
  183. } else {
  184. $vault = Join-Path $profileDir ".compartment\memory.vault"
  185. }
  186. Write-Host ""
  187. $initRan = $false
  188. if (Test-Path -LiteralPath $vault) {
  189. Write-Host "Your vault at $vault is kept as it is."
  190. Write-Host "Open it with: compartment unlock (or from the tray icon)"
  191. } else {
  192. Write-Host "Creating your encrypted vault..."
  193. Invoke-Compartment init
  194. if ($LASTEXITCODE -ne 0) {
  195. Stop-Install "compartment init stopped (exit code $LASTEXITCODE); its reason is above."
  196. }
  197. $initRan = $true
  198. }
  199. if (-not $onPathAlready) {
  200. $quoted = $userBin -replace "'", "''"
  201. Write-Host ""
  202. Write-Host "Note: $userBin is not on your PATH."
  203. Write-Host "Run this once in PowerShell so 'compartment' works in new terminals:"
  204. Write-Host " [Environment]::SetEnvironmentVariable('Path', '$quoted;' + [Environment]::GetEnvironmentVariable('Path', 'User'), 'User')"
  205. }
  206. Write-Host ""
  207. Write-Host "Done. Compartment is installed."
  208. if ($initRan) {
  209. Write-Host "``init`` connected the agents it found (Claude Code, Hermes Agent,"
  210. Write-Host "OpenClaw); restart them to load it."
  211. }
  212. Write-Host @"
  213. To connect an agent:
  214. compartment integrate claude # Claude Code + Claude Desktop
  215. compartment integrate hermes # Hermes Agent
  216. compartment integrate --list # every MCP client it can wire
  217. Verify anytime: compartment selftest
  218. "@
src/compartment/systray.py · Bundled script · 1,860 lines · 1 finding marked
  1. """Windows tray app: Compartment in the notification area.
  2. The Windows counterpart of `menubar.py`, and deliberately the same product:
  3. click the icon and a panel shows whether the vault is open, the three settings
  4. worth changing day to day, and the last handful of things it remembered.
  5. Design notes:
  6. * Everything above the widgets is shared. State, settings, locking and the
  7. first-run marker all come from `menubar`, which keeps no AppKit at module
  8. level for exactly this reason. One data layer, one set of tests, two
  9. front ends - the platforms differ only in how a window is drawn.
  10. * The vault is never opened in this process. One child process,
  11. `compartment.vaultview`, keeps it open read-only while the panel is in use
  12. and reads only what changed; the panel opens at once from the last state
  13. it knew and refreshes in the background. Same design as macOS - it is the
  14. same PanelState.
  15. * Tk owns the main thread and pystray runs detached. Tk is not thread-safe and
  16. its mainloop must be on the main thread; pystray's Windows backend is a
  17. message loop that is happy anywhere. Tray callbacks therefore never touch a
  18. widget directly - they hand work back with `after(0, ...)`.
  19. * `tkinter` is in the standard library and `pystray` is pure Python, so the
  20. tray app adds no compiled dependency to a Windows install.
  21. """
  22. from __future__ import annotations
  23. import csv
  24. import os
  25. import re
  26. import shutil
  27. import subprocess
  28. import sys
  29. import time
  30. from pathlib import Path
  31. from .home import env, home
  32. from .menubar import (APP_COMMAND, AUTO_LOCK_CHOICES, INTEGRATION_TARGETS,
  33. RECENT_COUNT,
  34. acquire_instance_lock, auto_lock_label, backup_vault,
  35. change_passphrase, claim_first_run, create_vault,
  36. default_backup_filename, default_vault, integrate,
  37. lock_holder_pid, lock_vault, merge_vault,
  38. open_dashboard, stop_dashboard,
  39. offers_settings, release_instance_lock,
  40. run_in_background, self_check,
  41. starter_note, summarise, unlock_vault,
  42. PanelState)
  43. from .menubar import quit_running as _stop_lock_holder
  44. PANEL_WIDTH = 440
  45. PANEL_MAX_HEIGHT = 640
  46. TASKBAR_MARGIN = 56 # room for the taskbar the panel sits above
  47. RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
  48. RUN_VALUE = "Compartment"
  49. SCALE_ENV = "COMPARTMENT_UI_SCALE"
  50. def ui_scale() -> float:
  51. """How many pixels to a logical unit.
  52. A process that does not declare DPI awareness gets bitmap-stretched by
  53. Windows on a high-DPI display: correctly sized and visibly blurry. Asking
  54. the system for its DPI and scaling the panel to match draws it sharp
  55. instead, at the same physical size.
  56. Returns 1.0 off Windows and on ordinary 96 DPI screens, so the common
  57. case is unchanged. COMPARTMENT_UI_SCALE overrides, for anyone who wants
  58. the panel bigger or smaller than their display asks for.
  59. """
  60. override = os.environ.get(SCALE_ENV)
  61. if override:
  62. try:
  63. v = float(override)
  64. except ValueError:
  65. v = 0.0
  66. if 0.5 <= v <= 4.0:
  67. return v
  68. try:
  69. import ctypes
  70. # Declaring awareness must happen before the first window exists.
  71. try:
  72. ctypes.windll.shcore.SetProcessDpiAwareness(1) # system-DPI aware
  73. except Exception: # noqa: BLE001
  74. ctypes.windll.user32.SetProcessDPIAware() # pre-8.1 fallback
  75. dpi = ctypes.windll.user32.GetDpiForSystem()
  76. return max(1.0, round(dpi / 96.0, 2))
  77. except Exception: # noqa: BLE001
  78. return 1.0 # not Windows
  79. def icon_path() -> Path:
  80. """The tray icon, drawn by tools/make_icon.py and shipped as package data."""
  81. return Path(__file__).resolve().parent / "data" / "tray.ico"
  82. def panel_rows(state: dict) -> list[tuple[str, str]]:
  83. """The panel as (kind, text) rows.
  84. Pure, so the layout is testable on any OS without a display: the Windows
  85. CI runner checks what the panel *says* without ever drawing it.
  86. """
  87. rows: list[tuple[str, str]] = [("state", summarise(state))]
  88. if state.get("error"):
  89. rows.append(("error", str(state["error"])))
  90. # Making the vault, locking it and unlocking it all belong in the panel.
  91. # The vault is the product, and none of the three should mean finding a
  92. # terminal - least of all the first one, on an install that never put a
  93. # `compartment` command in one.
  94. if not state.get("exists"):
  95. rows.append(("create", "Create vault"))
  96. else:
  97. # Unlock only for a vault known to be locked: offering it on a guess
  98. # is how a failed read used to look like a locked vault. Lock in every
  99. # other state, unknown included, since locking is always safe.
  100. rows.append(("unlock", "Unlock") if state["locked"] is True
  101. else ("lock", "Lock"))
  102. # Encrypted .vault backup works whether the vault is locked or open.
  103. rows.append(("backup", "Back up…"))
  104. # Merging another backup or changing the passphrase needs the vault
  105. # open in RAM, so both are offered only while unlocked.
  106. if state["locked"] is False:
  107. rows.append(("merge", "Merge…"))
  108. rows.append(("change", "Change password"))
  109. if state.get("backup_note"):
  110. rows.append(("backup_note", str(state["backup_note"])))
  111. s = state["settings"]
  112. # Not before there is a vault: see offers_settings.
  113. if offers_settings(state):
  114. rows.append(("heading", "SETTINGS"))
  115. rows.append(("toggle:capture_hook",
  116. "Create memories automatically: "
  117. f"{'on' if s['capture_hook'] else 'off'}"))
  118. rows.append(("toggle:search_starter_facts",
  119. f"Search starter facts: "
  120. f"{'on' if s['search_starter_facts'] else 'off'}"))
  121. rows.append(("toggle:expire_memories",
  122. f"Forget memories when they expire: "
  123. f"{'on' if s.get('expire_memories', True) else 'off'}"))
  124. rows.append(("choice:auto_lock_minutes",
  125. f"Auto-lock: {auto_lock_label(s['auto_lock_minutes'])}"))
  126. # Installing leaves you with a vault that nothing is using until an agent
  127. # is wired to it. One button per agent, so that step is not a terminal
  128. # command someone has to know about.
  129. rows.append(("heading", "CONNECT AN AGENT"))
  130. wired = state.get("integrations") or {}
  131. for target, name in INTEGRATION_TARGETS:
  132. rows.append((f"connect:{target}",
  133. f"{name} ✓" if wired.get(target) else name))
  134. # Only the result of a click. The heading and the buttons say the rest,
  135. # and a standing explanation here made the panel taller than it is
  136. # allowed to be.
  137. if state.get("connect_note"):
  138. rows.append(("note", state["connect_note"]))
  139. rows.append(("heading", f"LAST {RECENT_COUNT} MEMORIES"))
  140. recent = state.get("recent") or []
  141. if not state.get("exists"):
  142. rows.append(("empty", "nothing yet - create the vault above"))
  143. elif state["locked"]:
  144. rows.append(("empty", "unlock the vault to see them"))
  145. elif state["locked"] is None or state.get("checking"):
  146. rows.append(("empty", "reading the vault…" if state.get("checking")
  147. else "not available until the vault can be read"))
  148. elif not recent:
  149. rows.append(("empty", starter_note(state)))
  150. for r in recent:
  151. rows.append(("memory", (r.get("text") or "").strip()))
  152. return rows
  153. # --- start at login ---------------------------------------------------------
  154. # The Run key is per-user, needs no elevation and no COM, and is what the
  155. # Startup folder ends up writing anyway. Failure is reported, never raised: a
  156. # refusal to autostart must not take the app down with it.
  157. def _winreg():
  158. import winreg # Windows-only stdlib
  159. return winreg
  160. def _autostart_command(vault: str | None = None) -> str:
  161. """What Windows runs at sign-in.
  162. Two things this has to get right. It launches through pythonw.exe, the
  163. one interpreter that opens no console, because anything else opens a
  164. console window behind a tray app that has no window, at every single
  165. sign-in. And it carries the vault path, because a user running a
  166. non-default vault would otherwise silently get the default one back
  167. after a reboot.
  168. """
  169. exe, args = _autostart_parts(vault)
  170. return f'"{exe}" {args}'
  171. def _autostart_parts(vault: str | None = None) -> tuple[str, str]:
  172. """The same command, split. A scheduled task wants the program and its
  173. arguments in separate XML elements, and re-parsing a quoted command line
  174. to get them back would be a second place for the quoting to be wrong.
  175. pythonw.exe beside this interpreter comes first, and the console script
  176. only when there is none. compartment.exe, which pip and uv write for the
  177. console script, is a console program like python.exe: started at
  178. sign-in it opened a console window that stayed for the whole session,
  179. since that process IS the tray app, and closing the window quit it. It
  180. used to come first. Every venv, uv tool environment and python.org
  181. install has a pythonw.exe beside python.exe, and it runs the same
  182. environment's compartment.
  183. """
  184. vault = vault or env("VAULT") or str(home() / "memory.vault")
  185. pyw = Path(sys.executable).with_name("pythonw.exe")
  186. if pyw.is_file():
  187. return str(pyw), f'-m compartment.cli --vault "{vault}" tray'
  188. exe = shutil.which("compartment")
  189. if exe:
  190. return exe, f'--vault "{vault}" tray'
  191. return sys.executable, f'-m compartment.cli --vault "{vault}" tray'
  192. # --- the Linux application entry --------------------------------------------
  193. # A Linux desktop has no tray to leave an icon in, so being findable means
  194. # being in the applications menu. The entry is per-user, needs no root, and
  195. # names an absolute icon path so nothing has to be installed into an icon
  196. # theme or a cache rebuilt.
  197. DESKTOP_FILE = "compartment.desktop"
  198. def desktop_entry_path() -> Path:
  199. base = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
  200. return Path(base) / "applications" / DESKTOP_FILE
  201. def app_icon_path() -> Path:
  202. return Path(__file__).resolve().parent / "data" / "app.png"
  203. def _panel_command(vault: str | None = None) -> str:
  204. exe = shutil.which("compartment")
  205. vault = vault or env("VAULT") or str(home() / "memory.vault")
  206. if exe:
  207. return f'"{exe}" --vault "{vault}" panel'
  208. return f'"{sys.executable}" -m compartment.cli --vault "{vault}" panel'
  209. def install_desktop_entry(vault: str | None = None) -> str:
  210. """Put Compartment in the applications menu. Returns what happened."""
  211. path = desktop_entry_path()
  212. try:
  213. path.parent.mkdir(parents=True, exist_ok=True)
  214. icon = app_icon_path()
  215. path.write_text(
  216. "[Desktop Entry]\n"
  217. "Type=Application\n"
  218. "Name=Compartment\n"
  219. "Comment=Encrypted memory for AI agents\n"
  220. f"Exec={_panel_command(vault)}\n"
  221. + (f"Icon={icon}\n" if icon.is_file() else "")
  222. + "Terminal=false\n"
  223. "Categories=Utility;Security;\n"
  224. "Keywords=memory;vault;mcp;agent;\n",
  225. encoding="utf-8")
  226. path.chmod(0o644)
  227. except OSError as exc:
  228. return f"error: {exc}"
  229. # Best effort: most desktops notice a new file by themselves, and the
  230. # ones that want telling are not worth failing an install over.
  231. try:
  232. subprocess.run(["update-desktop-database", str(path.parent)],
  233. capture_output=True, timeout=15)
  234. except (OSError, subprocess.SubprocessError):
  235. pass
  236. return str(path)
  237. def remove_desktop_entry() -> bool:
  238. try:
  239. desktop_entry_path().unlink(missing_ok=True)
  240. return True
  241. except OSError:
  242. return False
  243. # --- starting at login on Linux ---------------------------------------------
  244. # An entry in the applications menu makes Compartment findable. It does not
  245. # make it run, and the two were being treated as one thing: `login_status`
  246. # answered "on" whenever the menu entry existed, so a desktop that had never
  247. # started Compartment at login reported that it did. The autostart directory
  248. # is a different directory with a different meaning, and this is it.
  249. def autostart_entry_path() -> Path:
  250. base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
  251. return Path(base) / "autostart" / DESKTOP_FILE
  252. def install_autostart_entry(vault: str | None = None) -> str:
  253. """Start Compartment at login, the way every XDG desktop reads it."""
  254. path = autostart_entry_path()
  255. try:
  256. path.parent.mkdir(parents=True, exist_ok=True)
  257. icon = app_icon_path()
  258. path.write_text(
  259. "[Desktop Entry]\n"
  260. "Type=Application\n"
  261. "Name=Compartment\n"
  262. "Comment=Encrypted memory for AI agents\n"
  263. f"Exec={_panel_command(vault)}\n"
  264. + (f"Icon={icon}\n" if icon.is_file() else "")
  265. + "Terminal=false\n"
  266. # GNOME and KDE both read these, and without them a session can
  267. # decide an autostart entry is stale and skip it.
  268. "X-GNOME-Autostart-enabled=true\n"
  269. "Hidden=false\n"
  270. "NoDisplay=false\n",
  271. encoding="utf-8")
  272. path.chmod(0o644)
  273. except OSError as exc:
  274. return f"error: {exc}"
  275. return str(path)
  276. def remove_autostart_entry() -> bool:
  277. try:
  278. autostart_entry_path().unlink(missing_ok=True)
  279. return True
  280. except OSError:
  281. return False
  282. # --- being put back when it dies --------------------------------------------
  283. # An autostart entry and a Run key both start the panel once at sign-in and
  284. # then stop caring, which is the fault macOS had before KeepAlive: anything
  285. # that ends the process - a crash, an exception, an upgrade replacing the
  286. # binary underneath it - took the icon away until the next sign-in, with
  287. # nothing said. Both systems do have a supervisor; neither of them is the
  288. # mechanism that was being used.
  289. #
  290. # The rule for both is the one launchd already follows: bring back a copy
  291. # that DIED, leave alone a copy that LEFT. systemd spells that
  292. # `Restart=on-failure` and Task Scheduler spells it `RestartOnFailure`; Quit
  293. # exits zero under either, so the button stays the only way to remove the
  294. # icon for the rest of the session.
  295. #
  296. # One starter at a time, never two. Two things starting the panel at login
  297. # means one of them loses the single-instance lock and stands down with exit
  298. # zero, and exit zero is exactly the exit a supervisor is built to leave
  299. # alone - so a redundant autostart entry does not add a safety net, it
  300. # quietly removes the one that was there.
  301. SYSTEMD_UNIT = "compartment.service"
  302. SCHEDULED_TASK = "Compartment"
  303. def _systemctl(*argv: str) -> tuple[int, str]:
  304. try:
  305. r = subprocess.run(["systemctl", "--user", *argv], capture_output=True,
  306. text=True, timeout=30)
  307. except (OSError, subprocess.SubprocessError) as exc:
  308. return 1, str(exc)
  309. return r.returncode, ((r.stdout or "") + (r.stderr or "")).strip()
  310. def systemd_unit_path() -> Path:
  311. base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
  312. return Path(base) / "systemd" / "user" / SYSTEMD_UNIT
  313. def systemd_available() -> bool:
  314. """Is there a systemd user manager on the other end of systemctl?
  315. Not "is this a systemd distribution". A container, a bare X session or an
  316. ssh login can have systemd running the machine and no user manager to
  317. talk to, and installing a unit into that is writing a file nothing will
  318. ever read.
  319. """
  320. if not shutil.which("systemctl"):
  321. return False
  322. _code, out = _systemctl("is-system-running")
  323. low = out.lower()
  324. # "degraded" exits non-zero and is a perfectly usable manager. Only being
  325. # unable to reach one at all is a no.
  326. return not ("failed to connect" in low or "offline" in low
  327. or "no medium" in low or not out)
  328. def graphical_session_active() -> bool:
  329. """Does this login's desktop start graphical-session.target?
  330. The unit is WantedBy that target, so it starts at login only on a
  331. desktop whose session manager activates it: GNOME, KDE Plasma, and
  332. compositors set up for it. Xfce, MATE, Cinnamon (Linux Mint's default),
  333. LXQt and a bare window manager never do, and there an enabled unit is a
  334. unit that never starts - while the autostart entry it replaced, which
  335. every XDG desktop reads, was deleted as the redundant second starter.
  336. Asked while the desktop is up (install time, from its terminal); asked
  337. from SSH or a text console it is inactive too, and the autostart entry,
  338. which works everywhere, is the right answer there as well.
  339. """
  340. return _systemctl("is-active", "graphical-session.target")[0] == 0
  341. def systemd_unit_text(vault: str | None = None) -> str:
  342. return (
  343. "[Unit]\n"
  344. "Description=Compartment - encrypted memory for AI agents\n"
  345. "Documentation=https://github.com/MaxFreedomPollard/Compartment\n"
  346. "PartOf=graphical-session.target\n"
  347. # A user manager with no display can never draw the panel. Five tries
  348. # and it stops, rather than restarting for ever on a machine where it
  349. # cannot possibly work.
  350. "StartLimitIntervalSec=120\n"
  351. "StartLimitBurst=5\n"
  352. "\n"
  353. "[Service]\n"
  354. "Type=simple\n"
  355. f"ExecStart={_panel_command(vault)}\n"
  356. # The Linux half of KeepAlive SuccessfulExit=false: back if it died,
  357. # left alone if it left. Quit exits zero.
  358. "Restart=on-failure\n"
  359. "RestartSec=3\n"
  360. "\n"
  361. "[Install]\n"
  362. "WantedBy=graphical-session.target\n")
  363. def systemd_enabled() -> bool:
  364. """Does systemd say the unit starts at login? It is the authority."""
  365. if not systemd_unit_path().is_file():
  366. return False
  367. code, out = _systemctl("is-enabled", SYSTEMD_UNIT)
  368. first = out.splitlines()[0].strip() if out else ""
  369. return code == 0 and first == "enabled"
  370. def systemd_active() -> bool:
  371. return _systemctl("is-active", SYSTEMD_UNIT)[0] == 0
  372. def install_systemd_unit(vault: str | None = None) -> str:
  373. """Write the unit, enable it, start it, and check every step."""
  374. path = systemd_unit_path()
  375. try:
  376. path.parent.mkdir(parents=True, exist_ok=True)
  377. path.write_text(systemd_unit_text(vault), encoding="utf-8")
  378. path.chmod(0o644)
  379. except OSError as exc:
  380. return f"error: {exc}"
  381. _systemctl("daemon-reload")
  382. code, out = _systemctl("enable", "--now", SYSTEMD_UNIT)
  383. if code != 0:
  384. return f"error: {out or 'systemd refused the unit'}"
  385. if not systemd_enabled():
  386. return "error: the unit did not stay enabled"
  387. return "on"
  388. def remove_systemd_unit() -> bool:
  389. _systemctl("disable", "--now", SYSTEMD_UNIT)
  390. try:
  391. systemd_unit_path().unlink(missing_ok=True)
  392. except OSError:
  393. return False
  394. _systemctl("daemon-reload")
  395. return not systemd_enabled()
  396. def _schtasks(*argv: str) -> tuple[int, str]:
  397. try:
  398. r = subprocess.run(["schtasks", *argv], capture_output=True,
  399. text=True, timeout=60)
  400. except (OSError, subprocess.SubprocessError) as exc:
  401. return 1, str(exc)
  402. return r.returncode, ((r.stdout or "") + (r.stderr or "")).strip()
  403. def _xml(text: str) -> str:
  404. return (text.replace("&", "&amp;").replace("<", "&lt;")
  405. .replace(">", "&gt;").replace('"', "&quot;"))
  406. def scheduled_task_xml(vault: str | None = None) -> str:
  407. """A logon task that restarts the panel if it fails.
  408. Written as XML rather than assembled from `schtasks` flags because the
  409. restart-on-failure setting - the entire reason for preferring a task to
  410. the Run key - has no flag.
  411. """
  412. exe, args = _autostart_parts(vault)
  413. user = os.environ.get("USERNAME") or ""
  414. domain = os.environ.get("USERDOMAIN") or ""
  415. who = f"{domain}\\{user}" if domain and user else user
  416. return (
  417. '<?xml version="1.0" encoding="UTF-16"?>\n'
  418. '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/'
  419. '2004/02/mit/task">\n'
  420. " <RegistrationInfo>\n"
  421. " <Description>Compartment - encrypted memory for AI agents"
  422. "</Description>\n"
  423. " </RegistrationInfo>\n"
  424. " <Triggers>\n"
  425. " <LogonTrigger>\n"
  426. " <Enabled>true</Enabled>\n"
  427. f" <UserId>{_xml(who)}</UserId>\n"
  428. " </LogonTrigger>\n"
  429. " </Triggers>\n"
  430. " <Principals>\n"
  431. ' <Principal id="Author">\n'
  432. f" <UserId>{_xml(who)}</UserId>\n"
  433. # Without an interactive token the task runs in a session that has no
  434. # desktop, and a tray icon there is an icon nobody can ever see.
  435. " <LogonType>InteractiveToken</LogonType>\n"
  436. " <RunLevel>LeastPrivilege</RunLevel>\n"
  437. " </Principal>\n"
  438. " </Principals>\n"
  439. " <Settings>\n"
  440. # The Windows half of KeepAlive SuccessfulExit=false. Task Scheduler
  441. # counts a non-zero exit as a failure and starts it again; Quit exits
  442. # zero and is left alone.
  443. " <RestartOnFailure>\n"
  444. " <Interval>PT1M</Interval>\n"
  445. " <Count>3</Count>\n"
  446. " </RestartOnFailure>\n"
  447. " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
  448. " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n"
  449. " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n"
  450. " <StartWhenAvailable>true</StartWhenAvailable>\n"
  451. # A panel is meant to sit there. A time limit would have Task
  452. # Scheduler kill it after three days.
  453. " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n"
  454. " <Enabled>true</Enabled>\n"
  455. " <Hidden>false</Hidden>\n"
    • Note: Usual in code (tag names in paths and patterns): Contains a <hidden> block, a common wrapper for instructions hidden in a tool description
    • Line 530 on GitHub
  456. " </Settings>\n"
  457. ' <Actions Context="Author">\n'
  458. " <Exec>\n"
  459. f" <Command>{_xml(exe)}</Command>\n"
  460. f" <Arguments>{_xml(args)}</Arguments>\n"
  461. " </Exec>\n"
  462. " </Actions>\n"
  463. "</Task>\n")
  464. def scheduled_task_registered() -> bool:
  465. """Does Task Scheduler have the task? It is the authority."""
  466. return _schtasks("/query", "/tn", SCHEDULED_TASK)[0] == 0
  467. def install_scheduled_task(vault: str | None = None) -> str:
  468. import tempfile
  469. try:
  470. fd, tmp = tempfile.mkstemp(suffix=".xml")
  471. os.close(fd)
  472. # UTF-16 with a BOM: schtasks reads the encoding the declaration
  473. # names, and rejects the file outright when the two disagree.
  474. Path(tmp).write_text(scheduled_task_xml(vault), encoding="utf-16")
  475. except OSError as exc:
  476. return f"error: {exc}"
  477. try:
  478. code, out = _schtasks("/create", "/tn", SCHEDULED_TASK,
  479. "/xml", tmp, "/f")
  480. finally:
  481. try:
  482. Path(tmp).unlink()
  483. except OSError:
  484. pass
  485. if code != 0:
  486. return f"error: {out or 'Task Scheduler refused the task'}"
  487. if not scheduled_task_registered():
  488. return "error: the task did not survive being created"
  489. return "on"
  490. def remove_scheduled_task() -> bool:
  491. _schtasks("/end", "/tn", SCHEDULED_TASK)
  492. _schtasks("/delete", "/tn", SCHEDULED_TASK, "/f")
  493. return not scheduled_task_registered()
  494. def supervisor_status() -> str | None:
  495. """"on" if a supervisor has this, a reason if it has it broken, or None
  496. if there is no supervisor in play and the older mechanism answers."""
  497. if _is_linux():
  498. if not systemd_unit_path().is_file():
  499. return None
  500. return "on" if systemd_enabled() else "off (the unit is not enabled)"
  501. if sys.platform == "win32" and scheduled_task_registered():
  502. return "on"
  503. return None
  504. def start_supervised() -> bool:
  505. """Start the panel through its supervisor, so that the copy which comes
  506. up is the copy that will be brought back if it dies.
  507. Not on Windows, deliberately. `schtasks /run` starts the task in
  508. whatever session Task Scheduler picks rather than the one the person
  509. running the installer is looking at, and a tray icon in another session
  510. is an icon nobody can see - the install then had nothing to show for
  511. itself while the task's copy held the lock. The task is for the next
  512. sign-in, which is the job it is actually good at; the install starts a
  513. copy in the session it can see, exactly as it did before the task
  514. existed.
  515. """
  516. if _is_linux():
  517. return systemd_enabled() and _systemctl("start", SYSTEMD_UNIT)[0] == 0
  518. return False
  519. def restart_supervised() -> bool:
  520. """Stop and start the panel in one operation by the supervisor.
  521. What an upgrade needs, and for the same reason macOS uses `kickstart -k`:
  522. killing the process by hand races the supervisor, which relaunches the
  523. copy that exited non-zero while the caller is starting a replacement.
  524. """
  525. if _is_linux():
  526. return systemd_enabled() and _systemctl("restart", SYSTEMD_UNIT)[0] == 0
  527. if sys.platform == "win32":
  528. if not scheduled_task_registered():
  529. return False
  530. _schtasks("/end", "/tn", SCHEDULED_TASK)
  531. return _schtasks("/run", "/tn", SCHEDULED_TASK)[0] == 0
  532. return False
  533. def _is_supervised() -> bool:
  534. """Was this copy started by the supervisor?
  535. systemd sets INVOCATION_ID for every service it runs, so a copy under the
  536. unit can be told apart from one started by hand. Task Scheduler leaves no
  537. such mark, so this is always false on Windows - see
  538. `hand_over_to_supervisor`, which is Linux-only for that reason.
  539. """
  540. return bool(os.environ.get("INVOCATION_ID")) if _is_linux() else False
  541. def hand_over_to_supervisor(vault: str, timeout: float = 15.0) -> bool:
  542. """Let the supervised copy have the panel, and prove that it took it.
  543. The same precedence as macOS: a copy started by hand is not watched by
  544. anything, and while it holds the lock the supervisor's own copy stands
  545. down with exit zero - which `Restart=on-failure` reads as a deliberate
  546. exit, so systemd never starts it again either.
  547. Only ever hands over to a unit that is already enabled. A machine with no
  548. unit is either one that never had start at login or one where the user
  549. switched it off, and neither is ours to overrule.
  550. """
  551. if not _is_linux() or _is_supervised() or not systemd_enabled():
  552. return False
  553. before = set(running_pids())
  554. release_instance_lock()
  555. if _systemctl("start", SYSTEMD_UNIT)[0] == 0:
  556. deadline = time.monotonic() + timeout
  557. while time.monotonic() < deadline:
  558. if set(running_pids()) - before:
  559. return True
  560. time.sleep(0.2)
  561. # Nothing came up, so take the panel back rather than leave the user with
  562. # none. Unless the lock has gone in the meantime, which means the
  563. # handover happened after all, just slower than we waited.
  564. _handle, only = acquire_instance_lock(vault)
  565. return not only
  566. def _is_linux() -> bool:
  567. """This module draws the panel on Windows and on everything that is not
  568. macOS. Only the latter uses desktop entries, and macOS must never get
  569. one: it has its own front end, and writing into an XDG directory there
  570. would litter a machine that will never read it."""
  571. return sys.platform not in ("win32", "darwin")
  572. def autostart_is_enabled() -> bool:
  573. """Whether the autostart entry would actually start anything.
  574. There is no launchd here to ask, so the file is the authority - but the
  575. file says more than "I exist". Switching Compartment off in GNOME Tweaks
  576. or KDE's Autostart rewrites this same entry with `Hidden=true` rather
  577. than deleting it, and an entry carrying `X-GNOME-Autostart-enabled=false`
  578. is skipped in the same way. Reading only the filename reports "on" for
  579. both, which is the desktop equivalent of a plist that was never loaded.
  580. """
  581. path = autostart_entry_path()
  582. try:
  583. lines = [ln.strip().lower()
  584. for ln in path.read_text(encoding="utf-8",
  585. errors="replace").splitlines()]
  586. except OSError:
  587. return False
  588. if "hidden=true" in lines:
  589. return False
  590. return "x-gnome-autostart-enabled=false" not in lines
  591. def login_status() -> str:
  592. # A supervisor, where one is in play, is the authority on its own job -
  593. # the same reason macOS asks launchd instead of looking for the plist.
  594. supervised = supervisor_status()
  595. if supervised is not None:
  596. return supervised
  597. if _is_linux():
  598. # The autostart entry, not the applications-menu entry. Reading the
  599. # menu entry meant this said "on" for a machine that had never
  600. # started Compartment at login in its life.
  601. return "on" if autostart_is_enabled() else "off"
  602. try:
  603. winreg = _winreg()
  604. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:
  605. value, _kind = winreg.QueryValueEx(k, RUN_VALUE)
  606. except FileNotFoundError:
  607. return "off"
  608. except Exception as exc: # noqa: BLE001
  609. return f"unknown ({exc})"
  610. # A Run entry naming a program that is not there starts nothing at the
  611. # next sign-in, and an uninstalled Python or a moved virtualenv leaves
  612. # exactly that behind. The registry is the authority on the entry; the
  613. # filesystem is the authority on whether it points at anything.
  614. exe = _autostart_target(value)
  615. if exe and not Path(exe).is_file():
  616. return "off (the program it names is gone)"
  617. return "on"
  618. def _autostart_target(command: str) -> str | None:
  619. """The executable out of a Run command line, or None if it cannot be
  620. read confidently. `_autostart_command` always quotes it; anything else
  621. was written by something other than us and is not ours to second-guess."""
  622. command = (command or "").strip()
  623. if not command.startswith('"'):
  624. return None
  625. end = command.find('"', 1)
  626. return command[1:end] if end > 1 else None
  627. def _delete_run_value() -> None:
  628. """Drop the Run entry, if there is one. Used when the scheduled task
  629. takes over from it, so the two never start a copy each."""
  630. try:
  631. winreg = _winreg()
  632. with winreg.CreateKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:
  633. winreg.DeleteValue(k, RUN_VALUE)
  634. except Exception: # noqa: BLE001
  635. pass
  636. #: Present at the root of every Flatpak sandbox.
  637. _FLATPAK_INFO = "/.flatpak-info"
  638. def _app_sandbox() -> str | None:
  639. """The Flatpak or Snap this process is confined in, if any.
  640. Inside one, XDG_CONFIG_HOME and XDG_DATA_HOME (Flatpak) or HOME itself
  641. (Snap) point into the app's private directory, which the desktop never
  642. reads, and the Python an entry would name is the sandbox's own, which
  643. the desktop cannot run. `compartment init` typed into the terminal of a
  644. Flatpak editor wrote its autostart entry there and reported start at
  645. login as on."""
  646. flatpak = os.environ.get("FLATPAK_ID")
  647. if flatpak or os.path.isfile(_FLATPAK_INFO):
  648. return f"a Flatpak sandbox ({flatpak or 'unknown app'})"
  649. # Strict confinement only, which is what moves HOME to the snap's own
  650. # SNAP_USER_DATA. A classic snap - VS Code's, among others - sets
  651. # SNAP_NAME for every terminal it opens and confines nothing.
  652. snap = os.environ.get("SNAP_NAME")
  653. if (snap and os.environ.get("SNAP_USER_DATA")
  654. and os.environ.get("HOME") == os.environ.get("SNAP_USER_DATA")):
  655. return f"a Snap sandbox ({snap})"
  656. return None
  657. def set_login(enabled: bool, vault: str | None = None) -> str:
  658. """Register or drop start at sign-in. Returns what actually happened.
  659. The vault is carried through every mechanism. It used to be dropped at
  660. this door: `_autostart_command` and `install_autostart_entry` both take
  661. one and take care to keep it, and this called them with nothing - so a
  662. user running a second vault had start-at-login quietly registered
  663. against the default one, and got the wrong memory back at every sign-in.
  664. """
  665. if _is_linux():
  666. if not enabled:
  667. remove_systemd_unit()
  668. remove_autostart_entry()
  669. return "off" if remove_desktop_entry() else "error"
  670. sandbox = _app_sandbox()
  671. if sandbox:
  672. return (f"error: this is running inside {sandbox}, where an "
  673. "entry would be written somewhere your desktop never "
  674. "reads. Run `compartment panel --login on` from a "
  675. "terminal outside it.")
  676. # Both, and they are not the same thing: the menu entry is how the
  677. # app is found, the autostart entry is how it comes up at login.
  678. out = install_desktop_entry(vault)
  679. if out.startswith("error"):
  680. return out
  681. # Supervised where the machine can be. A unit that enables but never
  682. # starts is not proof of anything, so it has to be active too, and
  683. # anything short of that is undone rather than left half installed.
  684. # Only on a desktop that starts the unit's target at login at all.
  685. if systemd_available() and graphical_session_active():
  686. if install_systemd_unit(vault) == "on" and systemd_active():
  687. remove_autostart_entry() # exactly one starter
  688. return "on"
  689. remove_systemd_unit()
  690. auto = install_autostart_entry(vault)
  691. return "on" if not auto.startswith("error") else auto
  692. if sys.platform != "win32":
  693. return "error: start at login is handled by the menu bar app here"
  694. # Windows: a scheduled task restarts a panel that failed, the Run key
  695. # only ever starts one. Same rule as Linux - the better mechanism if it
  696. # takes, the older one if it does not, and never the two together. The
  697. # Run key is still cleared on the way out, because a version of this that
  698. # wrote one may have run on this machine before.
  699. if not enabled:
  700. remove_scheduled_task()
  701. elif install_scheduled_task(vault) == "on":
  702. _delete_run_value()
  703. return "on"
  704. try:
  705. winreg = _winreg()
  706. with winreg.CreateKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:
  707. if enabled:
  708. wanted = _autostart_command(vault)
  709. winreg.SetValueEx(k, RUN_VALUE, 0, winreg.REG_SZ, wanted)
  710. # Read it back. A write that the registry accepted and then
  711. # dropped - a policy, a locked hive, a roaming profile - used
  712. # to report "on" and start nothing at the next sign-in.
  713. try:
  714. got, _kind = winreg.QueryValueEx(k, RUN_VALUE)
  715. except FileNotFoundError:
  716. return "error: the Run entry did not survive the write"
  717. # And read back the value, not merely the name. A roaming
  718. # profile or a management policy can put its own command
  719. # there, and a Run entry that survived as somebody else's
  720. # command is not this app starting at sign-in.
  721. if got != wanted:
  722. return ("error: the Run entry holds a different command "
  723. f"({got!r})")
  724. return "on"
  725. try:
  726. winreg.DeleteValue(k, RUN_VALUE)
  727. except FileNotFoundError:
  728. pass
  729. return "off"
  730. except Exception as exc: # noqa: BLE001
  731. return f"error: {exc}"
  732. # --- when the panel cannot draw ---------------------------------------------
  733. # pip cannot install tkinter: it comes with the Python, or with a package of
  734. # the distribution's. "Install your distribution's Python Tk package" left
  735. # the user to find out what that is called, which differs on every family,
  736. # and is the wrong advice altogether for a Python the distribution did not
  737. # provide (pyenv, asdf, conda, one built from source), where the package
  738. # changes nothing.
  739. #: Per distribution family: the package that adds Tk to the distribution's
  740. #: own Python, and the headers a Python built from source needs to build it.
  741. _TK_BY_FAMILY = {
  742. "debian": ("sudo apt install python3-tk", "sudo apt install tk-dev"),
  743. "fedora": ("sudo dnf install python3-tkinter",
  744. "sudo dnf install tk-devel"),
  745. "suse": ("sudo zypper install python3-tk", "sudo zypper install tk-devel"),
  746. "arch": ("sudo pacman -S tk", "sudo pacman -S tk"),
  747. "alpine": ("sudo apk add python3-tkinter", "sudo apk add tk-dev"),
  748. "void": ("sudo xbps-install python3-tkinter",
  749. "sudo xbps-install tk-devel"),
  750. "gentoo": ("enable the tk USE flag for dev-lang/python, then: "
  751. "sudo emerge --oneshot dev-lang/python",
  752. "sudo emerge dev-lang/tk"),
  753. }
  754. #: os-release ID and ID_LIKE words, to a family above.
  755. _TK_FAMILY_OF = {
  756. "debian": "debian", "ubuntu": "debian", "linuxmint": "debian",
  757. "pop": "debian", "raspbian": "debian", "kali": "debian",
  758. "elementary": "debian", "zorin": "debian", "neon": "debian",
  759. "fedora": "fedora", "rhel": "fedora", "centos": "fedora",
  760. "rocky": "fedora", "almalinux": "fedora", "amzn": "fedora",
  761. "ol": "fedora", "nobara": "fedora",
  762. "suse": "suse", "opensuse": "suse", "sles": "suse",
  763. "arch": "arch", "manjaro": "arch", "endeavouros": "arch",
  764. "cachyos": "arch", "garuda": "arch", "steamos": "arch",
  765. "alpine": "alpine", "postmarketos": "alpine",
  766. "void": "void", "gentoo": "gentoo",
  767. }
  768. def _os_release() -> str:
  769. for path in ("/etc/os-release", "/usr/lib/os-release"):
  770. try:
  771. with open(path, encoding="utf-8", errors="replace") as fh:
  772. return fh.read()
  773. except OSError:
  774. continue
  775. return ""
  776. def _distro_family(os_release: str) -> str | None:
  777. fields = {}
  778. for line in os_release.splitlines():
  779. key, sep, value = line.partition("=")
  780. if sep:
  781. fields[key.strip()] = value.strip().strip("\"'").lower()
  782. words = [fields.get("ID", "")] + fields.get("ID_LIKE", "").split()
  783. for word in words:
  784. if not word:
  785. continue
  786. # opensuse-tumbleweed, opensuse-leap, sles_sap and the like
  787. for name in (word, word.split("-")[0], word.split("_")[0]):
  788. if name in _TK_FAMILY_OF:
  789. return _TK_FAMILY_OF[name]
  790. return None
  791. def tk_install_hint(os_release: str | None = None,
  792. base_prefix: str | None = None,
  793. platform: str | None = None) -> str:
  794. """The command that gives this Python tkinter, as exactly as this
  795. machine allows. Pure given its arguments, which default to this
  796. machine's, so every family is testable anywhere."""
  797. platform = platform or sys.platform
  798. prefix = base_prefix if base_prefix is not None else sys.base_prefix
  799. ver = f"{sys.version_info[0]}{sys.version_info[1]}"
  800. if "com.termux" in prefix:
  801. return "pkg install x11-repo && pkg install python-tkinter"
  802. if platform.startswith("freebsd"):
  803. return f"sudo pkg install py{ver}-tkinter"
  804. if platform.startswith("openbsd"):
  805. return "doas pkg_add python-tkinter"
  806. if platform.startswith("netbsd"):
  807. return f"sudo pkgin install py{ver}-Tk"
  808. if os.path.isdir(os.path.join(prefix, "conda-meta")):
  809. return "conda install tk"
  810. if "linuxbrew" in prefix or "homebrew" in prefix.lower():
  811. return ("brew install "
  812. f"python-tk@{sys.version_info[0]}.{sys.version_info[1]}")
  813. if "/uv/python/" in prefix.replace(os.sep, "/"):
  814. # uv's Pythons carry Tk; one without it is a damaged install.
  815. return ("uv python install --reinstall "
  816. f"{sys.version_info[0]}.{sys.version_info[1]}")
  817. family = _distro_family(_os_release() if os_release is None
  818. else os_release)
  819. system, headers = _TK_BY_FAMILY.get(family, (None, None))
  820. if prefix.rstrip("/") not in ("/usr", ""):
  821. # Not the distribution's Python: pyenv, asdf, a source build in
  822. # /usr/local. Its _tkinter is built when the Python is, against
  823. # Tk's headers, so the headers go in first and the Python is
  824. # built again.
  825. build = ("then build this Python again (pyenv: "
  826. "pyenv install --force "
  827. f"{sys.version_info[0]}.{sys.version_info[1]}."
  828. f"{sys.version_info[2]})")
  829. return (f"{headers}, {build}" if headers else
  830. f"install Tk's development headers, {build}")
  831. return system or ("install your distribution's Tk package for Python "
  832. "(often python3-tk or python3-tkinter)")
  833. def tk_missing_message(what: str = "panel") -> str:
  834. return ("error: this Python has no tkinter, which the "
  835. f"{what} needs.\n"
  836. f" This Python is {sys.executable}. To give it tkinter:\n"
  837. f" {tk_install_hint()}\n"
  838. " Or install Compartment with uv, which brings its own Python "
  839. "with tkinter in it:\n"
  840. " uv tool install compartment\n"
  841. " Everything else works without it: the CLI, the MCP server, "
  842. "and `compartment dash`.")
  843. def no_display_message(exc: Exception) -> str:
  844. """Why Tk could not open a window, in words that say what to do."""
  845. text = str(exc)
  846. low = text.lower()
  847. if "init.tcl" in low or "tk.tcl" in low:
  848. return (f"error: this Python's Tcl/Tk files are missing or not where "
  849. f"it looks for them ({text}).\n"
  850. " Reinstall this Python, or install Compartment with uv, "
  851. "whose Python carries its own:\n"
  852. " uv tool install compartment")
  853. if (sys.platform not in ("win32", "darwin")
  854. and os.environ.get("WAYLAND_DISPLAY")
  855. and not os.environ.get("DISPLAY")):
  856. # Tk draws through X11 only. A Wayland desktop runs XWayland for
  857. # programs like it, usually on demand; this one has none running.
  858. return ("error: the panel is drawn with Tk, which needs X11, and "
  859. "this Wayland session has no X server (DISPLAY is not set).\n"
  860. " Turn XWayland on in your compositor (sway: `xwayland "
  861. "enable`; GNOME and KDE start it by themselves when it is\n"
  862. " installed: package xwayland or xorg-x11-server-Xwayland), "
  863. "or use `compartment dash` to read the vault in a browser.")
  864. return (f"error: no graphical display to draw the panel on ({text}).\n"
  865. " On a headless machine use the CLI, or `compartment dash` to\n"
  866. " read the vault in a browser.")
  867. def panel_geometry(content: int, maximum: int) -> tuple[int, bool]:
  868. """How tall to draw the panel, and whether it needs a scrollbar.
  869. Split out from the Tk code so the rule is checked on every OS in CI: any
  870. content taller than the panel scrolls. It is never cut off - the panel
  871. losing its bottom silently is the whole reason this function exists.
  872. """
  873. if content > maximum:
  874. return maximum, True
  875. return max(content, 1), False
  876. # --- the app ---------------------------------------------------------------
  877. def has_tray() -> bool:
  878. """Is there a notification area to put an icon in?
  879. Windows has one everywhere. Linux does not: whether a tray icon appears
  880. depends on the desktop, and on GNOME or Wayland it can simply never show
  881. up, with nothing said. Silent absence is the worst possible failure for
  882. the control that unlocks your memories, so Linux gets the same panel as
  883. an ordinary window instead of an icon that may or may not exist.
  884. """
  885. return sys.platform == "win32"
  886. def run(vault: str | None = None, show: bool = False,
  887. render_to: str | None = None) -> int:
  888. vault_path = vault or default_vault()
  889. tray = has_tray()
  890. where = "notification area" if tray else "window"
  891. if render_to: # parity with --render
  892. print("error: --render is macOS only", file=sys.stderr)
  893. return 2
  894. # One copy per vault, however each was started: the Run key at sign-in,
  895. # `compartment init`, a launcher entry, or a person running it again.
  896. _lock, only = acquire_instance_lock(vault_path)
  897. if not only:
  898. if tray:
  899. print("Compartment is already running - open it from the "
  900. "notification area")
  901. else:
  902. print("Compartment is already open - look for its window")
  903. return 0
  904. # Precedence, the same as macOS: the copy a supervisor is watching owns
  905. # the panel, because it is the only one that comes back if it dies.
  906. if hand_over_to_supervisor(vault_path):
  907. print("Compartment is running as a background service, so that copy "
  908. "has the panel - systemd puts it back if it ever dies.")
  909. return 0
  910. # No detaching from the terminal here, unlike the macOS menu bar app.
  911. # `compartment tray` and `compartment panel` are expected to BE the
  912. # running app: start one from a console or a script and that process is
  913. # the panel, until it is stopped. Re-launching detached and exiting zero
  914. # would look, to anything holding the handle, exactly like the app dying
  915. # on its own. Start at sign-in is what survives the session here, and on
  916. # Linux and Windows that is now supervised.
  917. try:
  918. import tkinter as tk
  919. from tkinter import ttk
  920. except ImportError:
  921. print(tk_missing_message("tray panel" if tray else "panel"),
  922. file=sys.stderr)
  923. return 3
  924. pystray = Image = None
  925. if tray:
  926. try:
  927. import pystray
  928. from PIL import Image
  929. except ImportError:
  930. # Into this interpreter, by name. The [tray] extra this used to
  931. # name has been empty since the two became base dependencies,
  932. # so installing it changed nothing.
  933. print("error: the tray app needs pystray and Pillow, which this "
  934. "Python does not have.\n"
  935. f' "{sys.executable}" -m pip install pystray pillow',
  936. file=sys.stderr)
  937. return 3
  938. # Read the DPI (and declare awareness) before the first window exists.
  939. S = ui_scale()
  940. PW = int(PANEL_WIDTH * S)
  941. WRAP = PW - int(40 * S)
  942. PMH = int(PANEL_MAX_HEIGHT * S)
  943. TBM = int(TASKBAR_MARGIN * S)
  944. try:
  945. root = tk.Tk()
  946. except tk.TclError as exc:
  947. # A machine with no desktop (SSH, a container, a CI runner), a
  948. # Wayland session with no XWayland, or a Python whose Tcl files are
  949. # not where it looks. Say which, rather than show a Tk stack trace.
  950. print(no_display_message(exc), file=sys.stderr)
  951. return 4
  952. if S != 1.0:
  953. # Tk sizes fonts in points; this is what turns a point into a pixel.
  954. # 1.3333 is the 96-DPI baseline Tk already assumes on Windows.
  955. root.tk.call("tk", "scaling", 1.3333 * S)
  956. root.withdraw() # no stray empty window
  957. panel: dict = {"win": None, "note": None, "entries": [], "shown": None}
  958. # What the panel shows, kept current in the background: it opens at once
  959. # from what this holds, and a read that lands later updates it in place.
  960. # The read finishes on its own thread; Tk is not thread-safe, so it hands
  961. # back through after(0, ...), exactly as the tray icon's callbacks do.
  962. states = PanelState(vault_path)
  963. states.refresh(include_vault=False) # local files: instant
  964. states.on_change = lambda: root.after(0, landed)
  965. def off_ui(work, then) -> None:
  966. """work() on a thread of its own, then then(its result) back on Tk's
  967. thread: see run_in_background. A click's handler runs on Tk's
  968. thread, and one that waited on the CLI there froze the panel - and,
  969. through after(), the tray icon's menu - for as long as the CLI took.
  970. """
  971. run_in_background(work, lambda out: root.after(0, lambda: then(out)))
  972. def do_backup() -> None:
  973. if panel.get("backup_busy"):
  974. return
  975. from tkinter import filedialog
  976. parent = panel["win"] if (panel["win"] is not None
  977. and panel["win"].winfo_exists()) else root
  978. dest = filedialog.asksaveasfilename(
  979. parent=parent,
  980. title="Save Encrypted Vault Backup",
  981. initialfile=default_backup_filename(),
  982. defaultextension=".vault",
  983. filetypes=[("Encrypted Compartment Vault", "*.vault"),
  984. ("All files", "*.*")])
  985. if not dest:
  986. return
  987. panel["backup_busy"] = True
  988. panel["backup_note"] = "Saving encrypted backup…"
  989. redraw()
  990. def backed_up(out):
  991. _ok, msg = ((False, f"could not back up: {out}")
  992. if isinstance(out, Exception) else out)
  993. panel["backup_busy"] = False
  994. panel["backup_note"] = msg
  995. redraw()
  996. off_ui(lambda: backup_vault(vault_path, dest), backed_up)
  997. def _finish_merge(payload) -> None:
  998. panel["backup_busy"] = False
  999. if isinstance(payload, Exception):
  1000. panel["merging_src"] = None
  1001. panel["merge_note"] = None
  1002. panel["backup_note"] = f"could not merge: {payload}"
  1003. redraw()
  1004. return
  1005. src, (ok, msg, needs_pw) = payload
  1006. if needs_pw:
  1007. panel["merging_src"] = src
  1008. panel["merge_note"] = msg
  1009. panel["backup_note"] = None
  1010. show_panel()
  1011. return
  1012. panel["merging_src"] = None
  1013. panel["merge_note"] = None
  1014. panel["backup_note"] = msg
  1015. if ok:
  1016. refresh()
  1017. else:
  1018. redraw()
  1019. def do_merge() -> None:
  1020. if panel.get("backup_busy"):
  1021. return
  1022. from tkinter import filedialog
  1023. parent = panel["win"] if (panel["win"] is not None
  1024. and panel["win"].winfo_exists()) else root
  1025. src = filedialog.askopenfilename(
  1026. parent=parent,
  1027. title="Merge Encrypted Vault Backup",
  1028. filetypes=[("Encrypted Compartment Vault", "*.vault"),
  1029. ("All files", "*.*")])
  1030. if not src:
  1031. return
  1032. panel["backup_busy"] = True
  1033. panel["backup_note"] = f"Merging {Path(src).name}…"
  1034. redraw()
  1035. off_ui(lambda: (src, merge_vault(vault_path, src)), _finish_merge)
  1036. def _content(frame, state) -> None:
  1037. """Everything the panel shows. Packs into `frame`, never sizes it -
  1038. deciding how tall the window gets is build()'s job, below."""
  1039. s = state["settings"]
  1040. # Changing the passphrase gets the whole panel to itself, rather than
  1041. # being appended below a panel that is already full. Two boxes, Save
  1042. # and the reason the last attempt failed all belong on screen at once.
  1043. if (state["exists"] and state["locked"] is False
  1044. and panel.get("changing")):
  1045. ttk.Label(frame, text="Change password", wraplength=WRAP,
  1046. font=("Segoe UI", 10, "bold")).pack(anchor="w")
  1047. ttk.Label(frame, text=summarise(state), wraplength=WRAP,
  1048. foreground="#666").pack(anchor="w", pady=(2, 0))
  1049. ttk.Separator(frame).pack(fill="x", pady=10)
  1050. new = ttk.Entry(frame, show="•", width=34)
  1051. new.pack(anchor="w")
  1052. rep = ttk.Entry(frame, show="•", width=34)
  1053. panel["entries"] += [new, rep]
  1054. rep.pack(anchor="w", pady=(6, 0))
  1055. new.focus_set()
  1056. def do_change(*_):
  1057. first, again = new.get(), rep.get()
  1058. new.delete(0, "end") # never leave one on screen
  1059. rep.delete(0, "end")
  1060. def changed(out):
  1061. ok, note = ((False, "could not change the passphrase: "
  1062. f"{out}")
  1063. if isinstance(out, Exception) else out)
  1064. panel["changing"] = not ok
  1065. panel["change_note"] = note
  1066. refresh()
  1067. off_ui(lambda: change_passphrase(vault_path, first, again),
  1068. changed)
  1069. new.bind("<Return>", do_change)
  1070. rep.bind("<Return>", do_change)
  1071. if panel.get("change_note"):
  1072. ttk.Label(frame, text=panel["change_note"], wraplength=WRAP,
  1073. foreground="#b00020").pack(anchor="w", pady=(8, 0))
  1074. ttk.Label(frame, text="Both boxes must match. There is no recovery "
  1075. "phrase - if you forget this, the memories "
  1076. "are unrecoverable.",
  1077. foreground="#666", wraplength=WRAP,
  1078. justify="left").pack(anchor="w", pady=(8, 0))
  1079. bar = ttk.Frame(frame)
  1080. bar.pack(fill="x", pady=(10, 0))
  1081. ttk.Button(bar, text="Save", command=do_change).pack(side="left")
  1082. ttk.Button(bar, text="Cancel",
  1083. command=lambda: (panel.update(changing=False,
  1084. change_note=None),
  1085. refresh())).pack(side="left", padx=6)
  1086. return
  1087. if (state["exists"] and state["locked"] is False
  1088. and panel.get("merging_src")):
  1089. src_path = panel["merging_src"]
  1090. ttk.Label(frame, text=f"Merge {Path(src_path).name}",
  1091. wraplength=WRAP,
  1092. font=("Segoe UI", 10, "bold")).pack(anchor="w")
  1093. ttk.Label(frame,
  1094. text="This backup uses a different passphrase. Memories "
  1095. "are decrypted in RAM only; the backup file is "
  1096. "never modified.",
  1097. wraplength=WRAP, foreground="#666",
  1098. justify="left").pack(anchor="w", pady=(2, 0))
  1099. ttk.Separator(frame).pack(fill="x", pady=10)
  1100. mpw = ttk.Entry(frame, show="\u2022", width=34)
  1101. mpw.pack(anchor="w")
  1102. panel["entries"].append(mpw)
  1103. mpw.focus_set()
  1104. def submit_merge_pw(*_):
  1105. if panel.get("backup_busy"):
  1106. return
  1107. pw = mpw.get()
  1108. mpw.delete(0, "end")
  1109. if not pw:
  1110. panel["merge_note"] = "enter the backup vault's passphrase"
  1111. redraw()
  1112. return
  1113. panel["backup_busy"] = True
  1114. panel["merge_note"] = f"Merging {Path(src_path).name}…"
  1115. redraw()
  1116. off_ui(lambda: (src_path, merge_vault(vault_path, src_path, pw)),
  1117. _finish_merge)
  1118. mpw.bind("<Return>", submit_merge_pw)
  1119. if panel.get("merge_note"):
  1120. ttk.Label(frame, text=panel["merge_note"], wraplength=WRAP,
  1121. foreground="#b00020",
  1122. justify="left").pack(anchor="w", pady=(8, 0))
  1123. bar = ttk.Frame(frame)
  1124. bar.pack(fill="x", pady=(10, 0))
  1125. ttk.Button(bar, text="Merge",
  1126. state=("disabled" if panel.get("backup_busy")
  1127. else "normal"),
  1128. command=submit_merge_pw).pack(side="left")
  1129. ttk.Button(bar, text="Cancel",
  1130. command=lambda: (panel.update(merging_src=None,
  1131. merge_note=None),
  1132. redraw())).pack(side="left", padx=6)
  1133. return
  1134. ttk.Label(frame, text=summarise(state), wraplength=WRAP,
  1135. font=("Segoe UI", 10, "bold")).pack(anchor="w")
  1136. if state.get("error"):
  1137. ttk.Label(frame, text=str(state["error"]), foreground="#b00020",
  1138. wraplength=WRAP).pack(anchor="w", pady=(4, 0))
  1139. if not state["exists"]:
  1140. # The first-run step. Without it the panel says there is no vault,
  1141. # names a command this install never put on PATH, and offers no
  1142. # control at all: Unlock is hidden precisely because there is
  1143. # nothing to unlock.
  1144. new_pw = ttk.Entry(frame, show="\u2022", width=34)
  1145. new_pw.pack(anchor="w", pady=(8, 0))
  1146. new_rep = ttk.Entry(frame, show="\u2022", width=34)
  1147. panel["entries"] += [new_pw, new_rep]
  1148. new_rep.pack(anchor="w", pady=(6, 0))
  1149. new_pw.focus_set()
  1150. def do_create(*_):
  1151. """Say it is working, then work. Tk repaints between events
  1152. and not during one, so seeding the starting memories from
  1153. inside the handler would freeze the panel and then change a
  1154. line, which is what a dead button looks like."""
  1155. if panel.get("creating"):
  1156. return
  1157. pw, rep = new_pw.get(), new_rep.get()
  1158. if not pw or pw != rep:
  1159. panel["create_note"] = ("choose a passphrase" if not pw
  1160. else "the two entries do not match")
  1161. refresh()
  1162. return
  1163. panel["creating"] = True
  1164. panel["create_note"] = "Creating the vault…"
  1165. refresh()
  1166. def created(out):
  1167. panel["creating"] = False
  1168. panel["create_note"] = (
  1169. f"could not create the vault: {out}"
  1170. if isinstance(out, Exception) else out[1])
  1171. if os.path.exists(vault_path):
  1172. states.mark(exists=True, locked=None, checking=True,
  1173. error=None)
  1174. refresh()
  1175. off_ui(lambda: create_vault(vault_path, pw, pw), created)
  1176. new_pw.bind("<Return>", do_create)
  1177. new_rep.bind("<Return>", do_create)
  1178. ttk.Button(frame, text="Create vault",
  1179. state="disabled" if panel.get("creating") else "normal",
  1180. command=do_create).pack(anchor="w", pady=(8, 0))
  1181. if panel.get("create_note"):
  1182. ttk.Label(frame, text=panel["create_note"], wraplength=WRAP,
  1183. justify="left").pack(anchor="w", pady=(4, 0))
  1184. ttk.Label(frame, text="There is no recovery phrase - if you forget "
  1185. "this, the memories are unrecoverable.",
  1186. foreground="#666", wraplength=WRAP,
  1187. justify="left").pack(anchor="w", pady=(4, 0))
  1188. if state["exists"] and state["locked"]:
  1189. unlock_row = ttk.Frame(frame)
  1190. unlock_row.pack(fill="x", pady=(8, 0))
  1191. entry = ttk.Entry(unlock_row, show="\u2022", width=26)
  1192. entry.pack(side="left")
  1193. panel["entries"].append(entry)
  1194. entry.focus_set()
  1195. def do_unlock(*_):
  1196. pw = entry.get()
  1197. entry.delete(0, "end") # never leave it on screen
  1198. def unlocked(out):
  1199. ok, note = ((False, f"could not unlock: {out}")
  1200. if isinstance(out, Exception) else out)
  1201. panel["note"] = None if ok else note
  1202. if ok:
  1203. states.mark(locked=False, checking=True, error=None)
  1204. refresh()
  1205. off_ui(lambda: unlock_vault(vault_path, pw), unlocked)
  1206. entry.bind("<Return>", do_unlock)
  1207. ttk.Button(unlock_row, text="Unlock",
  1208. command=do_unlock).pack(side="right")
  1209. if panel.get("note"):
  1210. ttk.Label(frame, text=panel["note"], foreground="#b00020",
  1211. wraplength=WRAP).pack(anchor="w",
  1212. pady=(4, 0))
  1213. ttk.Label(frame, text="Stays unlocked until restart or Lock",
  1214. foreground="#666").pack(anchor="w")
  1215. # Not before there is a vault: see offers_settings.
  1216. if offers_settings(state):
  1217. ttk.Separator(frame).pack(fill="x", pady=10)
  1218. ttk.Label(frame, text="SETTINGS",
  1219. font=("Segoe UI", 8, "bold")).pack(anchor="w")
  1220. hook = tk.BooleanVar(value=s["capture_hook"])
  1221. starter = tk.BooleanVar(value=s["search_starter_facts"])
  1222. expiring = tk.BooleanVar(value=s.get("expire_memories", True))
  1223. def toggle(key, var):
  1224. # One that could not be saved says why; a refresh now would
  1225. # read the vault again and clear the reason off the panel.
  1226. if states.change_setting(key, bool(var.get())):
  1227. refresh()
  1228. else:
  1229. redraw()
  1230. ttk.Checkbutton(frame, text="Create memories automatically",
  1231. variable=hook,
  1232. command=lambda: toggle("capture_hook", hook)
  1233. ).pack(anchor="w", pady=(6, 0))
  1234. ttk.Checkbutton(frame, text="Search starter facts", variable=starter,
  1235. command=lambda: toggle("search_starter_facts", starter)
  1236. ).pack(anchor="w")
  1237. ttk.Checkbutton(frame, text="Forget memories when they expire",
  1238. variable=expiring,
  1239. command=lambda: toggle("expire_memories", expiring)
  1240. ).pack(anchor="w")
  1241. row = ttk.Frame(frame)
  1242. row.pack(fill="x", pady=(8, 0))
  1243. ttk.Label(row, text="Auto-lock").pack(side="left")
  1244. choice = tk.StringVar(value=auto_lock_label(s["auto_lock_minutes"]))
  1245. def set_lock(label):
  1246. for m in AUTO_LOCK_CHOICES:
  1247. if auto_lock_label(m) == label:
  1248. if not states.change_setting("auto_lock_minutes", m):
  1249. redraw() # keep the reason on screen
  1250. return
  1251. break
  1252. refresh()
  1253. ttk.OptionMenu(row, choice, choice.get(),
  1254. *[auto_lock_label(m) for m in AUTO_LOCK_CHOICES],
  1255. command=set_lock).pack(side="right")
  1256. ttk.Separator(frame).pack(fill="x", pady=10)
  1257. ttk.Label(frame, text="CONNECT AN AGENT",
  1258. font=("Segoe UI", 8, "bold")).pack(anchor="w")
  1259. def connect(target, name):
  1260. """Say it is working, then work, so the click is visibly seen.
  1261. Tk repaints between events and not during one, so doing the
  1262. wiring straight from the handler freezes the panel for a second
  1263. and then changes one line: indistinguishable from a dead button.
  1264. """
  1265. if panel.get("connect_busy"):
  1266. return # one at a time
  1267. panel["connect_busy"] = target
  1268. panel["connect_note"] = f"Connecting {name}…"
  1269. refresh()
  1270. def connected(out):
  1271. panel["connect_busy"] = None
  1272. panel["connect_note"] = (f"could not connect: {out}"
  1273. if isinstance(out, Exception)
  1274. else out[1])
  1275. refresh() # and the ticks, once that config is read
  1276. off_ui(lambda: integrate(vault_path, target), connected)
  1277. wired = state.get("integrations") or {}
  1278. connect_row = ttk.Frame(frame)
  1279. connect_row.pack(fill="x", pady=(6, 0))
  1280. _pad_x = max(1, int(3 * S))
  1281. _pad_y = max(1, int(2 * S))
  1282. try:
  1283. from tkinter import font as _tkfont
  1284. _cstyle = ttk.Style()
  1285. if _cstyle.theme_use() != "aqua":
  1286. _df = _tkfont.nametofont("TkDefaultFont").actual()
  1287. _cfont = (("Segoe UI", 8) if sys.platform == "win32"
  1288. else (_df["family"], max(9, abs(int(_df["size"])) - 1)))
  1289. _cstyle.configure("Connect.TButton", padding=(_pad_x, _pad_y),
  1290. font=_cfont)
  1291. _ckw = {"width": 0, "style": "Connect.TButton"}
  1292. except Exception: # noqa: BLE001
  1293. _ckw = {"width": 0}
  1294. for _i, (_target, _name) in enumerate(INTEGRATION_TARGETS):
  1295. ttk.Button(connect_row,
  1296. text=f"{_name} ✓" if wired.get(_target) else _name,
  1297. state=("disabled" if panel.get("connect_busy")
  1298. else "normal"),
  1299. command=lambda t=_target, n=_name: connect(t, n),
  1300. **_ckw
  1301. ).pack(side="left",
  1302. padx=(0, _pad_x if _i < len(INTEGRATION_TARGETS) - 1
  1303. else 0))
  1304. if panel.get("connect_note"): # only the result of a click
  1305. ttk.Label(frame, text=panel["connect_note"], wraplength=WRAP,
  1306. justify="left").pack(anchor="w", pady=(4, 0))
  1307. ttk.Separator(frame).pack(fill="x", pady=10)
  1308. ttk.Label(frame, text=f"LAST {RECENT_COUNT} MEMORIES",
  1309. font=("Segoe UI", 8, "bold")).pack(anchor="w")
  1310. recent = state.get("recent") or []
  1311. if state["locked"] or state["locked"] is None or state.get("checking"):
  1312. # the same words the rows give; never the empty-vault note for a
  1313. # vault that is merely locked or not read yet
  1314. empty = [text for kind, text in panel_rows(state)
  1315. if kind == "empty"]
  1316. if empty:
  1317. ttk.Label(frame, text=empty[0], foreground="#666",
  1318. wraplength=WRAP,
  1319. justify="left").pack(anchor="w", pady=(4, 0))
  1320. recent = []
  1321. elif not recent:
  1322. ttk.Label(frame, text=starter_note(state), foreground="#666",
  1323. wraplength=WRAP,
  1324. justify="left").pack(anchor="w", pady=(4, 0))
  1325. for r in recent:
  1326. ttk.Label(frame, text=(r.get("text") or "").strip(),
  1327. wraplength=WRAP,
  1328. justify="left").pack(anchor="w", pady=(4, 0))
  1329. if panel.get("change_note"): # result of the last attempt
  1330. ttk.Label(frame, text=panel["change_note"],
  1331. wraplength=WRAP).pack(anchor="w", pady=(8, 0))
  1332. ttk.Separator(frame).pack(fill="x", pady=10)
  1333. if state["exists"]:
  1334. vault_bar = ttk.Frame(frame)
  1335. vault_bar.pack(fill="x", pady=(0, 6))
  1336. busy_state = "disabled" if panel.get("backup_busy") else "normal"
  1337. ttk.Button(vault_bar, text="Back up…", state=busy_state,
  1338. command=do_backup).pack(side="left")
  1339. if state["locked"] is False:
  1340. ttk.Button(vault_bar, text="Merge…", state=busy_state,
  1341. command=do_merge).pack(side="left", padx=6)
  1342. if panel.get("backup_note"):
  1343. ttk.Label(frame, text=panel["backup_note"], wraplength=WRAP,
  1344. foreground="#666",
  1345. justify="left").pack(anchor="w", pady=(0, 6))
  1346. buttons = ttk.Frame(frame)
  1347. buttons.pack(fill="x")
  1348. ttk.Button(buttons, text="Refresh",
  1349. command=lambda: states.refresh_async(force=True)
  1350. ).pack(side="left")
  1351. # Lock whenever the vault is not known to be locked - including
  1352. # before the first read and after a failed one; locking is safe in
  1353. # every state. The rest waits for a definite "unlocked".
  1354. if state["exists"] and state["locked"] is not True:
  1355. ttk.Button(buttons, text="Lock now",
  1356. command=lambda: off_ui(
  1357. lambda: states.lock(lambda: lock_vault(vault_path)),
  1358. lambda _out: (panel.update(note=None,
  1359. changing=False,
  1360. merging_src=None),
  1361. refresh()))
  1362. ).pack(side="left", padx=6)
  1363. if state["exists"] and state["locked"] is False:
  1364. if not panel.get("changing"):
  1365. ttk.Button(buttons, text="Change password",
  1366. command=lambda: (panel.update(changing=True,
  1367. change_note=None),
  1368. refresh())).pack(side="left", padx=6)
  1369. ttk.Button(buttons, text="Dashboard",
  1370. command=lambda: open_dashboard(vault_path)
  1371. ).pack(side="left", padx=6)
  1372. ttk.Button(buttons, text="Quit", command=quit_app).pack(side="right")
  1373. def build(win) -> None:
  1374. """Fill the window, and give it a scrollbar if the content overflows.
  1375. The content goes inside a canvas rather than straight into the window.
  1376. A fixed-height window cut its own bottom off and said nothing about
  1377. it, which is how the passphrase form came to show one box out of two:
  1378. the second box and the Save button were not merely out of reach, there
  1379. was no sign on screen that they existed at all.
  1380. """
  1381. for child in win.winfo_children():
  1382. child.destroy()
  1383. panel["entries"] = []
  1384. state = states.snapshot() # reads nothing: a redraw never waits
  1385. panel["shown"] = state
  1386. canvas = tk.Canvas(win, highlightthickness=0, borderwidth=0, width=PW)
  1387. try: # match the themed background
  1388. canvas.configure(background=ttk.Style().lookup("TFrame",
  1389. "background"))
  1390. except tk.TclError: # a theme without one: leave it
  1391. pass
  1392. vbar = ttk.Scrollbar(win, orient="vertical", command=canvas.yview)
  1393. canvas.configure(yscrollcommand=vbar.set)
  1394. canvas.pack(side="left", fill="both", expand=True)
  1395. frame = ttk.Frame(canvas, padding=14)
  1396. canvas.create_window((0, 0), window=frame, anchor="nw", width=PW)
  1397. _content(frame, state)
  1398. frame.update_idletasks()
  1399. need = frame.winfo_reqheight()
  1400. height, scrolling = panel_geometry(need, PMH)
  1401. canvas.configure(height=height, scrollregion=(0, 0, PW, need))
  1402. if scrolling:
  1403. vbar.pack(side="right", fill="y")
  1404. # Bound on the window, not the canvas: the content covers the
  1405. # canvas, so the wheel event never reaches it. Windows reports
  1406. # the delta in multiples of 120.
  1407. win.bind("<MouseWheel>",
  1408. lambda e: canvas.yview_scroll(-(e.delta // 120), "units"))
  1409. vbar.update_idletasks()
  1410. panel["scroll_w"] = vbar.winfo_reqwidth()
  1411. else:
  1412. win.unbind("<MouseWheel>")
  1413. panel["scroll_w"] = 0
  1414. def place(win) -> None:
  1415. """Where the panel sits: by the tray icon, or centred without one."""
  1416. win.update_idletasks()
  1417. # The scrollbar sits beside the content, so widen the window by it
  1418. # rather than letting it eat a strip off the right of every line.
  1419. w = PW + panel.get("scroll_w", 0)
  1420. h = min(win.winfo_reqheight(), PMH)
  1421. if tray:
  1422. x = win.winfo_screenwidth() - w - 12 # above the taskbar
  1423. y = win.winfo_screenheight() - h - TBM
  1424. else:
  1425. # No icon to point at, so the bottom right corner would be an
  1426. # odd place for the only window the app has.
  1427. x = (win.winfo_screenwidth() - w) // 2
  1428. y = (win.winfo_screenheight() - h) // 3
  1429. win.geometry(f"{w}x{h}+{max(x, 0)}+{max(y, 0)}")
  1430. def show_panel() -> None:
  1431. win = panel["win"]
  1432. if win is None or not win.winfo_exists():
  1433. win = tk.Toplevel(root)
  1434. win.title("Compartment")
  1435. win.resizable(False, False)
  1436. if tray:
  1437. win.attributes("-topmost", True)
  1438. if icon_path().is_file():
  1439. try:
  1440. win.iconbitmap(str(icon_path()))
  1441. except Exception: # noqa: BLE001
  1442. pass # an icon is a nicety
  1443. # With an icon in the tray, closing the window hides it and the
  1444. # app lives on. Without one, a hidden window is an app with no
  1445. # way back to it, so closing means quitting.
  1446. win.protocol("WM_DELETE_WINDOW",
  1447. win.withdraw if tray else quit_app)
  1448. panel["win"] = win
  1449. build(win)
  1450. place(win)
  1451. win.deiconify()
  1452. win.lift()
  1453. win.focus_force()
  1454. # Only now, with the panel already up from what was known. Nothing
  1455. # changed on disk since the last look means nothing is read at all.
  1456. states.refresh_async()
  1457. def redraw() -> None:
  1458. win = panel["win"]
  1459. if win is not None and win.winfo_exists():
  1460. build(win)
  1461. place(win)
  1462. def refresh() -> None:
  1463. """After a click: show its result now, and re-read whatever it may
  1464. have changed in the background."""
  1465. redraw()
  1466. states.refresh_async()
  1467. def landed() -> None:
  1468. """A background read finished. Redraw in place - only when the panel
  1469. is up, something on it changed, and nobody is typing into it: a
  1470. redraw replaces the fields, and a half-typed passphrase must not
  1471. vanish. Anything skipped is drawn at the next open or click."""
  1472. win = panel["win"]
  1473. if win is None or not win.winfo_exists() or win.state() != "normal":
  1474. return
  1475. if states.snapshot() == panel.get("shown"):
  1476. return
  1477. for e in panel.get("entries") or []:
  1478. try:
  1479. if e.winfo_exists() and e.get():
  1480. return
  1481. except Exception: # noqa: BLE001
  1482. pass
  1483. redraw()
  1484. def quit_app() -> None:
  1485. states.close()
  1486. stop_dashboard()
  1487. icon = panel.get("icon")
  1488. if icon is not None:
  1489. try:
  1490. icon.stop()
  1491. except Exception: # noqa: BLE001
  1492. pass
  1493. root.quit()
  1494. # Tray callbacks arrive on pystray's thread; hand them to Tk's.
  1495. def from_tray(fn):
  1496. return lambda *_: root.after(0, fn)
  1497. if tray:
  1498. image = (Image.open(icon_path()) if icon_path().is_file()
  1499. else Image.new("RGBA", (32, 32), (240, 234, 224, 255)))
  1500. icon = pystray.Icon(
  1501. "compartment", image, "Compartment",
  1502. menu=pystray.Menu(
  1503. pystray.MenuItem("Open Compartment", from_tray(show_panel),
  1504. default=True),
  1505. pystray.MenuItem("Back up vault…", from_tray(do_backup)),
  1506. pystray.MenuItem("Lock now",
  1507. from_tray(lambda: off_ui(
  1508. lambda: states.lock(
  1509. lambda: lock_vault(vault_path)),
  1510. lambda _out: (panel.update(note=None),
  1511. refresh())))),
  1512. pystray.MenuItem("Open dashboard",
  1513. from_tray(lambda: open_dashboard(vault_path))),
  1514. pystray.Menu.SEPARATOR,
  1515. pystray.MenuItem("Quit", from_tray(quit_app)),
  1516. ))
  1517. panel["icon"] = icon
  1518. icon.run_detached()
  1519. # First launch opens the panel by itself. A tray icon nobody has seen
  1520. # before is indistinguishable from an app that failed to start, which is
  1521. # the single most expensive failure this app can have. Without an icon
  1522. # there is nothing else to look at, so the window always opens.
  1523. # Read the vault now, in the background, so the first click already has
  1524. # numbers to show.
  1525. states.refresh_async()
  1526. if show or not tray or claim_first_run(vault_path):
  1527. root.after(200, show_panel)
  1528. root.mainloop()
  1529. return 0
  1530. #: Every process on Windows with the command line that started it and the
  1531. #: sign-in session it runs in, as CSV. SessionId is last, so the first three
  1532. #: columns are where they always were.
  1533. _WINDOWS_PROCESSES = ("Get-CimInstance Win32_Process | Select-Object "
  1534. "ProcessId, ParentProcessId, CommandLine, SessionId | "
  1535. "ConvertTo-Csv -NoTypeInformation")
  1536. def _windows_session() -> str | None:
  1537. """The Windows session this process runs in (one per signed-in user,
  1538. fast user switching included), or None if it cannot be asked."""
  1539. try:
  1540. import ctypes
  1541. from ctypes import wintypes
  1542. sid = wintypes.DWORD()
  1543. if ctypes.windll.kernel32.ProcessIdToSessionId(os.getpid(),
  1544. ctypes.byref(sid)):
  1545. return str(sid.value)
  1546. except Exception: # noqa: BLE001
  1547. pass
  1548. return None
  1549. #: A Windows command line that is the panel: the CLI, then its subcommand.
  1550. _WINDOWS_APP = re.compile(r"compartment.*\s(menubar|panel|tray)(\s|$)",
  1551. re.IGNORECASE)
  1552. def running_pids() -> list[int]:
  1553. """Every other panel copy on this machine.
  1554. Windows answers from each process's command line. It used to answer with
  1555. an empty list, which is worse than not asking: every caller reads that as
  1556. "nothing is running", so the install waited fifteen seconds for an app
  1557. that was already up and then started a second one. A check that can
  1558. never succeed is not a check. Nor is one that always succeeds: by image
  1559. name, which is what tasklist went by, every console script is a
  1560. compartment.exe - each agent's MCP server, and the launcher of the very
  1561. update asking - so the app was "running" whenever any agent was. This
  1562. process and its launcher are never counted.
  1563. """
  1564. if sys.platform == "win32":
  1565. try:
  1566. out = subprocess.run(
  1567. ["powershell", "-NoProfile", "-NonInteractive", "-Command",
  1568. _WINDOWS_PROCESSES],
  1569. capture_output=True, text=True, encoding="utf-8",
  1570. errors="replace", timeout=30).stdout
  1571. except (OSError, subprocess.SubprocessError):
  1572. return []
  1573. mine, pids = {os.getpid(), os.getppid()}, []
  1574. # Only this session's. With fast user switching, a second person
  1575. # signed in on the same PC has a tray app of their own, and from an
  1576. # elevated prompt their command lines are readable too: `init` then
  1577. # took theirs as this user's app coming up, and started none.
  1578. session = _windows_session()
  1579. # Anything that is not a row - the header, a message instead of a
  1580. # table - has no pid in its first field to misread.
  1581. for row in csv.reader((out or "").splitlines()):
  1582. if (len(row) > 2 and row[0].isdigit()
  1583. and int(row[0]) not in mine
  1584. and _WINDOWS_APP.search(row[2])
  1585. and (session is None or len(row) < 4
  1586. or row[3] == session)):
  1587. pids.append(int(row[0]))
  1588. return pids
  1589. # The app's own command line and this user's processes, as on macOS:
  1590. # see menubar.APP_COMMAND.
  1591. uid = getattr(os, "getuid", None)
  1592. try:
  1593. out = subprocess.run(
  1594. ["pgrep", *(["-u", str(uid())] if uid else []), "-f",
  1595. APP_COMMAND],
  1596. capture_output=True, text=True, timeout=15).stdout
  1597. except (OSError, subprocess.SubprocessError):
  1598. return []
  1599. me = os.getpid()
  1600. pids = []
  1601. for line in out.split():
  1602. try:
  1603. pid = int(line)
  1604. except ValueError:
  1605. continue
  1606. if pid != me:
  1607. pids.append(pid)
  1608. return pids
  1609. def quit_running(vault: str | None = None, timeout: float = 10.0) -> bool:
  1610. """Stop the panel running for this vault before an update or uninstall
  1611. replaces it.
  1612. Reports whether the app actually went, not whether a signal was sent.
  1613. The caller's next move is to start the replacement, and it must not do
  1614. that while the old copy still holds the single-instance lock: the new
  1615. one would stand down and the user would be told the app had restarted
  1616. while looking at the build it was meant to replace.
  1617. """
  1618. if sys.platform == "win32":
  1619. # The one process this vault's lock names, and only while it is
  1620. # still the panel: Windows soon gives a dead process's pid to another.
  1621. # `taskkill /IM compartment.exe` also stopped every agent's MCP server
  1622. # and the launcher of the update or uninstall running this.
  1623. pid = lock_holder_pid(vault or default_vault())
  1624. if pid is None or pid not in running_pids():
  1625. return False
  1626. try:
  1627. r = subprocess.run(["taskkill", "/F", "/PID", str(pid)],
  1628. capture_output=True, timeout=30)
  1629. except (OSError, subprocess.SubprocessError):
  1630. return False
  1631. # 128 is taskkill's "no such process", which is not a failure to
  1632. # stop anything - it is nothing to stop. Anything else that is not
  1633. # zero means the copy is still there.
  1634. return r.returncode == 0
  1635. # Only the process this vault's lock names, as on macOS: signalling
  1636. # every pgrep match took an editor or a pager open on systray.py with it.
  1637. return _stop_lock_holder(vault, timeout)
  1638. __all__ = ["run", "self_check", "login_status", "set_login", "quit_running",
  1639. "running_pids", "panel_rows",
  1640. "autostart_entry_path", "install_autostart_entry",
  1641. "autostart_is_enabled", "remove_autostart_entry",
  1642. "systemd_unit_path", "systemd_unit_text", "systemd_available",
  1643. "graphical_session_active",
  1644. "systemd_enabled", "install_systemd_unit", "remove_systemd_unit",
  1645. "scheduled_task_xml", "install_scheduled_task",
  1646. "remove_scheduled_task", "scheduled_task_registered",
  1647. "start_supervised", "restart_supervised",
  1648. "hand_over_to_supervisor",
  1649. "icon_path"]

Ratings and comments

Sign in to rate this skill.

Sign in

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