SLOPSHOPPER

Cognee Memory

Cognee knowledge graph memory for Claude Code — session-aware storage, auto-routing recall, and persistent learning across sessions. Supports local mode and…

panebandspinnerrowsguardcommand
★ 101v1.7.4Apache-2.0updated 2026-10-26topoteretes/cognee-integrations/integrations/claude-code
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cognee-memory
│ ┃ cognee-fix ✕ › fix the failing auth test and add an audit log call │ ┃ ✕ Memory reported a problem │ ┃ reason: unknown ⏺ Read(src/auth.ts) │ ┃ The row shows a reason the plugin recorded; ⎿ Read 6 lines │ ┃ the doctor report below has the details. ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ 1. Run doctor below. ⏺ Bash(bun test) │ ┃ 2. A new session re-checks everything. ⎿ 3 pass, 1 fail │ ┃ │ ┃ [ run doctor ] close ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /cognee-dataset │ ⎿ cognee-memory: Cognee: no datasets listed (is memory connected?) │ │ ✻ Thinking · saving…… ⠋ cognee memory · … · saving… The dataset name ↑ is a picker: pick another dataset, or "+ new dataset…" to create one [ next ] skip ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⠋ cognee memory · … · saving… The dataset name ↑ is a picker: pick another dataset, or "+ new dataset…" to create one [ next ] sk ⟨Claude Code's own drawing⟩
Pane · cognee-fix
✕ Memory reported a problem reason: unknown The row shows a reason the plugin recorded; the doctor report below has the details. 1. Run doctor below. 2. A new session re-checks everything. [ run doctor ] close
README

<a href="https://www.cognee.ai"> <img src="https://raw.githubusercontent.com/topoteretes/cognee-integrations/main/assets/cognee-logo.svg" alt="Cognee" width="260"> </a> <a href="https://docs.cognee.ai">Docs</a> · <a href="https://discord.gg/NQPKmU5CCg">Discord</a> · <a href="https://github.com/topoteretes/cognee">Cognee core</a>

Cognee Memory Plugin for Claude Code

Adds persistent memory to Claude Code through Cognee.

The integration:

  • captures prompts, tool traces, and assistant responses into session memory
  • injects relevant context on prompt submit
  • syncs session memory into graph memory on session end/final exit

What this plugin runs, stores and sends

Everything below is the plugin's own readable Python and shell under this folder; it runs no code from anywhere else.

Captured. Your prompts, the tool calls Claude makes (name, arguments and output, filtered by the capture controls), and Claude's answers, plus a short memory anchor before compaction. Credentials, private keys and database URLs are redacted before anything is stored or uploaded, and .env, credential and key files are never captured. COGNEE_CAPTURE=false turns automatic capture off; recall and explicit remember keep working.

Where it goes. To the Cognee server you configure, and nowhere else.

  • Local mode (default): a cognee server the plugin starts on this machine, bound to localhost:8011. Memory is stored on this machine. To build the graph, that server sends captured text to the LLM and embedding provider you configured (LLM_API_KEY, LLM_PROVIDER), or to Claude Code through the observer below.
  • Cloud mode: your Cognee Cloud instance at COGNEE_BASE_URL, over HTTPS, authenticated with your COGNEE_API_KEY. The status line's credit balance comes from the Cognee platform API (api.aws.cognee.ai).

Memory is kept until you delete it (the cognee-forget skill, or deleting the dataset). The plugin never expires server-side memory on its own.

Other network calls. Local mode installs cognee==1.6.5 from PyPI into ~/.cognee-plugin/venv once. The background idle watcher fetches this repository's marketplace.json from raw.githubusercontent.com at most hourly to offer updates (COGNEE_UPDATE_CHECK=off). No telemetry, no analytics: nothing is sent to Anthropic, Cognee or any third party beyond the calls above.

Claude settings. In cloud mode the plugin disables native auto-memory unless you explicitly enabled it, keeping an ownership marker and previous value for restoration. Set COGNEE_DISABLE_AUTO_MEMORY=false to opt out. Existing memory files are retained. See Memory preference.

Stored locally. ~/.cognee-plugin/claude-code/ (logs, status markers, buffered turns, swept automatically; see Logs and state), ~/.cognee-plugin/venv/, ~/.cognee-plugin/api_key.json, and your settings in ~/.cognee/.env.

Settings it writes. One entry, and only where it is needed: in a session whose status row the hooks module draws above the prompt, nothing is written; in a session where the module does not load (an older Claude Code, --safe-mode, an organisation that allows only its own mods), session start installs the statusLine entry in ~/.claude/settings.json that draws the line below the prompt, and refreshes it when the plugin moved. Only an entry whose command runs the plugin's own cognee-statusline.sh is ever written or replaced; a status line you set yourself is never touched. Nothing else in your Claude Code settings is touched.

Claude's own files. The plugin reads the hook payloads Claude Code sends it, not your transcript or Claude Code's memory files, and writes to neither.

Code that runs inside Claude Code. hooks/register.ts is a hooks module (a Claude Code mod) that draws the memory status row above the prompt (in a terminal and in the Desktop app), shows what memory is doing while it works, makes the dataset name a picker and serves two tools Claude can call directly. On its own it reads one file, the plugin's own activity marker under ~/.cognee-plugin/claude-code/phase/, writes one, band/<session>.json, which tells the settings-file status line to stay quiet for that session, and runs one program, the plugin's own status-line renderer (scripts/cognee_statusline_render.py --json, local, no network), on the events the hooks fire. On your explicit action in the fix dialog it also runs cognee-doctor.sh (read-only diagnostics) and appends a value you typed to ~/.cognee/.env. Everything else it runs is one of this folder's scripts, on your action or Claude's: switch-dataset.py --list once when the band is first drawn and switch-dataset.py <name> when you pick a dataset or run /cognee-dataset <name>; the search tool runs cognee-search.sh (and recall-trim.py on its output); the remember tool runs cognee-remember.sh. Those are the same programs the skills run, with the same server traffic. The module itself makes no network requests, writes no settings, reads only HOME / USERPROFILE from the environment, and answers only its own two tools. claude plugin validate lists exactly that.

Background processes. Detached helpers that outlive a hook: the idle watcher and exit watcher (session sync and status), and in local mode the cognee server and, when enabled, the Claude observer shim. All are scripts from this folder.

Credentials it reads. COGNEE_API_KEY, COGNEE_BASE_URL and LLM_API_KEY from ~/.cognee/.env or the environment. The API key goes only to the Cognee server you configured; the LLM key only to the local server's process.

Your Claude subscription. In local mode with no LLM_API_KEY set and the claude CLI on PATH, the server's own LLM calls (cognify, improve) run as claude -p --safe-mode under your Claude Code login and count against your subscription usage. Your login is passed only to that child process, never to any server. Session start says so every time it is in use; COGNEE_LLM_OBSERVER=false turns it off. Details under Claude observer.

Install

Requirements. Any Python 3.9 or newer available as python3 (or python) on PATH runs the hooks — they are stdlib-only HTTP clients and never import cognee, so the Python 3.9.6 that ships with macOS's Xcode Command Line Tools is enough for them. Local mode additionally needs a Python 3.10–3.14 installed on the machine (python.org, Homebrew, pyenv, or uv python install 3.12): the plugin builds its own virtualenv for the Cognee server under ~/.cognee-plugin/venv from an interpreter it finds, and installs exactly cognee==<pinned version> into it. The plugin never downloads installers or interpreters — it uses uv if you already have it (with interpreter downloads disabled), otherwise the stdlib venv + pip with the newest python3.x it finds on PATH. If no 3.10+ interpreter exists it refuses, logs host_python_too_old_for_venv to hook.log, and every session start says so until one is installed. Cloud mode never builds a runtime. Claude Code: the memory pipeline (hooks, skills, recall, sync) runs on any Claude Code that reads plugin userConfig; the live status row, spinner text and the two memory tools come from the hooks module and need Claude Code 2.1.287 or newer (2.1.286 in the Desktop app), see Status line. (SDK-based integrations such as LangGraph or CrewAI import cognee in-process and need Python 3.10+; see CONFIGURATION.md.)

If local mode refuses to start. A session that opens with "Cognee requires Python 3.10 or newer (up to 3.14), and no such interpreter is installed on this machine" means exactly that: the hooks ran (they only need 3.9), but the Cognee server has nothing to run on, and the plugin will not download an interpreter. The status line shows ✕ (cognee_needs_python_3_10) and doctor.py reports Runtime Python: MISSING until you install one (brew install python@3.12, python.org, pyenv, or uv python install 3.12) and start a new session — nothing else to configure. Cloud mode has no such requirement.

Install from the Claude Code marketplace. The recommended way is from your shell, before launching Claude Code, so the first claude launch is a clean session that runs the plugin bootstrap automatically — no in-app restart needed:

claude plugin marketplace add topoteretes/cognee-integrations
claude plugin install cognee-memory@cognee

These CLI subcommands use the exact same plugin manager as the in-chat /plugin commands — same marketplace clone, same install cache, same global state — they just run before you enter the terminal. Default install scope is user (global); pass --scope project or --scope local to confine it.

Then configure your runtime mode — once — in ~/.cognee/.env. The file is created with a commented template on the first session start; values in it act exactly like shell exports (a real export in your shell still overrides the file, per terminal). It is shared with the Codex plugin, so both read the same configuration. Lines may optionally start with export , so existing export lines can be pasted verbatim. Pick one of the two modes below — or configure both and flip a terminal with a single export (see Which mode wins, and how to switch).

Cognee Cloud or a remote server — set both (one paste, no editor needed):

mkdir -p ~/.cognee
cat >> ~/.cognee/.env <<'EOF'
COGNEE_BASE_URL="https://your-instance.cognee.ai"
COGNEE_API_KEY="ck_..."
EOF
chmod 600 ~/.cognee/.env

