Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): give each desktop channel its own home folder (#5262)

tim-inkeep16e869af30cf
diff --git a/.changeset/beta-own-home.md b/.changeset/beta-own-home.md
new file mode 100644
index 000000000..2696faf24
--- /dev/null
+++ b/.changeset/beta-own-home.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+OpenKnowledge Beta now keeps its data and credentials separate from the stable app, in `~/.ok-beta`. After updating, Beta starts fresh: settings, logs, themes, agent chat history, and user config begin empty, and you sign in again. Earlier Beta data in `~/.ok` stays there for the stable app.
diff --git a/docs/content/contribute/translations.mdx b/docs/content/contribute/translations.mdx
index 56699c870..f11a69015 100644
--- a/docs/content/contribute/translations.mdx
+++ b/docs/content/contribute/translations.mdx
@@ -19,7 +19,7 @@ Language is an app appearance setting and can be set directly in the config [con
## Run OpenKnowledge in the language you're checking
-Set the language in the UI setting or set it by hand in `~/.ok/global.yml`:
+Set the language in the UI setting or set it by hand in `~/.ok/global.yml` (`~/.ok-beta/global.yml` in OpenKnowledge Beta):
```yaml
appearance:
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 0bc60f0ef..22419a3bc 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -297,7 +297,7 @@ In-app agent chats in the Agents panel follow the same rule and the same setting
Shell commands in an in-app chat still prompt one at a time. When the command an agent asks to run is read-only (listing, reading, and searching files, `git status`, `log`, `diff` and other read-only git subcommands, and plain `curl` GET probes), the prompt adds **Allow read-only commands while this chat is open**. Choosing it approves that command and every later read-only command in the same chat without a prompt. A pipeline or compound command counts as read-only only when every stage does, and output can go only to `/dev/null` or into another stream (`2>&1`). Globs and variables are fine in the arguments of commands that cannot change anything, such as `cat`, `ls`, `grep` and `echo`, but `git`, `curl`, `find`, `sort` and the other commands whose options the classifier checks prompt when handed one. Command substitution, and anything else the classifier cannot prove read-only, keeps prompting. The grant shows as **Read-only allowed** on the agent settings trigger, lasts while the chat stays open (a restarted server prompts again), and **Ask again before read-only commands** in that menu revokes it.
-In-app Claude Code and Codex chats can also get a browser they can drive. Turn on **Settings → Preferences → “Let agent chats use a browser”** ([`agents.browserTools`](../reference/configuration.mdx), off by default) and each Claude Code or Codex chat you start afterwards gets the [Playwright MCP](https://github.com/microsoft/playwright-mcp) server, so the agent can open pages, click, type, and take screenshots, for example to check a site it just built. Other agents' chats don't get it, because OpenKnowledge can't tell their browser actions apart from their other tools. It needs Google Chrome and Node.js installed. OpenKnowledge starts the server with the `npx` on the agent's own PATH, from a folder of its own outside the project, so npm never uses the project's `package.json`, `node_modules`, or `.npmrc`; if it can't find a usable `npx`, or the browser can't be set up, the chat starts without the browser and says so in the conversation, and the server log has the details. Without Chrome, the agent's browser actions fail with a message that Chrome is missing. The browser opens in its own window (headless on Linux with no display) with a fresh profile kept in memory, so it starts signed out of everything, and pages cannot add tools of their own. Every browser action asks for your approval, with no option to always allow it, unless the agent skips approvals itself: through its mode (the **Agent mode** item in the chat's agent settings menu) or its own permission settings, such as a Claude Code rule that allows the browser's tools. Everything the browser saves, whether or not the agent names the file, goes to a folder OpenKnowledge keeps for the chat under `~/.ok/agent-browser/`, outside the project, and is removed when you delete the chat. Pages can also carry instructions aimed at the agent, and OpenKnowledge's own read and write tools still run without asking; turn off **Let agents use OpenKnowledge without asking** ([`agents.autoApproveOkTools`](../reference/configuration.mdx)) to approve those too.
+In-app Claude Code and Codex chats can also get a browser they can drive. Turn on **Settings → Preferences → “Let agent chats use a browser”** ([`agents.browserTools`](../reference/configuration.mdx), off by default) and each Claude Code or Codex chat you start afterwards gets the [Playwright MCP](https://github.com/microsoft/playwright-mcp) server, so the agent can open pages, click, type, and take screenshots, for example to check a site it just built. Other agents' chats don't get it, because OpenKnowledge can't tell their browser actions apart from their other tools. It needs Google Chrome and Node.js installed. OpenKnowledge starts the server with the `npx` on the agent's own PATH, from a folder of its own outside the project, so npm never uses the project's `package.json`, `node_modules`, or `.npmrc`; if it can't find a usable `npx`, or the browser can't be set up, the chat starts without the browser and says so in the conversation, and the server log has the details. Without Chrome, the agent's browser actions fail with a message that Chrome is missing. The browser opens in its own window (headless on Linux with no display) with a fresh profile kept in memory, so it starts signed out of everything, and pages cannot add tools of their own. Every browser action asks for your approval, with no option to always allow it, unless the agent skips approvals itself: through its mode (the **Agent mode** item in the chat's agent settings menu) or its own permission settings, such as a Claude Code rule that allows the browser's tools. Everything the browser saves, whether or not the agent names the file, goes to a folder OpenKnowledge keeps for the chat under `~/.ok/agent-browser/` (Beta: `~/.ok-beta/agent-browser/`), outside the project, and is removed when you delete the chat. Pages can also carry instructions aimed at the agent, and OpenKnowledge's own read and write tools still run without asking; turn off **Let agents use OpenKnowledge without asking** ([`agents.autoApproveOkTools`](../reference/configuration.mdx)) to approve those too.
## Tabs and split panes
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index bf50f618c..b44855edb 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -111,7 +111,7 @@ If you are logged in with the GitHub CLI, OpenKnowledge will use those credentia
Manage the connection from **Settings → Account**. **Connect GitHub** authorizes OpenKnowledge to browse and sync your repositories; **Disconnect** clears OpenKnowledge's GitHub token only. From a terminal, the [`ok auth`](/docs/reference/cli) subcommands manage the same credentials: `ok auth signout` matches **Disconnect**, `ok auth pat` stores a Personal Access Token when device authentication isn't an option, and `--host` targets GitHub Enterprise.
-For GitHub Enterprise Server, add the host under **Settings → Account → GitHub Enterprise Server hosts**, or declare it in your user configuration, `~/.ok/global.yml`, then restart OpenKnowledge:
+For GitHub Enterprise Server, add the host under **Settings → Account → GitHub Enterprise Server hosts**, or declare it in your user configuration, `~/.ok/global.yml` (`~/.ok-beta/global.yml` in OpenKnowledge Beta), then restart OpenKnowledge:
```yaml
git:
diff --git a/docs/content/plugins/themes.mdx b/docs/content/plugins/themes.mdx
index c6f1936b0..151678c61 100644
--- a/docs/content/plugins/themes.mdx
+++ b/docs/content/plugins/themes.mdx
@@ -29,7 +29,7 @@ Click **Create new theme**, name it, and the editor opens. Two ways to fill it i
## Theme files
-Saved themes are plain Tinted Theming YAML files in `~/.ok/themes/`, one file per theme, filename as identity. Drop a downloaded scheme file there (`.yaml` or `.yml` only) and it appears in the gallery, since the folder is re-scanned when the Themes page opens. A file that doesn't parse is listed with the reason rather than silently dropped, so it can always be fixed.
+Saved themes are plain Tinted Theming YAML files in `~/.ok/themes/` (`~/.ok-beta/themes/` in OpenKnowledge Beta), one file per theme, filename as identity. Drop a downloaded scheme file there (`.yaml` or `.yml` only) and it appears in the gallery, since the folder is re-scanned when the Themes page opens. A file that doesn't parse is listed with the reason rather than silently dropped, so it can always be fixed.
Deleting a theme from its tile deletes the file, with an undo window before it's gone for good.
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index 08a1d7847..5c772eb88 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -96,7 +96,7 @@ ok auth login
If you're already logged in with the `gh` CLI, you can skip this step.
-`ok auth` also provides `status` (show who's logged in), `repos` (list repositories you can access), `signout` (remove stored credentials), and `pat` (store a Personal Access Token). Every subcommand takes `--host <hostname>`. GitHub Enterprise hosts must be declared as `git.hosts.<host>.provider: github` in `~/.ok/global.yml` before commands contact them. See [configuration](/docs/reference/configuration).
+`ok auth` also provides `status` (show who's logged in), `repos` (list repositories you can access), `signout` (remove stored credentials), and `pat` (store a Personal Access Token). Every subcommand takes `--host <hostname>`. GitHub Enterprise hosts must be declared as `git.hosts.<host>.provider: github` in `~/.ok/global.yml` (`~/.ok-beta/global.yml` for `ok-beta`) before commands contact them. See [configuration](/docs/reference/configuration).
Without `--host`, commands select the recognized GitHub origin, or `github.com` when no origin exists. An unrecognized origin requires explicit host selection, so commands cannot contact or clear credentials for a different host by accident. `status` and `repos` contact GitHub APIs. `signout --host <hostname>` only removes local credentials and works even after that host's declaration has been removed.
@@ -146,7 +146,7 @@ Serve this project's web UI and `/mcp` endpoint to your other devices through an
| `ok config migrate` | Remove keys the schema no longer reads from your config files (`--dry-run` to preview; `--scope` to narrow — defaults to every layer) |
| `ok skills installed` | List every skill installed across your agents (read-only, cross-harness) |
| `ok skills import <source>` | Import a skill as versioned content from skills.sh, a GitHub `owner/repo`, a git URL, or a local path |
-| `ok bug-report` | Package a support bundle — recent app logs, the project's server logs and lock diagnostics, and system info — as an auto-redacted zip under `~/.ok/bug-reports/`, revealed in your file manager when it's done (`--no-reveal` to skip). Collects the same `standard` set as the desktop app's **Help → Report a bug…**; `ok diagnose bundle` produces the `full` superset (telemetry spans, live server state) into the project's `.ok/local/diagnostics/` |
+| `ok bug-report` | Package a support bundle — recent app logs, the project's server logs and lock diagnostics, and system info — as an auto-redacted zip under `~/.ok/bug-reports/` (`~/.ok-beta/bug-reports/` for `ok-beta`), revealed in your file manager when it's done (`--no-reveal` to skip). Collects the same `standard` set as the desktop app's **Help → Report a bug…**; `ok diagnose bundle` produces the `full` superset (telemetry spans, live server state) into the project's `.ok/local/diagnostics/` |
## Global flags
@@ -160,11 +160,11 @@ The rest of the CLI exists mostly for tooling and automation. Your AI editor spa
`ok deinit [path]` reverses `ok init` for one project (the current project when `path` is omitted): it removes the project's `.ok/` directory, OpenKnowledge's editor MCP entries, its own git-exclude lines, and shadow repo, leaving your markdown untouched. Shared editor settings and their symlinks are preserved; ignore rules for shared config files stay while those files still exist.
-`ok uninstall` removes the global footprint — running servers, credentials, the PATH shim, OpenKnowledge's editor MCP entries and bundled skills, app data, and `~/.ok` (keeping authored skills in `~/.ok/skills` unless you pass `--purge-content`). Your markdown and other skills in your editors' skill directories stay. An interactive run lets you select projects to deinitialize; `--yes` removes only the global footprint unless you also pass `--all-projects`, which covers current, recent, and discovered running projects. The CLI binary stays installed; the command ends by printing how to remove it (`npm uninstall -g @inkeep/open-knowledge` for the install above).
+`ok uninstall` removes the global footprint: running servers, credentials, the PATH shim, OpenKnowledge's editor MCP entries and bundled skills, app data, and `~/.ok`. It keeps the `~/.ok` entries every product shares: `~/.ok/machine-id`, the user skills store `~/.ok/skills`, `~/.ok/skills-lock.json`, and the Global-scope skill bookkeeping in `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, and `~/.ok/local/skill-move-retained.json`. It removes only the running product's footprint: `ok-beta uninstall` removes `~/.ok-beta` and Beta's credentials and leaves Stable's `~/.ok` alone. No product's uninstall removes `~/.ok/machine-id`. With `--purge-content`, either product also removes the shared `~/.ok/skills`, unless an earlier uninstall step failed. See [Stable and Beta home folders](/docs/reference/what-open-knowledge-writes#stable-and-beta-home-folders). Your markdown and other skills in your editors' skill directories stay. An interactive run lets you select projects to deinitialize; `--yes` removes only the global footprint unless you also pass `--all-projects`, which covers current, recent, and discovered running projects. The CLI binary stays installed; the command ends by printing how to remove it (`npm uninstall -g @inkeep/open-knowledge` for the install above).
Both `ok deinit` and `ok uninstall` wait for servers to exit before deleting their state. If a server cannot be safely stopped or an integration cannot be cleaned up, the command reports the problem and retains state needed for repair and retry. Applied cleanup exits `1` when anything remains unresolved. With `--yes --json`, inspect `failed[]` for those items and their reasons; `skipped[]` covers intentionally preserved entries. Repair the reported problem and rerun the command.
-On Windows, confirming that a running server really is the process the lock names uses OpenKnowledge's bundled native component. Removal refuses rather than signalling a process it has not identified, and the refusal names which of two things went wrong. If the component could not be loaded, reinstalling OpenKnowledge restores it — the same remedy as for [its TOML writer](#set-up-a-project). If the component loaded but Windows refused the query, reinstalling will not help: that is usually a permissions difference, so rerun from an account that can inspect the server process. Either way you can instead stop the server yourself and confirm it has exited, then rerun. The failure detail itself is recorded in `~/.ok/logs`, not printed.
+On Windows, confirming that a running server really is the process the lock names uses OpenKnowledge's bundled native component. Removal refuses rather than signalling a process it has not identified, and the refusal names which of two things went wrong. If the component could not be loaded, reinstalling OpenKnowledge restores it — the same remedy as for [its TOML writer](#set-up-a-project). If the component loaded but Windows refused the query, reinstalling will not help: that is usually a permissions difference, so rerun from an account that can inspect the server process. Either way you can instead stop the server yourself and confirm it has exited, then rerun. The failure detail itself is recorded in `~/.ok/logs` (`~/.ok-beta/logs` for `ok-beta`), not printed.
`ok deinit` needs the project's `.ok/` directory; once that directory is gone, it reports nothing to remove. Remove any retained Pi trust entry manually using its reported exact key and file, as described in [installation details](./what-open-knowledge-writes.mdx#pi-folder-trust).
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index 997048159..c789b6198 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -7,7 +7,7 @@ description: The .ok/config.yml schema and environment variables.
OpenKnowledge reads YAML config from three places:
- **Project**: `./.ok/config.yml` (this project, committed to git)
-- **User**: `~/.ok/global.yml` (every project on your machine)
+- **User**: `~/.ok/global.yml` (every project on your machine; OpenKnowledge Beta reads `~/.ok-beta/global.yml`)
- **Project-local**: `./.ok/local/config.yml` (this project on this machine; gitignored). Holds per-machine-per-project preferences such as `autoSync.mode`. Maintained by the editor (auto-sync onboarding modal, sync popover, Settings pane Sync section); you don't normally hand-edit it.
All files are optional; defaults cover everything.
@@ -26,7 +26,7 @@ In the desktop app, Settings follows the focused window. An editor opens the ful
The **Scope** column says which file a setting belongs in:
- **project** → `.ok/config.yml` (shared in git)
-- **user** → `~/.ok/global.yml` (personal, all projects)
+- **user** → `~/.ok/global.yml` (personal, all projects; Beta: `~/.ok-beta/global.yml`)
- **project-local** → `.ok/local/config.yml` (this machine only, gitignored)
A key set in a file more specific than its scope (a user-scope key in `.ok/config.yml`, for example) is ignored.
@@ -72,7 +72,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi
| `terminal.shell` | string | (unset) | project-local | Absolute Windows shell executable override, for example `C:\Program Files\PowerShell\7\pwsh.exe`. PowerShell, `cmd.exe`, and Git Bash (`bash.exe`) support OpenKnowledge-managed launches (agent chat tabs and fixed commands such as **Resolve in terminal** or **Install Slidev**) and dropped-file path insertion. A different existing executable remains active for plain terminal tabs and shows a capability notice; requested agent and command launches open only the plain shell without running the agent or command, and dropped-file paths are refused. Use `wsl` inside a supported shell rather than setting `wsl.exe` here. Agent-launch prompts are pasted without being submitted on Windows, so review the prompt and press Enter to send it. Empty or unset values use automatic discovery (PowerShell 7, Windows PowerShell, then `ComSpec` / `cmd.exe`). Unreadable, invalid, relative, or missing paths show a notice and fall back to discovery. Human-managed and never shared through git, clone, or sync. |
| `slides.enabled` | boolean | `false` | user | Whether the [Slidev plugin](/docs/plugins/slidev) appears in **Settings → Plugins**. Off by default. When on, a document whose frontmatter contains `slides: true` gets an **Open in Slidev** action that opens the deck in its own window, rendered by a [Slidev](https://sli.dev/) you install yourself — OpenKnowledge does not download or bundle one. Install it globally (`npm install -g @slidev/cli @slidev/theme-default`) or add those packages to the project (a project-local install takes precedence). Slidev themes ship separately from the CLI and a deck cannot open without the theme it declares. Desktop only; the action stays hidden until a `slidev` binary resolves. |
| `agents.autoApproveOkTools` | boolean | `true` | user | Auto-approve OpenKnowledge's own MCP tools for agents launched from the built-in [docked terminal](/docs/features/editor#terminal) (plus the `ok open` command on Claude) and for in-app Agents-panel chats with any ACP agent, so reading and writing the knowledge base runs without a per-call approval prompt. Destructive tools (`delete`, `move`, `share_link`, `install`, `import`) still prompt; other shell commands and non-OpenKnowledge file edits are untouched. Per-machine preference; toggle from **Settings → Terminal**. Best-effort per agent — Claude uses an allow/ask list, Codex uses its per-server `approve` mode (and only when its OpenKnowledge entry is already configured). |
-| `agents.browserTools` | boolean | `false` | user | Give in-app Claude Code and Codex chats a browser they can drive: each one started after you turn it on gets the [Playwright MCP](https://github.com/microsoft/playwright-mcp) server, so the agent can open pages, click, type, and take screenshots. It is launched with the `npx` on the agent's PATH from OpenKnowledge's own folder, so npm never uses the project's npm files; without a usable `npx`, or when the browser can't be set up, the chat starts without it and says so in the conversation. Needs Google Chrome and Node.js installed. The browser opens in its own window (headless on Linux with no display) with a fresh in-memory profile; everything the browser saves goes to a folder for the chat under `~/.ok/agent-browser/` and is removed with the chat. Every browser action asks for approval, with no option to always allow it, unless the agent's own mode or permission settings skip approvals. Other agents' chats don't get it. Per-machine preference; toggle from **Settings → Preferences**. |
+| `agents.browserTools` | boolean | `false` | user | Give in-app Claude Code and Codex chats a browser they can drive: each one started after you turn it on gets the [Playwright MCP](https://github.com/microsoft/playwright-mcp) server, so the agent can open pages, click, type, and take screenshots. It is launched with the `npx` on the agent's PATH from OpenKnowledge's own folder, so npm never uses the project's npm files; without a usable `npx`, or when the browser can't be set up, the chat starts without it and says so in the conversation. Needs Google Chrome and Node.js installed. The browser opens in its own window (headless on Linux with no display) with a fresh in-memory profile; everything the browser saves goes to a folder for the chat under `~/.ok/agent-browser/` (Beta: `~/.ok-beta/agent-browser/`) and is removed with the chat. Every browser action asks for approval, with no option to always allow it, unless the agent's own mode or permission settings skip approvals. Other agents' chats don't get it. Per-machine preference; toggle from **Settings → Preferences**. |
| `telemetry.localSink.enabled` | boolean | `true` | project | Write local diagnostic spans + logs under `.ok/local/` for `ok diagnose bundle` to collect. Local-only: nothing leaves the machine until you run `bundle`. Set `false` for sensitive workspaces. |
| `telemetry.localSink.spans.maxBytes` | number | `52428800` (~50 MB) | project | Max size of the local diagnostic spans file before it rotates. |
| `telemetry.localSink.logs.maxBytes` | number | `26214400` (~25 MB) | project | Max size of the local diagnostic logs file before it rotates. |
@@ -138,7 +138,7 @@ Most users never set these — the schema settings above cover the common cases.
The MCP `search` tool can fuse an **embeddings-based semantic signal** into its ranking, so an agent's query surfaces conceptually-related pages even when they share no keywords (a query about "auth retries" can surface a page titled "Session Token Refresh"). It is **off by default** and additive. With it off, search everywhere (the MCP tool and the cmd-K omnibar) is purely lexical and stays on-machine. When it is enabled, the omnibar's **By meaning** pill appears once the endpoint has a usable credential: a stored key, or a loopback endpoint that needs none (step 2 below). A remote endpoint without a stored key stays lexical and hides the pill. Typing never embeds; pressing Enter fires one semantic search, sending the query to the embeddings provider.
<Callout type="warn">
- **Content egress.** When semantic search is enabled **and** a key is set (or the endpoint is a keyless local server), the search query and the matching page content are sent to whichever OpenAI-compatible endpoint the project has configured (OpenAI by default). Only content that is already in your corpus is embedded — anything excluded by `.okignore` / `.gitignore` is never sent — and embedding is lazy: nothing leaves the machine until a semantic search actually runs. Keys live only in a 0600 `~/.ok/secrets.yml` file, keyed by project + endpoint so a key never travels to a host it wasn't set for; never in `config.yml`, the project tree, logs, or telemetry.
+ **Content egress.** When semantic search is enabled **and** a key is set (or the endpoint is a keyless local server), the search query and the matching page content are sent to whichever OpenAI-compatible endpoint the project has configured (OpenAI by default). Only content that is already in your corpus is embedded — anything excluded by `.okignore` / `.gitignore` is never sent — and embedding is lazy: nothing leaves the machine until a semantic search actually runs. Keys live only in a 0600 `~/.ok/secrets.yml` file (`~/.ok-beta/secrets.yml` in Beta), keyed by project + endpoint so a key never travels to a host it wasn't set for; never in `config.yml`, the project tree, logs, or telemetry.
</Callout>
To turn it on (per project, per machine):
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 143c713a4..3d126834d 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -20,6 +20,17 @@ Writes fall into two buckets, and each table's **Scope** column tells you which:
- **In-project** — inside your project folder. Either **committed** (shared through git with your team) or **gitignored** (this machine only, under `.ok/local/` or `.git/`).
- **Outside-project** — your **home directory** (`~/.ok/`, `~/Library/...`), your **shell startup files** (`~/.zshrc` and friends), your editors' **user-level configs**, or the OS credential store.
+#### Stable and Beta home folders
+
+Every `~/.ok/` path on this page belongs to Stable, except the shared entries listed below. OpenKnowledge Beta, and the `ok-beta` CLI, write the other files under `~/.ok-beta/` instead, and keep credentials in the OS credential store under the service `open-knowledge-beta` rather than `open-knowledge`. These entries stay under `~/.ok/` for both products:
+
+- `~/.ok/machine-id`, a random id that identifies this machine to project server locks.
+- `~/.ok/skills/`, the user skills store.
+- `~/.ok/skills-lock.json`, provenance for skills imported at Global scope.
+- `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, and `~/.ok/local/skill-move-retained.json`, the install markers, placement records (where each copy of a skill was written, and whether as a copy or a link), and unfinished-scope-move bookkeeping for Global-scope skills.
+
+No product's uninstall removes `~/.ok/machine-id`, and Stable's `ok uninstall` keeps every entry in this list. See [the uninstall notes](#opt-outs-in-one-place) for how `--purge-content` treats the shared skills store.
+
OpenKnowledge installs one of two ways, and the footprint differs a little between them. Pick yours below — each tab lists the complete set of writes for that path. The [opt-outs](#opt-outs-in-one-place) and [what leaves your machine](#what-leaves-your-machine) at the end apply to both.
<Tabs groupId="ok-install" persist className="ok-flush-tabs ok-tabs-h2" items={['Desktop app', 'CLI']}>
@@ -34,14 +45,14 @@ How the app lands depends on your platform:
- **Windows** — a per-user installer: the app lands under `%LOCALAPPDATA%\Programs\`, with no admin prompt. Stable adds `ok` to your **user** `PATH` and registers `openknowledge://`; Beta adds `ok-beta` and `open-knowledge-beta` and registers `openknowledge-beta://`. These are registry values under `HKCU\Environment` and `HKCU\Software\Classes`, removed by the matching uninstaller. Each product also registers itself for `.md` and `.mdx` files under `HKCU\Software\Classes`, which can make it the default opener when you have not explicitly chosen one in Windows. Uninstall removes that product's Open With and file-handler registrations but does not restore a previous file-type default. To choose another opener, use **Settings → Apps → Default apps**. Your shell startup files are never touched.
- **Linux** — a deb or rpm package: Stable installs to `/opt/OpenKnowledge/` and symlinks `/usr/bin/ok`, `/usr/bin/open-knowledge`, and `/usr/bin/openknowledge`; Beta installs to `/opt/OpenKnowledge Beta/` and symlinks `/usr/bin/ok-beta`, `/usr/bin/open-knowledge-beta`, and `/usr/bin/openknowledge-beta`. Their desktop entries register `openknowledge://` and `openknowledge-beta://` respectively, and each installs its own AppArmor profile on Ubuntu 24.04+ so the Chromium sandbox keeps working. Your shell startup files are touched only with your consent, as described below.
-On every platform the app writes app-level state and logs on launch. The table below shows the macOS locations; Beta substitutes `OpenKnowledge Beta` for the app-data directory and uses its own updater cache. On Windows, Stable app state lives under `%APPDATA%\OpenKnowledge\` and Beta under `%APPDATA%\OpenKnowledge Beta\`. On Linux, the corresponding defaults are `~/.config/OpenKnowledge/` and `~/.config/OpenKnowledge Beta/` (or the matching XDG directories). Stable owns the traditional `~/.ok/bin` paths; Beta owns `~/.ok/variants/beta`.
+On every platform the app writes app-level state and logs on launch. The table below shows the macOS locations; Beta substitutes `OpenKnowledge Beta` for the app-data directory and uses its own updater cache. On Windows, Stable app state lives under `%APPDATA%\OpenKnowledge\` and Beta under `%APPDATA%\OpenKnowledge Beta\`. On Linux, the corresponding defaults are `~/.config/OpenKnowledge/` and `~/.config/OpenKnowledge Beta/` (or the matching XDG directories). Stable keeps its command-line shortcuts under `~/.ok/` and Beta keeps its own under `~/.ok-beta/`. When Beta sets up its `PATH` shim, it removes the `~/.ok/variants/beta/` folder that earlier Beta builds used.
| Path | What it is | Scope |
| --- | --- | --- |
| `~/Library/Application Support/OpenKnowledge/state.json` | Recent projects, window/view state, update channel | Outside-project (home dir) |
| `~/Library/Application Support/OpenKnowledge/path-install.json` | Records the `PATH`/shell changes it made and your `PATH`-consent choice, so they can be reverted | Outside-project (home dir) |
| `~/Library/Application Support/OpenKnowledge Beta/state.json` | Beta's separate recent projects, window/view state, and update channel | Outside-project (home dir) |
-| `~/.ok/variants/beta/path-install.json` | Records Beta's separate `PATH`/shell changes and consent choice | Outside-project (home dir) |
+| `~/.ok-beta/path-install.json` | Records Beta's separate `PATH`/shell changes and consent choice | Outside-project (home dir) |
| `~/.ok/logs/desktop.<date>.log` | Desktop app + renderer log | Outside-project (home dir) |
| `~/.ok/mcp-status.json` | Records your first-launch MCP-setup consent choice | Outside-project (home dir) |
| `~/Library/Caches/@inkeepopen-knowledge-desktop-updater/` | Staged auto-update downloads (electron-updater) | Outside-project (home dir) |
@@ -69,8 +80,8 @@ The first two rows below live in OpenKnowledge's own `~/.ok/` directory and are
| `~/.ok/bin/ok`, `~/.ok/bin/open-knowledge` | Symlinks to the CLI bundled inside the app | Outside-project (home dir) |
| `~/.ok/env.sh` | A managed shim that prepends `~/.ok/bin` to your `PATH` | Outside-project (home dir) |
| `~/.zshrc`, `~/.bash_profile`, `~/.bashrc` (Linux), `~/.config/fish/conf.d/open-knowledge.fish` | A **fenced managed block** that sources `~/.ok/env.sh` — written **only if you consent** in the first-launch dialog. The block is created in the startup file for your login shell, and maintained in any of these that already exists, except `~/.bashrc`, which is only ever touched on Linux | Outside-project (shell config) |
-| `~/.ok/variants/beta/bin/ok-beta`, `~/.ok/variants/beta/bin/open-knowledge-beta` | Beta-only symlinks to the CLI bundled inside OpenKnowledge Beta | Outside-project (home dir) |
-| `~/.ok/variants/beta/env.sh`, `~/.config/fish/conf.d/open-knowledge-beta.fish` | Beta's separate environment shim and fish startup file; other shells receive a separately fenced `open-knowledge beta cli` block | Outside-project (home dir / shell config) |
+| `~/.ok-beta/bin/ok-beta`, `~/.ok-beta/bin/open-knowledge-beta` | Beta-only symlinks to the CLI bundled inside OpenKnowledge Beta | Outside-project (home dir) |
+| `~/.ok-beta/env.sh`, `~/.config/fish/conf.d/open-knowledge-beta.fish` | Beta's separate environment shim and fish startup file; other shells receive a separately fenced `open-knowledge beta cli` block | Outside-project (home dir / shell config) |
If you decline, only `ok` typed in an *external* terminal (Terminal, iTerm) is affected — the app's built-in terminal, the MCP server, and the "Open with AI" launches all work without it. You can add it later from **File → Set up OpenKnowledge integrations…**. Machines that already had the block from a version before the consent dialog are treated as consented: the block is left in place and maintained.
@@ -98,14 +109,6 @@ Both are **consent-gated**, but at different moments. Declining `open-knowledge-
When you initialize or open a project, the app scaffolds the same project files the CLI's `ok init` creates, and registers the `open-knowledge` MCP server with the AI editors it detects. The MCP registration is **surgical** — it touches only its own entry and leaves your other settings, comments, and formatting byte-for-byte intact. "Its own entry" means the one named `open-knowledge`; if that name is already taken by something OpenKnowledge does not recognize, see [Opt-outs in one place](#opt-outs-in-one-place).
-#### Beta uses its own entry
-
-Each product registers under its own name, so Stable and Beta can both be connected to the same editor without overwriting each other. Stable uses `open-knowledge`; Beta uses `open-knowledge-beta`, with its own launcher that runs OpenKnowledge Beta and falls back to `npx @inkeep/open-knowledge@beta`. Everywhere this page names the `open-knowledge` entry, Beta's app, repair sweeps, and `ok-beta init` act only on `open-knowledge-beta`, and Beta's Pi bridge is `.pi/extensions/open-knowledge-beta.ts`. Agents see Beta's tools as `mcp__open-knowledge-beta__*`, and Pi sees them as `ok-beta_*`.
-
-Earlier releases of the separately installed `OpenKnowledge Beta` app registered under `open-knowledge`, and updating does not move that entry. If an editor's config has no `open-knowledge-beta` entry, reconnect that editor from **Settings → Agent connections** in OpenKnowledge Beta, then remove the old `open-knowledge` entry from the file listed under [`ok init`](#ok-init) if you don't also run Stable. An older Beta install still named `OpenKnowledge` keeps using `open-knowledge`; leave that entry in place.
-
-A CLI process decides which product it belongs to in this order: the `OK_CHANNEL` environment variable (`stable` or `beta`; any other value is an error), then the name of the executable it runs as, and otherwise Stable. The CLI bundled in OpenKnowledge Beta resolves as Beta from its executable name, and Beta's launcher sets `OK_CHANNEL=beta` before it falls back to npx. A CLI run under plain Node, such as `npx @inkeep/open-knowledge@beta init` typed by hand, resolves as Stable and writes the `open-knowledge` entry unless you set `OK_CHANNEL=beta`.
-
| Path | What it is | Scope |
| --- | --- | --- |
| `.ok/`, `.ok/config.yml` | Project directory and its [config](./configuration.mdx) | In-project, committed |
@@ -119,6 +122,20 @@ A CLI process decides which product it belongs to in this order: the `OK_CHANNEL
The **Scope** column assumes you share this setup with your team. New projects don't: they keep OpenKnowledge's config to yourself, adding every in-project path above to `.git/info/exclude`, so those files are written but stay out of git.
+#### Beta uses its own entry
+
+Each product registers under its own name, so Stable and Beta can both be connected to the same editor without overwriting each other. Stable uses `open-knowledge`; Beta uses `open-knowledge-beta`, with its own launcher that runs OpenKnowledge Beta and falls back to `npx @inkeep/open-knowledge@beta`. Everywhere this page names the `open-knowledge` entry, Beta's app, repair sweeps, and `ok-beta init` act only on `open-knowledge-beta`, and Beta's Pi bridge is `.pi/extensions/open-knowledge-beta.ts`. Agents see Beta's tools as `mcp__open-knowledge-beta__*`, and Pi sees them as `ok-beta_*`.
+
+Earlier releases of the separately installed `OpenKnowledge Beta` app registered under `open-knowledge`, and updating does not move that entry. If an editor's config has no `open-knowledge-beta` entry, reconnect that editor from **Settings → Agent connections** in OpenKnowledge Beta, then remove the old `open-knowledge` entry from the file listed under [`ok init`](#ok-init) if you don't also run Stable. An older Beta install still named `OpenKnowledge` keeps using `open-knowledge`; leave that entry in place.
+
+A CLI process decides which product it belongs to in this order: the `OK_CHANNEL` environment variable (`stable` or `beta`; any other value is an error), then the name of the executable it runs as, and otherwise Stable. The CLI bundled in OpenKnowledge Beta resolves as Beta from its executable name, and Beta's launcher sets `OK_CHANNEL=beta` before it falls back to npx. A CLI run under plain Node, such as `npx @inkeep/open-knowledge@beta init` typed by hand, resolves as Stable and writes the `open-knowledge` entry unless you set `OK_CHANNEL=beta`.
+
+#### Upgrading Beta to its own home folder
+
+Beta now keeps its data in `~/.ok-beta/` (see [Stable and Beta home folders](#stable-and-beta-home-folders)), so the first launch after this change starts fresh: settings, logs, saved themes, agent chat history, and your user config in `global.yml`, including any GitHub Enterprise Server host declarations, all begin empty. Beta also reads credentials from its own credential-store service, so sign in again. The data an earlier Beta wrote to `~/.ok/` stays there for Stable; copy `~/.ok/global.yml` or `~/.ok/themes/` into `~/.ok-beta/` yourself if you want them in Beta too.
+
+An earlier Beta stored its GitHub token in the OS credential store under the service `open-knowledge`. That token stays there and now belongs to Stable: signing out of Beta and uninstalling Beta both leave it in place. Remove it with Stable's `ok auth signout`, or delete it from your credential store directly.
+
### While a project is open
The app runs a collaboration server for the open project. It writes runtime state, gitignored under `.ok/local/`, plus a shadow git repo that powers the timeline and recovery features:
@@ -154,6 +171,8 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite
### Home directory and credentials (`~/.ok/`)
+Beta writes the `~/.ok/` entries below under `~/.ok-beta/` instead, except the shared Global-scope skill files (`~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, and `~/.ok/skills-lock.json`), which every product keeps in `~/.ok/`; see [Stable and Beta home folders](#stable-and-beta-home-folders).
+
| Path | What it is | Sensitive? |
| --- | --- | --- |
| `~/.ok/global.yml` | User-global [config](./configuration.mdx) (applies to every project) | No |
@@ -161,7 +180,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite
| `~/.ok/auth.yml` | Auth-token fallback, used only when the Keychain is unavailable. Written `0600` | **Yes** (`0600`) |
| `~/.ok/skill-state.yml`, `~/.ok/skill-install-events.jsonl` | Skill-install bookkeeping | No |
| `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No |
-| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-move-retained.json` | The same skill-install markers and unfinished-scope-move bookkeeping the tables above list under a project's `.ok/local/`, written under your home directory for Global-scope skills instead | No |
+| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, `~/.ok/skills-lock.json` | The same skill-install markers, placement records, unfinished-scope-move bookkeeping, and import provenance that a project keeps under its own `.ok/`, written under your home directory for Global-scope skills instead. Shared by every product: Beta writes these to `~/.ok/` too | No |
| `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |
| `~/.ok/agent-browser/<chat>/` | Only while **Let agent chats use a browser** is on: `npm/`, the folder that chat's browser server starts from, rebuilt each time it launches, and `files/`, everything the browser saves. Removed when you delete the chat in OpenKnowledge; turning the setting off keeps it, and nothing else clears it, so delete the folder yourself to remove every chat's saved files at once | No |
| `_npx/<hash>/` in the npm cache that launch uses: your own npm cache (`~/.npm` unless your `npm_config_cache` says otherwise) when the agent runs through your system npx, or OpenKnowledge's managed Node.js runtime cache at `~/.ok/runtimes/cache/node` when no usable system Node.js was found and the agent runs on that runtime | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. Never for custom agent commands or uv-managed adapters | No |
@@ -170,7 +189,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite
| `~/.ok/logs/`, `~/.ok/bug-reports/` | Desktop and CLI logs, and bug-report bundles from `ok bug-report` and the app's **Help → Report a bug…** dialog (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`). Each report from the dialog also gets a small YAML record holding its send state and a secret-redacted copy of the note you wrote, so report history can still show what a report was about. The zip is deleted once the report is sent; the record is kept, and both go when you delete the report from report history. If that record ever can't be read back, OpenKnowledge leaves it exactly as it is rather than overwriting your note, and writes a second tiny `.sent.yaml` file beside it when a report does send, so history still shows it as sent instead of offering to send it again | No |
| `~/.ok/bin/`, `~/.ok/env.sh` | `PATH` shim (see [Shell and `PATH`](#shell-and-path) above) | No |
-**Auth tokens** (for GitHub sync, sharing, and cloning) are stored in your OS credential store under the service name `open-knowledge` — the **Keychain** on macOS, **Credential Manager** on Windows, and the Secret Service keyring (libsecret) on Linux. The `~/.ok/auth.yml` file is only a fallback for headless environments where the credential store isn't reachable; when it becomes available, the token is migrated into it and the file copy is removed.
+**Auth tokens** (for GitHub sync, sharing, and cloning) are stored in your OS credential store under the service name `open-knowledge` (`open-knowledge-beta` for Beta) — the **Keychain** on macOS, **Credential Manager** on Windows, and the Secret Service keyring (libsecret) on Linux. The `~/.ok/auth.yml` file is only a fallback for headless environments where the credential store isn't reachable; when it becomes available, the token is migrated into it and the file copy is removed.
The **Install for Claude Chat & Cowork** command (command palette or Help menu) builds `~/Downloads/openknowledge.skill` on demand and hands it to Claude Desktop for upload; the build is version-gated via `~/.ok/skill-state.yml`.
@@ -292,6 +311,8 @@ Projects initialized by an older CLI may lack the `local/` rule in `.ok/.gitigno
### Home directory and credentials (`~/.ok/`)
+Beta writes the `~/.ok/` entries below under `~/.ok-beta/` instead, except the shared Global-scope skill files (`~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, and `~/.ok/skills-lock.json`), which every product keeps in `~/.ok/`; see [Stable and Beta home folders](#stable-and-beta-home-folders). Upgrading from an earlier Beta that used `~/.ok/`? See [Upgrading Beta to its own home folder](#upgrading-beta-to-its-own-home-folder).
+
| Path | What it is | Sensitive? |
| --- | --- | --- |
| `~/.ok/global.yml` | User-global [config](./configuration.mdx) (applies to every project) | No |
@@ -299,7 +320,7 @@ Projects initialized by an older CLI may lack the `local/` rule in `.ok/.gitigno
| `~/.ok/auth.yml` | Auth-token fallback, used when no OS credential store is reachable. Written `0600` | **Yes** (`0600`) |
| `~/.ok/skill-state.yml`, `~/.ok/skill-install-events.jsonl` | Skill-install bookkeeping | No |
| `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No |
-| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-move-retained.json` | The same skill-install markers and unfinished-scope-move bookkeeping the tables above list under a project's `.ok/local/`, written under your home directory for Global-scope skills instead | No |
+| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, `~/.ok/skills-lock.json` | The same skill-install markers, placement records, unfinished-scope-move bookkeeping, and import provenance that a project keeps under its own `.ok/`, written under your home directory for Global-scope skills instead. Shared by every product: Beta writes these to `~/.ok/` too | No |
| `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No |
| `~/.ok/agent-browser/<chat>/` | Only while **Let agent chats use a browser** is on: `npm/`, the folder that chat's browser server starts from, rebuilt each time it launches, and `files/`, everything the browser saves. Removed when you delete the chat in OpenKnowledge; turning the setting off keeps it, and nothing else clears it, so delete the folder yourself to remove every chat's saved files at once | No |
| `_npx/<hash>/` in the npm cache that launch uses: your own npm cache (`~/.npm` unless your `npm_config_cache` says otherwise) when the agent runs through your system npx, or OpenKnowledge's managed Node.js runtime cache at `~/.ok/runtimes/cache/node` when no usable system Node.js was found and the agent runs on that runtime | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. Never for custom agent commands or uv-managed adapters | No |
@@ -307,7 +328,7 @@ Projects initialized by an older CLI may lack the `local/` rule in `.ok/.gitigno
| `~/.ok/logs/` | CLI logs (`cli.<date>.log`), size- and age-capped | No |
| `~/.ok/bug-reports/` | Bug-report bundles from `ok bug-report` — the desktop app's **Help → Report a bug…** dialog writes here too (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`). A report filed from the dialog also leaves a small YAML record beside its bundle, holding the report's send state and a secret-redacted copy of the note you wrote so report history can name it. That record outlives the bundle: the zip is deleted once the report is sent, and the record is kept until you delete the report from report history. If the record ever can't be read back, OpenKnowledge leaves it exactly as it is rather than overwriting your note, and writes a second tiny `.sent.yaml` file beside it when a report does send. That marker holds only the send time and the report's reference, never your note, and it is removed with the rest of the report | No |
-**Auth tokens** (for GitHub sync, sharing, and cloning) are stored in your operating system's secure credential store when one is available — the macOS **Keychain** (service `open-knowledge`), or the platform equivalent (Windows Credential Manager, Linux Secret Service) — falling back to a `0600` `~/.ok/auth.yml` file on headless systems (a Linux server, CI) where none is reachable.
+**Auth tokens** (for GitHub sync, sharing, and cloning) are stored in your operating system's secure credential store when one is available — the macOS **Keychain** (service `open-knowledge`, or `open-knowledge-beta` for Beta), or the platform equivalent (Windows Credential Manager, Linux Secret Service) — falling back to a `0600` `~/.ok/auth.yml` file on headless systems (a Linux server, CI) where none is reachable.
</Tab>
@@ -357,7 +378,7 @@ Bridge setup requires a project directory it can resolve and access, and refuses
| Local diagnostic logs and telemetry | `telemetry.localSink.enabled: false` in config |
| Auto-starting the MCP server | `OK_MCP_AUTOSTART=0` |
-To review the footprint after the fact, `ok diagnose` reports what's on disk (and the desktop `path-install.json` records exactly which shell/`PATH` changes were made). To reverse it, `ok deinit` removes OpenKnowledge from one project and `ok uninstall` removes the global footprint, with optional project cleanup. Both keep your markdown and authored skills by default; OpenKnowledge's bundled skills are removed. Shared configs and their symlinks are preserved, and incomplete cleanup reports a failure while retaining state needed to retry. Both commands take `--dry-run` to preview. See the [CLI reference](./cli.mdx#remove-openknowledge) for project selection and scripting behavior.
+To review the footprint after the fact, `ok diagnose` reports what's on disk (and the desktop `path-install.json` records exactly which shell/`PATH` changes were made). To reverse it, `ok deinit` removes OpenKnowledge from one project and `ok uninstall` removes the global footprint, with optional project cleanup. It keeps the [shared `~/.ok/` entries](#stable-and-beta-home-folders): no product's uninstall removes `~/.ok/machine-id`, and Stable's keeps the rest of that list too. `--purge-content` also removes the user skills store at `~/.ok/skills/`, which every product shares, whichever product you uninstall; it is skipped if an earlier uninstall step failed. Both keep your markdown and authored skills by default; OpenKnowledge's bundled skills are removed. Shared configs and their symlinks are preserved, and incomplete cleanup reports a failure while retaining state needed to retry. Both commands take `--dry-run` to preview. See the [CLI reference](./cli.mdx#remove-openknowledge) for project selection and scripting behavior.
In the desktop app you don't need the CLI for finer control, and the split follows what each thing is. **Settings → Agent connections** lists every agent OpenKnowledge can wire up, grouped by how you reach it — In app, Terminal, External apps. Each row says whether OpenKnowledge can reach that agent's tools and offers the action that fits: **Add MCP & skill** when nothing is set up, **Manage** when something is, and **Remove** when the tool itself is present but you have turned it off. A tool that is not on this machine always leads with **Install**, or **How to set up** when OpenKnowledge has no download link for it; neither writes anything. When OpenKnowledge files are still on disk for a tool that is not on this machine, the row keeps whichever of **Install** or **How to set up** it already had, and adds a muted **Remove** link beside the hint — `Not installed · OpenKnowledge files present`, or `Not detected on this machine · OpenKnowledge files present` for a tool OpenKnowledge cannot launch directly. Where one tool has two rows — a CLI and its editor, sharing a single setup — that hint and link appear only when OpenKnowledge can confirm the other row's tool is also absent, so the row for the half you do not have never offers to delete a setup the other half is using — and when it cannot tell, it says nothing rather than guess. Both scopes are chosen in the same place: the dialog behind those actions groups what it writes under *This project* and *This machine*, so a project-scoped MCP config and a user-global one sit side by side, each naming the file it touches. *Skills* live on their own page at both scopes: **Settings → Skills Studio** carries the skills OpenKnowledge ships (user scope) or the project's own skill (project scope), each with an explicit Install/Uninstall button behind a confirmation naming every path it touches, plus the folders your AI tools read skills from. Removal keeps the guest discipline you would expect: only entries OpenKnowledge recognizably wrote are removed, and anything you customized is left intact.
diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.ts
index 3e235bd4a..75c48c9da 100644
--- a/packages/app/src/server/hocuspocus-plugin.ts
+++ b/packages/app/src/server/hocuspocus-plugin.ts
@@ -1,12 +1,11 @@
import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
-import { homedir } from 'node:os';
import { relative, resolve } from 'node:path';
import {
ASSET_EXTENSIONS,
EXECUTABLE_BLOCKLIST_EXTENSIONS,
INLINE_RENDERABLE_EXTENSIONS,
- OK_DIR,
} from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import {
AcpThreadManager,
buildIngressPolicy,
@@ -190,7 +189,7 @@ export function hocuspocusPlugin(): Plugin {
: new AcpThreadManager({
contentDir: CONTENT_DIR,
localDir: currentSrv.lockDir,
- globalDir: resolve(homedir(), OK_DIR),
+ globalDir: okUserHomeDir(),
registry: currentSrv.acpRegistry,
permissions: currentSrv.acpPermissions,
sessionManager,
diff --git a/packages/cli/src/auth/token-store.test.ts b/packages/cli/src/auth/token-store.test.ts
index 68aa70201..4ef01b6f4 100644
--- a/packages/cli/src/auth/token-store.test.ts
+++ b/packages/cli/src/auth/token-store.test.ts
@@ -752,3 +752,70 @@ describe('createTokenStore cross-backend read fallback', () => {
expect(await store.get('github.com')).toBeNull();
});
});
+
+describe('credentials per channel', () => {
+ let fakeHome: string;
+
+ beforeEach(() => {
+ resetKeyringMockState();
+ fakeHome = mkdtempSync(join(tmpdir(), 'ok-ts-channel-'));
+ vi.stubEnv('HOME', fakeHome);
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ rmSync(fakeHome, { recursive: true, force: true });
+ });
+
+ test('Stable keeps the open-knowledge keychain service and ~/.ok/auth.yml', async () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ const { createTokenStore, FileBackend: ChannelFileBackend } = await import('./token-store.ts');
+ await (await createTokenStore(join(fakeHome, 'unused.yml'))).set('github.com', 'a', 't');
+ expect(keyringMockState.setPasswordCalls.map((c) => c.service)).toEqual(['open-knowledge']);
+ await new ChannelFileBackend().set('github.com', 'a', 't');
+ expect(readFileSync(join(fakeHome, '.ok', 'auth.yml'), 'utf-8')).toContain('github.com');
+ });
+
+ test('Beta uses its own keychain service and ~/.ok-beta/auth.yml, sharing nothing', async () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ const { createTokenStore, FileBackend: ChannelFileBackend } = await import('./token-store.ts');
+ await (await createTokenStore(join(fakeHome, 'unused.yml'))).set('github.com', 'a', 't');
+ expect(keyringMockState.setPasswordCalls.map((c) => c.service)).toEqual([
+ 'open-knowledge-beta',
+ ]);
+ await new ChannelFileBackend().set('github.com', 'a', 't');
+ expect(readFileSync(join(fakeHome, '.ok-beta', 'auth.yml'), 'utf-8')).toContain('github.com');
+ expect(() => readFileSync(join(fakeHome, '.ok', 'auth.yml'), 'utf-8')).toThrow();
+ });
+
+ test('Beta reads, clears and clears-all only its own keychain service', async () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ keyringMockState.getPasswordReturns.set(
+ 'open-knowledge:github.com',
+ JSON.stringify({ login: 'stable', token: 'gho_stable' }),
+ );
+ keyringMockState.getPasswordReturns.set(
+ 'open-knowledge-beta:github.com',
+ JSON.stringify({ login: 'beta', token: 'gho_beta' }),
+ );
+ const { createTokenStore, clearTokenFromAllBackends } = await import('./token-store.ts');
+ const authFile = join(fakeHome, 'unused.yml');
+ const store = await createTokenStore(authFile);
+
+ expect((await store.get('github.com'))?.token).toBe('gho_beta');
+
+ await store.clear('github.com');
+ expect(keyringMockState.deletePasswordCalls.map((c) => c.service)).toEqual([
+ 'open-knowledge-beta',
+ ]);
+
+ keyringMockState.deletePasswordCalls = [];
+ const result = await clearTokenFromAllBackends('github.com', authFile);
+ expect(result.touched).toEqual(['keychain']);
+ expect(keyringMockState.deletePasswordCalls.map((c) => c.service)).toEqual([
+ 'open-knowledge-beta',
+ ]);
+ });
+});
diff --git a/packages/cli/src/auth/token-store.ts b/packages/cli/src/auth/token-store.ts
index 00257f7cc..be65dcaa4 100644
--- a/packages/cli/src/auth/token-store.ts
+++ b/packages/cli/src/auth/token-store.ts
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
-import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
-import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import { currentDesktopProduct, okUserHomeDisplayPath } from '@inkeep/open-knowledge-core';
+import { atomicWriteFileSync, okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { parse as yamlParse, stringify as yamlStringify } from 'yaml';
interface TokenEntry {
@@ -24,7 +24,13 @@ export interface TokenStore {
clear(host: string): Promise<void>;
}
-const KEYRING_SERVICE = 'open-knowledge';
+export function authFileDisplayPath(): string {
+ return okUserHomeDisplayPath('auth.yml');
+}
+
+function keyringService(): string {
+ return currentDesktopProduct().keyringService;
+}
function safeDiag(fn: () => void): void {
try {
@@ -54,7 +60,7 @@ class KeyringBackend implements TokenStore {
const { Entry } = await import('@napi-rs/keyring');
let raw: string | null;
try {
- raw = new Entry(KEYRING_SERVICE, host).getPassword();
+ raw = new Entry(keyringService(), host).getPassword();
} catch (e) {
safeDiag(() =>
this.onKeychainRead?.({
@@ -88,7 +94,7 @@ class KeyringBackend implements TokenStore {
extra?: Pick<TokenEntry, 'gitProtocol' | 'name' | 'email'>,
): Promise<void> {
const { Entry } = await import('@napi-rs/keyring');
- const entry = new Entry(KEYRING_SERVICE, host);
+ const entry = new Entry(keyringService(), host);
const data: TokenEntry = { login, token, ...extra };
entry.setPassword(JSON.stringify(data));
}
@@ -96,7 +102,7 @@ class KeyringBackend implements TokenStore {
async clear(host: string): Promise<void> {
const { Entry } = await import('@napi-rs/keyring');
try {
- const entry = new Entry(KEYRING_SERVICE, host);
+ const entry = new Entry(keyringService(), host);
entry.deletePassword();
} catch {}
}
@@ -107,7 +113,7 @@ export class FileBackend implements TokenStore {
private readonly authFile: string;
constructor(authFile?: string) {
- this.authFile = authFile ?? join(homedir(), '.ok', 'auth.yml');
+ this.authFile = authFile ?? join(okUserHomeDir(), 'auth.yml');
}
private read(): Record<string, TokenEntry> {
@@ -177,7 +183,7 @@ class KeychainWithFileFallback implements TokenStore {
});
await this.file.clear(host);
process.stderr.write(
- `[auth] migrated ${host} credential from ~/.ok/auth.yml to the OS keychain\n`,
+ `[auth] migrated ${host} credential from ${authFileDisplayPath()} to the OS keychain\n`,
);
} catch {}
return fromFile;
@@ -204,7 +210,7 @@ export async function createTokenStore(
): Promise<TokenStore> {
try {
const { Entry } = await import('@napi-rs/keyring');
- new Entry(KEYRING_SERVICE, '__probe__');
+ new Entry(keyringService(), '__probe__');
process.stderr.write('[auth] token storage: OS keychain\n');
safeDiag(() => diag?.onBackendSelected?.({ backend: 'keyring' }));
return new KeychainWithFileFallback(
@@ -214,7 +220,7 @@ export async function createTokenStore(
} catch (e) {
const reason = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
process.stderr.write(
- `[auth] token storage: file (~/.ok/auth.yml) — OS keychain unavailable: ${reason}\n`,
+ `[auth] token storage: file (${authFileDisplayPath()}) — OS keychain unavailable: ${reason}\n`,
);
safeDiag(() => diag?.onBackendSelected?.({ backend: 'file', reason }));
return new FileBackend(authFile);
@@ -231,7 +237,7 @@ function lazyResolveTokenStore(authFile: string | undefined): () => Promise<Toke
const timeout = new Promise<TokenStore>((res) => {
timer = setTimeout(() => {
process.stderr.write(
- `[auth] token storage: keyring init exceeded ${TIMEOUT_MS}ms; falling back to file (~/.ok/auth.yml)\n`,
+ `[auth] token storage: keyring init exceeded ${TIMEOUT_MS}ms; falling back to file (${authFileDisplayPath()})\n`,
);
res(new FileBackend(authFile));
}, TIMEOUT_MS);
@@ -295,7 +301,7 @@ export async function clearTokenFromAllBackends(
let keychainError: string | undefined;
try {
const { Entry } = await import('@napi-rs/keyring');
- new Entry(KEYRING_SERVICE, '__probe__');
+ new Entry(keyringService(), '__probe__');
let readError: string | undefined;
const keyring = new KeyringBackend((info) => {
if (info.kind === 'read-error') readError = info.error ?? 'read-error';
@@ -305,7 +311,7 @@ export async function clearTokenFromAllBackends(
keychainError = readError;
} else if (existing != null) {
try {
- new Entry(KEYRING_SERVICE, host).deletePassword();
+ new Entry(keyringService(), host).deletePassword();
touched.push('keychain');
} catch (e) {
keychainError = e instanceof Error ? e.name : 'delete-error';
diff --git a/packages/cli/src/commands/auth/signout.ts b/packages/cli/src/commands/auth/signout.ts
index 0c92cbad8..b5e1ecb65 100644
--- a/packages/cli/src/commands/auth/signout.ts
+++ b/packages/cli/src/commands/auth/signout.ts
@@ -1,5 +1,5 @@
import { Command } from 'commander';
-import { clearTokenFromAllBackends } from '../../auth/token-store.ts';
+import { authFileDisplayPath, clearTokenFromAllBackends } from '../../auth/token-store.ts';
import { resolveSignoutHost } from './validate-host.ts';
interface SignoutOptions {
@@ -20,7 +20,7 @@ async function runSignout(opts: SignoutOptions): Promise<void> {
process.stderr.write(` cleared from OS keychain\n`);
}
if (touched.includes('file')) {
- process.stderr.write(` cleared from ~/.ok/auth.yml\n`);
+ process.stderr.write(` cleared from ${authFileDisplayPath()}\n`);
}
}
diff --git a/packages/cli/src/commands/auth/validate-host.test.ts b/packages/cli/src/commands/auth/validate-host.test.ts
index 26f9edc8b..1516966c3 100644
--- a/packages/cli/src/commands/auth/validate-host.test.ts
+++ b/packages/cli/src/commands/auth/validate-host.test.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { error as errorColor } from '../../ui/colors.ts';
import { gitHubHostRejection, resolveAuthHost, validateGitHubHost } from './validate-host.ts';
function hostsYaml(provider: string, ...hostnames: string[]): string {
@@ -70,6 +71,21 @@ describe('gitHubHostRejection', () => {
);
});
+ test('prints the Stable remedy byte-for-byte', () => {
+ vi.stubEnv('OK_CHANNEL', '');
+ expect(gitHubHostRejection('git.example.internal')).toBe(
+ `${errorColor('Error:')} git.example.internal is not a known GitHub host.\n` +
+ 'To use a GitHub Enterprise Server host, declare it in ~/.ok/global.yml:\n\n git:\n hosts:\n git.example.internal:\n provider: github\n',
+ );
+ });
+
+ test('names the Beta user config when the running channel is Beta', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ const rejection = gitHubHostRejection('git.example.internal');
+ expect(rejection).toContain('declare it in ~/.ok-beta/global.yml:\n');
+ expect(rejection).not.toContain('~/.ok/');
+ });
+
test('suggests a port-free hostname as the config key', () => {
expect(gitHubHostRejection('ghes.example.com:8443')).toContain(
' ghes.example.com:\n provider: github',
diff --git a/packages/cli/src/commands/auth/validate-host.ts b/packages/cli/src/commands/auth/validate-host.ts
index 20f0b9e1a..42e7c9bd1 100644
--- a/packages/cli/src/commands/auth/validate-host.ts
+++ b/packages/cli/src/commands/auth/validate-host.ts
@@ -1,4 +1,8 @@
-import { isGitHubHost, normalizeGitHostname } from '@inkeep/open-knowledge-core';
+import {
+ isGitHubHost,
+ normalizeGitHostname,
+ okUserHomeDisplayPath,
+} from '@inkeep/open-knowledge-core';
import {
findEnclosingProjectRoot,
readDeclaredGitHubHosts,
@@ -12,7 +16,7 @@ function authProjectDir(): string {
}
function declarationRemedy(host: string): string {
- return `~/.ok/global.yml:\n\n git:\n hosts:\n ${host}:\n provider: github\n`;
+ return `${okUserHomeDisplayPath('global.yml')}:\n\n git:\n hosts:\n ${host}:\n provider: github\n`;
}
function explicitGitHubHostRejection(host: string): string {
diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.ts
index fd152a89b..2962e6ff5 100644
--- a/packages/cli/src/commands/bug-report-bundle.ts
+++ b/packages/cli/src/commands/bug-report-bundle.ts
@@ -1,7 +1,7 @@
import { execSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
-import { freemem, homedir, type as osType, platform, release, totalmem, uptime } from 'node:os';
+import { freemem, type as osType, platform, release, totalmem, uptime } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import {
ACP_LAUNCH_FAILURE_LOG,
@@ -11,6 +11,7 @@ import {
REPORT_SIDECAR_BUNDLE_DIR,
SERVER_CRASH_LOG,
} from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
import type { ZipFile } from 'yazl';
import type { DesktopMetadata } from '../diagnose/bundle.ts';
@@ -24,7 +25,7 @@ import { redactContent, SECRET_PATTERN_NAMES } from './bug-report-redact.ts';
import { DESKTOP_BUNDLE_ID } from './desktop-dispatch.ts';
export function okBugReportsDir(): string {
- return join(homedir(), '.ok', 'bug-reports');
+ return join(okUserHomeDir(), 'bug-reports');
}
export function defaultBugReportZipPath(now: Date = new Date()): string {
@@ -356,7 +357,7 @@ export async function collectStandardBundle(
): Promise<StandardBundleResult> {
const { redact, outputPath, logger } = opts;
const revealDocNames = opts.revealDocNames ?? false;
- const userLogsDir = opts.userLogsDir ?? join(homedir(), '.ok', 'logs');
+ const userLogsDir = opts.userLogsDir ?? join(okUserHomeDir(), 'logs');
const projectSlug = opts.projectDir ? resolveProjectSlug(opts.projectDir, logger) : null;
mkdirSync(dirname(outputPath), { recursive: true });
diff --git a/packages/cli/src/commands/cowork.ts b/packages/cli/src/commands/cowork.ts
index 9ddd86083..4a111a701 100644
--- a/packages/cli/src/commands/cowork.ts
+++ b/packages/cli/src/commands/cowork.ts
@@ -1,3 +1,4 @@
+import { okUserHomeDisplayPath } from '@inkeep/open-knowledge-core';
import {
type BuildAndOpenSkillResult,
buildAndOpenSkill,
@@ -49,7 +50,7 @@ function formatSkipCurrentMessage(result: BuildAndOpenSkillResult): string {
const recordedAt = result.recordedAt ?? 'unknown';
return [
info(`OpenKnowledge skill ${accent(`v${version}`)} already delivered to Claude Desktop.`),
- dim(` Recorded at ${recordedAt} in ~/.ok/skill-state.yml`),
+ dim(` Recorded at ${recordedAt} in ${okUserHomeDisplayPath('skill-state.yml')}`),
dim(` Use ${accent('--force')} to rebuild and re-open the install dialog.`),
].join('\n');
}
diff --git a/packages/cli/src/commands/embeddings/index.ts b/packages/cli/src/commands/embeddings/index.ts
index d7963c558..88b12f4f6 100644
--- a/packages/cli/src/commands/embeddings/index.ts
+++ b/packages/cli/src/commands/embeddings/index.ts
@@ -6,6 +6,7 @@ import {
DEFAULT_EMBEDDINGS_MODEL,
humanFormat,
isSemanticSearchOffered,
+ okUserHomeDisplayPath,
type SemanticIndexStatus,
SemanticIndexStatusSchema,
} from '@inkeep/open-knowledge-core';
@@ -118,7 +119,7 @@ function setKeyCommand(): Command {
}
process.stderr.write(
`✓ Embeddings API key stored for ${baseUrl}\n` +
- ' (kept in ~/.ok/secrets.yml, 0600, this machine only — never in the project).\n' +
+ ` (kept in ${okUserHomeDisplayPath('secrets.yml')}, 0600, this machine only — never in the project).\n` +
' Enable semantic search with `ok embeddings enable`, or in\n' +
' OK Desktop → Settings → This project → Search.\n',
);
@@ -365,7 +366,7 @@ function statusCommand(): Command {
}
const keyLabel = hasKey
- ? `set for this endpoint — ${keySource === 'env' ? `environment (${EMBEDDINGS_API_KEY_ENV})` : '~/.ok/secrets.yml'}`
+ ? `set for this endpoint — ${keySource === 'env' ? `environment (${EMBEDDINGS_API_KEY_ENV})` : okUserHomeDisplayPath('secrets.yml')}`
: keyNotRequired
? 'not required (loopback endpoint)'
: 'not set';
diff --git a/packages/cli/src/commands/pi-acp-bridge.ts b/packages/cli/src/commands/pi-acp-bridge.ts
index 7cb0748ba..21b2568fa 100644
--- a/packages/cli/src/commands/pi-acp-bridge.ts
+++ b/packages/cli/src/commands/pi-acp-bridge.ts
@@ -14,7 +14,7 @@ import type {
PiBridgeWriteAction,
PiTrustWriteAction,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
-import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import { atomicWriteFileSync, okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { buildPiExtensionSource, isOwnPiManagedFileEntry } from '../integrations/pi-extension.ts';
import {
type ConfigFileDeclineReason,
@@ -644,7 +644,7 @@ function accessPiTrustReceipts<T>(home: string, operation: () => T): T {
} catch (error) {
if (error instanceof PiTrustReceiptError) throw error;
throw new Error(
- `Could not access OpenKnowledge's Pi trust ownership records at ${escapeDisplayPath(join(home, '.ok', 'pi-trust'))}: ${escapeDisplayPath(error instanceof Error ? error.message : String(error))}. Check the records and their permissions, then retry.`,
+ `Could not access OpenKnowledge's Pi trust ownership records at ${escapeDisplayPath(join(okUserHomeDir(home), 'pi-trust'))}: ${escapeDisplayPath(error instanceof Error ? error.message : String(error))}. Check the records and their permissions, then retry.`,
{ cause: error },
);
}
diff --git a/packages/cli/src/commands/pi-trust-grants.ts b/packages/cli/src/commands/pi-trust-grants.ts
index 98703df9a..6902dcf83 100644
--- a/packages/cli/src/commands/pi-trust-grants.ts
+++ b/packages/cli/src/commands/pi-trust-grants.ts
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
import { lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { isDeepStrictEqual } from 'node:util';
-import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import { atomicWriteFileSync, okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { escapeDisplayPath } from '../utils/escape-display-path.ts';
import { isObject } from '../utils/is-object.ts';
@@ -27,7 +27,7 @@ function digest(path: string): string {
}
function receiptsRoot(home: string): string {
- return join(resolve(home), '.ok', 'pi-trust');
+ return join(okUserHomeDir(resolve(home)), 'pi-trust');
}
function receiptsDirectory(home: string, cwd: string): string {
diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.ts
index b326fc4b1..654c5abf1 100644
--- a/packages/cli/src/commands/removal-plan.test.ts
+++ b/packages/cli/src/commands/removal-plan.test.ts
@@ -11,9 +11,10 @@ import {
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
-import { dirname, join } from 'node:path';
+import { dirname, join, relative } from 'node:path';
+import { SHARED_OK_ENTRIES } from '@inkeep/open-knowledge-core';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
-import { describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { DESKTOP_UPDATER_CACHE_DIR_NAME } from '../integrations/desktop-state.ts';
import { readPathInstallMarker } from '../integrations/path-shim.ts';
import {
@@ -441,13 +442,16 @@ describe('runRemoval — uninstall end to end', () => {
}
});
- test('--purge-content also removes user-authored ~/.ok/skills', async () => {
+ test('--purge-content also removes user-authored ~/.ok/skills but keeps the shared machine-id', async () => {
const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
try {
seedHome(home);
+ write(join(home, '.ok', 'machine-id'), 'abc\n');
const plan = buildUninstallPlan(baseInput(home, { purgeContent: true }));
await runRemoval(plan, stubDeps());
- expect(existsSync(join(home, '.ok'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'skills'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ expect(readFileSync(join(home, '.ok', 'machine-id'), 'utf-8')).toBe('abc\n');
} finally {
rmSync(home, { recursive: true, force: true });
}
@@ -1314,3 +1318,206 @@ describe('shell configuration symlinks', () => {
},
);
});
+
+describe('uninstall owns only its own channel', () => {
+ const STABLE_BLOCK =
+ '# >>> open-knowledge cli >>>\n[ -f "$HOME/.ok/env.sh" ] && . "$HOME/.ok/env.sh"\n# <<< open-knowledge cli <<<\n';
+ const BETA_BLOCK =
+ '# >>> open-knowledge beta cli >>>\n[ -f "$HOME/.ok-beta/env.sh" ] && . "$HOME/.ok-beta/env.sh"\n# <<< open-knowledge beta cli <<<\n';
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ function seedBothChannels(home: string): string {
+ write(join(home, '.ok', 'auth.yml'), 'github.com: {}\n');
+ write(join(home, '.ok-beta', 'auth.yml'), 'github.com: {}\n');
+ write(join(home, '.ok', 'machine-id'), 'shared-id\n');
+ write(join(home, '.ok', 'skills', 'mine', 'SKILL.md'), '# mine\n');
+ const zshrc = join(home, '.zshrc');
+ writeFileSync(zshrc, `export EDITOR=vim\n\n${STABLE_BLOCK}\n${BETA_BLOCK}`);
+ return zshrc;
+ }
+
+ function planPaths(ops: readonly RemovalOp[]): string[] {
+ return ops.flatMap((op) => ('path' in op ? [op.path] : 'rcFile' in op ? [op.rcFile] : []));
+ }
+
+ test('Stable removes ~/.ok and its own rc block, never ~/.ok-beta or Beta app data', async () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-channel-'));
+ try {
+ const zshrc = seedBothChannels(home);
+ const plan = buildUninstallPlan(baseInput(home, { marker: null }));
+ const globalOp = plan.ops.find((o) => o.group === 'Global directory');
+ expect(globalOp).toMatchObject({
+ path: join(home, '.ok'),
+ label:
+ 'Remove ~/.ok (keeping ~/.ok/machine-id, ~/.ok/skills, ~/.ok/skills-lock.json, ~/.ok/local/installed-skills.json, ~/.ok/local/skill-placements.json, ~/.ok/local/skill-move-retained.json, shared by every channel)',
+ });
+ const paths = planPaths(plan.ops);
+ expect(paths).toContain(join(home, 'Library', 'Application Support', 'OpenKnowledge'));
+ expect(paths).toContain(join(home, 'Library', 'Caches', DESKTOP_UPDATER_CACHE_DIR_NAME));
+ expect(paths.filter((p) => relative(home, p).toLowerCase().includes('beta'))).toEqual([]);
+
+ expect((await runRemoval(plan, stubDeps())).failed).toHaveLength(0);
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ expect(readFileSync(join(home, '.ok', 'machine-id'), 'utf-8')).toBe('shared-id\n');
+ expect(existsSync(join(home, '.ok', 'skills', 'mine', 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(home, '.ok-beta', 'auth.yml'))).toBe(true);
+ const after = readFileSync(zshrc, 'utf-8');
+ expect(after).not.toContain('# >>> open-knowledge cli >>>');
+ expect(after).toContain(BETA_BLOCK);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('Beta removes ~/.ok-beta and its own rc block, never ~/.ok or Stable app data', async () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-channel-'));
+ try {
+ const zshrc = seedBothChannels(home);
+ const plan = buildUninstallPlan(baseInput(home, { marker: null }));
+ const globalOp = plan.ops.find((o) => o.group === 'Global directory');
+ expect(globalOp).toMatchObject({
+ path: join(home, '.ok-beta'),
+ label: 'Remove ~/.ok-beta (keeping ~/.ok/skills, shared by every channel)',
+ });
+ expect(globalOp).not.toHaveProperty('preserve');
+ const paths = planPaths(plan.ops);
+ expect(paths).toContain(join(home, 'Library', 'Application Support', 'OpenKnowledge Beta'));
+ expect(paths).toContain(
+ join(home, 'Library', 'Caches', 'openknowledge-beta-desktop-updater'),
+ );
+ expect(
+ paths.filter(
+ (p) =>
+ p === join(home, '.ok') ||
+ p.startsWith(`${join(home, '.ok')}/`) ||
+ p.endsWith('/OpenKnowledge') ||
+ p.endsWith('/Open Knowledge') ||
+ p.endsWith(DESKTOP_UPDATER_CACHE_DIR_NAME),
+ ),
+ ).toEqual([]);
+
+ expect((await runRemoval(plan, stubDeps())).failed).toHaveLength(0);
+ expect(existsSync(join(home, '.ok-beta', 'auth.yml'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);
+ expect(readFileSync(join(home, '.ok', 'machine-id'), 'utf-8')).toBe('shared-id\n');
+ expect(existsSync(join(home, '.ok', 'skills', 'mine', 'SKILL.md'))).toBe(true);
+ const after = readFileSync(zshrc, 'utf-8');
+ expect(after).toContain(STABLE_BLOCK);
+ expect(after).not.toContain('open-knowledge beta cli');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('Beta --purge-content removes the shared ~/.ok/skills store, never ~/.ok/machine-id', async () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-channel-'));
+ try {
+ seedBothChannels(home);
+ const plan = buildUninstallPlan(baseInput(home, { marker: null, purgeContent: true }));
+ expect(plan.ops.filter((o) => o.group === 'Global directory')).toMatchObject([
+ { path: join(home, '.ok-beta'), label: 'Remove ~/.ok-beta' },
+ {
+ path: join(home, '.ok', 'skills'),
+ label: 'Remove ~/.ok/skills (user-authored skills, shared by every channel)',
+ },
+ ]);
+
+ expect((await runRemoval(plan, stubDeps())).failed).toHaveLength(0);
+ expect(existsSync(join(home, '.ok-beta'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'skills'))).toBe(false);
+ expect(readFileSync(join(home, '.ok', 'machine-id'), 'utf-8')).toBe('shared-id\n');
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ const SHARED_BOOKKEEPING = [
+ ['skills-lock.json'],
+ ['local', 'installed-skills.json'],
+ ['local', 'skill-placements.json'],
+ ['local', 'skill-move-retained.json'],
+ ];
+
+ test.each([false, true])(
+ 'Stable keeps machine-id and the global skill bookkeeping every channel reads (purgeContent=%s)',
+ async (purgeContent) => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-channel-'));
+ try {
+ seedBothChannels(home);
+ for (const rel of SHARED_BOOKKEEPING) write(join(home, '.ok', ...rel), '{}\n');
+ write(join(home, '.ok', 'local', 'logs', 'server.log'), 'log\n');
+ write(join(home, '.ok', 'local', 'conflicts.json'), '{}\n');
+ const plan = buildUninstallPlan(baseInput(home, { marker: null, purgeContent }));
+ const globalOp = plan.ops.find((o) => o.group === 'Global directory');
+ for (const entry of SHARED_OK_ENTRIES) {
+ if (purgeContent && entry === 'skills') continue;
+ expect(globalOp?.label).toContain(`~/.ok/${entry},`);
+ }
+ expect(globalOp?.label?.startsWith('Remove ~/.ok (including user-authored skills;')).toBe(
+ purgeContent,
+ );
+
+ expect((await runRemoval(plan, stubDeps())).failed).toHaveLength(0);
+ for (const rel of SHARED_BOOKKEEPING) {
+ expect(readFileSync(join(home, '.ok', ...rel), 'utf-8')).toBe('{}\n');
+ }
+ expect(readFileSync(join(home, '.ok', 'machine-id'), 'utf-8')).toBe('shared-id\n');
+ expect(existsSync(join(home, '.ok', 'local', 'logs'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'local', 'conflicts.json'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'skills', 'mine', 'SKILL.md'))).toBe(!purgeContent);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ },
+ );
+
+ test('Beta --purge-content leaves ~/.ok/skills untouched after an earlier failure', async () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-channel-'));
+ try {
+ seedBothChannels(home);
+ const plan = buildUninstallPlan(baseInput(home, { marker: null, purgeContent: true }));
+ const outcome = await runRemoval(
+ plan,
+ stubDeps({ clearToken: async () => ({ touched: [], keychainError: 'locked' }) }),
+ );
+ const skillsResult = outcome.results.find(
+ (r) => r.op.kind === 'remove-path' && r.op.path === join(home, '.ok', 'skills'),
+ );
+ expect(skillsResult?.status).toBe('blocked');
+ expect(existsSync(join(home, '.ok', 'skills', 'mine', 'SKILL.md'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test.each([
+ ['stable', 'open-knowledge'],
+ ['beta', 'open-knowledge-beta'],
+ ])('a keychain failure on %s names that channel keychain service', async (channel, service) => {
+ vi.stubEnv('OK_CHANNEL', channel);
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-channel-'));
+ try {
+ const plan = buildUninstallPlan(baseInput(home, { marker: null }));
+ const outcome = await runRemoval(
+ plan,
+ stubDeps({ clearToken: async () => ({ touched: [], keychainError: 'locked' }) }),
+ );
+ const keychain = outcome.results.find((r) => r.op.kind === 'keychain-token');
+ expect(keychain?.detail).toBe(
+ `keychain unreachable (locked); remove manually: Keychain Access → service "${service}"`,
+ );
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.ts
index ba883046d..268297b06 100644
--- a/packages/cli/src/commands/removal-plan.ts
+++ b/packages/cli/src/commands/removal-plan.ts
@@ -1,7 +1,14 @@
import { lstatSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';
import { basename, join, relative, resolve, sep } from 'node:path';
-import { PROJECT_SKILL_PROJECTION_PATHS } from '@inkeep/open-knowledge-core';
-import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import {
+ currentDesktopProduct,
+ OK_DIR,
+ PROJECT_SKILL_PROJECTION_PATHS,
+ resolveDesktopProductName,
+ SHARED_OK_ENTRIES,
+ SKILLS_STORE_DIRNAME,
+} from '@inkeep/open-knowledge-core';
+import { atomicWriteFileSync, okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import {
createProbeFailureReporter,
@@ -20,6 +27,7 @@ import {
import {
extraSymlinkStillOurs,
type PathInstallMarker,
+ pathShimFishConfName,
stripManagedPathBlock,
} from '../integrations/path-shim.ts';
import { userGlobalSkillBundleTargets } from '../integrations/skill-teardown.ts';
@@ -96,6 +104,18 @@ export interface RemovalOutcome {
failed: RemovalOpResult[];
}
+function sharedOkEntriesKept(purgeContent: boolean): string[] {
+ return purgeContent
+ ? SHARED_OK_ENTRIES.filter((entry) => entry !== SKILLS_STORE_DIRNAME)
+ : [...SHARED_OK_ENTRIES];
+}
+
+export function sharedOkEntriesList(purgeContent: boolean): string {
+ return sharedOkEntriesKept(purgeContent)
+ .map((entry) => `~/${OK_DIR}/${entry}`)
+ .join(', ');
+}
+
function tildify(p: string, home: string): string {
return p === home ? '~' : p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p;
}
@@ -286,16 +306,38 @@ export function buildUninstallPlan(input: UninstallPlanInput): RemovalPlan {
),
);
- ops.push({
- kind: 'remove-path',
- group: 'Global directory',
- requiresSuccessfulCleanup: true,
- label: purgeContent
- ? 'Remove ~/.ok (including user-authored skills)'
- : 'Remove ~/.ok (keeping ~/.ok/skills)',
- path: join(home, '.ok'),
- preserve: purgeContent ? undefined : ['skills'],
- });
+ const { userHomeDirName } = currentDesktopProduct();
+ if (userHomeDirName === OK_DIR) {
+ ops.push({
+ kind: 'remove-path',
+ group: 'Global directory',
+ requiresSuccessfulCleanup: true,
+ label: purgeContent
+ ? `Remove ~/${OK_DIR} (including user-authored skills; keeping ${sharedOkEntriesList(true)}, shared by every channel)`
+ : `Remove ~/${OK_DIR} (keeping ${sharedOkEntriesList(false)}, shared by every channel)`,
+ path: okUserHomeDir(home),
+ preserve: sharedOkEntriesKept(purgeContent),
+ });
+ } else {
+ ops.push({
+ kind: 'remove-path',
+ group: 'Global directory',
+ requiresSuccessfulCleanup: true,
+ label: purgeContent
+ ? `Remove ~/${userHomeDirName}`
+ : `Remove ~/${userHomeDirName} (keeping ~/${OK_DIR}/${SKILLS_STORE_DIRNAME}, shared by every channel)`,
+ path: okUserHomeDir(home),
+ });
+ if (purgeContent) {
+ ops.push({
+ kind: 'remove-path',
+ group: 'Global directory',
+ requiresSuccessfulCleanup: true,
+ label: `Remove ~/${OK_DIR}/${SKILLS_STORE_DIRNAME} (user-authored skills, shared by every channel)`,
+ path: join(home, OK_DIR, SKILLS_STORE_DIRNAME),
+ });
+ }
+ }
return { scope: 'uninstall', ops };
}
@@ -304,7 +346,7 @@ function standardRcFiles(home: string): string[] {
return [
join(home, '.zshrc'),
join(home, '.bash_profile'),
- join(home, '.config', 'fish', 'conf.d', 'open-knowledge.fish'),
+ join(home, '.config', 'fish', 'conf.d', pathShimFishConfName()),
];
}
@@ -350,7 +392,7 @@ export function applicationDataOps(
},
];
- if (platform === 'darwin') {
+ if (platform === 'darwin' && resolveDesktopProductName() === 'stable') {
const legacy = desktopUserDataDir({ ...options, productName: DESKTOP_LEGACY_PRODUCT_NAME });
ops.push({
kind: 'remove-path',
@@ -524,7 +566,7 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRe
return {
op,
status: 'failed',
- detail: `keychain unreachable (${keychainError}); remove manually: Keychain Access → service "open-knowledge"`,
+ detail: `keychain unreachable (${keychainError}); remove manually: Keychain Access → service "${currentDesktopProduct().keyringService}"`,
};
}
return { op, status: touched.length > 0 ? 'removed' : 'not-present' };
@@ -728,20 +770,31 @@ function executeRemovePath(op: Extract<RemovalOp, { kind: 'remove-path' }>): Rem
}
if (op.preserve && op.preserve.length > 0) {
- const keep = new Set(op.preserve);
- let removedAny = false;
- for (const entry of readdirSync(op.path)) {
- if (keep.has(entry)) continue;
- rmSync(join(op.path, entry), { recursive: true, force: true });
- removedAny = true;
- }
- return { op, status: removedAny ? 'removed' : 'not-present' };
+ return { op, status: removeAllExcept(op.path, op.preserve) ? 'removed' : 'not-present' };
}
rmSync(op.path, { recursive: true, force: true });
return { op, status: 'removed' };
}
+function removeAllExcept(dir: string, keep: readonly string[]): boolean {
+ let removedAny = false;
+ for (const entry of readdirSync(dir)) {
+ if (keep.includes(entry)) continue;
+ const path = join(dir, entry);
+ const nested = keep.flatMap((kept) =>
+ kept.startsWith(`${entry}/`) ? [kept.slice(entry.length + 1)] : [],
+ );
+ if (nested.length > 0 && lstatSync(path).isDirectory()) {
+ if (removeAllExcept(path, nested)) removedAny = true;
+ continue;
+ }
+ rmSync(path, { recursive: true, force: true });
+ removedAny = true;
+ }
+ return removedAny;
+}
+
function removableGitExcludePaths(projectRoot: string): readonly string[] {
const sharedPaths = new Set<string>([join(projectRoot, '.claude', 'launch.json')]);
for (const id of ALL_EDITOR_IDS) {
diff --git a/packages/cli/src/commands/stop-for-removal.ts b/packages/cli/src/commands/stop-for-removal.ts
index a7fd05f5e..e70be4fac 100644
--- a/packages/cli/src/commands/stop-for-removal.ts
+++ b/packages/cli/src/commands/stop-for-removal.ts
@@ -1,6 +1,7 @@
import { realpath } from 'node:fs/promises';
import { resolve } from 'node:path';
import { setTimeout } from 'node:timers/promises';
+import { okUserHomeDisplayPath } from '@inkeep/open-knowledge-core';
import {
createProbeFailureReporter,
isLockProcessRunning,
@@ -178,7 +179,7 @@ export async function stopServerForRemoval(
: 'Stop the server manually. ';
const causeRecord =
nativeFailures.length > 0
- ? 'The failure detail is recorded in the CLI log under ~/.ok/logs. '
+ ? `The failure detail is recorded in the CLI log under ${okUserHomeDisplayPath('logs')}. `
: '';
throw refusal(
`Cannot verify the identity of process ${state.lock.pid} recorded in the server lock at ${state.lockPath}; the OS process-start query failed or is unavailable, so it was not signalled. ` +
diff --git a/packages/cli/src/commands/uninstall.test.ts b/packages/cli/src/commands/uninstall.test.ts
index 032dc5455..9154e780d 100644
--- a/packages/cli/src/commands/uninstall.test.ts
+++ b/packages/cli/src/commands/uninstall.test.ts
@@ -2,9 +2,15 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
-import { describe, expect, test } from 'vitest';
+import { SHARED_OK_ENTRIES } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { ensurePiBridge } from './pi-acp-bridge.ts';
-import { detectInstallMethods, resolveRecentDeinitProjects, runUninstall } from './uninstall.ts';
+import {
+ detectInstallMethods,
+ resolveRecentDeinitProjects,
+ runUninstall,
+ uninstallCommand,
+} from './uninstall.ts';
function write(path: string, content: string): void {
mkdirSync(dirname(path), { recursive: true });
@@ -565,3 +571,24 @@ test.each([false, true])(
}
},
);
+
+describe('uninstallCommand', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test('building the command never resolves the channel', () => {
+ vi.stubEnv('OK_CHANNEL', 'bogus');
+ const command = uninstallCommand();
+ expect(command.description()).toContain('~/.ok (~/.ok-beta on Beta)');
+ const kept =
+ '~/.ok/machine-id, ~/.ok/skills-lock.json, ~/.ok/local/installed-skills.json, ~/.ok/local/skill-placements.json, ~/.ok/local/skill-move-retained.json';
+ expect(command.description()).toContain(`always keeps ${kept}, shared by every channel.`);
+ expect(command.options.find((o) => o.long === '--purge-content')?.description).toBe(
+ `Also remove user-authored content (~/.ok/skills, shared by every channel); still keeps ${kept}`,
+ );
+ for (const entry of SHARED_OK_ENTRIES) {
+ expect(command.description()).toContain(`~/.ok/${entry}`);
+ }
+ });
+});
diff --git a/packages/cli/src/commands/uninstall.ts b/packages/cli/src/commands/uninstall.ts
index 9190f8d71..586ebd8c3 100644
--- a/packages/cli/src/commands/uninstall.ts
+++ b/packages/cli/src/commands/uninstall.ts
@@ -21,6 +21,7 @@ import {
describeAttachedClients,
type RunRemovalDeps,
runRemoval,
+ sharedOkEntriesList,
} from './removal-plan.ts';
import {
formatRemovalOutcome,
@@ -428,7 +429,7 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<Uninsta
export function uninstallCommand(): Command {
return new Command('uninstall')
.description(
- 'Remove OpenKnowledge from your machine — credentials, PATH entries, editor MCP configs, skill bundles, app data, and ~/.ok. Keeps your markdown content and your authored skills (~/.ok/skills) unless --purge-content. Detects the app install and prints how to remove it; never self-deletes.',
+ `Remove OpenKnowledge from your machine — credentials, PATH entries, editor MCP configs, skill bundles, app data, and ~/${DESKTOP_PRODUCTS.stable.userHomeDirName} (~/${DESKTOP_PRODUCTS.beta.userHomeDirName} on Beta). Keeps your markdown content and your authored skills (~/.ok/skills) unless --purge-content, and always keeps ${sharedOkEntriesList(true)}, shared by every channel. Detects the app install and prints how to remove it; never self-deletes.`,
)
.option(
'-y, --yes',
@@ -436,7 +437,10 @@ export function uninstallCommand(): Command {
)
.option('--dry-run', 'Print the removal plan and exit without changing anything')
.option('--json', 'Emit a machine-readable plan/outcome (requires --yes or --dry-run)')
- .option('--purge-content', 'Also remove user-authored content (~/.ok/skills)')
+ .option(
+ '--purge-content',
+ `Also remove user-authored content (~/.ok/skills, shared by every channel); still keeps ${sharedOkEntriesList(true)}`,
+ )
.option(
'--all-projects',
'Also deinit every recent/running project (by default no project is removed — you pick them interactively)',
diff --git a/packages/cli/src/integrations/desktop-state.ts b/packages/cli/src/integrations/desktop-state.ts
index 870e34208..06131f0f4 100644
--- a/packages/cli/src/integrations/desktop-state.ts
+++ b/packages/cli/src/integrations/desktop-state.ts
@@ -1,6 +1,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
+import { currentDesktopProduct } from '@inkeep/open-knowledge-core';
import {
type AppSupportOptions,
pathApiForPlatform,
@@ -17,7 +18,7 @@ interface DesktopUserDataOptions extends AppSupportOptions {
export function desktopUserDataDir(options: DesktopUserDataOptions = {}): string {
const platformName = options.platformName ?? process.platform;
- const productName = options.productName ?? DESKTOP_PRODUCT_NAME;
+ const productName = options.productName ?? currentDesktopProduct().productName;
return pathApiForPlatform(platformName).join(
resolveAppSupportPath({ ...options, platformName }),
productName,
@@ -39,7 +40,7 @@ export function desktopUpdaterCacheDir(options: AppSupportOptions = {}): string
base = env.XDG_CACHE_HOME || pathApi.join(home, '.cache');
}
- return pathApi.join(base, DESKTOP_UPDATER_CACHE_DIR_NAME);
+ return pathApi.join(base, `${currentDesktopProduct().packageName.replaceAll('/', '')}-updater`);
}
export interface DesktopRecentProject {
diff --git a/packages/cli/src/integrations/path-shim.test.ts b/packages/cli/src/integrations/path-shim.test.ts
index c04045e2c..de0fe42e2 100644
--- a/packages/cli/src/integrations/path-shim.test.ts
+++ b/packages/cli/src/integrations/path-shim.test.ts
@@ -1,12 +1,14 @@
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { pathShimBlockLabel, pathShimFishConfFileName } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
extraSymlinkStillOurs,
PATH_SHIM_BEGIN,
PATH_SHIM_END,
pathInstallMarkerPath,
+ pathShimFishConfName,
readPathInstallMarker,
stripManagedPathBlock,
} from './path-shim.ts';
@@ -108,3 +110,46 @@ describe('extraSymlinkStillOurs', () => {
}
});
});
+
+describe('path shim per channel', () => {
+ const BETA_BLOCK =
+ '# >>> open-knowledge beta cli >>>\n[ -f "$HOME/.ok-beta/env.sh" ] && . "$HOME/.ok-beta/env.sh"\n# <<< open-knowledge beta cli <<<\n';
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test('Stable keeps its Application Support marker and strips only the Stable block', () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ expect(pathInstallMarkerPath('/home/me')).toBe(
+ join('/home/me', 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json'),
+ );
+ const { text } = stripManagedPathBlock(`${block()}${BETA_BLOCK}`);
+ expect(text).toBe(BETA_BLOCK);
+ });
+
+ test('Beta reads its marker under ~/.ok-beta and strips only the Beta block', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ expect(pathInstallMarkerPath('/home/me')).toBe(
+ join('/home/me', '.ok-beta', 'path-install.json'),
+ );
+ const { text, changed } = stripManagedPathBlock(`${block()}${BETA_BLOCK}`);
+ expect(changed).toBe(true);
+ expect(text).toBe(block());
+ });
+
+ test('Beta removes the fish file and block the desktop installer writes', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ expect(pathShimFishConfName()).toBe(pathShimFishConfFileName('beta'));
+ expect(pathShimFishConfName()).toBe('open-knowledge-beta.fish');
+ const label = pathShimBlockLabel('beta');
+ expect(label).toBe('open-knowledge beta cli');
+ const fish = `# >>> ${label} >>>\nset -gx PATH "$HOME/.ok-beta/bin" $PATH\n# <<< ${label} <<<\n`;
+ expect(stripManagedPathBlock(fish)).toEqual({ text: '', changed: true, emptyAfter: true });
+ });
+
+ test('Stable keeps its fish file name', () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ expect(pathShimFishConfName()).toBe('open-knowledge.fish');
+ });
+});
diff --git a/packages/cli/src/integrations/path-shim.ts b/packages/cli/src/integrations/path-shim.ts
index d64894a38..7e2544567 100644
--- a/packages/cli/src/integrations/path-shim.ts
+++ b/packages/cli/src/integrations/path-shim.ts
@@ -4,7 +4,12 @@ import {
readFileSync as fsReadFileSync,
readlinkSync as fsReadlinkSync,
} from 'node:fs';
-import { join } from 'node:path';
+import {
+ pathShimBlockLabel,
+ pathShimFishConfFileName,
+ pathShimMarkerPath,
+ resolveDesktopProductName,
+} from '@inkeep/open-knowledge-core';
export const PATH_SHIM_BEGIN = '# >>> open-knowledge cli >>>';
export const PATH_SHIM_END = '# <<< open-knowledge cli <<<';
@@ -43,7 +48,18 @@ export interface PathInstallMarker {
}
export function pathInstallMarkerPath(home: string): string {
- return join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json');
+ return pathShimMarkerPath(resolveDesktopProductName(), home);
+}
+
+export function pathShimFishConfName(): string {
+ return pathShimFishConfFileName(resolveDesktopProductName());
+}
+
+function channelPathShimBlockRe(): RegExp {
+ const name = resolveDesktopProductName();
+ if (name === 'stable') return PATH_SHIM_BLOCK_RE;
+ const label = pathShimBlockLabel(name);
+ return new RegExp(`^# >>> ${label} >>>\\n[\\s\\S]*?^# <<< ${label} <<<\\n?`, 'm');
}
export interface PathShimFsOps {
@@ -79,7 +95,7 @@ export function stripManagedPathBlock(text: string): {
changed: boolean;
emptyAfter: boolean;
} {
- const next = text.replace(PATH_SHIM_BLOCK_RE, '');
+ const next = text.replace(channelPathShimBlockRe(), '');
return { text: next, changed: next !== text, emptyAfter: next.trim() === '' };
}
diff --git a/packages/cli/src/mcp/stderr-mirror.ts b/packages/cli/src/mcp/stderr-mirror.ts
index c00c6f7c4..36691375a 100644
--- a/packages/cli/src/mcp/stderr-mirror.ts
+++ b/packages/cli/src/mcp/stderr-mirror.ts
@@ -1,6 +1,6 @@
import { appendFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
-import { homedir } from 'node:os';
import { join } from 'node:path';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
const MAX_AGE_DAYS = 7;
const MAX_TOTAL_BYTES = 45 * 1024 * 1024;
@@ -9,7 +9,7 @@ const MAX_CONSECUTIVE_FAILURES = 5;
const MIRROR_FILE_PATTERN = /^mcp\.\d{4}-\d{2}-\d{2}\.log$/;
function defaultMcpLogsDir(): string {
- return join(homedir(), '.ok', 'logs');
+ return join(okUserHomeDir(), 'logs');
}
export function pruneMirrorLogs(logsDir: string, now: () => Date = () => new Date()): void {
diff --git a/packages/cli/src/report-bundle.ts b/packages/cli/src/report-bundle.ts
index faffd4748..d1b169a2a 100644
--- a/packages/cli/src/report-bundle.ts
+++ b/packages/cli/src/report-bundle.ts
@@ -5,6 +5,7 @@ import type {
ReportBundleLevel as CoreReportBundleLevel,
ReportBundleSummary as CoreReportBundleSummary,
} from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { parse as parseYaml } from 'yaml';
import {
type BundleExtraFile,
@@ -89,7 +90,7 @@ async function collectFullBundle(
note: opts.note,
extraFiles: opts.extraFiles,
userLogFiles: [
- ...collectUserLogFiles(projectSlug, opts.userLogsDir ?? join(homedir(), '.ok', 'logs')),
+ ...collectUserLogFiles(projectSlug, opts.userLogsDir ?? join(okUserHomeDir(), 'logs')),
...collectShipItLogFiles(opts.cachesDir ?? join(homedir(), 'Library', 'Caches')),
],
userStateFiles: collectBugReportLedgerFiles(opts.bugReportsDir ?? okBugReportsDir()),
diff --git a/packages/core/src/config/errors.test.ts b/packages/core/src/config/errors.test.ts
index 6fb7a955e..10dfc5973 100644
--- a/packages/core/src/config/errors.test.ts
+++ b/packages/core/src/config/errors.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'vitest';
+import { describe, expect, test, vi } from 'vitest';
import {
ConfigDiagnosticSchema,
ConfigDiagnosticsReportSchema,
@@ -274,6 +274,23 @@ describe('humanFormat', () => {
expect(out).toContain('Move it to ~/.ok/global.yml');
});
+ test('SCOPE_VIOLATION names the Beta user config when the running channel is Beta', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ try {
+ const out = humanFormat({
+ code: 'SCOPE_VIOLATION',
+ path: ['appearance', 'theme'],
+ expectedScope: 'user',
+ actualScope: 'either',
+ });
+ expect(out).toContain('Move it to ~/.ok-beta/global.yml');
+ expect(out).toContain('(.ok/config.yml or ~/.ok-beta/global.yml)');
+ expect(out).not.toContain('~/.ok/');
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
test('MIXED_SCOPE summarizes per-path scope assignments with target files', () => {
const out = humanFormat({
code: 'MIXED_SCOPE',
diff --git a/packages/core/src/config/errors.ts b/packages/core/src/config/errors.ts
index 49ef66a7a..9c5028d09 100644
--- a/packages/core/src/config/errors.ts
+++ b/packages/core/src/config/errors.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { okUserHomeDisplayPath } from '../constants/ok-dir.ts';
export const ConfigIssueSourceSchema = z.object({
file: z.string(),
@@ -186,13 +187,13 @@ export function isKnownConfigError(
function scopeConfigFile(scope: FieldScope): string {
switch (scope) {
case 'user':
- return '~/.ok/global.yml';
+ return okUserHomeDisplayPath('global.yml');
case 'project':
return '.ok/config.yml';
case 'project-local':
return '.ok/local/config.yml';
case 'either':
- return '.ok/config.yml or ~/.ok/global.yml';
+ return `.ok/config.yml or ${okUserHomeDisplayPath('global.yml')}`;
}
}
diff --git a/packages/core/src/config/git-host-config.ts b/packages/core/src/config/git-host-config.ts
index f47dd23b4..5fc69d486 100644
--- a/packages/core/src/config/git-host-config.ts
+++ b/packages/core/src/config/git-host-config.ts
@@ -12,7 +12,7 @@ const gitHostEntryShape = {
reload: 'boot',
defaultScope: 'user',
description:
- "Declares that this git host is a GitHub Enterprise Server instance, so OpenKnowledge treats its remotes the way it treats github.com (OpenKnowledge credential handling, the push-permission check, share links, and the default host for `ok auth`). 'github' is the only accepted value today. A host that is not declared here and is not github.com is treated as a generic git remote, so OpenKnowledge leaves the machine's own git credentials alone and does not check push permission. Per-machine (user scope, `~/.ok/global.yml`); a value in a project's `.ok/config.yml` is ignored. The declaration takes effect when OpenKnowledge next starts.",
+ "Declares that this git host is a GitHub Enterprise Server instance, so OpenKnowledge treats its remotes the way it treats github.com (OpenKnowledge credential handling, the push-permission check, share links, and the default host for `ok auth`). 'github' is the only accepted value today. A host that is not declared here and is not github.com is treated as a generic git remote, so OpenKnowledge leaves the machine's own git credentials alone and does not check push permission. Per-machine (user scope, global.yml in the OpenKnowledge home folder); a value in a project's `.ok/config.yml` is ignored. The declaration takes effect when OpenKnowledge next starts.",
}),
};
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index c47c9ef64..c47eebcb9 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -510,7 +510,7 @@ export const ConfigSchema = z.looseObject({
reload: 'boot',
defaultScope: 'user',
description:
- "Per-git-host declarations, keyed by hostname (for example ghes.example.com). Each entry says how OpenKnowledge should treat remotes on that host; today the only key an entry carries is `provider`. Hosts absent from this map are treated as generic git remotes. Per-machine (user scope, `~/.ok/global.yml`); a value in a project's `.ok/config.yml` is ignored. Declarations take effect when OpenKnowledge next starts.",
+ "Per-git-host declarations, keyed by hostname (for example ghes.example.com). Each entry says how OpenKnowledge should treat remotes on that host; today the only key an entry carries is `provider`. Hosts absent from this map are treated as generic git remotes. Per-machine (user scope, global.yml in the OpenKnowledge home folder); a value in a project's `.ok/config.yml` is ignored. Declarations take effect when OpenKnowledge next starts.",
})
.default({})
.catch({}),
@@ -799,7 +799,7 @@ export const ConfigSchema = z.looseObject({
reload: 'live',
defaultScope: 'project-local',
description:
- 'Base URL of the OpenAI-compatible embeddings API (default https://api.openai.com/v1). Override to point at a self-hosted server (Ollama / vLLM / LM Studio) or another provider. The API key is NOT stored here — set it with `ok embeddings set-key` (`~/.ok/secrets.yml`); it is sent to whichever endpoint this names.',
+ 'Base URL of the OpenAI-compatible embeddings API (default https://api.openai.com/v1). Override to point at a self-hosted server (Ollama / vLLM / LM Studio) or another provider. The API key is NOT stored here — set it with `ok embeddings set-key` (stored in secrets.yml in the OpenKnowledge home folder); it is sent to whichever endpoint this names.',
})
.default(DEFAULT_EMBEDDINGS_BASE_URL),
model: z
diff --git a/packages/core/src/config/write-config-patch.ts b/packages/core/src/config/write-config-patch.ts
index 9d623e0ff..cf69e5dc1 100644
--- a/packages/core/src/config/write-config-patch.ts
+++ b/packages/core/src/config/write-config-patch.ts
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
import { dirname, isAbsolute, resolve } from 'node:path';
import { isMap, isSeq, type ParsedNode, parseDocument } from 'yaml';
import { LOCAL_DIR, OK_DIR } from '../constants/ok-dir.ts';
+import { okUserHomeDir } from '../constants/ok-user-home.ts';
import { atomicWriteFile } from '../util/atomic-yaml-write.ts';
import { FileLockTimeoutError, withFileLock } from '../util/file-lock.ts';
import type { ConfigValidationError, WriteScope } from './errors.ts';
@@ -56,8 +57,7 @@ export function resolveConfigPath(
homedirOverride?: string,
): string {
if (scope === 'user') {
- const home = homedirOverride ?? homedir();
- return resolve(home, OK_DIR, USER_CONFIG_FILENAME);
+ return resolve(okUserHomeDir(homedirOverride ?? homedir()), USER_CONFIG_FILENAME);
}
const absCwd = isAbsolute(cwd) ? cwd : resolve(cwd);
if (scope === 'project-local') {
diff --git a/packages/core/src/constants/ok-dir.test.ts b/packages/core/src/constants/ok-dir.test.ts
index abfc57ef2..89766be45 100644
--- a/packages/core/src/constants/ok-dir.test.ts
+++ b/packages/core/src/constants/ok-dir.test.ts
@@ -1,6 +1,25 @@
import { posix } from 'node:path';
-import { describe, expect, test } from 'vitest';
-import { OK_BIN_DIRNAME, OK_DIR, posixOkManagedBinDir } from './ok-dir.ts';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { OK_BIN_DIRNAME, OK_DIR, okUserHomeDisplayPath, posixOkManagedBinDir } from './ok-dir.ts';
+
+describe('okUserHomeDisplayPath', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test('names the Stable home folder by default', () => {
+ vi.stubEnv('OK_CHANNEL', '');
+ expect(okUserHomeDisplayPath()).toBe('~/.ok');
+ expect(okUserHomeDisplayPath('global.yml')).toBe('~/.ok/global.yml');
+ expect(okUserHomeDisplayPath('logs')).toBe('~/.ok/logs');
+ });
+
+ test('names the Beta home folder when the running channel is Beta', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ expect(okUserHomeDisplayPath('global.yml')).toBe('~/.ok-beta/global.yml');
+ expect(okUserHomeDisplayPath('secrets.yml')).toBe('~/.ok-beta/secrets.yml');
+ });
+});
describe('posixOkManagedBinDir', () => {
test('is the OK dir plus the bin dirname, under the given home', () => {
diff --git a/packages/core/src/constants/ok-dir.ts b/packages/core/src/constants/ok-dir.ts
index d048e3564..64d2a1b8c 100644
--- a/packages/core/src/constants/ok-dir.ts
+++ b/packages/core/src/constants/ok-dir.ts
@@ -1,3 +1,5 @@
+import { currentDesktopProduct } from './product.ts';
+
export const OK_DIR = '.ok';
export const OK_PROJECT_MARKER = '.ok/config.yml';
@@ -37,7 +39,14 @@ const activeMachineLocalRootDirs: ReadonlySet<string> = new Set(OK_ACTIVE_MACHIN
export const OK_LEGACY_MACHINE_LOCAL_ROOT_DIRS: readonly OkMachineLocalRootDir[] =
OK_MACHINE_LOCAL_ROOT_DIRS.filter((name) => !activeMachineLocalRootDirs.has(name));
-export function posixOkManagedBinDir(homeDir: string): string {
+export function posixOkManagedBinDir(
+ homeDir: string,
+ userHomeDirName: string = currentDesktopProduct().userHomeDirName,
+): string {
const base = homeDir.replace(/\/+/g, '/').replace(/\/+$/, '');
- return `${base}/${OK_DIR}/${OK_BIN_DIRNAME}`;
+ return `${base}/${userHomeDirName}/${OK_BIN_DIRNAME}`;
+}
+
+export function okUserHomeDisplayPath(...segments: string[]): string {
+ return ['~', currentDesktopProduct().userHomeDirName, ...segments].join('/');
}
diff --git a/packages/core/src/constants/ok-user-home.test.ts b/packages/core/src/constants/ok-user-home.test.ts
new file mode 100644
index 000000000..493af3564
--- /dev/null
+++ b/packages/core/src/constants/ok-user-home.test.ts
@@ -0,0 +1,52 @@
+import { join, relative, resolve } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { resolveConfigPath } from '../config/write-config-patch.ts';
+import { posixOkManagedBinDir } from './ok-dir.ts';
+import { okUserHomeDir } from './ok-user-home.ts';
+
+const HOME = '/Users/someone';
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('per-channel user home', () => {
+ it('keeps Stable on ~/.ok exactly as before', () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ expect(okUserHomeDir(HOME)).toBe(join(HOME, '.ok'));
+ expect(posixOkManagedBinDir(HOME)).toBe('/Users/someone/.ok/bin');
+ expect(resolveConfigPath('user', '/project', HOME)).toBe(resolve(HOME, '.ok', 'global.yml'));
+ });
+
+ it('gives Beta a sibling ~/.ok-beta root for its home, PATH shims, and user config', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ expect(okUserHomeDir(HOME)).toBe(join(HOME, '.ok-beta'));
+ expect(posixOkManagedBinDir(HOME)).toBe('/Users/someone/.ok-beta/bin');
+ expect(resolveConfigPath('user', '/project', HOME)).toBe(
+ resolve(HOME, '.ok-beta', 'global.yml'),
+ );
+ });
+
+ it('never nests one channel root inside the other', () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ const stable = okUserHomeDir(HOME);
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ const beta = okUserHomeDir(HOME);
+ expect(relative(stable, beta).startsWith('..')).toBe(true);
+ expect(relative(beta, stable).startsWith('..')).toBe(true);
+ });
+
+ it('resolves the channel from a Beta executable without an override', () => {
+ vi.stubEnv('OK_CHANNEL', undefined);
+ const execPath = process.execPath;
+ Object.defineProperty(process, 'execPath', {
+ value: '/Applications/OpenKnowledge Beta.app/Contents/MacOS/OpenKnowledge Beta',
+ configurable: true,
+ });
+ try {
+ expect(okUserHomeDir(HOME)).toBe(join(HOME, '.ok-beta'));
+ } finally {
+ Object.defineProperty(process, 'execPath', { value: execPath, configurable: true });
+ }
+ });
+});
diff --git a/packages/core/src/constants/ok-user-home.ts b/packages/core/src/constants/ok-user-home.ts
new file mode 100644
index 000000000..7069eb720
--- /dev/null
+++ b/packages/core/src/constants/ok-user-home.ts
@@ -0,0 +1,7 @@
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { currentDesktopProduct } from './product.ts';
+
+export function okUserHomeDir(home: string = homedir()): string {
+ return join(home, currentDesktopProduct().userHomeDirName);
+}
diff --git a/packages/core/src/constants/path-shim-layout.test.ts b/packages/core/src/constants/path-shim-layout.test.ts
new file mode 100644
index 000000000..c486e98aa
--- /dev/null
+++ b/packages/core/src/constants/path-shim-layout.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from 'vitest';
+import {
+ pathShimBinDir,
+ pathShimBlockLabel,
+ pathShimFishConfFileName,
+ pathShimHomeDirName,
+ pathShimMarkerPath,
+} from './path-shim-layout.ts';
+
+describe('path shim layout', () => {
+ test('Stable keeps its historical names and paths', () => {
+ expect(pathShimHomeDirName('stable')).toBe('.ok');
+ expect(pathShimBinDir('stable', '/Users/a/')).toBe('/Users/a/.ok/bin');
+ expect(pathShimMarkerPath('stable', '/Users/a')).toBe(
+ '/Users/a/Library/Application Support/OpenKnowledge/path-install.json',
+ );
+ expect(pathShimBlockLabel('stable')).toBe('open-knowledge cli');
+ expect(pathShimFishConfFileName('stable')).toBe('open-knowledge.fish');
+ });
+
+ test('Beta lives under ~/.ok-beta with its own block and fish file', () => {
+ expect(pathShimHomeDirName('beta')).toBe('.ok-beta');
+ expect(pathShimBinDir('beta', '/Users/a')).toBe('/Users/a/.ok-beta/bin');
+ expect(pathShimMarkerPath('beta', '/Users/a')).toBe('/Users/a/.ok-beta/path-install.json');
+ expect(pathShimBlockLabel('beta')).toBe('open-knowledge beta cli');
+ expect(pathShimFishConfFileName('beta')).toBe('open-knowledge-beta.fish');
+ });
+});
diff --git a/packages/core/src/constants/path-shim-layout.ts b/packages/core/src/constants/path-shim-layout.ts
new file mode 100644
index 000000000..c97b64067
--- /dev/null
+++ b/packages/core/src/constants/path-shim-layout.ts
@@ -0,0 +1,29 @@
+import { posixOkManagedBinDir } from './ok-dir.ts';
+import { DESKTOP_PRODUCTS, type DesktopProductName } from './product.ts';
+
+function posixHome(home: string): string {
+ return home.replace(/\/+/g, '/').replace(/\/+$/, '');
+}
+
+export function pathShimHomeDirName(channel: DesktopProductName): string {
+ return DESKTOP_PRODUCTS[channel].userHomeDirName;
+}
+
+export function pathShimBinDir(channel: DesktopProductName, home: string): string {
+ return posixOkManagedBinDir(home, pathShimHomeDirName(channel));
+}
+
+export function pathShimMarkerPath(channel: DesktopProductName, home: string): string {
+ if (channel === 'stable') {
+ return `${posixHome(home)}/Library/Application Support/OpenKnowledge/path-install.json`;
+ }
+ return `${posixHome(home)}/${pathShimHomeDirName(channel)}/path-install.json`;
+}
+
+export function pathShimBlockLabel(channel: DesktopProductName): string {
+ return channel === 'stable' ? 'open-knowledge cli' : `open-knowledge ${channel} cli`;
+}
+
+export function pathShimFishConfFileName(channel: DesktopProductName): string {
+ return channel === 'stable' ? 'open-knowledge.fish' : `open-knowledge-${channel}.fish`;
+}
diff --git a/packages/core/src/constants/product.test.ts b/packages/core/src/constants/product.test.ts
index 3b8a30c33..71380b267 100644
--- a/packages/core/src/constants/product.test.ts
+++ b/packages/core/src/constants/product.test.ts
@@ -41,4 +41,12 @@ describe('resolveDesktopProductName', () => {
expect(new Set(products.map((p) => p.mcpServerName)).size).toBe(products.length);
expect(new Set(products.map((p) => p.mcpChainTag)).size).toBe(products.length);
});
+
+ it('gives every channel a distinct user home and keychain service, keeping Stable unchanged', () => {
+ const products = Object.values(DESKTOP_PRODUCTS);
+ expect(new Set(products.map((p) => p.userHomeDirName)).size).toBe(products.length);
+ expect(new Set(products.map((p) => p.keyringService)).size).toBe(products.length);
+ expect(DESKTOP_PRODUCTS.stable.userHomeDirName).toBe('.ok');
+ expect(DESKTOP_PRODUCTS.stable.keyringService).toBe('open-knowledge');
+ });
});
diff --git a/packages/core/src/constants/product.ts b/packages/core/src/constants/product.ts
index e3821c381..cab573218 100644
--- a/packages/core/src/constants/product.ts
+++ b/packages/core/src/constants/product.ts
@@ -12,6 +12,8 @@ export const DESKTOP_PRODUCTS = {
mcpServerName: 'open-knowledge',
mcpChainTag: '',
npmDistTag: 'latest',
+ userHomeDirName: '.ok',
+ keyringService: 'open-knowledge',
},
beta: {
appId: 'com.inkeep.open-knowledge.beta',
@@ -26,6 +28,8 @@ export const DESKTOP_PRODUCTS = {
mcpServerName: 'open-knowledge-beta',
mcpChainTag: '-beta',
npmDistTag: 'beta',
+ userHomeDirName: '.ok-beta',
+ keyringService: 'open-knowledge-beta',
},
} as const;
diff --git a/packages/core/src/constants/shared-ok-entries.test.ts b/packages/core/src/constants/shared-ok-entries.test.ts
new file mode 100644
index 000000000..a1f235fb8
--- /dev/null
+++ b/packages/core/src/constants/shared-ok-entries.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'vitest';
+import { INSTALLED_SKILLS_REL } from '../installed-skills/schema.ts';
+import { SKILLS_LOCK_REL } from '../skills-catalog/acquire/lockfile.ts';
+import { LOCAL_DIR, OK_DIR } from './ok-dir.ts';
+import {
+ MACHINE_ID_FILENAME,
+ SHARED_OK_ENTRIES,
+ SKILL_MOVE_RETAINED_FILENAME,
+ SKILL_PLACEMENTS_FILENAME,
+ SKILLS_STORE_DIRNAME,
+} from './shared-ok-entries.ts';
+
+function okRelative(rel: readonly string[]): string {
+ expect(rel[0]).toBe(OK_DIR);
+ return rel.slice(1).join('/');
+}
+
+describe('SHARED_OK_ENTRIES', () => {
+ test('each entry is the path its writer uses under the OK dir', () => {
+ expect([...SHARED_OK_ENTRIES]).toEqual([
+ 'machine-id',
+ 'skills',
+ 'skills-lock.json',
+ 'local/installed-skills.json',
+ 'local/skill-placements.json',
+ 'local/skill-move-retained.json',
+ ]);
+ expect(SHARED_OK_ENTRIES).toEqual([
+ MACHINE_ID_FILENAME,
+ SKILLS_STORE_DIRNAME,
+ okRelative(SKILLS_LOCK_REL),
+ okRelative(INSTALLED_SKILLS_REL),
+ `${LOCAL_DIR}/${SKILL_PLACEMENTS_FILENAME}`,
+ `${LOCAL_DIR}/${SKILL_MOVE_RETAINED_FILENAME}`,
+ ]);
+ });
+});
diff --git a/packages/core/src/constants/shared-ok-entries.ts b/packages/core/src/constants/shared-ok-entries.ts
new file mode 100644
index 000000000..5f79e4b7b
--- /dev/null
+++ b/packages/core/src/constants/shared-ok-entries.ts
@@ -0,0 +1,20 @@
+import { INSTALLED_SKILLS_FILENAME } from '../installed-skills/schema.ts';
+import { SKILLS_LOCK_FILENAME } from '../skills-catalog/acquire/lockfile.ts';
+import { LOCAL_DIR } from './ok-dir.ts';
+
+export const MACHINE_ID_FILENAME = 'machine-id';
+
+export const SKILLS_STORE_DIRNAME = 'skills';
+
+export const SKILL_PLACEMENTS_FILENAME = 'skill-placements.json';
+
+export const SKILL_MOVE_RETAINED_FILENAME = 'skill-move-retained.json';
+
+export const SHARED_OK_ENTRIES: readonly string[] = [
+ MACHINE_ID_FILENAME,
+ SKILLS_STORE_DIRNAME,
+ SKILLS_LOCK_FILENAME,
+ `${LOCAL_DIR}/${INSTALLED_SKILLS_FILENAME}`,
+ `${LOCAL_DIR}/${SKILL_PLACEMENTS_FILENAME}`,
+ `${LOCAL_DIR}/${SKILL_MOVE_RETAINED_FILENAME}`,
+];
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 717e50d80..7d3f71f1d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -516,10 +516,18 @@ export {
OK_PROJECT_MARKER,
type OkMachineLocalRootDir,
type OkMachineLocalRootFile,
+ okUserHomeDisplayPath,
posixOkManagedBinDir,
SAVED_THEMES_DIRNAME,
WORKTREES_DIRNAME,
} from './constants/ok-dir.ts';
+export {
+ pathShimBinDir,
+ pathShimBlockLabel,
+ pathShimFishConfFileName,
+ pathShimHomeDirName,
+ pathShimMarkerPath,
+} from './constants/path-shim-layout.ts';
export {
PREVIEW_EMBED_STARTERS,
type PreviewEmbedStarter,
@@ -543,6 +551,13 @@ export {
} from './constants/product.ts';
export { isReservedLogDoc } from './constants/reserved-docs.ts';
export { DEFAULT_SERVER_HOST } from './constants/server.ts';
+export {
+ MACHINE_ID_FILENAME,
+ SHARED_OK_ENTRIES,
+ SKILL_MOVE_RETAINED_FILENAME,
+ SKILL_PLACEMENTS_FILENAME,
+ SKILLS_STORE_DIRNAME,
+} from './constants/shared-ok-entries.ts';
export {
AGENTS_SKILLS_ROOT,
extractSkillRefs,
@@ -1872,7 +1887,6 @@ export {
emptySkillState,
resolveBundleEnabled,
SKILL_STATE_FILENAME,
- SKILL_STATE_REL,
SKILL_STATE_SCHEMA_VERSION,
SKILL_STATE_SURFACES,
SKILL_STATE_TARGETS,
diff --git a/packages/core/src/installed-skills/schema.ts b/packages/core/src/installed-skills/schema.ts
index dab77a6d1..9ad21bed4 100644
--- a/packages/core/src/installed-skills/schema.ts
+++ b/packages/core/src/installed-skills/schema.ts
@@ -1,10 +1,10 @@
import { z } from 'zod';
import { MANAGED_ARTIFACT_SCOPES } from '../constants/cc1.ts';
-import { OK_DIR } from '../constants/ok-dir.ts';
+import { LOCAL_DIR, OK_DIR } from '../constants/ok-dir.ts';
export const INSTALLED_SKILLS_FILENAME = 'installed-skills.json';
-export const INSTALLED_SKILLS_REL = [OK_DIR, 'local', INSTALLED_SKILLS_FILENAME] as const;
+export const INSTALLED_SKILLS_REL = [OK_DIR, LOCAL_DIR, INSTALLED_SKILLS_FILENAME] as const;
export const INSTALLED_SKILLS_SCHEMA_VERSION = 1;
diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts
index 437e1345f..c9f1d9355 100644
--- a/packages/core/src/server.ts
+++ b/packages/core/src/server.ts
@@ -25,6 +25,7 @@ export {
type WriteConfigPatchSuccess,
writeConfigPatch,
} from './config/write-config-patch.ts';
+export { okUserHomeDir } from './constants/ok-user-home.ts';
export {
LOCALE_OVERRIDE_ENV_VAR,
type LocaleEnvironment,
diff --git a/packages/core/src/skill-state/schema.ts b/packages/core/src/skill-state/schema.ts
index bcdda5582..b5c4ff987 100644
--- a/packages/core/src/skill-state/schema.ts
+++ b/packages/core/src/skill-state/schema.ts
@@ -1,11 +1,8 @@
import { z } from 'zod';
-import { OK_DIR } from '../constants/ok-dir.ts';
import { skillStateFieldRegistry } from './field-registry.ts';
export const SKILL_STATE_FILENAME = 'skill-state.yml';
-export const SKILL_STATE_REL = [OK_DIR, SKILL_STATE_FILENAME] as const;
-
export const SKILL_STATE_TARGETS = ['claude-cowork', 'cli-hosts'] as const;
export type SkillStateTarget = (typeof SKILL_STATE_TARGETS)[number];
diff --git a/packages/desktop/src/main/bug-report-agent-chat.ts b/packages/desktop/src/main/bug-report-agent-chat.ts
index 6675afdd9..51b0cfeda 100644
--- a/packages/desktop/src/main/bug-report-agent-chat.ts
+++ b/packages/desktop/src/main/bug-report-agent-chat.ts
@@ -4,8 +4,9 @@ import { type FileHandle, lstat, open, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { BundleExtraFile } from '@inkeep/open-knowledge';
-import { BUG_REPORT_AGENT_CHAT_ZIP_DIR, OK_DIR, redactSecrets } from '@inkeep/open-knowledge-core';
+import { BUG_REPORT_AGENT_CHAT_ZIP_DIR, redactSecrets } from '@inkeep/open-knowledge-core';
import type { CodexLegacyAgentIdentity } from '@inkeep/open-knowledge-core/acp/codex-legacy-notice';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import {
acpThreadStoreRoots,
acpThreadsDir,
@@ -63,7 +64,7 @@ export function defaultAgentChatThreadDirs(
home: string = homedir(),
): string[] {
return acpThreadStoreRoots(
- join(home, OK_DIR),
+ okUserHomeDir(home),
projectDir === null ? null : getLocalDir(projectDir),
).map((root) => acpThreadsDir(root));
}
diff --git a/packages/desktop/src/main/desktop-logger.test.ts b/packages/desktop/src/main/desktop-logger.test.ts
index fede95e23..18188990a 100644
--- a/packages/desktop/src/main/desktop-logger.test.ts
+++ b/packages/desktop/src/main/desktop-logger.test.ts
@@ -1,5 +1,9 @@
+import { once } from 'node:events';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import pino from 'pino';
-import { describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { flushDesktopLogger, getLogger, getRootDesktopLogger } from './desktop-logger.ts';
describe('flushDesktopLogger', () => {
@@ -30,3 +34,36 @@ describe('error serialization (what the raw-err discipline buys)', () => {
}
});
});
+
+describe('logs dir per channel', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ });
+
+ test('importing under an unsupported OK_CHANNEL does not throw', async () => {
+ vi.stubEnv('OK_CHANNEL', 'bogus');
+ vi.resetModules();
+ await expect(import('./desktop-logger.ts')).resolves.toBeDefined();
+ });
+
+ test('Beta writes logs under ~/.ok-beta/logs, not ~/.ok/logs', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-desktop-logs-'));
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ vi.resetModules();
+ try {
+ const { getRootDesktopLogger } = await import('./desktop-logger.ts');
+ const stream = (
+ getRootDesktopLogger() as unknown as Record<symbol, NodeJS.EventEmitter & { end(): void }>
+ )[pino.symbols.streamSym];
+ const closed = once(stream, 'close');
+ stream.end();
+ await closed;
+ expect(existsSync(join(home, '.ok-beta', 'logs'))).toBe(true);
+ expect(existsSync(join(home, '.ok', 'logs'))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/desktop/src/main/desktop-logger.ts b/packages/desktop/src/main/desktop-logger.ts
index fc1fbc505..c0ac02176 100644
--- a/packages/desktop/src/main/desktop-logger.ts
+++ b/packages/desktop/src/main/desktop-logger.ts
@@ -1,9 +1,11 @@
import { mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
-import { homedir } from 'node:os';
import { join } from 'node:path';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import pino from 'pino';
-const OK_LOGS_DIR = join(homedir(), '.ok', 'logs');
+function okLogsDir(): string {
+ return join(okUserHomeDir(), 'logs');
+}
const MAX_AGE_DAYS = 7;
const MAX_DIR_SIZE_BYTES = 45 * 1024 * 1024;
@@ -87,10 +89,10 @@ let rootDest: { flushSync: () => void } | undefined;
function getRootLogger(): pino.Logger {
if (rootLogger) return rootLogger;
- mkdirSync(OK_LOGS_DIR, { recursive: true });
- setTimeout(() => pruneLogsDir(OK_LOGS_DIR), 5000);
+ mkdirSync(okLogsDir(), { recursive: true });
+ setTimeout(() => pruneLogsDir(okLogsDir()), 5000);
- const filePath = join(OK_LOGS_DIR, logFileName);
+ const filePath = join(okLogsDir(), logFileName);
const dest = pino.destination({ dest: filePath, append: true, sync: false });
rootDest = dest as unknown as { flushSync: () => void };
diff --git a/packages/desktop/src/main/ipc-handlers.ts b/packages/desktop/src/main/ipc-handlers.ts
index cafe15326..3bfa111d6 100644
--- a/packages/desktop/src/main/ipc-handlers.ts
+++ b/packages/desktop/src/main/ipc-handlers.ts
@@ -1,6 +1,7 @@
import { execFile } from 'node:child_process';
import { join } from 'node:path';
import { okBugReportsDir } from '@inkeep/open-knowledge';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { userGlobalSkillRoots } from '@inkeep/open-knowledge-core/skills-catalog';
import {
createOsProbe,
@@ -258,15 +259,15 @@ interface RecordHandoffDeps {
readonly warn?: (message: string) => void;
}
-export const STATS_FILE_RELATIVE_PATH = ['.ok', 'stats.jsonl'] as const;
+export const STATS_FILE_NAME = 'stats.jsonl';
export async function recordHandoff(
deps: RecordHandoffDeps,
line: HandoffStatsLine,
): Promise<void> {
const home = deps.homedir();
- const dir = join(home, STATS_FILE_RELATIVE_PATH[0]);
- const file = join(dir, STATS_FILE_RELATIVE_PATH[1]);
+ const dir = okUserHomeDir(home);
+ const file = join(dir, STATS_FILE_NAME);
const json = `${JSON.stringify(line)}\n`;
const warn = deps.warn ?? ((m: string) => console.warn(m));
diff --git a/packages/desktop/src/main/mcp-wiring.test.ts b/packages/desktop/src/main/mcp-wiring.test.ts
index 7b8033f5e..cec2c90fe 100644
--- a/packages/desktop/src/main/mcp-wiring.test.ts
+++ b/packages/desktop/src/main/mcp-wiring.test.ts
@@ -17,7 +17,7 @@ import {
type EditorMcpTarget,
type McpEntryClassification,
} from '@inkeep/open-knowledge';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { classifyExistingMcpEntry as classifyWithOverridableEngine } from '../../../cli/src/commands/init.ts';
import {
createTomlConfigEngine,
@@ -599,6 +599,25 @@ describe('MCP status marker', () => {
expect(JSON.parse(fs.files['/home/alice/.ok/mcp-status.json'])).toEqual(marker);
});
+ test("Beta keeps its own marker under ~/.ok-beta and never reads Stable's", () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ try {
+ const fs = memoryFs({
+ '/home/alice/.ok/mcp-status.json': JSON.stringify({
+ configured: true,
+ configuredAt: '2026-05-26T00:00:00.000Z',
+ editors: ['claude'],
+ }),
+ });
+ expect(readMcpStatusMarker('/home/alice', fs)).toBeNull();
+ const marker: McpStatusMarker = { configured: false, skippedAt: '2026-09-30T00:00:00.000Z' };
+ writeMcpStatusMarker('/home/alice', marker, fs);
+ expect(JSON.parse(fs.files['/home/alice/.ok-beta/mcp-status.json'])).toEqual(marker);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
test('reader accepts legacy confirmed marker carrying cliPath', () => {
const fs = memoryFs({
'/home/alice/.ok/mcp-status.json': JSON.stringify({
diff --git a/packages/desktop/src/main/mcp-wiring.ts b/packages/desktop/src/main/mcp-wiring.ts
index b1efe7a34..dd519a70c 100644
--- a/packages/desktop/src/main/mcp-wiring.ts
+++ b/packages/desktop/src/main/mcp-wiring.ts
@@ -18,6 +18,7 @@ import {
type McpEntryClassification,
} from '@inkeep/open-knowledge';
import { CONNECTION_ROW_AGENT_IDS, classifyMcpLauncherEntry } from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import type { IpcMain, IpcMainInvokeEvent } from 'electron';
import type {
McpWiringConfirmRequest,
@@ -33,7 +34,6 @@ import { type SendableWebContents, sendToRenderer } from '../shared/ipc-send.ts'
import { classifyInstallShape } from './install-shape.ts';
import { logIpcError } from './ipc-log.ts';
-const MCP_STATUS_DIR_NAME = '.ok';
const MCP_STATUS_FILE_NAME = 'mcp-status.json';
export type McpStatusMarker =
@@ -74,7 +74,7 @@ const defaultFsOps: McpWiringFsOps = {
};
function mcpStatusMarkerPath(home: string): string {
- return join(home, MCP_STATUS_DIR_NAME, MCP_STATUS_FILE_NAME);
+ return join(okUserHomeDir(home), MCP_STATUS_FILE_NAME);
}
export function readMcpStatusMarker(
diff --git a/packages/desktop/src/main/path-install-beta.test.ts b/packages/desktop/src/main/path-install-beta.test.ts
index 7e13488a1..f6609b22e 100644
--- a/packages/desktop/src/main/path-install-beta.test.ts
+++ b/packages/desktop/src/main/path-install-beta.test.ts
@@ -1,7 +1,18 @@
-import { existsSync, mkdtempSync, readFileSync, readlinkSync, writeFileSync } from 'node:fs';
+import * as nodeFs from 'node:fs';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readlinkSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { pathShimBlockLabel, pathShimFishConfFileName } from '@inkeep/open-knowledge-core';
import { describe, expect, test, vi } from 'vitest';
+import { okManagedBinDirs } from '../shared/ok-child-env.ts';
vi.mock('../shared/desktop-variant.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../shared/desktop-variant.ts')>();
@@ -40,13 +51,11 @@ describe('Beta CLI path install', () => {
});
expect(result.status).toBe('installed');
- const betaRoot = join(userHome, '.ok', 'variants', 'beta');
+ const betaRoot = join(userHome, '.ok-beta');
expect(pathInstallMarkerPath(userHome)).toBe(join(betaRoot, 'path-install.json'));
expect(readlinkSync(join(betaRoot, 'bin', 'ok-beta'))).toBe(BETA_WRAPPER);
expect(readlinkSync(join(betaRoot, 'bin', 'open-knowledge-beta'))).toBe(BETA_WRAPPER);
- expect(readFileSync(join(betaRoot, 'env.sh'), 'utf8')).toContain(
- '$' + '{HOME}/.ok/variants/beta/bin',
- );
+ expect(readFileSync(join(betaRoot, 'env.sh'), 'utf8')).toContain('$' + '{HOME}/.ok-beta/bin');
const installedRc = readFileSync(zshrc, 'utf8');
expect(installedRc).toContain(stableBlock);
expect(installedRc).toContain('# >>> open-knowledge beta cli >>>');
@@ -62,5 +71,349 @@ describe('Beta CLI path install', () => {
expect(removedRc).toContain(stableBlock);
expect(removedRc).not.toContain('open-knowledge beta cli');
expect(existsSync(join(userHome, '.ok', 'path-install.json'))).toBe(false);
+ expect(existsSync(join(userHome, '.ok'))).toBe(false);
+ });
+
+ test('moves an existing Beta install off ~/.ok/variants/beta and rewrites its rc block', async () => {
+ const userHome = home();
+ const legacyRoot = join(userHome, '.ok', 'variants', 'beta');
+ const zshrc = join(userHome, '.zshrc');
+ const bashProfile = join(userHome, '.bash_profile');
+ const legacyBlock =
+ '# >>> open-knowledge beta cli >>>\n[ -f "$HOME/.ok/variants/beta/env.sh" ] && . "$HOME/.ok/variants/beta/env.sh"\n# <<< open-knowledge beta cli <<<\n';
+ const stableBlock = '# >>> open-knowledge cli >>>\nstable\n# <<< open-knowledge cli <<<\n';
+ writeFileSync(zshrc, `${stableBlock}${legacyBlock}`);
+ writeFileSync(bashProfile, 'export A=1\n');
+ mkdirSync(join(legacyRoot, 'bin'), { recursive: true });
+ symlinkSync(BETA_WRAPPER, join(legacyRoot, 'bin', 'ok-beta'));
+ writeFileSync(join(userHome, '.ok', 'machine-id'), 'stable-id\n');
+ writeFileSync(
+ join(legacyRoot, 'path-install.json'),
+ JSON.stringify({
+ version: 1,
+ installedAt: '2026-09-23T00:00:00.000Z',
+ bundleVersion: '0.77.7-beta.0',
+ bundleWrapperPath: BETA_WRAPPER,
+ binDir: join(legacyRoot, 'bin'),
+ envShimPath: join(legacyRoot, 'env.sh'),
+ rcFiles: [zshrc],
+ rcOptOuts: [bashProfile],
+ pathDiscovery: null,
+ extraSymlinks: [],
+ consent: { status: 'granted', at: '2026-09-23T00:00:00.000Z' },
+ }),
+ );
+
+ const result = await ensureCliOnPath({
+ executablePath: BETA_EXE,
+ isPackaged: true,
+ platform: 'darwin',
+ home: userHome,
+ bundleVersion: '0.77.8-beta.0',
+ env: { HOME: userHome, SHELL: '/bin/bash' },
+ spawn: async () => ({
+ code: 0,
+ stdout: `/usr/bin:/bin:${join(legacyRoot, 'bin')}`,
+ stderr: '',
+ }),
+ });
+
+ expect(result.status).toBe('installed');
+ const betaRoot = join(userHome, '.ok-beta');
+ expect(readlinkSync(join(betaRoot, 'bin', 'ok-beta'))).toBe(BETA_WRAPPER);
+ const marker = JSON.parse(readFileSync(join(betaRoot, 'path-install.json'), 'utf8'));
+ expect(marker.rcOptOuts).toEqual([bashProfile]);
+ expect(marker.consent.status).toBe('granted');
+ const rc = readFileSync(zshrc, 'utf8');
+ expect(rc).toContain(stableBlock);
+ expect(rc).toContain('$HOME/.ok-beta/env.sh');
+ expect(rc).not.toContain('variants/beta');
+ expect(readFileSync(bashProfile, 'utf8')).toBe('export A=1\n');
+ expect(existsSync(legacyRoot)).toBe(false);
+ expect(readFileSync(join(userHome, '.ok', 'machine-id'), 'utf8')).toBe('stable-id\n');
+ });
+});
+
+type FsOps = NonNullable<Parameters<typeof ensureCliOnPath>[0]['fs']>;
+
+function fsWith(overrides: Partial<FsOps>): FsOps {
+ return {
+ existsSync: (path) => nodeFs.existsSync(path),
+ readFileSync: (path, encoding) => nodeFs.readFileSync(path, encoding),
+ writeFileSync: (path, content) => nodeFs.writeFileSync(path, content),
+ mkdirSync: (path, options) => {
+ nodeFs.mkdirSync(path, options);
+ },
+ unlinkSync: (path) => nodeFs.unlinkSync(path),
+ symlinkSync: (target, path) => nodeFs.symlinkSync(target, path),
+ renameSync: (oldPath, newPath) => nodeFs.renameSync(oldPath, newPath),
+ readlinkSync: (path) => nodeFs.readlinkSync(path),
+ lstatSync: (path) => nodeFs.lstatSync(path),
+ rmSync: (path, options) => nodeFs.rmSync(path, options),
+ ...overrides,
+ };
+}
+
+function seedLegacyBetaInstall(userHome: string): { legacyRoot: string; zshrc: string } {
+ const legacyRoot = join(userHome, '.ok', 'variants', 'beta');
+ const zshrc = join(userHome, '.zshrc');
+ writeFileSync(
+ zshrc,
+ '# >>> open-knowledge beta cli >>>\n[ -f "$HOME/.ok/variants/beta/env.sh" ] && . "$HOME/.ok/variants/beta/env.sh"\n# <<< open-knowledge beta cli <<<\n',
+ );
+ mkdirSync(join(legacyRoot, 'bin'), { recursive: true });
+ writeFileSync(
+ join(legacyRoot, 'path-install.json'),
+ JSON.stringify({
+ version: 1,
+ installedAt: '2026-09-23T00:00:00.000Z',
+ bundleVersion: '0.77.7-beta.0',
+ bundleWrapperPath: BETA_WRAPPER,
+ binDir: join(legacyRoot, 'bin'),
+ envShimPath: join(legacyRoot, 'env.sh'),
+ rcFiles: [zshrc],
+ rcOptOuts: [],
+ pathDiscovery: null,
+ extraSymlinks: [],
+ consent: { status: 'granted', at: '2026-09-23T00:00:00.000Z' },
+ }),
+ );
+ return { legacyRoot, zshrc };
+}
+
+function launch(
+ userHome: string,
+ extra: Partial<Parameters<typeof ensureCliOnPath>[0]> = {},
+): ReturnType<typeof ensureCliOnPath> {
+ return ensureCliOnPath({
+ executablePath: BETA_EXE,
+ isPackaged: true,
+ platform: 'darwin',
+ home: userHome,
+ bundleVersion: '0.77.8-beta.0',
+ env: { HOME: userHome, SHELL: '/bin/zsh' },
+ spawn: async () => ({ code: 0, stdout: '/usr/bin:/bin', stderr: '' }),
+ ...extra,
+ });
+}
+
+describe('Beta fish shim', () => {
+ test('installs and removes the Beta fish file named by the shared layout', async () => {
+ const userHome = home();
+ const confD = join(userHome, '.config', 'fish', 'conf.d');
+ const fishFile = join(confD, 'open-knowledge-beta.fish');
+ expect(pathShimFishConfFileName('beta')).toBe('open-knowledge-beta.fish');
+
+ const result = await launch(userHome, {
+ env: { HOME: userHome, SHELL: '/usr/bin/fish' },
+ consentDecision: { status: 'granted', at: '2026-09-23T00:00:00.000Z' },
+ });
+
+ expect(result.status).toBe('installed');
+ expect(nodeFs.readdirSync(confD)).toEqual(['open-knowledge-beta.fish']);
+ const fish = readFileSync(fishFile, 'utf8');
+ expect(fish).toContain(`# >>> ${pathShimBlockLabel('beta')} >>>`);
+ expect(fish).toContain('# >>> open-knowledge beta cli >>>');
+ expect(fish).toContain('$HOME/.ok-beta/bin');
+
+ expect(
+ removePathShimFromRcFiles({
+ home: userHome,
+ platform: 'darwin',
+ env: { SHELL: '/usr/bin/fish' },
+ }),
+ ).toMatchObject({ status: 'removed', strippedFiles: [fishFile] });
+ expect(existsSync(fishFile)).toBe(false);
+ });
+});
+
+describe('Beta legacy home cleanup', () => {
+ test('a failed legacy removal names the directory and is retried on the next launch', async () => {
+ const userHome = home();
+ const { legacyRoot } = seedLegacyBetaInstall(userHome);
+ const events: Array<Record<string, unknown>> = [];
+ const logger = { event: (payload: Record<string, unknown>) => events.push(payload) };
+
+ const first = await launch(userHome, {
+ logger,
+ fs: fsWith({
+ rmSync: () => {
+ throw new Error('EBUSY: resource busy');
+ },
+ }),
+ });
+
+ expect(first.status).toBe('installed');
+ expect(existsSync(legacyRoot)).toBe(true);
+ expect(events).toContainEqual({
+ event: 'path-install-legacy-home-remove-failed',
+ path: legacyRoot,
+ error: 'EBUSY: resource busy',
+ });
+
+ events.length = 0;
+ const rmCalls: string[] = [];
+ const second = await launch(userHome, {
+ logger,
+ fs: fsWith({
+ rmSync: (path, options) => {
+ rmCalls.push(path);
+ nodeFs.rmSync(path, options);
+ },
+ }),
+ });
+
+ expect(second.status).toBe('healthy-current');
+ expect(rmCalls).toEqual([legacyRoot]);
+ expect(existsSync(legacyRoot)).toBe(false);
+ expect(events.map((e) => e.event)).toContain('path-install-legacy-home-removed');
+ expect(readFileSync(join(userHome, '.zshrc'), 'utf8')).toContain('$HOME/.ok-beta/env.sh');
+ });
+
+ test('the current marker wins over a leftover legacy marker, and the legacy home is cleared', async () => {
+ const userHome = home();
+ writeFileSync(join(userHome, '.zshrc'), '');
+ const installed = await launch(userHome, {
+ consentDecision: { status: 'granted', at: '2026-09-23T00:00:00.000Z' },
+ });
+ expect(installed.status).toBe('installed');
+ const legacyRoot = join(userHome, '.ok', 'variants', 'beta');
+ mkdirSync(legacyRoot, { recursive: true });
+ writeFileSync(
+ join(legacyRoot, 'path-install.json'),
+ JSON.stringify({
+ version: 1,
+ installedAt: '2020-01-01T00:00:00.000Z',
+ bundleVersion: 'legacy',
+ bundleWrapperPath: '/stale/ok.sh',
+ binDir: join(legacyRoot, 'bin'),
+ envShimPath: join(legacyRoot, 'env.sh'),
+ rcFiles: [],
+ rcOptOuts: [],
+ pathDiscovery: null,
+ extraSymlinks: [],
+ consent: { status: 'declined', at: '2020-01-01T00:00:00.000Z' },
+ }),
+ );
+
+ const result = await launch(userHome, { bundleVersion: '0.77.9-beta.0' });
+
+ expect(result.status).toBe('healthy-current');
+ if (result.status !== 'healthy-current') throw new Error('unreachable');
+ expect(result.marker.bundleVersion).toBe('0.77.8-beta.0');
+ expect(result.marker.consent?.status).toBe('granted');
+ expect(existsSync(legacyRoot)).toBe(false);
+ });
+
+ test('an install that fails before writing the new marker leaves the legacy home in place', async () => {
+ const userHome = home();
+ const { legacyRoot } = seedLegacyBetaInstall(userHome);
+ const rmCalls: string[] = [];
+
+ const result = await launch(userHome, {
+ logger: { event: () => {} },
+ fs: fsWith({
+ symlinkSync: () => {
+ throw new Error('EACCES: permission denied');
+ },
+ rmSync: (path) => {
+ rmCalls.push(path);
+ },
+ }),
+ });
+
+ expect(result.status).toBe('failed-all');
+ expect(rmCalls).toEqual([]);
+ expect(existsSync(legacyRoot)).toBe(true);
+ expect(existsSync(pathInstallMarkerPath(userHome))).toBe(false);
+ });
+});
+
+function seedStuckBetaInstall(userHome: string): { legacyRoot: string; zshrc: string } {
+ const seeded = seedLegacyBetaInstall(userHome);
+ const bin = join(userHome, '.ok-beta', 'bin');
+ mkdirSync(bin, { recursive: true });
+ symlinkSync(BETA_WRAPPER, join(bin, 'ok-beta'));
+ symlinkSync(BETA_WRAPPER, join(bin, 'open-knowledge-beta'));
+ return seeded;
+}
+
+describe('Beta install interrupted after the new links were created', () => {
+ test('a legacy marker never counts as healthy, so the new marker and rc block get written', async () => {
+ const userHome = home();
+ const { legacyRoot, zshrc } = seedStuckBetaInstall(userHome);
+
+ const result = await launch(userHome, {
+ logger: { event: () => {} },
+ spawn: async () => ({
+ code: 0,
+ stdout: `/usr/bin:/bin:${join(userHome, '.ok-beta', 'bin')}`,
+ stderr: '',
+ }),
+ });
+
+ expect(result.status).toBe('installed');
+ expect(existsSync(pathInstallMarkerPath(userHome))).toBe(true);
+ expect(existsSync(legacyRoot)).toBe(false);
+ const rc = readFileSync(zshrc, 'utf8');
+ expect(rc).toContain('$HOME/.ok-beta/env.sh');
+ expect(rc).not.toContain('variants/beta');
+ });
+
+ test('the legacy home survives a failed marker write and is cleared on the next launch', async () => {
+ const userHome = home();
+ const { legacyRoot } = seedStuckBetaInstall(userHome);
+ const rmCalls: string[] = [];
+
+ const failed = await launch(userHome, {
+ logger: { event: () => {} },
+ fs: fsWith({
+ writeFileSync: (path, content) => {
+ if (path === pathInstallMarkerPath(userHome)) throw new Error('ENOSPC: no space left');
+ nodeFs.writeFileSync(path, content);
+ },
+ rmSync: (path) => {
+ rmCalls.push(path);
+ },
+ }),
+ });
+
+ expect(failed.status).toBe('failed-all');
+ expect(rmCalls).toEqual([]);
+ expect(existsSync(legacyRoot)).toBe(true);
+
+ const retried = await launch(userHome, { logger: { event: () => {} } });
+
+ expect(retried.status).not.toBe('failed-all');
+ expect(existsSync(pathInstallMarkerPath(userHome))).toBe(true);
+ expect(existsSync(legacyRoot)).toBe(false);
+ });
+});
+
+describe('Beta installer and runtime agree on the bin dir', () => {
+ test('the marker, env.sh and rc block all name the dir the runtime puts on PATH', async () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ try {
+ const userHome = home();
+ writeFileSync(join(userHome, '.zshrc'), '');
+ const result = await launch(userHome, {
+ env: { HOME: userHome, SHELL: '/usr/bin/fish' },
+ consentDecision: { status: 'granted', at: '2026-09-23T00:00:00.000Z' },
+ });
+ if (result.status !== 'installed') throw new Error(`unexpected ${result.status}`);
+ const runtimeBin = okManagedBinDirs({ platform: 'darwin', home: userHome })[0];
+ expect(runtimeBin).toBe(join(userHome, '.ok-beta', 'bin'));
+ expect(result.marker.binDir).toBe(runtimeBin);
+ const relative = runtimeBin?.slice(userHome.length);
+ expect(readFileSync(result.marker.envShimPath, 'utf8')).toContain(`"$\{HOME}${relative}"`);
+ expect(
+ readFileSync(
+ join(userHome, '.config', 'fish', 'conf.d', 'open-knowledge-beta.fish'),
+ 'utf8',
+ ),
+ ).toContain(`"$HOME${relative}"`);
+ } finally {
+ vi.unstubAllEnvs();
+ }
});
});
diff --git a/packages/desktop/src/main/path-install.test.ts b/packages/desktop/src/main/path-install.test.ts
index a0e616360..56c52e47e 100644
--- a/packages/desktop/src/main/path-install.test.ts
+++ b/packages/desktop/src/main/path-install.test.ts
@@ -11,7 +11,8 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { describe, expect, test, vi } from 'vitest';
+import { okManagedBinDirs } from '../shared/ok-child-env.ts';
import {
computePathInstallDescriptor,
computePathLeg,
@@ -400,6 +401,7 @@ describe('ensureCliOnPath', () => {
lstatSync: () => {
throw enoent();
},
+ rmSync: () => {},
},
logger: { event: () => {} },
}),
@@ -745,3 +747,26 @@ describe('isPathShimInstalled / removePathShimFromRcFiles — the Settings → A
expect(readFileSync(zshrc, 'utf8')).not.toContain('open-knowledge cli');
});
});
+
+describe('Stable installer and runtime agree on the bin dir', () => {
+ test('the marker, env.sh and rc block all name the dir the runtime puts on PATH', async () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ try {
+ const h = home();
+ const result = await ensureCliOnPath(
+ baseOpts(h, { env: { HOME: h, SHELL: '/usr/bin/fish' }, consentDecision: GRANTED }),
+ );
+ if (result.status !== 'installed') throw new Error(`unexpected ${result.status}`);
+ const runtimeBin = okManagedBinDirs({ platform: 'darwin', home: h })[0];
+ expect(runtimeBin).toBe(join(h, '.ok', 'bin'));
+ expect(result.marker.binDir).toBe(runtimeBin);
+ const relative = runtimeBin?.slice(h.length);
+ expect(readFileSync(result.marker.envShimPath, 'utf8')).toContain(`"$\{HOME}${relative}"`);
+ expect(
+ readFileSync(join(h, '.config', 'fish', 'conf.d', 'open-knowledge.fish'), 'utf8'),
+ ).toContain(`"$HOME${relative}"`);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.ts
index 96ad33b57..9809e58b2 100644
--- a/packages/desktop/src/main/path-install.ts
+++ b/packages/desktop/src/main/path-install.ts
@@ -6,30 +6,34 @@ import {
readFileSync as fsReadFileSync,
readlinkSync as fsReadlinkSync,
renameSync as fsRenameSync,
+ rmSync as fsRmSync,
symlinkSync as fsSymlinkSync,
unlinkSync as fsUnlinkSync,
writeFileSync as fsWriteFileSync,
} from 'node:fs';
import { dirname, join } from 'node:path';
+import type { PathDiscovery, PathInstallConsent, PathInstallMarker } from '@inkeep/open-knowledge';
import {
- type PathDiscovery,
- type PathInstallConsent,
- type PathInstallMarker,
- pathInstallMarkerPath as stablePathInstallMarkerPath,
-} from '@inkeep/open-knowledge';
-import { posixOkManagedBinDir } from '@inkeep/open-knowledge-core';
+ pathShimBinDir,
+ pathShimBlockLabel,
+ pathShimFishConfFileName,
+ pathShimHomeDirName,
+ pathShimMarkerPath,
+} from '@inkeep/open-knowledge-core';
import { DESKTOP_VARIANT } from '../shared/desktop-variant.ts';
import type { McpWiringPathInstallDescriptor } from '../shared/ipc-channels.ts';
import { classifyInstallShape } from './install-shape.ts';
const NAMES = DESKTOP_VARIANT.cliCommandNames;
-const CLI_HOME_PREFIX = DESKTOP_VARIANT.cliHomeSegment
+const CHANNEL = DESKTOP_VARIANT.name;
+const CLI_HOME_PREFIX = pathShimHomeDirName(CHANNEL);
+const RC_BIN_DIR = pathShimBinDir(CHANNEL, '$HOME');
+const ENV_SH_BIN_DIR = pathShimBinDir(CHANNEL, `\${HOME}`);
+const FISH_CONF_NAME = pathShimFishConfFileName(CHANNEL);
+const LEGACY_CLI_HOME_PREFIX = DESKTOP_VARIANT.cliHomeSegment
? `.ok/variants/${DESKTOP_VARIANT.cliHomeSegment}`
- : '.ok';
-const CLI_BLOCK_NAME =
- DESKTOP_VARIANT.name === 'stable'
- ? 'open-knowledge cli'
- : `open-knowledge ${DESKTOP_VARIANT.name} cli`;
+ : null;
+const CLI_BLOCK_NAME = pathShimBlockLabel(CHANNEL);
const BEGIN = `# >>> ${CLI_BLOCK_NAME} >>>`;
const END = `# <<< ${CLI_BLOCK_NAME} <<<`;
const BLOCK_RE = new RegExp(
@@ -38,8 +42,29 @@ const BLOCK_RE = new RegExp(
);
export function pathInstallMarkerPath(home: string): string {
- if (DESKTOP_VARIANT.name === 'stable') return stablePathInstallMarkerPath(home);
- return join(home, CLI_HOME_PREFIX, 'path-install.json');
+ return pathShimMarkerPath(CHANNEL, home);
+}
+
+function legacyMarkerPath(home: string, fs: PathInstallFsOps): string | null {
+ if (LEGACY_CLI_HOME_PREFIX === null) return null;
+ const path = join(home, LEGACY_CLI_HOME_PREFIX, 'path-install.json');
+ return fs.existsSync(path) ? path : null;
+}
+
+function removeLegacyCliHome(home: string, fs: PathInstallFsOps, logger: PathInstallLogger): void {
+ if (LEGACY_CLI_HOME_PREFIX === null) return;
+ const dir = join(home, LEGACY_CLI_HOME_PREFIX);
+ if (!fs.existsSync(dir)) return;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ logger.event({ event: 'path-install-legacy-home-removed' });
+ } catch (err) {
+ logger.event({
+ event: 'path-install-legacy-home-remove-failed',
+ path: dir,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
}
interface PathInstallFsOps {
@@ -52,6 +77,7 @@ interface PathInstallFsOps {
renameSync(oldPath: string, newPath: string): void;
readlinkSync(path: string): string;
lstatSync(path: string): { isSymbolicLink(): boolean };
+ rmSync(path: string, options: { recursive: boolean; force: boolean }): void;
}
const defaultFsOps: PathInstallFsOps = {
@@ -64,6 +90,7 @@ const defaultFsOps: PathInstallFsOps = {
renameSync: (oldPath, newPath) => fsRenameSync(oldPath, newPath),
readlinkSync: (path) => fsReadlinkSync(path),
lstatSync: (path) => fsLstatSync(path),
+ rmSync: (path, options) => fsRmSync(path, options),
};
interface PathInstallLogger {
@@ -130,8 +157,9 @@ function readMarker(
fs: PathInstallFsOps,
logger: PathInstallLogger,
): PathInstallMarker | null {
- const path = pathInstallMarkerPath(home);
- if (!fs.existsSync(path)) return null;
+ const current = pathInstallMarkerPath(home);
+ const path = fs.existsSync(current) ? current : legacyMarkerPath(home, fs);
+ if (path === null) return null;
try {
const parsed = JSON.parse(fs.readFileSync(path, 'utf8')) as PathInstallMarker;
if (parsed?.version !== 1) {
@@ -163,9 +191,7 @@ function writeMarker(home: string, marker: PathInstallMarker, fs: PathInstallFsO
}
function okBin(home: string): string {
- return DESKTOP_VARIANT.name === 'stable'
- ? posixOkManagedBinDir(home)
- : join(home, CLI_HOME_PREFIX, 'bin');
+ return pathShimBinDir(CHANNEL, home);
}
function envShim(home: string): string {
@@ -180,7 +206,7 @@ function block(): string {
}
function fishBlock(): string {
- return `${BEGIN}\n${MANAGED_HINT}\nif test -d "$HOME/${CLI_HOME_PREFIX}/bin"\n if not contains "$HOME/${CLI_HOME_PREFIX}/bin" $PATH\n set -gx PATH "$HOME/${CLI_HOME_PREFIX}/bin" $PATH\n end\nend\n${END}\n`;
+ return `${BEGIN}\n${MANAGED_HINT}\nif test -d "${RC_BIN_DIR}"\n if not contains "${RC_BIN_DIR}" $PATH\n set -gx PATH "${RC_BIN_DIR}" $PATH\n end\nend\n${END}\n`;
}
function rcTargets(
@@ -213,13 +239,7 @@ function rcTargets(
...(fishDetected
? [
{
- path: join(
- fishConfigDir,
- 'conf.d',
- DESKTOP_VARIANT.name === 'stable'
- ? 'open-knowledge.fish'
- : `open-knowledge-${DESKTOP_VARIANT.name}.fish`,
- ),
+ path: join(fishConfigDir, 'conf.d', FISH_CONF_NAME),
create: true,
content: fishBlock(),
},
@@ -457,8 +477,14 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
const wrapper = shape.wrapperPath;
const prior = readMarker(home, fs, logger);
+ const priorIsLegacy = prior !== null && !fs.existsSync(pathInstallMarkerPath(home));
const explicitDecision = opts.consentDecision !== undefined;
- if (prior && !explicitDecision && markerHealthy(prior, home, wrapper, fs, logger)) {
+ if (
+ prior &&
+ !priorIsLegacy &&
+ !explicitDecision &&
+ markerHealthy(prior, home, wrapper, fs, logger)
+ ) {
if (!prior.consent && prior.rcFiles.length > 0) {
const marker: PathInstallMarker = {
...prior,
@@ -478,9 +504,11 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
source: 'grandfather',
rcFileCount: prior.rcFiles.length,
});
+ removeLegacyCliHome(home, fs, logger);
return { status: 'healthy-current', marker };
}
logger.event({ event: 'path-install-healthy-current', binDir: prior.binDir });
+ removeLegacyCliHome(home, fs, logger);
return { status: 'healthy-current', marker: prior };
}
@@ -500,7 +528,7 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
fs.mkdirSync(dirname(shim), { recursive: true });
fs.writeFileSync(
shim,
- `# ${DESKTOP_VARIANT.productName} CLI environment — managed file, do not edit.\ncase ":\${PATH}:" in\n *:"\${HOME}/${CLI_HOME_PREFIX}/bin":*) ;;\n *) export PATH="\${HOME}/${CLI_HOME_PREFIX}/bin:\${PATH}" ;;\nesac\n`,
+ `# ${DESKTOP_VARIANT.productName} CLI environment — managed file, do not edit.\ncase ":\${PATH}:" in\n *:"${ENV_SH_BIN_DIR}":*) ;;\n *) export PATH="${ENV_SH_BIN_DIR}:\${PATH}" ;;\nesac\n`,
);
phase = 'discoverPath';
@@ -522,6 +550,7 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
const canSkipRc =
!explicitGrant &&
prior != null &&
+ !priorIsLegacy &&
discovery?.okBinAlreadyOnPath === true &&
activePriorRcFiles.every((file) => rcBlockHealthy(file, fs));
const nowIso = (opts.now?.() ?? new Date()).toISOString();
@@ -564,6 +593,7 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
...(consent ? { consent } : {}),
};
writeMarker(home, marker, fs);
+ removeLegacyCliHome(home, fs, logger);
if (consent && consent.status !== prior?.consent?.status) {
logger.event({
event:
@@ -658,15 +688,7 @@ export function removePathShimFromRcFiles(opts: {
}): RemovePathShimResult {
const { home, fs = defaultFsOps, logger = DEFAULT_LOGGER } = opts;
const marker = readMarker(home, fs, logger);
- const okOwnedFishConf = join(
- home,
- '.config',
- 'fish',
- 'conf.d',
- DESKTOP_VARIANT.name === 'stable'
- ? 'open-knowledge.fish'
- : `open-knowledge-${DESKTOP_VARIANT.name}.fish`,
- );
+ const okOwnedFishConf = join(home, '.config', 'fish', 'conf.d', FISH_CONF_NAME);
const candidates = new Set<string>([
...rcTargets(home, (opts.env ?? process.env).SHELL, fs, opts.platform).map(
(target) => target.path,
diff --git a/packages/desktop/tests/main/ipc-handlers.test.ts b/packages/desktop/tests/main/ipc-handlers.test.ts
index a161e87ba..25b3d1e42 100644
--- a/packages/desktop/tests/main/ipc-handlers.test.ts
+++ b/packages/desktop/tests/main/ipc-handlers.test.ts
@@ -7,7 +7,7 @@ import {
extractTrashDetail,
isPathWithinProject,
recordHandoff,
- STATS_FILE_RELATIVE_PATH,
+ STATS_FILE_NAME,
showItemInFolder,
spawnCursor,
trashItem,
@@ -746,7 +746,7 @@ describe('recordHandoff', () => {
expect(calls.mkdir).toEqual(['/Users/test/.ok']);
expect(calls.appendFile).toHaveLength(1);
expect(calls.appendFile[0]?.path).toBe('/Users/test/.ok/stats.jsonl');
- expect(STATS_FILE_RELATIVE_PATH).toEqual(['.ok', 'stats.jsonl']);
+ expect(STATS_FILE_NAME).toBe('stats.jsonl');
});
test('serializes the full schema verbatim including optional reason on errors', async () => {
diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.ts
index 82e830c26..9d56782e9 100644
--- a/packages/server/src/acp/launch.ts
+++ b/packages/server/src/acp/launch.ts
@@ -3,7 +3,8 @@ import { constants, existsSync, statSync } from 'node:fs';
import { access, chmod, readFile, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
-import { augmentAgentSpawnPath, OK_DIR, OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';
+import { augmentAgentSpawnPath, OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { z } from 'zod';
import {
tracedMkdir,
@@ -56,7 +57,7 @@ export class AgentLaunchError extends Error {
}
function defaultBinaryCacheDir(): string {
- return join(homedir(), OK_DIR, 'acp-agents');
+ return join(okUserHomeDir(), 'acp-agents');
}
function isDir(dir: string): boolean {
@@ -1048,7 +1049,7 @@ export function windowsCmdWrap(cmd: string, args: string[]): { cmd: string; args
}
function acpNpxIsolatedCwd(): string {
- const dir = join(homedir(), OK_DIR, 'acp-npx-cwd');
+ const dir = join(okUserHomeDir(), 'acp-npx-cwd');
tracedMkdirSync(dir, { recursive: true, mode: 0o700 });
const marker = join(dir, 'package.json');
if (!existsSync(marker)) {
diff --git a/packages/server/src/acp/managed-runtime.ts b/packages/server/src/acp/managed-runtime.ts
index 0679602b2..64a8e9e9a 100644
--- a/packages/server/src/acp/managed-runtime.ts
+++ b/packages/server/src/acp/managed-runtime.ts
@@ -1,8 +1,8 @@
import { randomUUID } from 'node:crypto';
import { access, constants, readdir, stat } from 'node:fs/promises';
-import { arch, homedir, platform } from 'node:os';
+import { arch, platform } from 'node:os';
import { dirname, join } from 'node:path';
-import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { tracedMkdir, tracedRename, tracedRm } from '../fs-traced.ts';
import type { PinoLogger } from '../logger.ts';
import {
@@ -75,12 +75,8 @@ export function describeRuntime(kind: ManagedRuntimeKind): RuntimeDescriptor {
};
}
-function okHomeDir(): string {
- return join(homedir(), OK_DIR);
-}
-
function defaultRuntimeRoot(): string {
- return join(okHomeDir(), 'runtimes');
+ return join(okUserHomeDir(), 'runtimes');
}
function versionOf(kind: ManagedRuntimeKind): string {
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index c44db6303..31a675ff7 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -54,6 +54,7 @@ import {
pathspecArgs,
readFmMap,
SKILL_NAME_REGEX,
+ SKILLS_STORE_DIRNAME,
SkillScopeSchema,
SkillUninstallRequestSchema,
SkillUninstallSuccessSchema,
@@ -1878,8 +1879,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {
for (const scope of ['project', 'global'] as const) {
const skillsRoot =
scope === 'global'
- ? resolve(skillsHome, '.ok', 'skills')
- : resolve(contentDir, '.ok', 'skills');
+ ? resolve(skillsHome, OK_DIR, SKILLS_STORE_DIRNAME)
+ : resolve(contentDir, OK_DIR, SKILLS_STORE_DIRNAME);
for (const skill of resolveSkillsList(skillsRoot, scope).skills) {
admitted.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${scope}/${skill.name}`);
}
@@ -4118,8 +4119,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {
function resolveSkillsRoot(scope: 'project' | 'global'): string {
return scope === 'global'
- ? resolve(skillsHome, '.ok', 'skills')
- : resolve(contentDir, '.ok', 'skills');
+ ? resolve(skillsHome, OK_DIR, SKILLS_STORE_DIRNAME)
+ : resolve(contentDir, OK_DIR, SKILLS_STORE_DIRNAME);
}
function resolveSkillDirForRead(
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 2998b4103..5946989a8 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -15,7 +15,9 @@ import {
requiresExternalConsent,
resolveServerRuntimeConfig,
type ServerRuntimeConfig,
+ SKILLS_STORE_DIRNAME,
} from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { context, propagation } from '@opentelemetry/api';
import sirv from 'sirv';
@@ -464,7 +466,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
: new AcpThreadManager({
contentDir: opts.contentDir,
localDir: lockDir,
- globalDir: resolve(homedir(), OK_DIR),
+ globalDir: okUserHomeDir(),
registry: serverInstance.acpRegistry,
permissions: serverInstance.acpPermissions,
sessionManager,
@@ -744,7 +746,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
try {
const m = await migrateStoreSkillsInPlace({
projectDir,
- skillsRoot: resolve(opts.contentDir, OK_DIR, 'skills'),
+ skillsRoot: resolve(opts.contentDir, OK_DIR, SKILLS_STORE_DIRNAME),
inPlaceNames: genuineInPlaceNames(opts.contentDir, scanInPlaceSkills(opts.contentDir)),
});
if (m.migrated.length + m.skipped.length > 0) {
@@ -768,7 +770,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
const home = homedir();
const gm = await migrateStoreSkillsInPlace({
projectDir: home,
- skillsRoot: resolve(home, OK_DIR, 'skills'),
+ skillsRoot: resolve(home, OK_DIR, SKILLS_STORE_DIRNAME),
hostRoots: USER_HOST_ROOTS_BY_PRECEDENCE,
inPlaceNames: genuineInPlaceNames(home, scanGlobalInPlaceSkills(home)),
});
diff --git a/packages/server/src/embeddings/secrets-store.test.ts b/packages/server/src/embeddings/secrets-store.test.ts
index a0be6d413..f44671aea 100644
--- a/packages/server/src/embeddings/secrets-store.test.ts
+++ b/packages/server/src/embeddings/secrets-store.test.ts
@@ -12,7 +12,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { parse } from 'yaml';
import {
canonicalProjectKey,
@@ -20,6 +20,7 @@ import {
describeStoredEmbeddingsKey,
FileEmbeddingsBackend,
makeLazyEmbeddingsKeyStore,
+ secretsFilePath,
} from './secrets-store.ts';
const KEY = 'sk-secret-embeddings-key-1234567890';
@@ -223,3 +224,16 @@ describe('describe + list + canonicalProjectKey', () => {
expect((await s.resolveForProject(projectA, CUSTOM)).key).toBe(KEY);
});
});
+
+describe('secrets file per channel', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test('Stable keeps ~/.ok/secrets.yml and Beta uses ~/.ok-beta/secrets.yml', () => {
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ expect(secretsFilePath('/home/me')).toBe(join('/home/me', '.ok', 'secrets.yml'));
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ expect(secretsFilePath('/home/me')).toBe(join('/home/me', '.ok-beta', 'secrets.yml'));
+ });
+});
diff --git a/packages/server/src/embeddings/secrets-store.ts b/packages/server/src/embeddings/secrets-store.ts
index 9a667783a..56092275c 100644
--- a/packages/server/src/embeddings/secrets-store.ts
+++ b/packages/server/src/embeddings/secrets-store.ts
@@ -12,6 +12,7 @@ import {
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { DEFAULT_EMBEDDINGS_BASE_URL } from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { parse as yamlParse, stringify as yamlStringify } from 'yaml';
import {
tracedMkdirSync,
@@ -46,7 +47,7 @@ export function canonicalProjectKey(projectDir: string): string {
}
export function secretsFilePath(homedirOverride?: string): string {
- return join(homedirOverride ?? homedir(), '.ok', 'secrets.yml');
+ return join(okUserHomeDir(homedirOverride ?? homedir()), 'secrets.yml');
}
export interface EmbeddingsKeyPresence {
diff --git a/packages/server/src/file-logger.test.ts b/packages/server/src/file-logger.test.ts
index 44473dc81..2ef73cce1 100644
--- a/packages/server/src/file-logger.test.ts
+++ b/packages/server/src/file-logger.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync }
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import pino from 'pino';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { createFileLogger, flushFileLogger, MAX_FILE_SIZE } from './file-logger.ts';
const TEST_DIR = join(tmpdir(), `ok-file-logger-test-${process.pid}`);
@@ -190,3 +190,25 @@ describe('file logger', () => {
expect(flushed).toBe(true);
});
});
+
+describe('logs dir per channel', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ });
+
+ test('importing under an unsupported OK_CHANNEL does not throw', async () => {
+ vi.stubEnv('OK_CHANNEL', 'bogus');
+ vi.resetModules();
+ const mod = await import('./file-logger.ts');
+ expect(() => mod.getLogsDir()).toThrow(/OK_CHANNEL/);
+ });
+
+ test('Beta resolves logs under ~/.ok-beta/logs', async () => {
+ vi.stubEnv('HOME', '/tmp/ok-logs-home');
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ vi.resetModules();
+ const { getLogsDir } = await import('./file-logger.ts');
+ expect(getLogsDir()).toBe(join('/tmp/ok-logs-home', '.ok-beta', 'logs'));
+ });
+});
diff --git a/packages/server/src/file-logger.ts b/packages/server/src/file-logger.ts
index bd7abfdab..d22b5041f 100644
--- a/packages/server/src/file-logger.ts
+++ b/packages/server/src/file-logger.ts
@@ -1,10 +1,12 @@
import { mkdirSync, readdirSync, renameSync, statSync, unlinkSync } from 'node:fs';
-import { homedir } from 'node:os';
import { join } from 'node:path';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import type { LoggerOptions, Logger as PinoLoggerInstance } from 'pino';
import pino from 'pino';
-const OK_LOGS_DIR = join(homedir(), '.ok', 'logs');
+function okLogsDir(): string {
+ return join(okUserHomeDir(), 'logs');
+}
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const MAX_ROTATED_FILES = 2;
const MAX_AGE_DAYS = 7;
@@ -112,14 +114,14 @@ export interface FileLoggerOptions {
}
export function createFileLogger(opts: FileLoggerOptions): PinoLoggerInstance {
- ensureDir(OK_LOGS_DIR);
+ ensureDir(okLogsDir());
const date = todayDateString();
- const filePath = opts.filePath ?? join(OK_LOGS_DIR, `${opts.name}.${date}.log`);
+ const filePath = opts.filePath ?? join(okLogsDir(), `${opts.name}.${date}.log`);
rotateIfNeeded(filePath);
const scheduleTimer = opts._setTimeout ?? setTimeout;
- scheduleTimer(() => pruneLogsDir(OK_LOGS_DIR), 5000).unref();
+ scheduleTimer(() => pruneLogsDir(okLogsDir()), 5000).unref();
const dest = pino.destination({ dest: filePath, append: true, sync: true });
@@ -197,11 +199,11 @@ export function flushFileLogger(
}
export function getLogFilePath(name: string): string {
- return join(OK_LOGS_DIR, `${name}.${todayDateString()}.log`);
+ return join(okLogsDir(), `${name}.${todayDateString()}.log`);
}
export function getLogsDir(): string {
- return OK_LOGS_DIR;
+ return okLogsDir();
}
export { MAX_FILE_SIZE };
diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.ts
index e7c3d0fc4..c0575e638 100644
--- a/packages/server/src/git-handle.test.ts
+++ b/packages/server/src/git-handle.test.ts
@@ -5,6 +5,7 @@ import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { DESKTOP_PRODUCTS, resolveDesktopProductName } from '@inkeep/open-knowledge-core';
import shellQuote from 'shell-quote';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
@@ -422,6 +423,31 @@ describe('buildSyncCredentialConfig()', () => {
expect(argvFromHelper(config)).toEqual([...argv, 'auth', 'git-credential']);
});
+ test('Beta channel from OK_CHANNEL under a node execPath pins OK_CHANNEL=beta into the helper', () => {
+ withEnvEntries({ OK_CHANNEL: 'beta' }, () => {
+ const argv = ['/usr/local/bin/node', '/opt/ok/cli.mjs'];
+ const config = buildSyncCredentialConfig(argv, { resetAmbient: true });
+ const helper = config.at(-1)?.slice('credential.helper=!'.length) ?? '';
+ const parsed = shellQuote.parse(helper);
+ expect(parsed).toEqual(['OK_CHANNEL=beta', ...argv, 'auth', 'git-credential']);
+ const helperEnv = { OK_CHANNEL: String(parsed[0]).split('=')[1] };
+ expect(DESKTOP_PRODUCTS[resolveDesktopProductName(helperEnv, argv[0])].keyringService).toBe(
+ 'open-knowledge-beta',
+ );
+ });
+ });
+
+ test('Stable channel keeps the helper unpinned', () => {
+ withEnvEntries({ OK_CHANNEL: undefined }, () => {
+ const config = buildSyncCredentialConfig(['/usr/local/bin/node', '/opt/ok/cli.mjs'], {
+ resetAmbient: true,
+ });
+ expect(config.at(-1)).toBe(
+ 'credential.helper=!/usr/local/bin/node /opt/ok/cli.mjs auth git-credential',
+ );
+ });
+ });
+
test('embedded single quote in the path round-trips safely', () => {
const argv = ["/Users/o'brien/OpenKnowledge.app/cli.sh"];
const config = buildSyncCredentialConfig(argv, { resetAmbient: true });
diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.ts
index 56cd32e64..5f37c9bc2 100644
--- a/packages/server/src/git-handle.ts
+++ b/packages/server/src/git-handle.ts
@@ -1,7 +1,11 @@
import { existsSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { delimiter, resolve } from 'node:path';
-import { augmentGitSpawnPath } from '@inkeep/open-knowledge-core';
+import {
+ augmentGitSpawnPath,
+ OK_CHANNEL_ENV,
+ resolveDesktopProductName,
+} from '@inkeep/open-knowledge-core';
import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';
import { shellEscape } from './bash/shell-escape.ts';
@@ -136,6 +140,8 @@ export function buildSyncCredentialConfig(
): string[] {
const argv = localOpCliArgs && localOpCliArgs.length > 0 ? localOpCliArgs : ['open-knowledge'];
const cliPrefix = argv.map(shellEscape).join(' ');
- const helper = `credential.helper=!${cliPrefix} auth git-credential`;
+ const channel = resolveDesktopProductName();
+ const channelPin = channel === 'stable' ? '' : `${OK_CHANNEL_ENV}=${channel} `;
+ const helper = `credential.helper=!${channelPin}${cliPrefix} auth git-credential`;
return opts.resetAmbient ? ['credential.helper=', helper] : [helper];
}
diff --git a/packages/server/src/http/local-op-routes.test.ts b/packages/server/src/http/local-op-routes.test.ts
index 19eb860b5..0998f4764 100644
--- a/packages/server/src/http/local-op-routes.test.ts
+++ b/packages/server/src/http/local-op-routes.test.ts
@@ -263,6 +263,30 @@ describe('auth-login stream displacement (a second start orphans the first clien
}
});
+ test('the undeclared-host refusal names the Beta user config when the running channel is Beta', async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-local-op-beta-home-'));
+ const home = mkdtempSync(join(tmpdir(), 'ok-local-op-beta-user-'));
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('USERPROFILE', home);
+ try {
+ execFileSync('git', ['init', '-q'], { cwd: projectDir });
+ execFileSync('git', ['remote', 'add', 'origin', 'https://git.example.internal/team/kb.git'], {
+ cwd: projectDir,
+ });
+ const baseUrl = await serveLocalOpGroup({ projectDir });
+ const res = await postJson(baseUrl, '/api/local-op/auth/status', {});
+ expect(res.status).toBe(409);
+ const body = (await res.json()) as { detail: string };
+ expect(body.detail).toContain('as github in ~/.ok-beta/global.yml and restart');
+ expect(body.detail).not.toContain('~/.ok/');
+ } finally {
+ vi.unstubAllEnvs();
+ rmSync(projectDir, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
test('gh-login rejects an explicit undeclared host before looking up gh and accepts a declaration', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-gh-login-host-'));
const probe = vi.fn(async () => null);
diff --git a/packages/server/src/http/local-op-routes.ts b/packages/server/src/http/local-op-routes.ts
index a18921aa7..e9248dad1 100644
--- a/packages/server/src/http/local-op-routes.ts
+++ b/packages/server/src/http/local-op-routes.ts
@@ -23,6 +23,7 @@ import {
LocalOpEmbeddingsTestResponseSchema,
LocalOpOkInitRequestSchema,
LocalOpOkInitResponseSchema,
+ okUserHomeDisplayPath,
} from '@inkeep/open-knowledge-core';
import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import {
@@ -513,7 +514,7 @@ export function createLocalOpRoutes(
const detail =
rejectedHost === null
? "The project's origin URL could not be parsed to determine its host. Set a supported origin URL or explicitly select a GitHub host."
- : `${rejectedHost} is not a declared GitHub host. If it runs GitHub Enterprise Server, declare git.hosts.${rejectedHost}.provider as github in ~/.ok/global.yml and restart OpenKnowledge.`;
+ : `${rejectedHost} is not a declared GitHub host. If it runs GitHub Enterprise Server, declare git.hosts.${rejectedHost}.provider as github in ${okUserHomeDisplayPath('global.yml')} and restart OpenKnowledge.`;
errorResponse(
res,
409,
diff --git a/packages/server/src/in-place-skills.ts b/packages/server/src/in-place-skills.ts
index a78bf9991..570cb0343 100644
--- a/packages/server/src/in-place-skills.ts
+++ b/packages/server/src/in-place-skills.ts
@@ -8,7 +8,9 @@ import {
estimateSkillCost,
HUB_READER_EDITORS,
LEGACY_SKILL_STORE_ROOT,
+ OK_DIR,
parseFrontmatterRecord,
+ SKILLS_STORE_DIRNAME,
type SkillCostTiers,
type SkillScope,
skillRootActivationPath,
@@ -97,7 +99,7 @@ function hostSkillRootsFor(
export function globalSkillGraphRoots(home: string): string[] {
const roots = knownSkillRootsFor(home, 'global').map((r) => join(home, r.root));
- const legacyStore = join(home, '.ok', 'skills');
+ const legacyStore = join(home, OK_DIR, SKILLS_STORE_DIRNAME);
return roots.includes(legacyStore) ? roots : [...roots, legacyStore];
}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 9b233277b..f93aa971f 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -605,7 +605,7 @@ export {
} from './skill-install.ts';
export {
recordSkillInstallEvent,
- SKILL_INSTALL_EVENTS_FILE_REL,
+ SKILL_INSTALL_EVENTS_FILENAME,
type SkillInstallEvent,
type SkillInstallEventOutcome,
type SkillInstallEventSurface,
diff --git a/packages/server/src/machine-id.test.ts b/packages/server/src/machine-id.test.ts
index 5fe9d0739..36aa23986 100644
Binary files a/packages/server/src/machine-id.test.ts and b/packages/server/src/machine-id.test.ts differ
diff --git a/packages/server/src/machine-id.ts b/packages/server/src/machine-id.ts
index 41a672bf7..3dc11d7d1 100644
--- a/packages/server/src/machine-id.ts
+++ b/packages/server/src/machine-id.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
+import { MACHINE_ID_FILENAME, OK_DIR } from '@inkeep/open-knowledge-core';
import { getLogger } from './logger.ts';
const MACHINE_ID_RE = /^[A-Za-z0-9-]{8,64}$/;
@@ -9,7 +10,7 @@ const MACHINE_ID_RE = /^[A-Za-z0-9-]{8,64}$/;
let cachedMachineId: string | null = null;
export function machineIdFilePath(homedirOverride?: string): string {
- return join(homedirOverride ?? homedir(), '.ok', 'machine-id');
+ return join(homedirOverride ?? homedir(), OK_DIR, MACHINE_ID_FILENAME);
}
export function getMachineId(homedirOverride?: string): string {
diff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.ts
index d83313c2a..cf98821e4 100644
--- a/packages/server/src/managed-artifact-persistence.ts
+++ b/packages/server/src/managed-artifact-persistence.ts
@@ -21,6 +21,7 @@ import {
import {
atomicWriteFile,
FileLockTimeoutError,
+ okUserHomeDir,
withFileLock,
} from '@inkeep/open-knowledge-core/server';
import type * as Y from 'yjs';
@@ -260,7 +261,7 @@ async function stashDiscardedEdit(
): Promise<void> {
try {
const safe = documentName.replace(/[^A-Za-z0-9._-]+/g, '__');
- const dir = resolve(homeFor(ctx), '.ok', 'edit-backups', 'discarded', safe);
+ const dir = resolve(okUserHomeDir(homeFor(ctx)), 'edit-backups', 'discarded', safe);
await tracedMkdir(dir, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
await atomicWriteFile(resolve(dir, `${stamp}.md`), content, { fs: tracedAtomicFs });
@@ -283,7 +284,7 @@ async function backupExternalSkillOnce(
if (ext.rel !== null) return;
try {
if (!existsSync(filePath)) return;
- const backupDir = resolve(homeFor(ctx), '.ok', 'edit-backups', ext.name);
+ const backupDir = resolve(okUserHomeDir(homeFor(ctx)), 'edit-backups', ext.name);
const backupPath = resolve(backupDir, 'SKILL.md.bak');
if (existsSync(backupPath)) return;
await tracedMkdir(backupDir, { recursive: true });
diff --git a/packages/server/src/saved-themes-store.test.ts b/packages/server/src/saved-themes-store.test.ts
index ea2cee9eb..8fdc0076f 100644
--- a/packages/server/src/saved-themes-store.test.ts
+++ b/packages/server/src/saved-themes-store.test.ts
@@ -10,7 +10,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { BASE16_SLOTS } from '@inkeep/open-knowledge-core';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
SAVED_THEME_FILE_BYTE_LIMIT,
SAVED_THEME_SCAN_CAP,
@@ -54,6 +54,15 @@ describe('savedThemesDir', () => {
test('resolves the store under <home>/.ok/themes', () => {
expect(savedThemesDir(home)).toBe(join(home, '.ok', 'themes'));
});
+
+ test('resolves Beta themes under <home>/.ok-beta/themes', () => {
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ try {
+ expect(savedThemesDir(home)).toBe(join(home, '.ok-beta', 'themes'));
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
});
describe('scanSavedThemes', () => {
diff --git a/packages/server/src/saved-themes-store.ts b/packages/server/src/saved-themes-store.ts
index a901f521d..99a87d3eb 100644
--- a/packages/server/src/saved-themes-store.ts
+++ b/packages/server/src/saved-themes-store.ts
@@ -14,11 +14,11 @@ import {
type Base16ParseError,
type Base16Scheme,
deriveSavedThemeId,
- OK_DIR,
parseBase16Scheme,
SAVED_THEMES_DIRNAME,
type SavedThemeIdError,
} from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { errnoCode } from './http/handler-utils.ts';
import { getLogger } from './logger.ts';
import {
@@ -78,7 +78,7 @@ export interface ScanSavedThemesOptions {
}
export function savedThemesDir(homedirOverride?: string): string {
- return resolve(homedirOverride ?? homedir(), OK_DIR, SAVED_THEMES_DIRNAME);
+ return resolve(okUserHomeDir(homedirOverride ?? homedir()), SAVED_THEMES_DIRNAME);
}
export function scanSavedThemes(options: ScanSavedThemesOptions = {}): SavedThemeScanResult {
diff --git a/packages/server/src/saved-themes-write.ts b/packages/server/src/saved-themes-write.ts
index 3a86a888f..d45904706 100644
--- a/packages/server/src/saved-themes-write.ts
+++ b/packages/server/src/saved-themes-write.ts
@@ -7,13 +7,13 @@ import {
base16ToYaml,
deriveSavedThemeId,
deriveSavedThemeName,
- OK_DIR,
parseSavedThemeId,
type SavedThemeIdError,
} from '@inkeep/open-knowledge-core';
import {
atomicWriteFile,
FileLockTimeoutError,
+ okUserHomeDir,
withFileLock,
} from '@inkeep/open-knowledge-core/server';
import { tracedAtomicFs, tracedMkdir, tracedUnlinkSync } from './fs-traced.ts';
@@ -41,7 +41,7 @@ async function withSavedThemeWriteLock<T>(
fn: () => Promise<T>,
timeoutMs?: number,
): Promise<T | SavedThemeLockTimeoutResult> {
- const lockDir = resolve(home, OK_DIR);
+ const lockDir = resolve(okUserHomeDir(home));
await tracedMkdir(lockDir, { recursive: true });
const rootKey = createHash('sha256').update(resolve(root)).digest('hex').slice(0, 24);
try {
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index a84ba3013..662a92a48 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -277,6 +277,7 @@ import {
shouldResetAmbientCredentials,
} from './share/git-context.ts';
import { resyncRecordedSkillCopies } from './skill-placements.ts';
+import { skillStateYamlPath } from './skill-state.ts';
import { assertCompatibleStateManifest } from './state-manifest.ts';
import { SyncEngine } from './sync-engine.ts';
import { createSyncHandshakeSpanExtension } from './sync-handshake-span-extension.ts';
@@ -3771,11 +3772,7 @@ export function createServer(options: ServerOptions): ServerInstance {
}
try {
- const skillStatePath = resolve(
- homeFor(persistence.managedArtifactCtx),
- '.ok',
- 'skill-state.yml',
- );
+ const skillStatePath = skillStateYamlPath(homeFor(persistence.managedArtifactCtx));
const skillStateCleanup = await startConfigFileWatcher(skillStatePath, () => {
signalChannel('files');
});
diff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.ts
index 1cfe2107e..f36653d6b 100644
--- a/packages/server/src/services/skill-install-ops.ts
+++ b/packages/server/src/services/skill-install-ops.ts
@@ -9,6 +9,7 @@ import {
SKILL_NAME_REGEX,
type SkillInstallWarningCode,
} from '@inkeep/open-knowledge-core';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import { parseSkillDir, type SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';
import { applySkillDirNameSync } from '../content/skills-write.ts';
import {
@@ -169,8 +170,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
const stash = (dirAbs: string, label: string): void => {
try {
const dest = resolve(
- deps.skillsHome,
- '.ok',
+ okUserHomeDir(deps.skillsHome),
'edit-backups',
'forks',
`${name}-${label}-${stamp}`,
diff --git a/packages/server/src/skill-install-events.test.ts b/packages/server/src/skill-install-events.test.ts
index 45a29fb63..df6b6d52a 100644
--- a/packages/server/src/skill-install-events.test.ts
+++ b/packages/server/src/skill-install-events.test.ts
@@ -5,7 +5,7 @@ import { join } from 'node:path';
import { describe, expect, test, vi } from 'vitest';
import {
recordSkillInstallEvent,
- SKILL_INSTALL_EVENTS_FILE_REL,
+ SKILL_INSTALL_EVENTS_FILENAME,
type SkillInstallEvent,
} from './skill-install-events.ts';
@@ -14,7 +14,7 @@ function freshHome(): string {
}
function eventsFilePath(home: string): string {
- return join(home, ...SKILL_INSTALL_EVENTS_FILE_REL);
+ return join(home, '.ok', SKILL_INSTALL_EVENTS_FILENAME);
}
function makeEvent(overrides: Partial<SkillInstallEvent> = {}): SkillInstallEvent {
diff --git a/packages/server/src/skill-install-events.ts b/packages/server/src/skill-install-events.ts
index fd414def7..3f2c194da 100644
--- a/packages/server/src/skill-install-events.ts
+++ b/packages/server/src/skill-install-events.ts
@@ -1,10 +1,11 @@
import { dirname, join } from 'node:path';
+import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';
import type { BundleId } from './build-skill-zip.ts';
import { tracedMkdir, tracedWriteFile } from './fs-traced.ts';
import { getLogger } from './logger.ts';
import type { SkillStateLogger, SkillStateTarget } from './skill-state.ts';
-export const SKILL_INSTALL_EVENTS_FILE_REL = ['.ok', 'skill-install-events.jsonl'] as const;
+export const SKILL_INSTALL_EVENTS_FILENAME = 'skill-install-events.jsonl';
export type SkillInstallEventSurface =
| 'server-build-and-open'
@@ -49,7 +50,7 @@ export async function recordSkillInstallEvent(
);
return;
}
- const file = join(home, ...SKILL_INSTALL_EVENTS_FILE_REL);
+ const file = join(okUserHomeDir(home), SKILL_INSTALL_EVENTS_FILENAME);
const json = `${JSON.stringify(event)}\n`;
try {
diff --git a/packages/server/src/skill-move-retained-store.ts b/packages/server/src/skill-move-retained-store.ts
index c161b7a4c..0cf1240cf 100644
--- a/packages/server/src/skill-move-retained-store.ts
+++ b/packages/server/src/skill-move-retained-store.ts
@@ -1,13 +1,16 @@
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
-import { isSkillSourceStateCode, type SkillSourceStateCode } from '@inkeep/open-knowledge-core';
+import {
+ isSkillSourceStateCode,
+ SKILL_MOVE_RETAINED_FILENAME,
+ type SkillSourceStateCode,
+} from '@inkeep/open-knowledge-core';
import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
import { getLocalDir } from './config/paths.ts';
import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
import { createKeyedSerializer } from './keyed-serializer.ts';
import { getLogger } from './logger.ts';
-const RETAINED_FILENAME = 'skill-move-retained.json';
const SCHEMA_VERSION = 1;
export type SkillMoveScope = 'project' | 'global';
@@ -36,7 +39,7 @@ function retainedKey(scope: SkillMoveScope, name: string): string {
}
function retainedPath(base: string): string {
- return join(getLocalDir(base), RETAINED_FILENAME);
+ return join(getLocalDir(base), SKILL_MOVE_RETAINED_FILENAME);
}
function isRecord(value: unknown): value is Record<string, unknown> {
diff --git a/packages/server/src/skill-placements-store.ts b/packages/server/src/skill-placements-store.ts
index e5a8074c3..93cde5370 100644
--- a/packages/server/src/skill-placements-store.ts
+++ b/packages/server/src/skill-placements-store.ts
@@ -1,11 +1,12 @@
import { existsSync, readFileSync, realpathSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
+import { LOCAL_DIR, OK_DIR, SKILL_PLACEMENTS_FILENAME } from '@inkeep/open-knowledge-core';
import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
import { createKeyedSerializer } from './keyed-serializer.ts';
import { getLogger } from './logger.ts';
-const PLACEMENTS_REL = ['.ok', 'local', 'skill-placements.json'] as const;
+const PLACEMENTS_REL = [OK_DIR, LOCAL_DIR, SKILL_PLACEMENTS_FILENAME] as const;
const SCHEMA_VERSION = 1;
export interface SkillPlacement {
diff --git a/packages/server/src/skill-state.test.ts b/packages/server/src/skill-state.test.ts
index ef71dee40..02d77c98b 100644
--- a/packages/server/src/skill-state.test.ts
+++ b/packages/server/src/skill-state.test.ts
@@ -3,7 +3,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
clearInstallReported,
readAllTargets,
@@ -299,3 +299,23 @@ describe('clearInstallReported', () => {
expect([...(await readInstallReported(home))]).toEqual(['o/r#a']);
});
});
+
+describe('skill-state file per channel', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ test('Stable keeps ~/.ok/skill-state.yml and Beta writes ~/.ok-beta/skill-state.yml', async () => {
+ const home = freshHome();
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ expect(skillStateYamlPath(home)).toBe(join(home, '.ok', 'skill-state.yml'));
+ vi.stubEnv('OK_CHANNEL', 'beta');
+ expect(skillStateYamlPath(home)).toBe(join(home, '.ok-beta', 'skill-state.yml'));
+ await writeBundleDecision(home, 'discovery', true);
+ expect(await readFile(join(home, '.ok-beta', 'skill-state.yml'), 'utf8')).toContain(
+ 'discovery',
+ );
+ vi.stubEnv('OK_CHANNEL', 'stable');
+ expect(await readBundleDecision(home, 'discovery')).toBeNull();
+ });
+});
diff --git a/packages/server/src/skill-state.ts b/packages/server/src/skill-state.ts
index 5cec1cba4..e77214919 100644
--- a/packages/server/src/skill-state.ts
+++ b/packages/server/src/skill-state.ts
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import {
emptySkillState,
- SKILL_STATE_REL,
+ SKILL_STATE_FILENAME,
SKILL_STATE_TARGETS,
SKILL_STATE_VERSION_RE,
type SkillState,
@@ -12,7 +12,7 @@ import {
type SkillStateSurface,
type SkillStateTarget,
} from '@inkeep/open-knowledge-core';
-import { atomicWriteFile, withFileLock } from '@inkeep/open-knowledge-core/server';
+import { atomicWriteFile, okUserHomeDir, withFileLock } from '@inkeep/open-knowledge-core/server';
import { type ParsedNode, parseDocument } from 'yaml';
import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
import { getLogger } from './logger.ts';
@@ -27,7 +27,7 @@ export {
} from '@inkeep/open-knowledge-core';
export function skillStateYamlPath(home: string): string {
- return join(home, ...SKILL_STATE_REL);
+ return join(okUserHomeDir(home), SKILL_STATE_FILENAME);
}
async function withSkillStateWriteLock<T>(home: string, fn: () => Promise<T>): Promise<T> {