The plugin is an HTTP client in both modes; the hooks never import cognee in-process. Cloud mode does not install a local Cognee runtime. The bundled virtualenv (~/.cognee-plugin/venv) is built only in local mode, where it runs the local Cognee server the hooks talk to.

Local mode (default when COGNEE_BASE_URL is not set) — the plugin bootstraps a local Cognee API at http://localhost:8011. COGNEE_API_KEY is auto-minted if absent. The server needs an LLM for cognify: either give it a provider key of your own —

mkdir -p ~/.cognee
cat >> ~/.cognee/.env <<'EOF'
LLM_API_KEY="sk-..."
EOF
chmod 600 ~/.cognee/.env

— or set nothing at all and let it run on your Claude subscription: with no LLM_API_KEY configured and the claude CLI on PATH, session start switches the local server's LLM calls to the Claude observer (claude -p behind a loopback OpenAI-compatible shim) and embeddings to a local model. No key, no extra account.

Default user and its password. The local server is started with DEFAULT_USER_EMAIL=default_user@example.com and DEFAULT_USER_PASSWORD=default_password, which is how cognee 1.6.0 and later create the default user at all (a server started without DEFAULT_USER_PASSWORD creates no default account, and the password is set once and never rewritten). The plugin logs in as that user to mint its owner API key, so a fresh install needs no manual step and an existing install keeps working. Exporting DEFAULT_USER_EMAIL/DEFAULT_USER_PASSWORD yourself overrides what the plugin passes; COGNEE_USER_EMAIL/COGNEE_USER_PASSWORD pick the user the plugin logs in as, and a non-default user must already exist on the server. When pointing at a server you run yourself (COGNEE_BASE_URL), either start it with DEFAULT_USER_PASSWORD set to the same value as COGNEE_USER_PASSWORD, or set COGNEE_API_KEY so no login is needed; a server without either answers the login with an error that says so.

Windows (PowerShell) — same idea, same file:

New-Item -ItemType Directory -Force "$env:USERPROFILE\.cognee" | Out-Null
@'
COGNEE_BASE_URL="https://your-instance.cognee.ai"
COGNEE_API_KEY="ck_..."
'@ | Add-Content "$env:USERPROFILE\.cognee\.env"

Re-running any of these blocks is safe: when a key appears more than once, the last value wins, so pasting again with a new value updates the configuration. Editing the file directly (nano ~/.cognee/.env) works too. Changes apply on the next session launch. Plain shell exports in the launching terminal still take precedence over ~/.cognee/.env — useful to override the shared config for one terminal. See Managing the env file for the file format and how to add, change, or remove variables later.

Which mode wins, and how to switch

You can configure both modes at once — keep COGNEE_BASE_URL + COGNEE_API_KEY and LLM_API_KEY in the file together. The mode is then decided per terminal, by three rules in order:

  1. A COGNEE_BACKEND export wins. export COGNEE_BACKEND=local (or =cloud) pins that terminal to that mode. Nothing else needs to change.
  2. Otherwise, cloud wins when configured. If COGNEE_BASE_URL is set (in the file or the shell), the plugin connects to it.
  3. Otherwise, local. With no URL anywhere, the plugin boots the local server.

So with both modes in ~/.cognee/.env:

claude                          # → cloud (the configured URL routes)
COGNEE_BACKEND=local claude     # → local, this launch only
export COGNEE_BACKEND=local     # → local for every launch from this shell

Details worth knowing:

  • The switch is pinned. COGNEE_BACKEND=cloud with no COGNEE_BASE_URL configured still counts as cloud: the plugin does not silently fall back to local, and the status line shows ✕ (missing_cognee_base_url) so you know exactly what to fix.
  • To go local, use the switch — not unset COGNEE_BASE_URL. Unsetting doesn't work: the env file re-injects the URL at the next launch. (Deleting the line from the file works, but that changes the default for every terminal.)
  • The shared COGNEE_BACKEND flips both the Claude Code and Codex plugins in that terminal. To flip only one, use COGNEE_CLAUDE_BACKEND / COGNEE_CODEX_BACKEND — the plugin-specific name beats the shared one.
  • Accepted values: local (aliases: native, sdk) and cloud (aliases: http, api, server). Anything else is ignored.
  • COGNEE_BACKEND can also live in ~/.cognee/.env to make a mode the durable default; a shell export still overrides it per terminal.
  • Not sure what a terminal resolved? The status line's mode field shows it live, and doctor.py prints the decision with its cause, e.g. Mode: Local — forced by COGNEE_BACKEND=local.

Then launch claude. All setup happens in the SessionStart hook, which fires once per fresh launch — so with the shell install above, the first launch connects memory with no extra steps.

If you instead installed from inside the chat with the /plugin slash commands, you must restart Claude Code (start a new session) before memory connects: /reload-plugins makes the skills and agents available in the current session but does not run SessionStart. On a first-run marketplace install the marketplace is also fetched asynchronously, so SessionStart may not fire that session even with a reload. Either way, make sure your configuration is in ~/.cognee/.env (or exported in the shell you launch from).

On startup you should see a "Cognee Memory Connected" system message.

Auth

The integration authenticates with one principal (one API key, one user), and — on servers that support it — a plugin identity derived from that principal: a dedicated agent sub-user with its own labeled API key, provisioned via POST /api/v1/integrations/plugins/claude-code/provision. Running under a plugin identity lets the cognee dashboard attribute sessions, traces and datasets to this plugin; datasets the plugin creates are automatically shared with your user.

Key resolution order for data-plane traffic:

  1. ~/.cognee-plugin/claude-code/agent_key.json (the provisioned plugin identity)
  2. COGNEE_API_KEY env var
  3. ~/.cognee-plugin/api_key.json (cached from a previous mint)
  4. Auto-mint from the default local user (local mode only), then cache to api_key.json

Provisioning policy:

  • COGNEE_PLUGIN_IDENTITY selects the identity policy:
  • auto (default) — an identity in service of shared agent memory (below). When shared memory is on, session start provisions one (create-only, never rotating a key another machine holds), wires the shared role, and pins the canonical dataset; if that wiring cannot be done (older server, not the tenant owner, tenant-less user who already owns data) the plugin stays on the principal key and says why in cognee-doctor. With shared memory off it stays on the principal.
  • true — explicit identity: provisioning is required and never falls back to the owner. Servers without the SDK's create_only capability, a cached credential bound to another principal, or rejected credentials stop with an error instead of rotating keys or silently using the owner's authority.
  • false — principal mode; a cached identity is ignored.
  • A cached credential is bound to its server and principal. Under auto, a credential the server rejected or that belongs to another account is not used and the plugin runs as the principal (logged); under true that is an error, and reconnecting a revoked identity requires explicit reconnection.
  • Use dataset UUIDs for shared write targets. Dataset switching checks effective write permissions. Set COGNEE_PLUGIN_READ_DATASET_IDS to a JSON array of allowed UUIDs for graph recall across datasets you granted yourself; it takes precedence over the datasets shared memory resolved, and session history stays scoped to its own dataset.

Shared agent memory

A plugin identity is its own cognee user, and grants only flow child→parent: your user sees what the agent writes, but the agent sees nothing your user (or another plugin's agent) owns. Left alone, that would silo memory per plugin — Claude Code could not recall what Codex stored. Shared agent memory, on by default, makes every plugin agent of your user share one memory:

  • Session start ensures your user owns a tenant (one is created for a fresh, tenant-less install) and a cognee-agent role in it, adds the agent to both, and grants the role read+write on your datasets. Grants are backfilled on every session start and every ~60 s by the idle watcher, so a dataset another plugin creates becomes visible here without a restart.
  • The launch's dataset is a canonical, user-owned dataset addressed by UUID (the launch record's dataset_id for writes, dataset_ids for recall — including any same-named per-agent copies from before). Every hook and skill addresses it that way; a plain name would only resolve among datasets the agent itself owns.
  • All tenant/role/grant calls run as your user, never as the agent — the server only lets the tenant owner manage roles, so an agent key cannot widen its own access.

Turn it off with "shared_agent_memory": false in config.json or COGNEE_SHARED_AGENT_MEMORY=false for separated, per-plugin memory (name-addressed, agent-owned datasets). Opting out removes the agent from the shared role — it can no longer read or write your datasets — and starts it on a private dataset; it does not move data, so what it shared before stays in your user's dataset. Re-enabling puts the agent back into the same role and dataset. cognee-doctor shows the current state under Memory Sharing.

How the two settings combine

COGNEE_PLUGIN_IDENTITY decides who the plugin authenticates as, and how strictly; COGNEE_SHARED_AGENT_MEMORY decides what an agent identity can see. Sharing is a property of agent identities — your own user sees everything regardless — so the second setting only matters once an identity exists.

COGNEE_PLUGIN_IDENTITY \ COGNEE_SHARED_AGENT_MEMORYtrue (default)false
auto (default)Shared memory, graceful. Provisions an identity when the server allows it, wires the shared role, and falls back to your principal key whenever that cannot be done.Principal, unless already provisioned. A fresh install never provisions (auto provisions only in service of sharing). An identity provisioned earlier is kept, leaves the shared role, and writes to its own private dataset.
trueShared memory, strict. Same wiring; any obstacle (no create_only support, a credential bound to another principal, a rejected key) is an error — never a silent fall back to the owner's key.Separated identities, strict. Each plugin is its own agent with its own private memory, blind to your other datasets. This is the isolation mode: a leaked or revoked plugin key affects only that plugin.
falsePrincipal only. The sharing setting has no effect.Principal only. Identical to the cell above.

Practical reading: leave both at their defaults for one memory across all of your plugins; set COGNEE_PLUGIN_IDENTITY=true when you want the strict guarantees; add COGNEE_SHARED_AGENT_MEMORY=false to that for fully separated per-plugin memory. Setting COGNEE_PLUGIN_IDENTITY=false makes the sharing setting irrelevant. cognee-doctor reports the resulting state under API Key Source and Memory Sharing.

Mode selection rules

At startup (SessionStart):

  • COGNEE_BACKEND (or COGNEE_CLAUDE_BACKEND) exported → that mode, pinned — see Which mode wins
  • otherwise COGNEE_BASE_URL set → managed_endpoint, either local, or on Cognee Cloud (API key needed in cloud case)
  • otherwise → integration_local (local API bootstrap)

A forced-local switch also scrubs COGNEE_BASE_URL/COGNEE_API_KEY from the process environment, so the per-prompt recall/remember calls and every spawned worker resolve the same local endpoint — not just SessionStart. A forced-cloud switch with no URL configured never boots the local server; the connection attempt fails visibly instead (status line + doctor).

Self-hosted deployments on loopback: when the configured URL is a loopback address (127.0.0.1, localhost) and the server is down at session start, the plugin normally boots its embedded local server on that port. If the URL actually belongs to an externally managed deployment (docker compose stack, systemd service), set COGNEE_MANAGED_ENDPOINT=true: an outage then makes SessionStart report Cognee Memory OFFLINE loudly instead of silently booting an unrelated fallback instance over the deployment's port.

At hook runtime:

  • hooks resolve the endpoint through runtime endpoint auth (env + api_key.json), not only config intent
  • every hook talks to that endpoint over HTTP; there is no in-process (SDK) fallback

The hooks emit mode_decision logs with mode (always http), service_url, url_source, key_source, api_key_present.

Sessions

Each terminal launch maintains a small map file:

~/.cognee-plugin/claude-code/sessions/<host_session_id>.json
  → { "conn_uuid": "...", "session_id": "...", "host_key": "..." }
  • session_id — which Cognee session this terminal writes to and recalls from. Fixed at launch.
  • conn_uuid — per-launch liveness handle used for agent registration and server shutdown counting.

By default a new session_id is generated each launch. Set COGNEE_SESSION_ID to resume a specific session:

export COGNEE_SESSION_ID="my-project"

Two terminals can deliberately share a session by sett

Source 1 files
hooks/register.ts 1427 lines
1// Cognee memory: the in-process layer of the plugin.
2//
3// The settings hooks in hooks.json run the memory pipeline (recall, capture,
4// learning from the session, sync) exactly as before. This module adds what
5// only an in-process module can:
6//
7//   * the status row, above the prompt on every surface: it runs the plugin's
8//     own status-line renderer in `--json` mode and lays the result out, so
9//     the band shows the row the settings-file status line shows (the badge
10//     included). In a
11//     terminal the module marks its session (`band/<session>.json`) and the
12//     renderer then prints nothing for it, so the row is never drawn twice;
13//     with the `band` option off the settings status line is back below;
14//   * live activity: it reads the per-session marker the hooks write
15//     (`~/.cognee-plugin/claude-code/phase/<session>.json`) and shows it on
16//     the row and after the spinner (the answer's own credit line is the
17//     agent's, from the recall hook's instruction);
18//   * the dataset name on the row is a picker: choosing another writable
19//     dataset, or typing the name of a new one, switches the session there
20//     without a model turn (`/cognee-dataset <name>` does the same from the
21//     prompt);
22//   * a `see fix` button beside a red ✕ on the row: a dialog pane that says what
23//     is wrong in plain words and how to fix it, runs the plugin's doctor, and
24//     for a key or URL problem takes the value and writes it to ~/.cognee/.env;
25//   * a first-run tour: three dim hint lines under the row, each about the
26//     thing above it, shown once per machine (the plugin's store remembers)
27//     and again on `/cognee-tour`;
28//   * two tools the model calls directly, `mcp__cognee-memory__search` and
29//     `mcp__cognee-memory__remember`, served by the plugin's own shell
30//     wrappers: no skill file to read, no Bash row, structured arguments.
31//
32// Everything the module runs is one of the plugin's own scripts, as a local
33// process; the only network traffic is theirs, on the person's or the model's
34// explicit action, plus one listing of the writable datasets for the picker. Nothing here runs on a fixed timer while the session is
35// idle: the marker is read on the events the hooks fire, and polled once a
36// second only while an operation is running or for a short window after one
37// was started.
38//
39// Only native events are hooked (prompt.submit, tool.call, turn.complete,
40// session.compact, session.start, session.end), never the classic.* mirrors
41// of the settings hooks: the built-in guard bypasses a user-installed mod's
42// classic.* hooks for Team and Enterprise sign-ins and wherever managed
43// settings exist, so nothing here would run for those users.
44import type { Register, RenderElement } from 'claude-code'
45
46type Activity = { kind: 'active' | 'result'; phase: string; text: string; age: number; ok: boolean; count?: number }
47
48type Snapshot = {
49  enabled: boolean
50  state: string
51  reason: string
52  dataset: string
53  mode: string
54  credits: string
55  credits_exhausted?: boolean
56  billing_url?: string
57  update: string
58  text: string
59}
60
61// The brand lavender (#BC9BFF), a deeper violet on a light theme so it keeps
62// its contrast on white.
63const PURPLE_DARK = '#bc9bff'
64const PURPLE_LIGHT = '#7c4dff'
65
66type PhaseResult = { count?: unknown; at?: unknown; ok?: unknown; buffered?: unknown }
67type PhaseMarker = {
68  active?: { phase?: unknown; detail?: unknown; updated_at?: unknown } | null
69  results?: Record<string, PhaseResult>
70}
71
72const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
73const FRAME_MS = 120
74const POLL_MS = 1000
75// How long after a hook fired the marker keeps being polled for the async
76// work (saving, learning from the session) that hook started.
77const POLL_WINDOW_MS = 30_000
78// After a session start the connection marker lands when the SessionStart
79// hook finishes, which can be well after the module's first snapshot. While
80// the row still says "unknown", the snapshot is retaken every few seconds for
81// this long, then left to the next prompt.
82const WARMUP_MS = 120_000
83const WARMUP_RETRY_TICKS = 5
84// Mirrors the renderer: an active phase older than this is a hook that died.
85const STALE_MS = 90_000
86const DIM_AFTER_MS = 60_000
87// A result older than this is no longer news: it leaves the row.
88const HIDE_AFTER_MS = 300_000
89const RENDERER_TIMEOUT_MS = 5000
90const RENDERER_RETRY_MS = 60_000
91// Phases whose settings hook runs async, so the terminal spinner shows no
92// statusMessage for them; the mod adds its own suffix there. The sync hooks
93// (recall, anchor, session start) already announce themselves in a terminal.
94const ASYNC_PHASES = ['saving', 'consolidating', 'indexing', 'syncing']
95
96const ACTIVE_LABELS = {
97  connecting: 'connecting…',
98  setting_up: 'setting up memory',
99  recalling: 'recalling…',
100  saving: 'saving…',
101  consolidating: 'learning from this session…',
102  indexing: 'indexing repository…',
103  anchoring: 'preserving context…',
104  syncing: 'saving session…',
105  // The module's own work, never written to the marker.
106  searching: 'searching memory…',
107  remembering: 'remembering…',
108  switching: 'switching dataset…',
109} as const
110type Phase = keyof typeof ACTIVE_LABELS
111// What the module runs itself shows after a terminal spinner too: the tool row
112// there says only which tool runs.
113const OWN_PHASES = ['searching', 'remembering', 'switching']
114// How a call to each of the plugin's tools is labelled in the transcript.
115const TOOL_ROW_LABELS: Record<string, string> = {
116  'mcp__cognee-memory__search': 'Cognee search',
117  'mcp__cognee-memory__remember': 'Cognee remember',
118}
119
120const SEARCH_TIMEOUT_MS = 60_000
121// Above the wrapper's own worst case (a 120 s POST, an 8 s wait for the
122// cognify to become queryable, the interpreter's start), so the module never
123// cuts off a write that is still in flight and then calls it not stored.
124const REMEMBER_TIMEOUT_MS = 150_000
125// What the remember tool takes in one call. Each call runs a cognify on the
126// tenant's key (an LLM pass per chunk plus embeddings), and a typed tool
127// whose description invites a whole file lowers the bar for a large one.
128// Past these the call is refused with a pointer to the cognee-remember
129// skill, which has no cap.
130const REMEMBER_MAX_CHARS = 16_000
131const REMEMBER_MAX_FILE_BYTES = 64_000
132// And per session: each call is a paid cognify, and nothing else bounds how
133// many the model makes. Past either the call is refused with a pointer to the
134// skill, which has no allowance, so a person who wants more is never stopped.
135const REMEMBER_SESSION_CALLS = 5
136const REMEMBER_SESSION_BYTES = 64_000
137let rememberCalls = 0
138let rememberBytes = 0
139const LIST_TIMEOUT_MS = 20_000
140// A switch syncs the session it leaves first; that can take minutes.
141const SWITCH_TIMEOUT_MS = 600_000
142const NODE_SETS: Record<string, string> = {
143  user: 'user_context',
144  project: 'project_docs',
145  agent: 'agent_actions',
146}
147
148// ── module state (reset on a reload, which is fine: it is all redrawn) ──────
149let sessionId = ''
150let phasePath = ''
151let bandPath = ''
152let rendererPython: string | null = null
153let rendererFailures = 0
154// When the renderer last failed for the third time: the cutoff below expires
155// after RENDERER_RETRY_MS, so a slow start does not freeze the row for good.
156let rendererFailedAt = 0
157let snapshotInFlight = false
158let snapshot: Snapshot | null = null
159let active: Activity | null = null
160let result: Activity | null = null
161// When the shown activity was set, and whether the marker itself says one is
162// running: a 'saving' the Stop hook announced but nothing ever reported (a
163// cloud capture the worker could not deliver, no marker at all) expires
164// after the marker's own stale window instead of spinning for the session.
165let activeSince = 0
166let markerActive = false
167let frame = 0
168let spin: { cancel: () => void } | null = null
169let poll: { cancel: () => void } | null = null
170let pollUntil = 0
171let pollTicks = 0
172let warmupUntil = 0
173// The mark: cognee's waveform icon, drawn only where it can be drawn as
174// itself, the official SVG on the desktop row, read from the plugin's assets
175// at session start. Text gets no stand-in: no glyph in a terminal, nothing
176// after the spinner or in toasts (a character never looks like the mark).
177// The terminal's credit line draws the display logotype instead (LOGOTYPE).
178let markOn = true
179let waveSvg = ''
180let purple = PURPLE_DARK
181let bandOn = true
182let spinnerOn = true
183let toolsOn = true
184
185// The dataset picker on the band.
186type DatasetRow = { name: string; id: string; current: boolean }
187let switchTargets: DatasetRow[] = []
188let switching = false
189// The picker's last entry: picking it turns the picker into a text field for
190// a dataset that does not exist yet (the switch script creates it). Spaces
191// make the value one no dataset can be named, so it never collides.
192const NEW_DATASET = '+ new dataset…'
193let namingDataset = false
194// In a terminal the picker stays closed until asked for: a click anywhere on
195// the band gives the band the keys, and a focused picker shows its list.
196let pickerOpen = false
197
198// The first-run tour: one hint line under the row per step, about what is
199// right above it. Shown once per machine (the store key survives sessions);
200// bump TOUR_VERSION to show a rewritten tour once more. -1 is "not showing".
201const TOUR_VERSION = 1
202const TOUR_STEPS = [
203  'The dataset name ↑ is a picker: pick another dataset, or "+ new dataset…" to create one',
204  '↑ ● means memory is connected · local/cloud shows you where your memory lives · the end of the row says what memory is doing',
205  'Claude uses memories recalled by Cognee on every prompt · type /cognee (no Enter) to see its commands · /cognee-tour replays this tutorial',
206]
207let tourOn = true
208let tourStep = -1
209let tourChecked = false
210
211// The fix dialog: what the row's reason means and what to do about it. Each
212// guide is plain words first, then steps; `field` names the env-file variable
213// the pane takes a value for, when one value is the fix.
214const FIX_PANE = 'cognee-fix'
215const DOCTOR_TIMEOUT_MS = 30_000
216type FixGuide = { title: string; what: string; steps: string[]; field?: { name: string; placeholder: string } }
217const FIX_GUIDES: Record<string, FixGuide> = {
218  incorrect_cognee_api_key: {
219    title: 'The memory server rejected the plugin\'s API key',
220    what: 'The key this plugin sends to the Cognee server (`COGNEE_API_KEY`) is missing, wrong or expired, so nothing can be recalled or saved.',
221    steps: [
222      '**Cloud:** paste the API key from your Cognee Cloud account below, or put `COGNEE_API_KEY=ck_…` in `~/.cognee/.env`. A key exported in your shell wins over the file.',
223      '**Local:** delete `~/.cognee-plugin/api_key.json` and start a new session; the plugin mints a fresh key from the local server.',
224      'With a plugin identity (`COGNEE_PLUGIN_IDENTITY`), **run doctor** below: it says whether the cached identity credential was the one rejected.',
225      'A new prompt tries the new key; a new session applies it everywhere.',
226    ],
227    field: { name: 'COGNEE_API_KEY', placeholder: 'ck_… (saved to ~/.cognee/.env)' },
228  },
229  incorrect_llm_api_key: {
230    title: 'The local server cannot reach its LLM',
231    what: 'The Cognee server on this machine builds memory with an LLM, and the key it uses (`LLM_API_KEY`) is missing or the provider rejected it. The server itself is fine.',
232    steps: [
233      'Paste a working provider key below, or put `LLM_API_KEY=…` (and `LLM_PROVIDER` if not OpenAI) in `~/.cognee/.env`.',
234      'Or use your Claude subscription instead: remove `LLM_API_KEY` from `~/.cognee/.env` and keep the `claude` CLI on PATH; the next session routes the server\'s LLM calls through it.',
235      'Start a new session: the server reads its key at start.',
236    ],
237    field: { name: 'LLM_API_KEY', placeholder: 'sk-… (saved to ~/.cognee/.env)' },
238  },
239  missing_cognee_base_url: {
240    title: 'Cloud mode is forced, but no server URL is configured',
241    what: '`COGNEE_BACKEND=cloud` is exported in this shell, and no `COGNEE_BASE_URL` is set anywhere, so there is no server to talk to.',
242    steps: [
243      'Paste your Cognee Cloud URL below (it is saved as `COGNEE_BASE_URL` in `~/.cognee/.env`), and make sure `COGNEE_API_KEY` is set too.',
244      'Or go local for this terminal: `unset COGNEE_BACKEND`, then start a new session.',
245    ],
246    field: { name: 'COGNEE_BASE_URL', placeholder: 'https://your-instance.cognee.ai' },
247  },
248  cognee_needs_python_3_10: {
249    title: 'Local mode needs a Python the server can run on',
250    what: 'The hooks run on any Python 3.9+, but the Cognee server itself needs Python 3.10 to 3.14, and none was found on this machine. The plugin never downloads one.',
251    steps: [
252      'Install one: `brew install python@3.12`, `uv python install 3.12`, pyenv, or python.org.',
253      'Start a new session: the plugin builds its runtime under `~/.cognee-plugin/venv` and starts the server.',
254      'Or use Cognee Cloud instead, which needs no local Python: set `COGNEE_BASE_URL` and `COGNEE_API_KEY` in `~/.cognee/.env`.',
255    ],
256  },
257  unreachable: {
258    title: 'The memory server cannot be reached',
259    what: 'Connections are refused or the host does not resolve. In local mode the server process is not running (it may have died); in cloud mode the URL is wrong or the network is in the way.',
260    steps: [
261      '**Local:** start a new session; the plugin starts the server again. If it keeps failing, `~/.cognee-plugin/claude-code/hook.log` says why.',
262      '**Cloud:** check `COGNEE_BASE_URL` in `~/.cognee/.env` (or your shell), then your network or VPN.',
263      '**Run doctor** below: it shows the URL in use, the mode and the health check.',
264      'The dot turns green again on the next successful recall.',
265    ],
266  },
267  server_error: {
268    title: 'The memory server is answering with errors',
269    what: 'The server is up but replied with a server error (HTTP 5xx) to the last requests. Memory is not read or written until it recovers.',
270    steps: [
271      '**Run doctor** below for the health check and the server version.',
272      '**Local:** start a new session to restart the server; `~/.cognee-plugin/claude-code/hook.log` holds the error.',
273      '**Cloud:** retry in a moment; if it persists, the error belongs to the Cognee team.',
274    ],
275  },
276  not_responding: {
277    title: 'The memory server is not answering in time',
278    what: 'The server accepts connections but several recalls in a row timed out. It is usually busy (a large memory build) rather than down.',
279    steps: [
280      'Wait a little and send another prompt; a single answer in time clears the mark.',
281      'On a slow or loaded server, raise the per-prompt budget: `COGNEE_READY_PROBE_TIMEOUT=6` in `~/.cognee/.env`.',
282      '**Run doctor** below to see whether the health check answers at all.',
283    ],
284  },
285}
286const FIX_FALLBACK: FixGuide = {
287  title: 'Memory reported a problem',
288  what: 'The row shows a reason the plugin recorded; the doctor report below has the details.',
289  steps: ['**Run doctor** below.', 'A new session re-checks everything.'],
290}
291let fixReason = ''
292let fixOpen = false
293let doctorOutput = ''
294let doctorRunning = false
295let fixNote: { text: string; isError: boolean } | null = null
296// One listing per session, refreshed after a switch or by the pane's refresh.
297let datasetsListed = false
298let datasetsListing = false
299
300// ── pure helpers ────────────────────────────────────────────────────────────
301function plural(n: number, word: string): string {
302  if (n === 1) return `${n} ${word}`
303  return `${n} ${word.endsWith('y') ? word.slice(0, -1) + 'ies' : word + 's'}`
304}
305
306function toNumber(value: unknown): number | null {
307  const n = typeof value === 'number' ? value : Number(value)
308  return Number.isFinite(n) ? n : null
309}
310
311function activeLabel(phase: string, detail: string): string {
312  const label = (ACTIVE_LABELS as Record<string, string>)[phase] ?? ''
313  if (!label) return ''
314  if (phase === 'setting_up') return detail ? `${label} · ${detail}…` : `${label}…`
315  return label
316}
317
318// At rest: a number only for recall (what helped this turn), a ticked verb
319// for everything that keeps work. Mirrors the renderer's _result_label.
320function resultLabel(kind: string, entry: PhaseResult): string {
321  const ok = entry.ok !== false
322  const count = toNumber(entry.count)
323  switch (kind) {
324    case 'recalled':
325      if (!ok) return 'recall failed'
326      if (!count) return 'nothing relevant'
327      return `${plural(count, 'memory')} used`
328    case 'saved':
329      if (ok || count) return '✓ memory saved'
330      // Nothing landed this turn: spooled for replay, or dropped for good.
331      return entry.buffered === true ? 'save queued' : 'save failed'
332    case 'ready':
333      return ok ? 'memory ready' : 'memory unavailable'
334    case 'consolidated':
335      return ok ? '✓ learned' : 'learning failed'
336    case 'indexed':
337      return ok ? '✓ repository indexed' : 'indexing failed'
338    case 'anchored':
339      return ok ? '✓ context kept' : 'context not kept'
340    case 'synced':
341      return ok ? '✓ session saved' : 'session sync failed'
342    default:
343      return ''
344  }
345}
346
347// The same choice the renderer makes: an active phase wins, else the most
348// recent finished result; a stale active phase is ignored.
349function pickActivity(marker: PhaseMarker, nowMs: number): Activity | null {
350  const current = marker.active
351  if (current && typeof current === 'object' && typeof current.phase === 'string') {
352    const updated = toNumber(current.updated_at)
353    const ageMs = updated === null ? STALE_MS : nowMs - updated * 1000
354    if (ageMs < STALE_MS) {
355      const text = activeLabel(current.phase, typeof current.detail === 'string' ? current.detail : '')
356      if (text) return { kind: 'active', phase: current.phase, text, age: ageMs / 1000, ok: true }
357    }
358  }
359  const results = marker.results
360  if (!results || typeof results !== 'object') return null
361  let latestKind = ''
362  let latest: PhaseResult = {}
363  let latestAt = -1
364  for (const [kind, entry] of Object.entries(results)) {
365    if (!entry || typeof entry !== 'object') continue
366    const at = toNumber(entry.at)
367    if (at !== null && at > latestAt) {
368      latestKind = kind
369      latest = entry
370      latestAt = at
371    }
372  }
373  const text = latestKind ? resultLabel(latestKind, latest) : ''
374  if (!text) return null
375  const count = toNumber(latest.count)
376  return {
377    kind: 'result',
378    phase: latestKind,
379    text,
380    age: Math.max(0, (nowMs - latestAt * 1000) / 1000),
381    ok: latest.ok !== false,
382    ...(count === null ? {} : { count }),
383  }
384}
385
386function activity(phase: Phase): Activity {
387  return { kind: 'active', phase, text: ACTIVE_LABELS[phase], age: 0, ok: true }
388}
389
390// Whether a tree draws anything: text that is not blank, or a control. The
391// engine's own band is often an empty element, which still takes a row in a
392// terminal when stacked under ours, so an empty one is left out.
393// The credit line at the end of an answer, as the recall hook's instruction
394// has the model write it: "> 🧠 Cognee memory [m4, m5]: what it remembered".
395// Returns the text without it, the tags and the note; null when the text
396// does not end with one.
397const CREDIT_LINE = /^(?:>\s*)?🧠\s*Cognee memory \[([^\]]+)\]:\s*(.*)$/u
398
399// The display logotype from cognee.ai/brand-resources (logotype-lavender.svg),
400// which is built from squares on a grid, in braille: one square is one dot (a
401// cell holds 2 x 4, so a dot is about square). The letters keep the SVG's
402// widths (c, o, g 3 squares, n 4, e 2); the gap between letters is one dot,
403// the smallest there is (the SVG's is 0.59 of a square).
404const LOGOTYPE = ['⡏⠁⡏⡇⡏⡁⡧⣸⢸⠅⡯', '⠉⠁⠉⠁⠉⠁⠁⠈⠈⠁⠉']
405function splitCredit(text: string): { body: string; tags: string; note: string } | null {
406  const lines = text.replace(/\s+$/u, '').split('\n')
407  const last = lines[lines.length - 1] ?? ''
408  const m = CREDIT_LINE.exec(last.trim())
409  if (!m) return null
410  // The note continues the label's sentence ("...[m4]: the July notes"); drawn
411  // without the label it opens one, so its first letter is capitalised.
412  const note = (m[2] ?? '').trim().replace(/^\p{Ll}/u, c => c.toUpperCase())
413  return { body: lines.slice(0, -1).join('\n').replace(/\s+$/u, ''), tags: (m[1] ?? '').trim(), note }
414}
415
416// Whether the row should use the light-background purple: the env override
417// first, then Claude Code's theme row ("light", "light-daltonized", ...).
418async function lightTheme($: any): Promise<boolean> {
419  const forced = ((await $.env.get('COGNEE_STATUSLINE_THEME')) ?? '').toLowerCase()
420  if (forced === 'light') return true
421  if (forced === 'dark') return false
422  try {
423    const rows = (await $.config.list()) as { key?: string; value?: unknown }[]
424    const theme = String(rows.find(r => r.key === 'theme')?.value ?? '').toLowerCase()
425    return theme.startsWith('light')
426  } catch {
427    return false
428  }
429}
430
431function drawsSomething(tree: unknown): boolean {
432  if (tree === null || tree === undefined || tree === false) return false
433  if (typeof tree === 'string') return tree.trim().length > 0
434  if (typeof tree === 'number') return true
435  if (Array.isArray(tree)) return tree.some(drawsSomething)
436  if (typeof tree !== 'object') return false
437  const el = tree as { type?: unknown; props?: { children?: unknown } }
438  if (el.type !== 'Box' && el.type !== 'Text') return true
439  return drawsSomething(el.props?.children)
440}
441
442function asText(value: unknown): string {
443  if (typeof value === 'string') return value
444  if (value === null || value === undefined) return ''
445  try {
446    return JSON.stringify(value)
447  } catch {
448    return String(value)
449  }
450}
451
452// One recall entry (the wrapper's /api/v1/recall item) as text.
453function hitText(entry: Record<string, unknown>): string {
454  const source = asText(entry.source)
455  if (source === 'trace') {
456    const parts = [`${asText(entry.origin_function) || '?'} — ${asText(entry.status)}`]
457    if (entry.session_feedback) parts.push(`feedback: ${asText(entry.session_feedback)}`)
458    if (entry.method_return_value) parts.push(`output: ${asText(entry.method_return_value).slice(0, 600)}`)
459    return parts.join('\n')
460  }
461  const text = asText(entry.text) || asText(entry.content)
462  if (text) return text
463  const lines: string[] = []
464  if (entry.question) lines.push(`Q: ${asText(entry.question)}`)
465  if (entry.answer) lines.push(`A: ${asText(entry.answer)}`)
466  return lines.join('\n')
467}
468
469// What a search wrapper printed, as the model and the pane read it.
470function formatSearch(stdout: string, exitCode: number): { text: string; count: number; isError: boolean } {
471  const raw = stdout.trim()
472  if (!raw || raw === 'UNREACHABLE' || (exitCode !== 0 && !raw.startsWith('[') && !raw.startsWith('{'))) {
473    return { text: 'Cognee server unreachable: the search did not run. Retry once memory is ready.', count: 0, isError: true }
474  }
475  let parsed: unknown
476  try {
477    parsed = JSON.parse(raw)
478  } catch {
479    return { text: raw, count: raw ? 1 : 0, isError: exitCode !== 0 }
480  }
481  if (Array.isArray(parsed)) {
482    const entries = parsed.filter(x => x && typeof x === 'object') as Record<string, unknown>[]
483    if (entries.length === 0) return { text: 'No memories matched.', count: 0, isError: false }
484    const blocks = entries.map((entry, i) => {
485      const source = asText(entry.source) || 'memory'
486      return `### ${i + 1}. ${source}\n${hitText(entry).trim()}`
487    })
488    return { text: blocks.join('\n\n'), count: entries.length, isError: false }
489  }
490  if (parsed && typeof parsed === 'object' && 'error' in parsed) {
491    return { text: `Cognee search failed: ${asText((parsed as { error: unknown }).error)}`, count: 0, isError: true }
492  }
493  return { text: raw, count: 1, isError: false }
494}
495
496// What the remember wrapper printed, as one line for the model.
497function formatRemember(stdout: string, exitCode: number, dataset: string): { text: string; isError: boolean } {
498  const raw = stdout.trim()
499  if (!raw || raw === 'UNREACHABLE') {
500    return { text: 'Cognee server unreachable: nothing was stored. Retry once memory is ready.', isError: true }
501  }
502  let parsed: Record<string, unknown> = {}
503  try {
504    const value = JSON.parse(raw)
505    if (value && typeof value === 'object') parsed = value as Record<string, unknown>
506  } catch {
507    return { text: raw, isError: exitCode !== 0 }
508  }
509  if (parsed.error) return { text: `Cognee remember failed: ${asText(parsed.error)}`, isError: true }
510  if (parsed.ok === false) return { text: `Cognee rejected the write: ${raw}`, isError: true }
511  const where = dataset || asText(parsed.dataset) || 'the active dataset'
512  if (parsed.queryable === true) return { text: `Stored in ${where}; it is in the graph and recall will find it.`, isError: false }
513  const outcome = asText(parsed.wait_outcome)
514  if (outcome === 'errored') return { text: `Stored in ${where}, but building the graph from it failed; check the server log.`, isError: true }
515  return { text: `Stored in ${where}; the graph is still being built from it, so recall finds it in a moment.`, isError: false }
516}
517
518function datasetRows(value: unknown): DatasetRow[] {
519  if (!value || typeof value !== 'object') return []
520  const rows = (value as { datasets?: unknown }).datasets
521  if (!Array.isArray(rows)) return []
522  return rows
523    .filter(row => row && typeof row === 'object' && typeof (row as { name?: unknown }).name === 'string')
524    .map(row => {
525      const r = row as { name: string; id?: unknown; current?: unknown }
526      return { name: r.name, id: asText(r.id), current: r.current === true }
527    })
528}
529
530// ── helpers that reach the engine ───────────────────────────────────────────
531async function stateDir($: any): Promise<string> {
532  const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
533  return `${home}/.cognee-plugin/claude-code`
534}
535
536async function bindSession($: any): Promise<void> {
537  sessionId = await $.session.id()
538  const dir = await stateDir($)
539  phasePath = `${dir}/phase/${sessionId}.json`
540  bandPath = `${dir}/band/${sessionId}.json`
541  await markBand($)
542}
543
544// Tell the settings-file status line that this session's row is drawn above
545// the prompt: the renderer prints nothing for a session with this marker, so
546// the row is not shown twice. Written only while the band is on.
547async function markBand($: any): Promise<void> {
548  if (!bandOn || !bandPath) return
549  try {
550    await $.fs.write(bandPath, JSON.stringify({ session_id: sessionId, at: (await $.clock.now()) / 1000, plugin: 'cognee-memory' }))
551  } catch {
552    // the status line then stays; nothing else depends on the marker
553  }
554}
555
556function redraw($: any): void {
557  $.ui.invalidate('ui.render')
558}
559
560function setActive($: any, next: Activity): void {
561  active = next
562  if (!spin) {
563    spin = $.clock.every(FRAME_MS, () => {
564      frame = (frame + 1) % FRAMES.length
565      $.ui.invalidate('ui.render')
566    })
567  }
568  redraw($)
569}
570
571function clearActive($: any): void {
572  active = null
573  if (spin) {
574    spin.cancel()
575    spin = null
576  }
577  redraw($)
578}
579
580async function readPhase($: any): Promise<void> {
581  if (!phasePath) return
582  markerActive = false
583  let marker: PhaseMarker
584  try {
585    marker = JSON.parse(await $.fs.read(phasePath)) as PhaseMarker
586  } catch {
587    return
588  }
589  const now = await $.clock.now()
590  const shown = pickActivity(marker, now)
591  if (shown?.kind === 'active') {
592    markerActive = true
593    if (!active || active.phase !== shown.phase) {
594      setActive($, shown)
595      activeSince = now
596    }
597    return
598  }
599  result = shown
600  if (active) clearActive($)
601  else redraw($)
602}
603
604// Poll the marker once a second while something runs, and for a short window
605// after a hook fired (its async work lands within seconds). Stops by itself.
606async function startPoll($: any, windowMs: number): Promise<void> {
607  const now = await $.clock.now()
608  pollUntil = Math.max(pollUntil, now + windowMs)
609  if (poll) return
610  poll = $.clock.every(POLL_MS, async () => {
611    await readPhase($)
612    const at = await $.clock.now()
613    pollTicks += 1
614    if (active?.phase === 'saving' && !markerActive && at - activeSince > STALE_MS) clearActive($)
615    // Warming up: the connection is unconfirmed until the SessionStart hook
616    // writes its marker; retake the snapshot every few ticks until it is.
617    const settled = snapshot?.state === 'ok' || snapshot?.state === 'fail'
618    if (at < warmupUntil && !settled && pollTicks % WARMUP_RETRY_TICKS === 0) {
619      await refreshSnapshot($)
620    }
621    if (!active && at > pollUntil && poll) {
622      poll.cancel()
623      poll = null
624      await refreshSnapshot($)
625    }
626  })
627}
628
629type Ran = { exitCode: number; stdout: string; stderr: string }
630
631// One of the plugin's Python scripts, under whichever interpreter answers
632// first (python3 on macOS and Linux, python or py on Windows). Null when none
633// could start it.
634// 'timeout' when the script ran and was killed at its time: the next
635// interpreter is NOT tried then, since the script did run (a switch killed
636// mid-sync must not be started over; an append must not land twice). Only a
637// spawn that failed (no such interpreter) moves on to the next candidate.
638async function runPython($: any, args: string[], init: { stdin?: string; timeoutMs: number }): Promise<Ran | 'timeout' | null> {
639  // The interpreter that answered last goes first; the others stay as the
640  // fallback for when it can no longer be spawned (a venv gone, a PATH change).
641  const defaults = ['python3', 'python', 'py']
642  const candidates = rendererPython ? [rendererPython, ...defaults.filter(c => c !== rendererPython)] : defaults
643  for (const python of candidates) {
644    try {
645      const ran = (await $.process.run([python, ...args], init)) as Ran
646      rendererPython = python
647      return ran
648    } catch (err) {
649      const why = String(err)
650      if (/time|outlast|kill/i.test(why)) return 'timeout'
651      if (!/ENOENT|not found|no such|spawn|cannot (find|run|start)/i.test(why)) return null
652      // the next candidate
653    }
654  }
655  return null
656}
657
658// One of the plugin's shell wrappers (the same ones the skills run).
659// Null when the wrapper could not run at all; 'timeout' when it ran past its
660// time and was killed, which for a write means the outcome is unknown.
661async function runWrapper($: any, script: string, args: string[], timeoutMs: number): Promise<Ran | 'timeout' | null> {
662  try {
663    return (await $.process.run(['bash', `${$.plugin.root}/scripts/${script}`, ...args], { timeoutMs })) as Ran
664  } catch (err) {
665    return /time|outlast|kill/i.test(String(err)) ? 'timeout' : null
666  }
667}
668
669// A search, trimmed the way the prompt hook trims what it injects: a graph
670// item on cognee >= 1.6.0 carries the whole prompt the server's LLM would
671// have read, and only its retrieved context is worth showing. The trim is the
672// plugin's own Python (recall-trim.py); when it cannot run, the raw answer is
673// shown rather than nothing.
674async function runSearch($: any, query: string, args: string[]): Promise<Ran | null> {
675  const ran = await runWrapper($, 'cognee-search.sh', [query, ...args], SEARCH_TIMEOUT_MS)
676  if (ran === 'timeout') return null
677  if (!ran || ran.exitCode !== 0 || !ran.stdout.trimStart().startsWith('[')) return ran
678  const trimmedRun = await runPython($, [`${$.plugin.root}/scripts/recall-trim.py`, '--query', query], {
679    stdin: ran.stdout,
680    timeoutMs: RENDERER_TIMEOUT_MS,
681  })
682  const trimmed = trimmedRun === 'timeout' ? null : trimmedRun
683  if (!trimmed || trimmed.exitCode !== 0 || !trimmed.stdout.trim()) return ran
684  return { ...ran, stdout: trimmed.stdout }
685}
686
687// One run of the plugin's own renderer in --json mode: the dataset, mode,
688// connection state, credits and update nudge, as the terminal bar shows them.
689// Local process, no network. Runs only on events, never on a timer.
690async function refreshSnapshot($: any): Promise<void> {
691  if (!sessionId || snapshotInFlight) return
692  if (rendererFailures >= 3) {
693    if ((await $.clock.now()) - rendererFailedAt < RENDERER_RETRY_MS) return
694    rendererFailures = 0
695  }
696  snapshotInFlight = true
697  try {
698    const script = `${$.plugin.root}/scripts/cognee_statusline_render.py`
699    const stdin = JSON.stringify({ session_id: sessionId })
700    const ran = await runPython($, [script, '--json'], { stdin, timeoutMs: RENDERER_TIMEOUT_MS })
701    if (ran && ran !== 'timeout' && ran.exitCode === 0 && ran.stdout.trim()) {
702      try {
703        snapshot = JSON.parse(ran.stdout) as Snapshot
704        rendererFailures = 0
705        redraw($)
706        return
707      } catch {
708        // fall through
709      }
710    }
711    rendererFailures += 1
712    if (rendererFailures >= 3) rendererFailedAt = await $.clock.now()
713  } finally {
714    snapshotInFlight = false
715  }
716}
717
718// ── the fix dialog ──────────────────────────────────────────────────────────
719function fixGuide(reason: string): FixGuide {
720  return FIX_GUIDES[reason] ?? FIX_FALLBACK
721}
722
723async function openFix($: any, reason: string): Promise<void> {
724  fixReason = reason
725  fixOpen = true
726  fixNote = null
727  doctorOutput = ''
728  const opened = await $.ui.open({ id: FIX_PANE, title: 'Fix memory', focus: true, closeOnEscape: true, holdToasts: true, rows: 18 })
729  if (!opened.isPlaced) $.ui.toast(`fix: ${opened.reason}`)
730}
731
732async function runDoctor($: any): Promise<void> {
733  if (doctorRunning) return
734  doctorRunning = true
735  redraw($)
736  try {
737    const ran = await runWrapper($, 'cognee-doctor.sh', [], DOCTOR_TIMEOUT_MS)
738    if (ran === 'timeout') doctorOutput = `the doctor gave no answer within ${DOCTOR_TIMEOUT_MS / 1000} s`
739    else doctorOutput = ran ? (ran.stdout.trim() || ran.stderr.trim() || '(no output)') : 'could not run the doctor: bash not found'
740  } finally {
741    doctorRunning = false
742    redraw($)
743  }
744}
745
746// Append one variable to ~/.cognee/.env (the last value of a key wins there,
747// so appending is also how a value is changed). Written by the module, so the
748// secret never goes through a shell history.
749async function saveEnvValue($: any, name: string, value: string): Promise<void> {
750  const trimmed = value.trim()
751  if (!trimmed) return
752  if (/[\r\n]/.test(trimmed)) {
753    fixNote = { text: 'one line only', isError: true }
754    redraw($)
755    return
756  }
757  // The plugin's own env-file module does the write: it resolves the file the
758  // hooks read (COGNEE_ENV_FILE, else ~/.cognee/.env) and creates it 0600,
759  // which the fs API cannot. The value travels on stdin, never on argv.
760  const ran = await runPython($, [`${$.plugin.root}/scripts/_env_file.py`, '--append', name], { stdin: trimmed, timeoutMs: RENDERER_TIMEOUT_MS })
761  if (ran === 'timeout') {
762    fixNote = { text: `saving ${name} took too long; check the env file before trying again`, isError: true }
763    redraw($)
764    return
765  }
766  const written = ran && ran.exitCode === 0 ? ran.stdout.trim() : ''
767  if (written) fixNote = { text: `${name} saved to ${written}; a new session applies it`, isError: false }
768  else fixNote = { text: `could not save ${name}${ran?.stderr.trim() ? `: ${ran.stderr.trim()}` : ''}`, isError: true }
769  redraw($)
770}
771
772// ── the tour ────────────────────────────────────────────────────────────────
773// Once, at the first draw of the band (the person is looking at the row by
774// then; at session start the Desktop app has no surface yet).
775async function startTourIfFirstRun($: any): Promise<void> {
776  if (tourChecked) return
777  tourChecked = true
778  if (!tourOn) return
779  try {
780    const seen = (await $.store.get('tour')) as { version?: unknown } | undefined
781    if (seen && toNumber(seen.version) === TOUR_VERSION) return
782  } catch {
783    return
784  }
785  tourStep = 0
786  redraw($)
787}
788
789async function endTour($: any, finished: boolean): Promise<void> {
790  tourStep = -1
791  redraw($)
792  try {
793    await $.store.set('tour', { version: TOUR_VERSION, at: (await $.clock.now()) / 1000, finished })
794  } catch {
795    // shown again next session, which is the worst case
796  }
797  if (finished) $.ui.toast(`that is the tour · /cognee-tour replays it`)
798}
799
800// ── the dataset picker ──────────────────────────────────────────────────────
801function sessionKeyArgs(): string[] {
802  return sessionId ? ['--session-key', sessionId] : []
803}
804
805// The datasets the picker offers: the writable ones, from the plugin's own
806// switch script, once when the band is first drawn and after each switch.
807async function loadDatasets($: any): Promise<void> {
808  if (datasetsListing) return
809  datasetsListing = true
810  const switchable = await runPython($, [`${$.plugin.root}/scripts/switch-dataset.py`, '--list', '--json', ...sessionKeyArgs()], {
811    timeoutMs: LIST_TIMEOUT_MS,
812  })
813  try {
814    const parsed = switchable && switchable !== 'timeout' && switchable.stdout.trim() ? JSON.parse(switchable.stdout) : {}
815    if (!parsed.error) switchTargets = datasetRows(parsed)
816  } catch {
817    // the name stays plain text
818  }
819  datasetsListed = true
820  datasetsListing = false
821  redraw($)
822}
823
824// Move the session to another dataset: the plugin's switch script, which
825// syncs the session it leaves and starts a new one. No model turn.
826async function switchDataset($: any, target: string): Promise<string> {
827  const name = target.trim()
828  if (!name) return 'name a dataset'
829  if (switching) return 'a switch is already running'
830  switching = true
831  setActive($, activity('switching'))
832  let line = ''
833  try {
834    const ran = await runPython($, [`${$.plugin.root}/scripts/switch-dataset.py`, name, '--json', ...sessionKeyArgs()], {
835      timeoutMs: SWITCH_TIMEOUT_MS,
836    })
837    let parsed: Record<string, unknown> = {}
838    try {
839      parsed = ran && ran !== 'timeout' && ran.stdout.trim() ? (JSON.parse(ran.stdout) as Record<string, unknown>) : {}
840    } catch {
841      parsed = {}
842    }
843    if (ran === 'timeout') line = `the switch ran past ${SWITCH_TIMEOUT_MS / 60_000} min and was stopped; /cognee-dataset shows where the session is`
844    else if (!ran) line = 'could not start the switch: no python interpreter found'
845    else if (parsed.error) line = asText(parsed.error)
846    else if (parsed.switched === false) line = `already on ${asText(parsed.dataset) || name}`
847    else if (parsed.switched === true) {
848      const previous = (parsed.previous ?? {}) as { dataset?: unknown; synced?: unknown }
849      const synced = previous.synced === false ? ' (previous session NOT synced)' : ''
850      line = `switched to ${asText(parsed.dataset) || name}${synced}`
851    } else line = `switch failed${ran.stderr.trim() ? `: ${ran.stderr.trim().split('\n').pop()}` : ''}`
852    const failed = !parsed.switched && parsed.switched !== false
853    $.ui.toast(failed ? `✕ ${line}` : `${line}`)
854  } finally {
855    switching = false
856    clearActive($)
857  }
858  await refreshSnapshot($)
859  void loadDatasets($)
860  return line
861}
862
863export const register: Register = (on, options) => {
864  markOn = options.icon !== 'none'
865  bandOn = options.band !== false
866  spinnerOn = options.spinner !== false
867  toolsOn = options.tools !== false
868  tourOn = options.tour !== false
869
870  on('session.start', async ($, e, next) => {
871    // A fresh start (or a reload): timers of an earlier life of the module
872    // hold an engine interface that is gone; start over.
873    if (poll) {
874      poll.cancel()
875      poll = null
876    }
877    if (spin) {
878      spin.cancel()
879      spin = null
880    }
881    pollTicks = 0
882    // The brand lavender reads on a dark background; a light one gets the
883    // darker purple. COGNEE_STATUSLINE_THEME says which; without it, Claude
884    // Code's own theme does (a light theme, or auto on a light system, is
885    // only known to Claude Code when the theme is set explicitly).
886    purple = (await lightTheme($)) ? PURPLE_LIGHT : PURPLE_DARK
887    if (markOn && !waveSvg) {
888      try {
889        const source = await $.fs.read(`${$.plugin.root}/assets/icon-lavender.svg`)
890        if (typeof source === 'string' && source.trimStart().startsWith('<svg')) waveSvg = source
891      } catch {
892        // the text mark then stands in on the desktop too
893      }
894    }
895    await bindSession($)
896    await readPhase($)
897    await refreshSnapshot($)
898    // The band's dataset picker needs the writable datasets: one listing, not
899    // awaited (the session must not wait on a slow server). The Desktop app
900    // reports no surface at start (it attaches after), so the band's first
901    // draw starts the listing too; this covers a session that does say desktop.
902    if (bandOn && e.surface === 'desktop') void loadDatasets($)
903    await $.command.register({
904      name: 'cognee-dataset',
905      description: 'Switch this session to another Cognee dataset; without a name, list them.',
906      argumentHint: '[name]',
907    })
908    await $.command.register({
909      name: 'cognee-tour',
910      description: 'Replay the short tour of the Cognee status row.',
911    })
912    if (toolsOn) {
913      await $.tool.register({
914        name: 'search',
915        description:
916          'Search Cognee memory: the permanent knowledge graph of this session\'s dataset (scope "graph", the default), ' +
917          'or the indexed repository\'s code graph (scope "code"). Memory is already recalled automatically on every prompt; ' +
918          'call this for a deeper or differently worded search, for more results, or to read another dataset by its id. ' +
919          'Returns the matching memories as text; an empty result from a reachable server is authoritative.',
920        inputSchema: {
921          type: 'object',
922          properties: {
923            query: { type: 'string', description: 'What to look for, as a question or a few keywords.' },
924            top_k: { type: 'integer', minimum: 1, maximum: 50, default: 10, description: 'How many results to return.' },
925            scope: { type: 'string', enum: ['graph', 'code'], default: 'graph', description: 'graph: memory; code: the indexed repository.' },
926            dataset_id: {
927              type: 'string',
928              description: 'Read another dataset by its UUID (from the "Other Cognee datasets" hint). Leaves the session on the active dataset.',
929            },
930          },
931          required: ['query'],
932        },
933      })
934      await $.tool.register({
935        name: 'remember',
936        description:
937          'Store what the person asked to remember in Cognee memory (the active dataset\'s knowledge graph): ' +
938          'a preference, a correction, a fact about them, a decision, a note. Use it when they say "remember this", ' +
939          '"save this to memory" or "store this file", not on your own initiative: the session is captured automatically, ' +
940          'routine tool calls included, so do not store those or your working notes. ' +
941          'Category "user" for their preferences and facts about them; "project" for facts about the codebase, docs and decisions; ' +
942          '"agent" only when they ask you to keep a finding of yours. Pass "file" instead of "content" to store a file they named ' +
943          '(code then rides the code path). Each call runs a cognify on their key: a session allows ' +
944          `${REMEMBER_SESSION_CALLS} calls and ${REMEMBER_SESSION_BYTES} bytes in all; past that the cognee-remember skill is the way.`,
945        inputSchema: {
946          type: 'object',
947          properties: {
948            content: { type: 'string', description: 'The text to remember.' },
949            category: { type: 'string', enum: ['user', 'project', 'agent'], default: 'user' },
950            file: { type: 'string', description: 'A file path to store instead of inline content.' },
951          },
952        },
953      })
954    }
955    // A session start still connecting or bootstrapping: watch it land, and
956    // keep retaking the snapshot until the connection is confirmed.
957    warmupUntil = (await $.clock.now()) + WARMUP_MS
958    await startPoll($, snapshot?.state === 'ok' && !active ? POLL_WINDOW_MS : WARMUP_MS)
959    return next(e)
960  })
961
962  on('command.run', { command: 'cognee-tour' }, $ => {
963    tourChecked = true
964    tourStep = 0
965    redraw($)
966    return { text: 'Cognee: the tour is on the status row above the prompt.' }
967  })
968
969  // /cognee-dataset <name> switches from the prompt, on every surface; alone
970  // it lists the datasets the picker offers and opens the terminal's picker.
971  on('command.run', { command: 'cognee-dataset' }, async ($, e) => {
972    const name = e.args.trim()
973    if (!name) {
974      datasetsListed = false
975      await loadDatasets($)
976      if (switchTargets.length === 0) return { text: 'Cognee: no datasets listed (is memory connected?).' }
977      const rows = switchTargets.map(r => (r.current ? `  * ${r.name} (current)` : `  - ${r.name}`)).join('\n')
978      pickerOpen = true
979      redraw($)
980      return {
981        text: `Cognee datasets you can write to:\n${rows}\n\n/cognee-dataset <name> switches this session; the picker on the status row is open too (ctrl+x tab reaches it, arrows move, Enter picks).`,
982      }
983    }
984    const line = await switchDataset($, name)
985    return { text: `Cognee: ${line}.` }
986  })
987
988  // The model's direct line to memory: the same wrappers the skills run,
989  // without the skill file and the Bash row. A registered tool answers with
990  // the text the model reads (the engine takes a string or an array, never an
991  // object); a failure is a deny, which the model reads as an error result.
992  on('tool.call', { tool: 'mcp__cognee-memory__search' }, async ($, e) => {
993    const query = asText(e.query).trim()
994    if (!query) return { deny: 'query is required' }
995    const topK = Math.max(1, Math.min(50, toNumber(e.top_k) ?? 10))
996    const scope = e.scope === 'code' ? '--code' : '--graph'
997    const datasetId = asText(e.dataset_id).trim()
998    setActive($, activity('searching'))
999    let shown
1000    try {
1001      const ran = await runSearch($, query, [String(topK), scope, ...(datasetId ? ['--dataset-id', datasetId] : [])])
1002      shown = ran ? formatSearch(ran.stdout, ran.exitCode) : formatSearch('', 1)
1003    } finally {
1004      clearActive($)
1005    }
1006    const where = datasetId ? `dataset ${datasetId}` : scope === '--code' ? 'the code graph' : 'the active dataset'
1007    if (shown.isError) return { deny: shown.text }
1008    return { result: `${plural(shown.count, 'result')} from ${where}.\n\n${shown.text}` }
1009  }).catch($ => {
1010    clearActive($)
1011    return { deny: 'Cognee search failed inside the plugin; try the cognee-search skill.' }
1012  })
1013
1014  on('tool.call', { tool: 'mcp__cognee-memory__remember' }, async ($, e) => {
1015    const content = asText(e.content).trim()
1016    const file = asText(e.file).trim()
1017    if (!content && !file) return { deny: 'content or file is required' }
1018    if (content.length > REMEMBER_MAX_CHARS) {
1019      return {
1020        deny: `content is ${content.length} characters; the remember tool takes up to ${REMEMBER_MAX_CHARS}. Store a longer text with the cognee-remember skill.`,
1021      }
1022    }
1023    if (file) {
1024      const stat = await $.fs.stat(file)
1025      if (stat.kind !== 'file') return { deny: `${file} is not a file` }
1026      if (stat.size > REMEMBER_MAX_FILE_BYTES) {
1027        return {
1028          deny: `${file} is ${stat.size} bytes; the remember tool takes files up to ${REMEMBER_MAX_FILE_BYTES}. Store a larger file with the cognee-remember skill.`,
1029        }
1030      }
1031    }
1032    const size = file ? (await $.fs.stat(file)).size : content.length
1033    if (rememberCalls >= REMEMBER_SESSION_CALLS || rememberBytes + size > REMEMBER_SESSION_BYTES) {
1034      return {
1035        deny:
1036          `this session has used its remember allowance (${rememberCalls} of ${REMEMBER_SESSION_CALLS} calls, ` +
1037          `${rememberBytes} of ${REMEMBER_SESSION_BYTES} bytes). Store it with the cognee-remember skill if the person asked for it.`,
1038      }
1039    }
1040    const nodeSet = NODE_SETS[asText(e.category)] ?? 'user_context'
1041    // Counted before the call: a call that was cut off may have cost as much
1042    // as one that answered.
1043    rememberCalls += 1
1044    rememberBytes += size
1045    setActive($, activity('remembering'))
1046    let shown
1047    try {
1048      const args = file ? ['--file', file, '--node-set', nodeSet] : [content, '--node-set', nodeSet]
1049      const ran = await runWrapper($, 'cognee-remember.sh', args, REMEMBER_TIMEOUT_MS)
1050      if (ran === 'timeout') {
1051        // The POST may have landed; a resubmit would pay for a second cognify.
1052        shown = {
1053          text: `Cognee remember gave no answer within ${REMEMBER_TIMEOUT_MS / 1000} s; the write may have landed. Do not resubmit the same text: search for it first.`,
1054          isError: true,
1055        }
1056      } else shown = ran ? formatRemember(ran.stdout, ran.exitCode, snapshot?.dataset ?? '') : formatRemember('', 1, '')
1057    } finally {
1058      clearActive($)
1059    }
1060    if (shown.isError) return { deny: shown.text }
1061    return { result: shown.text }
1062  }).catch($ => {
1063    clearActive($)
1064    return { deny: 'Cognee remember failed inside the plugin; nothing was stored. Try the cognee-remember skill.' }
1065  })
1066
1067  // Fires at each prompt, before the turn starts; next(e) runs the plugin's
1068  // recall hook (UserPromptSubmit), whose header "Cognee memory: recall N
1069  // memory ..." may come back in the context. The marker the hook wrote is
1070  // the fallback. A /clear or /resume changes the session id, so rebind here.
1071  on('prompt.submit', async ($, e, next) => {
1072    const id = await $.session.id()
1073    if (id !== sessionId) await bindSession($)
1074    setActive($, activity('recalling'))
1075    let ran
1076    try {
1077      ran = await next(e)
1078    } finally {
1079      clearActive($)
1080    }
1081    if (ran && 'drop' in ran) return ran
1082    await readPhase($)
1083    // Not awaited: a process spawn on the path from prompt to answer only
1084    // updates the row, and the poll below refreshes it a second later anyway.
1085    void refreshSnapshot($)
1086    // The turn's tool calls are saved as they happen; watch for them.
1087    await startPoll($, POLL_WINDOW_MS)
1088    return ran
1089  }).catch(($, e, next) => next(e))
1090
1091  // Each tool call's PostToolUse hook saves a trace in the background once the
1092  // tool ran; next(e) is that run. Watch the marker for the save landing.
1093  on('tool.call', async ($, e, next) => {
1094    const ran = await next(e)
1095    await startPoll($, POLL_WINDOW_MS)
1096    return ran
1097  }).catch(($, e, next) => next(e))
1098
1099  // Compaction runs the plugin's PreCompact hook (the memory anchor) inside next(e).
1100  on('session.compact', async ($, e, next) => {
1101    setActive($, activity('anchoring'))
1102    try {
1103      return await next(e)
1104    } finally {
1105      clearActive($)
1106      await readPhase($)
1107    }
1108  }).catch(($, e, next) => next(e))
1109
1110  // /clear and /resume end the conversation and start another under a new id,
1111  // with no session.start: forget what was shown, and let the next prompt rebind.
1112  on('session.end', async ($, e, next) => {
1113    if (e.reason === 'clear' || e.reason === 'resume') {
1114      if (active) clearActive($)
1115      result = null
1116      snapshot = null
1117      namingDataset = false
1118      pickerOpen = false
1119      sessionId = ''
1120      rememberCalls = 0
1121      rememberBytes = 0
1122    }
1123    return next(e)
1124  })
1125
1126  // The Stop hook has started saving the answer by now; show it as it lands.
1127  // Never for a subagent's turn. The credit line inside an answer that used
1128  // memory is the agent's own, asked for by the recall hook.
1129  on('turn.complete', async ($, e, next) => {
1130    const ran = await next(e)
1131    if (e.agentId) return ran
1132    setActive($, activity('saving'))
1133    activeSince = await $.clock.now()
1134    await startPoll($, POLL_WINDOW_MS)
1135    return ran
1136  })
1137
1138  on('ui.close', { id: FIX_PANE }, ($, e, next) => {
1139    fixOpen = false
1140    return next(e)
1141  }).catch(($, e, next) => next(e))
1142
1143  // The fix dialog: the reason in plain words, the steps, the doctor's report
1144  // on request, and a field for the one value that fixes a key or URL problem.
1145  on('ui.render', { component: 'Pane', requestId: FIX_PANE }, async ($, e) => {
1146    const { Box, Text, Markdown, Button, Input, Code } = $.ui.resolve(e) as any
1147    const guide = fixGuide(fixReason)
1148    const rows: RenderElement[] = []
1149    rows.push(Text({ bold: true, color: 'red', children: [`✕ ${guide.title}`] }))
1150    rows.push(Text({ dimColor: true, children: [`reason: ${fixReason || 'unknown'}`] }))
1151    rows.push(Markdown({ text: `${guide.what}\n\n${guide.steps.map((step, i) => `${i + 1}. ${step}`).join('\n')}` }))
1152    if (guide.field && Input) {
1153      rows.push(Text({ children: [''] }))
1154      rows.push(
1155        Input({
1156          key: 'secret',
1157          label: `${guide.field.name} `,
1158          placeholder: guide.field.placeholder,
1159          submitLabel: 'save',
1160          onSubmit: (value: string) => void saveEnvValue($, guide.field!.name, value),
1161        }),
1162      )
1163    }
1164    if (fixNote) rows.push(Text({ color: fixNote.isError ? 'red' : 'green', children: [fixNote.text] }))
1165    rows.push(Text({ children: [''] }))
1166    rows.push(
1167      Box({
1168        flexDirection: 'row',
1169        children: [
1170          Button({ key: 'doctor', label: doctorRunning ? 'running doctor…' : 'run doctor', variant: 'primary', onPress: () => void runDoctor($) }),
1171          Text({ children: ['   '] }),
1172          Button({ key: 'closeFix', label: 'close', plain: true, dimColor: true, onPress: () => void $.ui.close({ id: FIX_PANE }) }),
1173        ],
1174      }),
1175    )
1176    if (doctorOutput) rows.push(Code({ source: doctorOutput }))
1177    return Box({ flexDirection: 'column', children: rows })
1178  })
1179
1180  // The status row, above the prompt on the desktop and in a terminal (where
1181  // the settings-file status line is told to stay quiet for this session), the
1182  // dataset name a picker: open on the desktop; in a terminal a button that
1183  // opens it (or /cognee-dataset alone). Once open, ctrl+x tab or a click
1184  // reaches it; arrows move, Enter picks, Escape returns to the prompt.
1185  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1186    const theirs = await next(e)
1187    if (!bandOn || e.props.hasSurvey) return theirs
1188    if (e.surface !== 'desktop' && e.surface !== 'terminal') return theirs
1189    const els = $.ui.resolve(e) as any
1190    const { Box, Text, Select, Input, Button, Link } = els
1191    const snap = snapshot
1192    const parts: RenderElement[] = []
1193    if (!datasetsListed && !datasetsListing) void loadDatasets($)
1194    void startTourIfFirstRun($)
1195    const current = switchTargets.find(r => r.current)?.name ?? snap?.dataset ?? ''
1196    const canPick = switchTargets.length > 0 && switchTargets.some(r => r.name === current)
1197    const picker = () =>
1198      Select({
1199        key: 'dataset',
1200        options: [...switchTargets.map(r => ({ value: r.name, label: r.name })), { value: NEW_DATASET, label: NEW_DATASET }],