Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): add `ok uninstall` and `ok deinit` removal verbs (#2388)

mike-inkeep4100c78ceb13
diff --git a/.changeset/ok-uninstall-deinit.md b/.changeset/ok-uninstall-deinit.md
new file mode 100644
index 000000000..2663079a4
--- /dev/null
+++ b/.changeset/ok-uninstall-deinit.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Add `ok uninstall` and `ok deinit` — one command each to reverse OpenKnowledge's footprint.
+
+`ok uninstall` removes OpenKnowledge from your whole machine: it stops running servers, clears credentials (the GitHub keychain token, `auth.yml`, and the embeddings key), reverts the PATH shim (strips the managed block from your shell rc files and removes the recorded `~/.ok/bin` symlinks), surgically removes only OpenKnowledge's own entry from each editor's MCP config (keeping your other servers, comments, and formatting), tears down the installed skill bundles, deletes the app-data directories, and finally removes `~/.ok`. It offers to also clean recent projects, and detects how the app was installed to print the exact removal command — it never deletes its own binary. Your markdown content and your authored skills (`~/.ok/skills`) are kept unless you pass `--purge-content`.
+
+`ok deinit` removes OpenKnowledge from a single project — its `.ok/`, editor MCP entries, `.claude/launch.json` entry, `.git/info/exclude` lines, and shadow repo — while leaving your markdown untouched, so re-running `ok start` re-scaffolds cleanly.
+
+Both commands are safe by default: a `--dry-run` preview, a confirmation that defaults to **No**, `--json` output, and surgical edits that never clobber your non-OpenKnowledge config.
diff --git a/packages/cli/src/auth/token-store.ts b/packages/cli/src/auth/token-store.ts
index bb8ebc2b0..acb38dc35 100644
--- a/packages/cli/src/auth/token-store.ts
+++ b/packages/cli/src/auth/token-store.ts
@@ -275,7 +275,7 @@ export function makeLazyTokenStore(authFile?: string): TokenStore {
export async function clearTokenFromAllBackends(
host: string,
authFile?: string,
-): Promise<{ touched: Array<'keychain' | 'file'> }> {
+): Promise<{ touched: Array<'keychain' | 'file'>; keychainError?: string }> {
const touched: Array<'keychain' | 'file'> = [];
const file = new FileBackend(authFile);
@@ -284,15 +284,26 @@ export async function clearTokenFromAllBackends(
touched.push('file');
}
+ let keychainError: string | undefined;
try {
const { Entry } = await import('@napi-rs/keyring');
new Entry(KEYRING_SERVICE, '__probe__');
- const keyring = new KeyringBackend();
- if ((await keyring.get(host)) != null) {
- await keyring.clear(host);
- touched.push('keychain');
+ let readError: string | undefined;
+ const keyring = new KeyringBackend((info) => {
+ if (info.kind === 'read-error') readError = info.error ?? 'read-error';
+ });
+ const existing = await keyring.get(host);
+ if (readError !== undefined) {
+ keychainError = readError;
+ } else if (existing != null) {
+ try {
+ new Entry(KEYRING_SERVICE, host).deletePassword();
+ touched.push('keychain');
+ } catch (e) {
+ keychainError = e instanceof Error ? e.name : 'delete-error';
+ }
}
} catch {}
- return { touched };
+ return { touched, keychainError };
}
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 126b4b71b..e30fe3af2 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -10,7 +10,7 @@ if (process.argv.includes('--no-color')) {
import { spawn } from 'node:child_process';
import { resolve } from 'node:path';
-import type { Config } from '@inkeep/open-knowledge-server';
+import { type Config, ConfigSchema } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { authCommand } from './commands/auth/index.ts';
import { bugReportCommand } from './commands/bug-report.ts';
@@ -18,6 +18,7 @@ import { cleanCommand } from './commands/clean.ts';
import { cloneCommand } from './commands/clone.ts';
import { configCommand } from './commands/config.ts';
import { coworkCommand } from './commands/cowork.ts';
+import { deinitCommand } from './commands/deinit.ts';
import { createRealDetectDeps, detectDesktop, launchDesktop } from './commands/desktop-dispatch.ts';
import { diagnoseCommand } from './commands/diagnose.ts';
import { embeddingsCommand } from './commands/embeddings/index.ts';
@@ -45,6 +46,7 @@ import { statusCommand } from './commands/status.ts';
import { stopCommand } from './commands/stop.ts';
import { syncCommand } from './commands/sync.ts';
import { uiCommand } from './commands/ui.ts';
+import { uninstallCommand } from './commands/uninstall.ts';
import { PACKAGE_VERSION } from './constants.ts';
import { loadConfig } from './index.ts';
import { recordInvocationCwd, resolveProjectAnchor } from './project-anchor.ts';
@@ -97,7 +99,19 @@ program
console.error(`[ok] Using OpenKnowledge project at ${anchorRoot}`);
}
- const { config } = loadConfig(anchorRoot ?? cwd);
+ let config: Config;
+ try {
+ config = loadConfig(anchorRoot ?? cwd).config;
+ } catch (err) {
+ if (subcommandName === 'uninstall' || subcommandName === 'deinit') {
+ console.error(
+ `[ok] project config could not be loaded; ${subcommandName} will use defaults: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ config = ConfigSchema.parse({});
+ } else {
+ throw err;
+ }
+ }
resolvedConfig = config;
const commandName = thisCommand.args?.[0] ?? thisCommand.name() ?? 'cli';
@@ -149,6 +163,9 @@ program.addCommand(stopCommand(() => resolvedConfig));
program.addCommand(cleanCommand(() => resolvedConfig));
program.addCommand(statusCommand(() => resolvedConfig));
+program.addCommand(deinitCommand());
+program.addCommand(uninstallCommand());
+
program.addCommand(psCommand());
program.addCommand(diagnoseCommand());
diff --git a/packages/cli/src/commands/deinit.test.ts b/packages/cli/src/commands/deinit.test.ts
new file mode 100644
index 000000000..7ff1babfe
--- /dev/null
+++ b/packages/cli/src/commands/deinit.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { Readable } from 'node:stream';
+import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import { runDeinit } from './deinit.ts';
+import { buildManagedServerEntry } from './editors.ts';
+
+const OWN_ENTRY = buildManagedServerEntry({ mode: 'published' });
+
+function write(path: string, content: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+}
+
+function seedProject(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-deinit-'));
+ write(join(dir, '.ok', 'config.yml'), 'content:\n dir: .\n');
+ write(join(dir, '.ok', 'local', 'server.lock'), '{}');
+ write(join(dir, '.okignore'), 'secret.md\n');
+ write(
+ join(dir, '.mcp.json'),
+ `${JSON.stringify({ mcpServers: { mine: { command: 'x' }, [MCP_SERVER_NAME]: OWN_ENTRY } }, null, 2)}\n`,
+ );
+ write(join(dir, '.claude', 'skills', 'open-knowledge', 'SKILL.md'), '# ok\n');
+ write(join(dir, 'notes.md'), '# my notes\n');
+ return dir;
+}
+
+describe('runDeinit', () => {
+ test('no-op with a clear message when the dir is not an OK project', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-deinit-'));
+ try {
+ const result = await runDeinit({ cwd: dir, home: dir, yes: true });
+ expect(result.status).toBe('no-op');
+ expect(result.exitCode).toBe(0);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('dry-run shows the plan and removes nothing', async () => {
+ const dir = seedProject();
+ try {
+ const result = await runDeinit({ cwd: dir, home: dir, dryRun: true });
+ expect(result.status).toBe('dry-run');
+ expect(result.message).toContain('Remove');
+ expect(existsSync(join(dir, '.ok'))).toBe(true); // untouched
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('empty prompt input (bare Enter) aborts — defaults to No', async () => {
+ const dir = seedProject();
+ try {
+ const result = await runDeinit({
+ cwd: dir,
+ home: dir,
+ confirmStream: Readable.from(['\n']),
+ });
+ expect(result.status).toBe('cancelled');
+ expect(existsSync(join(dir, '.ok'))).toBe(true); // nothing removed
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('removes the project footprint while leaving markdown content untouched', async () => {
+ const dir = seedProject();
+ try {
+ const result = await runDeinit({ cwd: dir, home: dir, yes: true });
+ expect(result.status).toBe('done');
+ expect(result.exitCode).toBe(0);
+ expect(existsSync(join(dir, '.ok'))).toBe(false);
+ expect(existsSync(join(dir, '.okignore'))).toBe(false);
+ expect(existsSync(join(dir, '.claude', 'skills', 'open-knowledge'))).toBe(false);
+ const mcp = JSON.parse(readFileSync(join(dir, '.mcp.json'), 'utf-8'));
+ expect(mcp.mcpServers[MCP_SERVER_NAME]).toBeUndefined();
+ expect(mcp.mcpServers.mine).toEqual({ command: 'x' });
+ expect(readFileSync(join(dir, 'notes.md'), 'utf-8')).toBe('# my notes\n');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('--json without --yes is rejected (no interactive prompt possible)', async () => {
+ const dir = seedProject();
+ try {
+ const result = await runDeinit({ cwd: dir, home: dir, json: true });
+ expect(result.status).toBe('failed');
+ expect(result.exitCode).toBe(1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('reports failed + exit 1 when an op fails (a server won’t stop)', async () => {
+ const dir = seedProject();
+ try {
+ const result = await runDeinit({
+ cwd: dir,
+ home: dir,
+ yes: true,
+ runRemovalDeps: {
+ stopServer: () => ({ stopped: 0, failed: [{ pid: 77, error: 'EPERM' }] }),
+ },
+ });
+ expect(result.status).toBe('failed');
+ expect(result.exitCode).toBe(1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/deinit.ts b/packages/cli/src/commands/deinit.ts
new file mode 100644
index 000000000..4b6c06549
--- /dev/null
+++ b/packages/cli/src/commands/deinit.ts
@@ -0,0 +1,112 @@
+import { existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { Command } from 'commander';
+import { accent, dim, error as errorColor } from '../ui/colors.ts';
+import { confirmDestructive } from '../ui/confirm.ts';
+import { buildDeinitPlan, type RunRemovalDeps, runRemoval } from './removal-plan.ts';
+import {
+ formatRemovalOutcome,
+ formatRemovalPlan,
+ removalOutcomeToJson,
+ removalPlanToJson,
+} from './removal-render.ts';
+
+export interface DeinitOptions {
+ cwd?: string;
+ home?: string;
+ yes?: boolean;
+ dryRun?: boolean;
+ json?: boolean;
+ confirmStream?: NodeJS.ReadableStream;
+ /** Test-only: stub the machine-touching removal primitives (stop-server, etc.)
+ * so the failed-exit branch is exercisable without real side effects. */
+ runRemovalDeps?: RunRemovalDeps;
+}
+
+export interface DeinitResult {
+ status: 'no-op' | 'dry-run' | 'cancelled' | 'done' | 'failed';
+ message: string;
+ exitCode: number;
+}
+
+export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult> {
+ const projectRoot = resolve(opts.cwd ?? process.cwd());
+ const home = opts.home ?? homedir();
+
+ if (!existsSync(join(projectRoot, '.ok'))) {
+ return {
+ status: 'no-op',
+ message: dim(`No OpenKnowledge project found at ${projectRoot}. Nothing to remove.`),
+ exitCode: 0,
+ };
+ }
+
+ const plan = buildDeinitPlan(projectRoot, home);
+
+ if (opts.dryRun) {
+ return {
+ status: 'dry-run',
+ message: opts.json
+ ? JSON.stringify(removalPlanToJson(plan), null, 2)
+ : `${accent('Would remove (dry-run — no changes made):')}\n\n${formatRemovalPlan(plan)}`,
+ exitCode: 0,
+ };
+ }
+
+ if (opts.json && !opts.yes) {
+ return {
+ status: 'failed',
+ message: `${errorColor('Error:')} --json requires --yes (or --dry-run) so there is no interactive prompt.`,
+ exitCode: 1,
+ };
+ }
+
+ if (!opts.yes) {
+ process.stderr.write(
+ `${accent(`Remove OpenKnowledge from ${projectRoot}:`)}\n\n${formatRemovalPlan(plan)}\n\n`,
+ );
+ const confirmed = await confirmDestructive(
+ `${accent('Remove these?')} ${dim('[y/N] ')}`,
+ opts.confirmStream,
+ );
+ if (!confirmed) {
+ return { status: 'cancelled', message: dim('Cancelled.'), exitCode: 0 };
+ }
+ }
+
+ const outcome = await runRemoval(plan, opts.runRemovalDeps);
+ return {
+ status: outcome.failed.length > 0 ? 'failed' : 'done',
+ message: opts.json
+ ? JSON.stringify(removalOutcomeToJson('deinit', outcome), null, 2)
+ : formatRemovalOutcome(outcome),
+ exitCode: outcome.failed.length > 0 ? 1 : 0,
+ };
+}
+
+export function deinitCommand(): Command {
+ return new Command('deinit')
+ .description(
+ 'Remove OpenKnowledge from this project (its .ok/, editor MCP entries, git-exclude lines, shadow repo) while leaving your markdown content untouched. Re-run `ok start` to re-scaffold.',
+ )
+ .argument('[path]', 'Project directory (defaults to the current project)')
+ .option('-y, --yes', 'Skip the confirmation prompt')
+ .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)')
+ .action(
+ async (
+ pathArg: string | undefined,
+ options: { yes?: boolean; dryRun?: boolean; json?: boolean },
+ ) => {
+ const result = await runDeinit({
+ cwd: pathArg ?? process.cwd(),
+ yes: options.yes,
+ dryRun: options.dryRun,
+ json: options.json,
+ });
+ process.stdout.write(`${result.message}\n`);
+ if (result.exitCode !== 0) process.exitCode = result.exitCode;
+ },
+ );
+}
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index 157d0838b..bcf44ac69 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -213,7 +213,7 @@ function matchesCanonicalExactly(
return e.args.every((v, i) => v === canonicalArgs[i]);
}
-interface AppSupportOptions {
+export interface AppSupportOptions {
home?: string;
platformName?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 875263dce..c72f08ec4 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -70,6 +70,7 @@ import {
resolveDevCliDistPath,
resolveEditorTargets,
} from './editors.ts';
+import { existingFileMode, isCrlfDominant } from './jsonc-surgical.ts';
import { LAUNCH_JSON_PORT } from './ui.ts';
const JSONC_PARSE_OPTIONS = { allowTrailingComma: true, disallowComments: false };
@@ -108,13 +109,6 @@ function writeTomlConfig(path: string, config: Record<string, unknown>): void {
atomicWriteFileSync(path, serialized.endsWith('\n') ? serialized : `${serialized}\n`);
}
-function isCrlfDominant(text: string): boolean {
- const crlf = (text.match(/\r\n/g) ?? []).length;
- if (crlf === 0) return false;
- const bareLf = (text.match(/\n/g) ?? []).length - crlf;
- return crlf >= bareLf;
-}
-
const JSON_CONFIG_MAX_BYTES = 10 * 1024 * 1024;
function jsonValueEqual(a: unknown, b: unknown): boolean {
@@ -141,19 +135,11 @@ function detectJsonIndent(body: string): { insertSpaces: boolean; tabSize: numbe
return { insertSpaces: true, tabSize: 2 };
}
-function existingFileMode(path: string): number | undefined {
- try {
- return statSync(path).mode & 0o777;
- } catch {
- return undefined;
- }
-}
-
type JsonUpsertOutcome =
| { kind: 'written' | 'overwritten' }
| { kind: 'declined'; reason: McpDeclineReason };
-function serverMapPath(
+export function serverMapPath(
topLevelKey: string,
subKey: string | undefined,
serverName: string,
diff --git a/packages/cli/src/commands/jsonc-surgical.ts b/packages/cli/src/commands/jsonc-surgical.ts
new file mode 100644
index 000000000..f87cff313
--- /dev/null
+++ b/packages/cli/src/commands/jsonc-surgical.ts
@@ -0,0 +1,42 @@
+import { statSync } from 'node:fs';
+import { applyEdits as applyJsoncEdits, modify as modifyJsonc } from 'jsonc-parser';
+
+function detectJsonIndent(body: string): { insertSpaces: boolean; tabSize: number } {
+ for (const line of body.split('\n')) {
+ const trimmed = line.trimStart();
+ if (trimmed.length === 0 || trimmed.length === line.length) continue;
+ if (line.charCodeAt(0) === 0x09) return { insertSpaces: false, tabSize: 1 };
+ return { insertSpaces: true, tabSize: line.length - trimmed.length };
+ }
+ return { insertSpaces: true, tabSize: 2 };
+}
+
+export function isCrlfDominant(text: string): boolean {
+ const crlf = (text.match(/\r\n/g) ?? []).length;
+ if (crlf === 0) return false;
+ const bareLf = (text.match(/\n/g) ?? []).length - crlf;
+ return crlf >= bareLf;
+}
+
+export function existingFileMode(path: string): number | undefined {
+ try {
+ return statSync(path).mode & 0o777;
+ } catch {
+ return undefined;
+ }
+}
+
+export function surgicalJsonDelete(
+ raw: string,
+ path: (string | number)[],
+): { text: string; changed: boolean } {
+ const hasBom = raw.charCodeAt(0) === 0xfeff;
+ const body = hasBom ? raw.slice(1) : raw;
+ const eol = body.includes('\r\n') ? '\r\n' : '\n';
+ const edits = modifyJsonc(body, path, undefined, {
+ formattingOptions: { ...detectJsonIndent(body), eol },
+ });
+ if (edits.length === 0) return { text: raw, changed: false };
+ const text = `${hasBom ? '\uFEFF' : ''}${applyJsoncEdits(body, edits)}`;
+ return { text, changed: text !== raw };
+}
diff --git a/packages/cli/src/commands/launch-json-removal.test.ts b/packages/cli/src/commands/launch-json-removal.test.ts
new file mode 100644
index 000000000..69a247662
--- /dev/null
+++ b/packages/cli/src/commands/launch-json-removal.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LAUNCH_CONFIG_NAME } from './init.ts';
+import { removeOwnLaunchEntry } from './launch-json-removal.ts';
+
+function project(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-launch-'));
+ mkdirSync(join(dir, '.claude'), { recursive: true });
+ return dir;
+}
+
+function writeLaunch(projectRoot: string, value: unknown): string {
+ const p = join(projectRoot, '.claude', 'launch.json');
+ writeFileSync(p, JSON.stringify(value, null, 2));
+ return p;
+}
+
+describe('removeOwnLaunchEntry', () => {
+ test('surgically removes OK’s entry, preserving a user’s other configuration', () => {
+ const dir = project();
+ try {
+ const p = writeLaunch(dir, {
+ version: '0.2.0',
+ configurations: [
+ { name: 'My App', type: 'node', request: 'launch' },
+ {
+ name: LAUNCH_CONFIG_NAME,
+ runtimeExecutable: '/bin/sh',
+ runtimeArgs: ['-l', '-c', 'x'],
+ },
+ ],
+ });
+ const outcome = removeOwnLaunchEntry(dir);
+ expect(outcome.kind).toBe('removed');
+ const after = JSON.parse(readFileSync(p, 'utf-8'));
+ expect(after.configurations).toHaveLength(1);
+ expect(after.configurations[0].name).toBe('My App');
+ expect(after.version).toBe('0.2.0');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('deletes the whole file when OK’s entry was the only configuration', () => {
+ const dir = project();
+ try {
+ const p = writeLaunch(dir, {
+ version: '0.2.0',
+ configurations: [
+ {
+ name: LAUNCH_CONFIG_NAME,
+ runtimeExecutable: '/bin/sh',
+ runtimeArgs: ['-l', '-c', 'x'],
+ },
+ ],
+ });
+ const outcome = removeOwnLaunchEntry(dir);
+ expect(outcome.kind).toBe('removed-file');
+ expect(existsSync(p)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('not-present when there is no file, no configurations, or no OK entry', () => {
+ const dir = project();
+ try {
+ expect(removeOwnLaunchEntry(dir).kind).toBe('not-present'); // no file
+ writeLaunch(dir, { configurations: [{ name: 'Only Mine', type: 'node' }] });
+ expect(removeOwnLaunchEntry(dir).kind).toBe('not-present'); // no OK entry
+ writeLaunch(dir, { version: '0.2.0' });
+ expect(removeOwnLaunchEntry(dir).kind).toBe('not-present'); // no configurations array
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('preserves a leading BOM while surgically removing OK’s entry', () => {
+ const dir = project();
+ try {
+ const p = join(dir, '.claude', 'launch.json');
+ const body = JSON.stringify(
+ {
+ version: '0.2.0',
+ configurations: [
+ { name: 'My App', type: 'node' },
+ {
+ name: LAUNCH_CONFIG_NAME,
+ runtimeExecutable: '/bin/sh',
+ runtimeArgs: ['-l', '-c', 'x'],
+ },
+ ],
+ },
+ null,
+ 2,
+ );
+ writeFileSync(p, `\uFEFF${body}`);
+ expect(removeOwnLaunchEntry(dir).kind).toBe('removed');
+ const after = readFileSync(p, 'utf-8');
+ expect(after.charCodeAt(0)).toBe(0xfeff); // BOM preserved
+ const parsed = JSON.parse(after.slice(1));
+ expect(parsed.configurations).toHaveLength(1);
+ expect(parsed.configurations[0].name).toBe('My App');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('declines a malformed launch.json, leaving it byte-identical', () => {
+ const dir = project();
+ try {
+ const p = join(dir, '.claude', 'launch.json');
+ const raw = '{ not valid json ]';
+ writeFileSync(p, raw);
+ expect(removeOwnLaunchEntry(dir).kind).toBe('declined');
+ expect(readFileSync(p, 'utf-8')).toBe(raw);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/launch-json-removal.ts b/packages/cli/src/commands/launch-json-removal.ts
new file mode 100644
index 000000000..96cfc3e80
--- /dev/null
+++ b/packages/cli/src/commands/launch-json-removal.ts
@@ -0,0 +1,63 @@
+import { existsSync, readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import {
+ getNodeValue,
+ type Node as JsoncNode,
+ type ParseError as JsoncParseError,
+ parseTree,
+} from 'jsonc-parser';
+import { isObject } from '../utils/is-object.ts';
+import { LAUNCH_CONFIG_NAME } from './init.ts';
+import { existingFileMode, surgicalJsonDelete } from './jsonc-surgical.ts';
+
+export type LaunchRemoveOutcome =
+ | { kind: 'removed' }
+ | { kind: 'removed-file' }
+ | { kind: 'not-present' }
+ | { kind: 'declined' };
+
+const JSONC_PARSE_OPTIONS = { allowTrailingComma: true, disallowComments: false };
+
+const JSONC_INVALID_SYMBOL_CODE = 1;
+function isBenignBomError(error: JsoncParseError, raw: string): boolean {
+ return (
+ error.error === JSONC_INVALID_SYMBOL_CODE && error.offset === 0 && raw.charCodeAt(0) === 0xfeff
+ );
+}
+
+export function removeOwnLaunchEntry(projectRoot: string): LaunchRemoveOutcome {
+ const configPath = join(projectRoot, '.claude', 'launch.json');
+ if (!existsSync(configPath)) return { kind: 'not-present' };
+
+ let raw: string;
+ try {
+ raw = readFileSync(configPath, 'utf-8');
+ } catch {
+ return { kind: 'declined' };
+ }
+
+ const errors: JsoncParseError[] = [];
+ const tree: JsoncNode | undefined = parseTree(raw, errors, JSONC_PARSE_OPTIONS) ?? undefined;
+ if (errors.some((e) => !isBenignBomError(e, raw))) return { kind: 'declined' };
+ if (!tree || tree.type !== 'object') return { kind: 'declined' };
+
+ const root = getNodeValue(tree) as Record<string, unknown>;
+ const configs = root.configurations;
+ if (!Array.isArray(configs)) return { kind: 'not-present' };
+
+ const index = configs.findIndex(
+ (c) => isObject(c) && (c as Record<string, unknown>).name === LAUNCH_CONFIG_NAME,
+ );
+ if (index === -1) return { kind: 'not-present' };
+
+ if (configs.length === 1) {
+ rmSync(configPath, { force: true });
+ return { kind: 'removed-file' };
+ }
+
+ const { text, changed } = surgicalJsonDelete(raw, ['configurations', index]);
+ if (!changed) return { kind: 'not-present' };
+ atomicWriteFileSync(configPath, text, { mode: existingFileMode(configPath) });
+ return { kind: 'removed' };
+}
diff --git a/packages/cli/src/commands/mcp-config-removal.test.ts b/packages/cli/src/commands/mcp-config-removal.test.ts
new file mode 100644
index 000000000..65053bdc3
--- /dev/null
+++ b/packages/cli/src/commands/mcp-config-removal.test.ts
@@ -0,0 +1,270 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import {
+ createTomlConfigEngine,
+ setTomlConfigEngineForTesting,
+} from '../native/toml-config-engine.ts';
+import { buildManagedServerEntry, EDITOR_TARGETS } from './editors.ts';
+import { removeOwnMcpEntry } from './mcp-config-removal.ts';
+
+function tmp(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-mcp-remove-'));
+}
+
+const OWN_ENTRY = buildManagedServerEntry({ mode: 'published' });
+
+describe('removeOwnMcpEntry — JSON', () => {
+ test('removes only OK’s entry, preserving a sibling server + its comment', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.json');
+ const raw = `{
+ "mcpServers": {
+ "other": { "command": "node", "args": ["server.js"] },
+ "${MCP_SERVER_NAME}": ${JSON.stringify(OWN_ENTRY)}
+ }
+}
+`;
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ const after = readFileSync(configPath, 'utf-8');
+ expect(after).toContain('// my mcp servers');
+ expect(after).toContain('"other"');
+ expect(after).toContain('"command": "node"');
+ expect(after).not.toContain(MCP_SERVER_NAME);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('leaves the config byte-identical when OK is the only entry (empty container kept)', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.json');
+ writeFileSync(
+ configPath,
+ `${JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: OWN_ENTRY } }, null, 2)}\n`,
+ );
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ const after = JSON.parse(readFileSync(configPath, 'utf-8'));
+ expect(after.mcpServers[MCP_SERVER_NAME]).toBeUndefined();
+ expect(after.mcpServers).toEqual({});
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('leaves a FOREIGN server that shares the open-knowledge key untouched', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.json');
+ const foreign = { command: '/usr/bin/evil', args: ['--pwn'] };
+ const raw = `${JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: foreign } }, null, 2)}\n`;
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath);
+ expect(outcome.kind).toBe('left-foreign');
+ expect(readFileSync(configPath, 'utf-8')).toBe(raw);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('not-present when the config is absent or has no OK entry', () => {
+ const dir = tmp();
+ try {
+ const missing = join(dir, 'missing.json');
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, missing).kind).toBe(
+ 'not-present',
+ );
+ const other = join(dir, 'other.json');
+ writeFileSync(other, `${JSON.stringify({ mcpServers: { other: { command: 'x' } } })}\n`);
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, other).kind).toBe(
+ 'not-present',
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('idempotent — a second removal reports not-present and does not rewrite', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.json');
+ writeFileSync(
+ configPath,
+ `${JSON.stringify({ mcpServers: { other: { command: 'x' }, [MCP_SERVER_NAME]: OWN_ENTRY } }, null, 2)}\n`,
+ );
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath).kind).toBe(
+ 'removed',
+ );
+ const afterFirst = readFileSync(configPath, 'utf-8');
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath).kind).toBe(
+ 'not-present',
+ );
+ expect(readFileSync(configPath, 'utf-8')).toBe(afterFirst);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('declines an unparseable config, leaving it byte-identical', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.json');
+ const raw = '{ this is not: valid json ]';
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath);
+ expect(outcome.kind).toBe('declined');
+ expect(readFileSync(configPath, 'utf-8')).toBe(raw);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('removes the OpenCode-shaped entry (mcp key + {type:local, command:[]})', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'opencode.json');
+ const ownOpencode = EDITOR_TARGETS.opencode.buildEntry(dir);
+ const raw = `${JSON.stringify({ mcp: { other: { type: 'local', command: ['x'] }, [MCP_SERVER_NAME]: ownOpencode } }, null, 2)}\n`;
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.opencode, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ const after = JSON.parse(readFileSync(configPath, 'utf-8'));
+ expect(after.mcp[MCP_SERVER_NAME]).toBeUndefined();
+ expect(after.mcp.other).toEqual({ type: 'local', command: ['x'] });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('removes OpenClaw’s nested entry at mcp.servers.open-knowledge (3-level path)', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'openclaw.json');
+ const own = EDITOR_TARGETS.openclaw.buildEntry(dir);
+ const raw = `${JSON.stringify({ mcp: { servers: { other: { command: 'x' }, [MCP_SERVER_NAME]: own } } }, null, 2)}\n`;
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.openclaw, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ const after = JSON.parse(readFileSync(configPath, 'utf-8'));
+ expect(after.mcp.servers[MCP_SERVER_NAME]).toBeUndefined();
+ expect(after.mcp.servers.other).toEqual({ command: 'x' }); // sibling preserved
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('preserves a leading BOM across the removal', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'bom.json');
+ const raw = `\uFEFF${JSON.stringify({ mcpServers: { other: { command: 'x' }, [MCP_SERVER_NAME]: OWN_ENTRY } }, null, 2)}\n`;
+ writeFileSync(configPath, raw);
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath).kind).toBe(
+ 'removed',
+ );
+ const after = readFileSync(configPath, 'utf-8');
+ expect(after.charCodeAt(0)).toBe(0xfeff);
+ expect(after).toContain('"other"');
+ expect(after).not.toContain(MCP_SERVER_NAME);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('removeOwnMcpEntry — TOML (Codex)', () => {
+ test('removes OK’s entry, preserving a sibling table + its comment', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.toml');
+ const chain = (OWN_ENTRY.args as string[])[2];
+ const raw = `# codex config\nmodel = "gpt-5"\n\n[mcp_servers.other]\ncommand = "node" # keep me\n\n[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "/bin/sh"\nargs = ["-l", "-c", ${JSON.stringify(chain)}]\n`;
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.codex, dir, undefined, configPath);
+ expect(outcome.kind).toBe('removed');
+ const after = readFileSync(configPath, 'utf-8');
+ expect(after).toContain('# codex config');
+ expect(after).toContain('model = "gpt-5"');
+ expect(after).toContain('[mcp_servers.other]');
+ expect(after).toContain('command = "node" # keep me');
+ expect(after).not.toContain(`[mcp_servers.${MCP_SERVER_NAME}]`);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('idempotent — removing an already-absent Codex entry is a no-op', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.toml');
+ const raw = '[mcp_servers.other]\ncommand = "node"\n';
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.codex, dir, undefined, configPath);
+ expect(outcome.kind).toBe('not-present');
+ expect(readFileSync(configPath, 'utf-8')).toBe(raw);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('preserves CRLF line endings across the removal', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.toml');
+ const chain = (OWN_ENTRY.args as string[])[2];
+ const raw = `# codex\r\n[mcp_servers.other]\r\ncommand = "node"\r\n\r\n[mcp_servers.${MCP_SERVER_NAME}]\r\ncommand = "/bin/sh"\r\nargs = ["-l", "-c", ${JSON.stringify(chain)}]\r\n`;
+ writeFileSync(configPath, raw);
+ expect(removeOwnMcpEntry(EDITOR_TARGETS.codex, dir, undefined, configPath).kind).toBe(
+ 'removed',
+ );
+ const after = readFileSync(configPath, 'utf-8');
+ expect(after.includes('\r\n')).toBe(true);
+ expect(after).not.toContain(`[mcp_servers.${MCP_SERVER_NAME}]`);
+ expect(after).toContain('[mcp_servers.other]');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('leaves a FOREIGN Codex entry (no OK chain sentinel) untouched', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.toml');
+ const raw = `[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "/usr/bin/evil"\nargs = ["--pwn"]\n`;
+ writeFileSync(configPath, raw);
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.codex, dir, undefined, configPath);
+ expect(outcome.kind).toBe('left-foreign');
+ expect(readFileSync(configPath, 'utf-8')).toBe(raw); // byte-identical
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('declines when the format-preserving native engine is unavailable', () => {
+ const dir = tmp();
+ try {
+ const configPath = join(dir, 'config.toml');
+ const chain = (OWN_ENTRY.args as string[])[2];
+ const raw = `[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "/bin/sh"\nargs = ["-l", "-c", ${JSON.stringify(chain)}]\n`;
+ writeFileSync(configPath, raw);
+ setTomlConfigEngineForTesting(createTomlConfigEngine(() => null));
+ try {
+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.codex, dir, undefined, configPath);
+ expect(outcome.kind).toBe('declined');
+ if (outcome.kind === 'declined') expect(outcome.reason).toBe('no-native-writer');
+ expect(readFileSync(configPath, 'utf-8')).toBe(raw); // byte-identical
+ } finally {
+ setTomlConfigEngineForTesting(null); // restore the lazy default
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/mcp-config-removal.ts b/packages/cli/src/commands/mcp-config-removal.ts
new file mode 100644
index 000000000..24ad89eb2
--- /dev/null
+++ b/packages/cli/src/commands/mcp-config-removal.ts
@@ -0,0 +1,116 @@
+import { readFileSync } from 'node:fs';
+import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import { getTomlConfigEngine } from '../native/toml-config-engine.ts';
+import { type EditorMcpTarget, isEntryUpToDate, isOwnManagedEntry } from './editors.ts';
+import { classifyExistingMcpEntry, type McpDeclineReason, serverMapPath } from './init.ts';
+import { existingFileMode, isCrlfDominant, surgicalJsonDelete } from './jsonc-surgical.ts';
+
+export type McpRemoveOutcome =
+ | { kind: 'removed' }
+ | { kind: 'not-present' }
+ | { kind: 'left-foreign' }
+ | { kind: 'declined'; reason: McpDeclineReason };
+
+function isRemovableOwnEntry(entry: unknown): boolean {
+ return isEntryUpToDate(entry) || isOwnManagedEntry(entry);
+}
+
+const JSON_CONFIG_MAX_BYTES = 10 * 1024 * 1024;
+
+export function removeOwnMcpEntry(
+ target: EditorMcpTarget,
+ cwd: string,
+ home?: string,
+ configPathOverride?: string,
+): McpRemoveOutcome {
+ const classified = classifyExistingMcpEntry(target, cwd, home, configPathOverride);
+ if (classified.kind === 'absent' || classified.kind === 'no-entry') {
+ return { kind: 'not-present' };
+ }
+ if (classified.kind === 'decline') {
+ return { kind: 'declined', reason: classified.reason };
+ }
+ if (!isRemovableOwnEntry(classified.entry)) {
+ return { kind: 'left-foreign' };
+ }
+
+ let configPath: string;
+ try {
+ configPath = configPathOverride ?? target.configPath(cwd, home);
+ } catch {
+ return { kind: 'not-present' };
+ }
+ const serverName = target.serverName(cwd);
+
+ return target.format === 'toml'
+ ? removeTomlEntry(configPath, serverName)
+ : removeJsonEntry(configPath, target.topLevelKey, target.serverMapSubKey, serverName);
+}
+
+function removeJsonEntry(
+ configPath: string,
+ topLevelKey: string,
+ subKey: string | undefined,
+ serverName: string,
+): McpRemoveOutcome {
+ let raw: string;
+ try {
+ raw = readFileSync(configPath, 'utf-8');
+ } catch {
+ return { kind: 'declined', reason: 'unparseable' };
+ }
+ if (Buffer.byteLength(raw, 'utf-8') > JSON_CONFIG_MAX_BYTES) {
+ return { kind: 'declined', reason: 'oversize' };
+ }
+
+ const { text, changed } = surgicalJsonDelete(raw, serverMapPath(topLevelKey, subKey, serverName));
+ if (!changed) {
+ return { kind: 'not-present' };
+ }
+ atomicWriteFileSync(configPath, text, { mode: existingFileMode(configPath) });
+ return { kind: 'removed' };
+}
+
+function removeTomlEntry(configPath: string, serverName: string): McpRemoveOutcome {
+ const engine = getTomlConfigEngine();
+ if (engine.backend === 'fallback') {
+ return { kind: 'declined', reason: 'no-native-writer' };
+ }
+
+ let raw: string;
+ try {
+ raw = readFileSync(configPath, 'utf-8');
+ } catch {
+ return { kind: 'declined', reason: 'unparseable' };
+ }
+
+ const hasBom = raw.charCodeAt(0) === 0xfeff;
+ const body = hasBom ? raw.slice(1) : raw;
+ const crlfDominant = isCrlfDominant(body);
+ const wantTrailingNewline = body.trim() === '' || body.endsWith('\n');
+
+ let result: { text: string; existed: boolean };
+ try {
+ result = engine.removeEntry(body, serverName);
+ } catch {
+ return { kind: 'declined', reason: 'unparseable' };
+ }
+ if (!result.existed) {
+ return { kind: 'not-present' };
+ }
+
+ let text = result.text;
+ if (wantTrailingNewline) {
+ if (!text.endsWith('\n')) text = `${text}\n`;
+ } else {
+ text = text.replace(/\n+$/, '');
+ }
+ if (crlfDominant) {
+ text = text.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
+ }
+ const newText = `${hasBom ? '\uFEFF' : ''}${text}`;
+ if (newText !== raw) {
+ atomicWriteFileSync(configPath, newText, { mode: existingFileMode(configPath) });
+ }
+ return { kind: 'removed' };
+}
diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.ts
new file mode 100644
index 000000000..1f5b94bd0
--- /dev/null
+++ b/packages/cli/src/commands/removal-plan.test.ts
@@ -0,0 +1,374 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import { readPathInstallMarker } from '../integrations/path-shim.ts';
+import { buildManagedServerEntry } from './editors.ts';
+import {
+ buildUninstallPlan,
+ deinitOps,
+ type RunRemovalDeps,
+ runRemoval,
+ type UninstallPlanInput,
+} from './removal-plan.ts';
+
+const OWN_ENTRY = buildManagedServerEntry({ mode: 'published' });
+
+function write(path: string, content: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+}
+
+function stubDeps(over: Partial<RunRemovalDeps> = {}): RunRemovalDeps {
+ return {
+ clearToken: async () => ({ touched: ['keychain', 'file'] }),
+ clearEmbeddingsKey: async () => ({ touched: ['file'] }),
+ stopServer: () => ({ stopped: 0, failed: [] }),
+ ...over,
+ };
+}
+
+function seedHome(home: string): void {
+ write(join(home, '.ok', 'auth.yml'), 'github.com: {}\n');
+ write(join(home, '.ok', 'secrets.yml'), 'key: x\n');
+ write(join(home, '.ok', 'logs', 'server.jsonl'), '{}\n');
+ write(join(home, '.ok', 'skills', 'my-note-skill', 'SKILL.md'), '# mine\n');
+ write(
+ join(home, 'Library', 'Application Support', 'OpenKnowledge', 'state.json'),
+ JSON.stringify({ recentProjects: [] }),
+ );
+ write(join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json'), '{}');
+ write(
+ join(home, 'Library', 'Application Support', 'Open Knowledge', 'state.json'),
+ JSON.stringify({ theirData: true }),
+ );
+ write(join(home, 'Library', 'Caches', 'OpenKnowledge-updater', 'pending.zip'), 'x');
+ write(join(home, '.agents', 'skills', 'open-knowledge-discovery', 'SKILL.md'), '# d\n');
+ write(join(home, '.claude', 'skills', 'open-knowledge-discovery', 'SKILL.md'), '# d\n');
+ write(join(home, '.agents', 'skills', 'open-knowledge-write-skill', 'SKILL.md'), '# w\n');
+ write(join(home, '.agents', 'skills', 'someone-elses-skill', 'SKILL.md'), '# theirs\n');
+ write(
+ join(home, '.claude.json'),
+ `${JSON.stringify({ mcpServers: { other: { command: 'x' }, [MCP_SERVER_NAME]: OWN_ENTRY } }, null, 2)}\n`,
+ );
+ write(
+ join(home, '.zshrc'),
+ `export EDITOR=vim\n\n# >>> open-knowledge cli >>>\n[ -f "$HOME/.ok/env.sh" ] && . "$HOME/.ok/env.sh"\n# <<< open-knowledge cli <<<\n\nalias ll='ls -la'\n`,
+ );
+ write(
+ join(home, '.config', 'fish', 'conf.d', 'open-knowledge.fish'),
+ `# >>> open-knowledge cli >>>\nset -gx PATH "$HOME/.ok/bin" $PATH\n# <<< open-knowledge cli <<<\n`,
+ );
+}
+
+function markerFor(home: string): UninstallPlanInput['marker'] {
+ const extraTarget = join(home, '.ok', 'bin', 'ok');
+ const extraLink = join(home, '.local', 'bin', 'ok');
+ mkdirSync(dirname(extraTarget), { recursive: true });
+ writeFileSync(extraTarget, 'wrapper');
+ mkdirSync(dirname(extraLink), { recursive: true });
+ rmSync(extraLink, { force: true });
+ symlinkSync(extraTarget, extraLink);
+ return {
+ version: 1,
+ installedAt: 'x',
+ bundleVersion: '1.0.0',
+ bundleWrapperPath: '/w',
+ binDir: join(home, '.ok', 'bin'),
+ envShimPath: join(home, '.ok', 'env.sh'),
+ rcFiles: [join(home, '.zshrc'), join(home, '.config', 'fish', 'conf.d', 'open-knowledge.fish')],
+ rcOptOuts: [],
+ pathDiscovery: null,
+ extraSymlinks: [{ path: extraLink, target: extraTarget, createdAt: 'x', kind: 'created' }],
+ };
+}
+
+function baseInput(home: string, over: Partial<UninstallPlanInput> = {}): UninstallPlanInput {
+ return {
+ home,
+ platform: 'darwin',
+ host: 'github.com',
+ lockDirs: [],
+ marker: markerFor(home),
+ recentDeinitProjectRoots: [],
+ purgeContent: false,
+ ...over,
+ };
+}
+
+describe('buildUninstallPlan ordering', () => {
+ test('stops servers first and removes ~/.ok last, with recent-project deinits before it', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ const plan = buildUninstallPlan(
+ baseInput(home, {
+ lockDirs: ['/some/project/.ok/local'],
+ recentDeinitProjectRoots: ['/recent/proj'],
+ }),
+ );
+ const kinds = plan.ops.map((o) => o.kind);
+ expect(kinds[0]).toBe('stop-server'); // servers first
+ const last = plan.ops[plan.ops.length - 1];
+ expect(last.kind).toBe('remove-path');
+ expect((last as { path: string }).path).toBe(join(home, '.ok'));
+ const recentIdx = plan.ops.findIndex((o) => o.group === 'Project: proj');
+ expect(recentIdx).toBeGreaterThan(-1);
+ expect(recentIdx).toBeLessThan(plan.ops.length - 1);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('on non-macOS the desktop-only surfaces (app data + PATH shim) are absent', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ const plan = buildUninstallPlan({
+ home,
+ platform: 'linux',
+ env: { XDG_CONFIG_HOME: join(home, '.config') },
+ host: 'github.com',
+ lockDirs: [],
+ marker: null, // no PATH shim on non-mac
+ recentDeinitProjectRoots: [],
+ purgeContent: false,
+ });
+ expect(plan.ops.some((o) => o.group === 'Application data')).toBe(false);
+ expect(plan.ops.some((o) => o.kind === 'shell-block')).toBe(false);
+ expect(plan.ops.some((o) => o.kind === 'keychain-token')).toBe(true);
+ expect(plan.ops.some((o) => o.group === 'Editor MCP configs')).toBe(true);
+ expect(plan.ops.some((o) => o.group === 'Skill bundles')).toBe(true);
+ expect(plan.ops[plan.ops.length - 1].kind).toBe('remove-path'); // ~/.ok last
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('strips the ~/.zshrc block even when the path-install manifest is ABSENT', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ const zshrc = join(home, '.zshrc');
+ writeFileSync(
+ zshrc,
+ `export EDITOR=vim\n\n# >>> open-knowledge cli >>>\n[ -f "$HOME/.ok/env.sh" ] && . "$HOME/.ok/env.sh"\n# <<< open-knowledge cli <<<\n\nalias ll='ls -la'\n`,
+ );
+ const plan = buildUninstallPlan(baseInput(home, { marker: null }));
+ const shellOps = plan.ops.filter((o) => o.kind === 'shell-block');
+ expect(shellOps.map((o) => (o as { rcFile: string }).rcFile)).toContain(zshrc);
+
+ await runRemoval(plan, stubDeps());
+ const after = readFileSync(zshrc, 'utf-8');
+ expect(after).not.toContain('open-knowledge cli');
+ expect(after).toContain('export EDITOR=vim');
+ expect(after).toContain("alias ll='ls -la'");
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('runRemoval — git-exclude write failure', () => {
+ const asRoot = typeof process.getuid === 'function' && process.getuid() === 0;
+ test.skipIf(asRoot)('a read-only .git/info/exclude surfaces as a failed op', async () => {
+ const projectRoot = mkdtempSync(join(tmpdir(), 'ok-gitx-'));
+ try {
+ const excludePath = join(projectRoot, '.git', 'info', 'exclude');
+ mkdirSync(dirname(excludePath), { recursive: true });
+ writeFileSync(excludePath, '.ok/\n'); // an OK path is excluded → removal is attempted
+ chmodSync(excludePath, 0o444); // read-only → the write-back fails (EACCES)
+
+ const op = {
+ kind: 'git-exclude' as const,
+ group: 'test',
+ label: 'Remove OK paths from .git/info/exclude',
+ projectRoot,
+ };
+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());
+ expect(outcome.failed).toHaveLength(1);
+ expect(outcome.failed[0].detail).toContain('inaccessible');
+ } finally {
+ try {
+ chmodSync(join(projectRoot, '.git', 'info', 'exclude'), 0o644);
+ } catch {}
+ rmSync(projectRoot, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('runRemoval — project path containment guard', () => {
+ test('refuses to remove a project artifact that escapes via a symlink', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-contain-'));
+ try {
+ const projectRoot = join(home, 'proj');
+ const outside = join(home, 'outside-secret');
+ mkdirSync(outside, { recursive: true });
+ writeFileSync(join(outside, 'keep.txt'), 'do not delete');
+ mkdirSync(projectRoot, { recursive: true });
+ symlinkSync(outside, join(projectRoot, '.claude'));
+
+ const escaping = {
+ kind: 'remove-path' as const,
+ group: 'test',
+ label: 'Remove .claude/skills/open-knowledge/',
+ path: join(projectRoot, '.claude', 'skills', 'open-knowledge'),
+ containWithin: projectRoot,
+ };
+ const outcome = await runRemoval({ scope: 'deinit', ops: [escaping] }, stubDeps());
+ expect(outcome.failed).toHaveLength(1);
+ expect(existsSync(join(outside, 'keep.txt'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('runRemoval — uninstall end to end', () => {
+ test('reverses the whole footprint, preserving user content + foreign files', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ seedHome(home);
+ const plan = buildUninstallPlan(baseInput(home));
+ const outcome = await runRemoval(plan, stubDeps());
+ expect(outcome.failed).toHaveLength(0);
+
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'logs'))).toBe(false);
+ expect(existsSync(join(home, '.ok', 'skills', 'my-note-skill', 'SKILL.md'))).toBe(true);
+
+ expect(existsSync(join(home, 'Library', 'Application Support', 'OpenKnowledge'))).toBe(false);
+ expect(existsSync(join(home, 'Library', 'Application Support', 'Open Knowledge'))).toBe(true);
+ expect(existsSync(join(home, 'Library', 'Caches', 'OpenKnowledge-updater'))).toBe(false);
+
+ expect(existsSync(join(home, '.agents', 'skills', 'open-knowledge-discovery'))).toBe(false);
+ expect(existsSync(join(home, '.claude', 'skills', 'open-knowledge-discovery'))).toBe(false);
+ expect(existsSync(join(home, '.agents', 'skills', 'open-knowledge-write-skill'))).toBe(false);
+ expect(existsSync(join(home, '.agents', 'skills', 'someone-elses-skill'))).toBe(true);
+
+ const claudeCfg = JSON.parse(readFileSync(join(home, '.claude.json'), 'utf-8'));
+ expect(claudeCfg.mcpServers[MCP_SERVER_NAME]).toBeUndefined();
+ expect(claudeCfg.mcpServers.other).toEqual({ command: 'x' });
+
+ const zshrc = readFileSync(join(home, '.zshrc'), 'utf-8');
+ expect(zshrc).toContain('export EDITOR=vim');
+ expect(zshrc).toContain("alias ll='ls -la'");
+ expect(zshrc).not.toContain('open-knowledge cli');
+ expect(existsSync(join(home, '.config', 'fish', 'conf.d', 'open-knowledge.fish'))).toBe(
+ false,
+ );
+
+ expect(existsSync(join(home, '.local', 'bin', 'ok'))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('--purge-content also removes user-authored ~/.ok/skills', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ seedHome(home);
+ const plan = buildUninstallPlan(baseInput(home, { purgeContent: true }));
+ await runRemoval(plan, stubDeps());
+ expect(existsSync(join(home, '.ok'))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('a locked keychain is marked failed with a manual hint, never aborting the run', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ seedHome(home);
+ const plan = buildUninstallPlan(baseInput(home));
+ const outcome = await runRemoval(
+ plan,
+ stubDeps({
+ clearToken: async () => ({ touched: [], keychainError: 'SecKeychainError' }),
+ }),
+ );
+ const keychain = outcome.results.find((r) => r.op.kind === 'keychain-token');
+ expect(keychain?.status).toBe('failed');
+ expect(keychain?.detail).toContain('Keychain Access');
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('a stop-server failure surfaces as failed (a live process may still hold the files)', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ seedHome(home);
+ const plan = buildUninstallPlan(baseInput(home, { lockDirs: ['/proj/.ok/local'] }));
+ const outcome = await runRemoval(
+ plan,
+ stubDeps({
+ stopServer: () => ({ stopped: 0, failed: [{ pid: 4242, error: 'EPERM' }] }),
+ }),
+ );
+ const stop = outcome.results.find((r) => r.op.kind === 'stop-server');
+ expect(stop?.status).toBe('failed');
+ expect(stop?.detail).toContain('4242');
+ expect(outcome.failed.some((r) => r.op.kind === 'stop-server')).toBe(true);
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('idempotent — a second run is a clean no-op (nothing removed, nothing failed)', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));
+ try {
+ seedHome(home);
+ const input = baseInput(home); // fabricates the marker + extra symlink
+ await runRemoval(buildUninstallPlan(input), stubDeps());
+ const secondInput: UninstallPlanInput = { ...input, marker: readPathInstallMarker(home) };
+ const second = await runRemoval(
+ buildUninstallPlan(secondInput),
+ stubDeps({
+ clearToken: async () => ({ touched: [] }),
+ clearEmbeddingsKey: async () => ({ touched: [] }),
+ }),
+ );
+ expect(second.failed).toHaveLength(0);
+ expect(second.removed).toHaveLength(0);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('deinitOps', () => {
+ test('emits stop + surgical MCP + launch + git-exclude + whole-remove + shadow ops', () => {
+ const projectRoot = mkdtempSync(join(tmpdir(), 'ok-deinit-'));
+ try {
+ const ops = deinitOps(projectRoot, '/home/x');
+ const kinds = ops.map((o) => o.kind);
+ expect(kinds[0]).toBe('stop-server');
+ expect(kinds).toContain('mcp-entry'); // project MCP configs
+ expect(kinds).toContain('launch-entry');
+ expect(kinds).toContain('git-exclude');
+ const okRemoval = ops.find(
+ (o) =>
+ o.kind === 'remove-path' && (o as { path: string }).path === join(projectRoot, '.ok'),
+ );
+ expect(okRemoval).toBeDefined();
+ const mcpWholeRemove = ops.find(
+ (o) =>
+ o.kind === 'remove-path' &&
+ (o as { path: string }).path === join(projectRoot, '.mcp.json'),
+ );
+ expect(mcpWholeRemove).toBeUndefined();
+ } finally {
+ rmSync(projectRoot, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.ts
new file mode 100644
index 000000000..6fd92613c
--- /dev/null
+++ b/packages/cli/src/commands/removal-plan.ts
@@ -0,0 +1,499 @@
+import { existsSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';
+import { basename, join, relative, sep } from 'node:path';
+import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
+import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { resolveLockDir } from '@inkeep/open-knowledge-server';
+import { clearEmbeddingsKeyFromAllBackends } from '../auth/embeddings-key-store.ts';
+import { clearTokenFromAllBackends } from '../auth/token-store.ts';
+import {
+ DESKTOP_LEGACY_PRODUCT_NAME,
+ desktopUserDataDir,
+ stateDirIsOurs,
+} from '../integrations/desktop-state.ts';
+import {
+ extraSymlinkStillOurs,
+ type PathInstallMarker,
+ stripManagedPathBlock,
+} from '../integrations/path-shim.ts';
+import { userGlobalSkillBundleTargets } from '../integrations/skill-teardown.ts';
+import { assertProjectPathSafe } from '../integrations/write-project-skill.ts';
+import {
+ getExcludedOkPaths,
+ getOkArtifactPaths,
+ removeOkPathsFromGitExclude,
+} from '../sharing/git-exclude.ts';
+import { ALL_EDITOR_IDS, EDITOR_TARGETS, type EditorId } from './editors.ts';
+import { existingFileMode } from './jsonc-surgical.ts';
+import { removeOwnLaunchEntry } from './launch-json-removal.ts';
+import { removeOwnMcpEntry } from './mcp-config-removal.ts';
+import { runStop } from './stop.ts';
+
+export type RemovalGroup = string;
+
+export type RemovalOp =
+ | { kind: 'stop-server'; group: RemovalGroup; label: string; lockDir: string }
+ | { kind: 'keychain-token'; group: RemovalGroup; label: string; host: string }
+ | { kind: 'embeddings-key'; group: RemovalGroup; label: string }
+ | { kind: 'shell-block'; group: RemovalGroup; label: string; rcFile: string }
+ | { kind: 'extra-symlink'; group: RemovalGroup; label: string; path: string; target: string }
+ | {
+ kind: 'mcp-entry';
+ group: RemovalGroup;
+ label: string;
+ editorId: EditorId;
+ scope: 'user' | 'project';
+ cwd: string;
+ home: string;
+ configPath?: string;
+ }
+ | { kind: 'launch-entry'; group: RemovalGroup; label: string; projectRoot: string }
+ | { kind: 'git-exclude'; group: RemovalGroup; label: string; projectRoot: string }
+ | {
+ kind: 'remove-path';
+ group: RemovalGroup;
+ label: string;
+ path: string;
+ preserve?: string[];
+ requireOurState?: boolean;
+ containWithin?: string;
+ };
+
+export interface RemovalPlan {
+ scope: 'uninstall' | 'deinit';
+ ops: RemovalOp[];
+}
+
+/** Per-op result. `not-present` = nothing was there (a clean no-op);
+ * `skipped` = deliberately left (foreign config, unverified dir);
+ * `failed` = an error the run isolated + continued past. */
+type RemovalStatus = 'removed' | 'not-present' | 'skipped' | 'failed';
+
+interface RemovalOpResult {
+ op: RemovalOp;
+ status: RemovalStatus;
+ /** Bounded human detail — a decline reason, a foreign marker, an error, or a
+ * manual-removal hint. Never config contents. */
+ detail?: string;
+}
+
+export interface RemovalOutcome {
+ results: RemovalOpResult[];
+ removed: RemovalOpResult[];
+ failed: RemovalOpResult[];
+}
+
+function tildify(p: string, home: string): string {
+ return p === home ? '~' : p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p;
+}
+
+function toPosix(p: string): string {
+ return sep === '/' ? p : p.split(sep).join('/');
+}
+
+export function deinitOps(
+ projectRoot: string,
+ home: string,
+ group: RemovalGroup = 'This project',
+): RemovalOp[] {
+ const ops: RemovalOp[] = [];
+
+ ops.push({
+ kind: 'stop-server',
+ group,
+ label: 'Stop the project server (if running)',
+ lockDir: resolveLockDir(projectRoot),
+ });
+
+ const mcpRelPaths = new Set<string>();
+ for (const id of ALL_EDITOR_IDS) {
+ const target = EDITOR_TARGETS[id];
+ if (!target.projectConfigPath) continue;
+ const configPath = target.projectConfigPath(projectRoot);
+ mcpRelPaths.add(toPosix(relative(projectRoot, configPath)));
+ ops.push({
+ kind: 'mcp-entry',
+ group,
+ label: `Remove OK's MCP entry from ${target.label} (${toPosix(relative(projectRoot, configPath))})`,
+ editorId: id,
+ scope: 'project',
+ cwd: projectRoot,
+ home,
+ configPath,
+ });
+ }
+
+ ops.push({
+ kind: 'launch-entry',
+ group,
+ label: "Remove OK's entry from .claude/launch.json",
+ projectRoot,
+ });
+
+ ops.push({
+ kind: 'git-exclude',
+ group,
+ label: 'Remove OK paths from .git/info/exclude',
+ projectRoot,
+ });
+
+ for (const rel of getOkArtifactPaths(projectRoot)) {
+ const bare = rel.replace(/\/$/, '');
+ if (mcpRelPaths.has(bare)) continue; // handled surgically above
+ if (bare === '.claude/launch.json') continue; // handled by launch-entry
+ ops.push({
+ kind: 'remove-path',
+ group,
+ label: `Remove ${rel}`,
+ path: join(projectRoot, bare),
+ containWithin: projectRoot,
+ });
+ }
+
+ try {
+ ops.push({
+ kind: 'remove-path',
+ group,
+ label: 'Remove the OK shadow repo (.git/ok/)',
+ path: resolveShadowDir(projectRoot),
+ });
+ } catch {}
+
+ return ops;
+}
+
+export function buildDeinitPlan(projectRoot: string, home: string): RemovalPlan {
+ return { scope: 'deinit', ops: deinitOps(projectRoot, home) };
+}
+
+export interface UninstallPlanInput {
+ home: string;
+ platform: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ host: string;
+ lockDirs: string[];
+ marker: PathInstallMarker | null;
+ recentDeinitProjectRoots: string[];
+ purgeContent: boolean;
+}
+
+export function buildUninstallPlan(input: UninstallPlanInput): RemovalPlan {
+ const { home, platform, host, lockDirs, marker, recentDeinitProjectRoots, purgeContent } = input;
+ const ops: RemovalOp[] = [];
+
+ for (const lockDir of lockDirs) {
+ ops.push({
+ kind: 'stop-server',
+ group: 'Running servers',
+ label: `Stop server at ${tildify(join(lockDir, '..', '..'), home)}`,
+ lockDir,
+ });
+ }
+
+ ops.push({
+ kind: 'keychain-token',
+ group: 'Credentials',
+ label: `Remove the GitHub credential (${host}) from the OS keychain + auth.yml`,
+ host,
+ });
+ ops.push({
+ kind: 'embeddings-key',
+ group: 'Credentials',
+ label: 'Remove the embeddings API key (secrets.yml)',
+ });
+
+ ops.push(...pathRevertOps(marker, home));
+
+ for (const id of ALL_EDITOR_IDS) {
+ const target = EDITOR_TARGETS[id];
+ let configPath: string;
+ try {
+ configPath = target.configPath('', home);
+ } catch {
+ continue; // platform-unavailable target (e.g. Claude Desktop on Linux)
+ }
+ ops.push({
+ kind: 'mcp-entry',
+ group: 'Editor MCP configs',
+ label: `Remove OK's MCP entry from ${target.label} (${tildify(configPath, home)})`,
+ editorId: id,
+ scope: 'user',
+ cwd: home,
+ home,
+ configPath,
+ });
+ }
+
+ for (const target of userGlobalSkillBundleTargets(home)) {
+ ops.push({
+ kind: 'remove-path',
+ group: 'Skill bundles',
+ label: `Remove ${tildify(target.path, home)}`,
+ path: target.path,
+ });
+ }
+
+ ops.push(...applicationDataOps(home, platform, input.env));
+
+ for (const projectRoot of recentDeinitProjectRoots) {
+ ops.push(...deinitOps(projectRoot, home, `Project: ${basename(projectRoot)}`));
+ }
+
+ ops.push({
+ kind: 'remove-path',
+ group: 'Global directory',
+ label: purgeContent
+ ? 'Remove ~/.ok (including user-authored skills)'
+ : 'Remove ~/.ok (keeping ~/.ok/skills)',
+ path: join(home, '.ok'),
+ preserve: purgeContent ? undefined : ['skills'],
+ });
+
+ return { scope: 'uninstall', ops };
+}
+
+function standardRcFiles(home: string): string[] {
+ return [
+ join(home, '.zshrc'),
+ join(home, '.bash_profile'),
+ join(home, '.config', 'fish', 'conf.d', 'open-knowledge.fish'),
+ ];
+}
+
+function pathRevertOps(marker: PathInstallMarker | null, home: string): RemovalOp[] {
+ const ops: RemovalOp[] = [];
+ const rcCandidates = new Set([...standardRcFiles(home), ...(marker?.rcFiles ?? [])]);
+ for (const rcFile of rcCandidates) {
+ if (!existsSync(rcFile)) continue;
+ ops.push({
+ kind: 'shell-block',
+ group: 'Shell PATH',
+ label: `Strip the OK block from ${tildify(rcFile, home)}`,
+ rcFile,
+ });
+ }
+ for (const extra of marker?.extraSymlinks ?? []) {
+ ops.push({
+ kind: 'extra-symlink',
+ group: 'Shell PATH',
+ label: `Remove the ok symlink at ${tildify(extra.path, home)}`,
+ path: extra.path,
+ target: extra.target,
+ });
+ }
+ return ops;
+}
+
+function applicationDataOps(
+ home: string,
+ platform: NodeJS.Platform,
+ env: NodeJS.ProcessEnv | undefined,
+): RemovalOp[] {
+ if (platform !== 'darwin') return [];
+ const options = { home, platformName: platform, env };
+
+ const current = desktopUserDataDir(options);
+ const legacy = desktopUserDataDir({ ...options, productName: DESKTOP_LEGACY_PRODUCT_NAME });
+ const updaterCache = join(home, 'Library', 'Caches', 'OpenKnowledge-updater');
+
+ return [
+ {
+ kind: 'remove-path',
+ group: 'Application data',
+ label: `Remove ${tildify(current, home)}`,
+ path: current,
+ },
+ {
+ kind: 'remove-path',
+ group: 'Application data',
+ label: `Remove ${tildify(legacy, home)} (only if it is OpenKnowledge's)`,
+ path: legacy,
+ requireOurState: true,
+ },
+ {
+ kind: 'remove-path',
+ group: 'Application data',
+ label: `Remove ${tildify(updaterCache, home)}`,
+ path: updaterCache,
+ },
+ ];
+}
+
+export interface RunRemovalDeps {
+ clearToken?: (
+ host: string,
+ ) => Promise<{ touched: Array<'keychain' | 'file'>; keychainError?: string }>;
+ clearEmbeddingsKey?: () => Promise<{ touched: Array<'file'> }>;
+ stopServer?: (lockDir: string) => {
+ stopped: number;
+ failed: Array<{ pid: number; error: string }>;
+ };
+}
+
+export async function runRemoval(
+ plan: RemovalPlan,
+ deps: RunRemovalDeps = {},
+): Promise<RemovalOutcome> {
+ const clearToken = deps.clearToken ?? clearTokenFromAllBackends;
+ const clearEmbeddingsKey = deps.clearEmbeddingsKey ?? clearEmbeddingsKeyFromAllBackends;
+ const stopServer =
+ deps.stopServer ??
+ ((lockDir: string) => {
+ const outcome = runStop({ lockDir, log: () => {}, error: () => {} });
+ return {
+ stopped: outcome.stopped.length,
+ failed: outcome.failed.map((f) => ({ pid: f.target.pid, error: f.error })),
+ };
+ });
+
+ const results: RemovalOpResult[] = [];
+ for (const op of plan.ops) {
+ try {
+ results.push(await executeOp(op, { clearToken, clearEmbeddingsKey, stopServer }));
+ } catch (err) {
+ results.push({
+ op,
+ status: 'failed',
+ detail: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ return {
+ results,
+ removed: results.filter((r) => r.status === 'removed'),
+ failed: results.filter((r) => r.status === 'failed'),
+ };
+}
+
+type ResolvedDeps = Required<RunRemovalDeps>;
+
+async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpResult> {
+ switch (op.kind) {
+ case 'stop-server': {
+ const { stopped, failed } = deps.stopServer(op.lockDir);
+ if (failed.length > 0) {
+ const detail = failed.map((f) => `pid ${f.pid}: ${f.error}`).join('; ');
+ return {
+ op,
+ status: 'failed',
+ detail: `could not stop the server (${detail}); a process may still be using files that were removed`,
+ };
+ }
+ return { op, status: stopped > 0 ? 'removed' : 'not-present' };
+ }
+ case 'keychain-token': {
+ const { touched, keychainError } = await deps.clearToken(op.host);
+ if (keychainError) {
+ return {
+ op,
+ status: 'failed',
+ detail: `keychain unreachable (${keychainError}); remove manually: Keychain Access → service "open-knowledge"`,
+ };
+ }
+ return { op, status: touched.length > 0 ? 'removed' : 'not-present' };
+ }
+ case 'embeddings-key': {
+ const { touched } = await deps.clearEmbeddingsKey();
+ return { op, status: touched.length > 0 ? 'removed' : 'not-present' };
+ }
+ case 'shell-block': {
+ if (!existsSync(op.rcFile)) return { op, status: 'not-present' };
+ const before = readFileSync(op.rcFile, 'utf-8');
+ const { text, changed, emptyAfter } = stripManagedPathBlock(before);
+ if (!changed) return { op, status: 'not-present' };
+ if (emptyAfter) {
+ rmSync(op.rcFile, { force: true });
+ return { op, status: 'removed', detail: 'file removed (was OK-owned)' };
+ }
+ atomicWriteFileSync(op.rcFile, text, { mode: existingFileMode(op.rcFile) });
+ return { op, status: 'removed' };
+ }
+ case 'extra-symlink': {
+ if (!extraSymlinkStillOurs(op.path, op.target)) return { op, status: 'not-present' };
+ unlinkSync(op.path);
+ return { op, status: 'removed' };
+ }
+ case 'mcp-entry': {
+ const outcome = removeOwnMcpEntry(
+ EDITOR_TARGETS[op.editorId],
+ op.cwd,
+ op.home,
+ op.configPath,
+ );
+ switch (outcome.kind) {
+ case 'removed':
+ return { op, status: 'removed' };
+ case 'not-present':
+ return { op, status: 'not-present' };
+ case 'left-foreign':
+ return { op, status: 'skipped', detail: 'left a non-OK server in place' };
+ case 'declined':
+ return { op, status: 'skipped', detail: `declined (${outcome.reason})` };
+ default: {
+ const _exhaustive: never = outcome;
+ throw new Error(
+ `unhandled mcp-remove outcome: ${(_exhaustive as { kind: string }).kind}`,
+ );
+ }
+ }
+ }
+ case 'launch-entry': {
+ const outcome = removeOwnLaunchEntry(op.projectRoot);
+ switch (outcome.kind) {
+ case 'removed':
+ case 'removed-file':
+ return { op, status: 'removed' };
+ case 'not-present':
+ return { op, status: 'not-present' };
+ case 'declined':
+ return { op, status: 'skipped', detail: 'declined (unparseable)' };
+ default: {
+ const _exhaustive: never = outcome;
+ throw new Error(
+ `unhandled launch-remove outcome: ${(_exhaustive as { kind: string }).kind}`,
+ );
+ }
+ }
+ }
+ case 'git-exclude': {
+ const excluded = getExcludedOkPaths(op.projectRoot);
+ if (excluded.length === 0) return { op, status: 'not-present' };
+ const result = removeOkPathsFromGitExclude(
+ op.projectRoot,
+ getOkArtifactPaths(op.projectRoot),
+ );
+ if (result.kind === 'no-exclude') {
+ return result.reason === 'inaccessible'
+ ? { op, status: 'failed', detail: 'could not write .git/info/exclude (inaccessible)' }
+ : { op, status: 'not-present', detail: result.reason };
+ }
+ return { op, status: result.removed.length > 0 ? 'removed' : 'not-present' };
+ }
+ case 'remove-path':
+ return executeRemovePath(op);
+ }
+}
+
+function executeRemovePath(op: Extract<RemovalOp, { kind: 'remove-path' }>): RemovalOpResult {
+ if (op.requireOurState && !stateDirIsOurs(op.path)) {
+ return { op, status: 'skipped', detail: 'not verified as OpenKnowledge — left untouched' };
+ }
+ if (op.containWithin) {
+ assertProjectPathSafe(op.path, op.containWithin);
+ }
+ if (!existsSync(op.path)) return { op, status: 'not-present' };
+
+ 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' };
+ }
+
+ rmSync(op.path, { recursive: true, force: true });
+ return { op, status: 'removed' };
+}
diff --git a/packages/cli/src/commands/removal-render.ts b/packages/cli/src/commands/removal-render.ts
new file mode 100644
index 000000000..452fa3407
--- /dev/null
+++ b/packages/cli/src/commands/removal-render.ts
@@ -0,0 +1,95 @@
+import { accent, dim, error as errorColor, success, warning } from '../ui/colors.ts';
+import type { RemovalOp, RemovalOutcome, RemovalPlan } from './removal-plan.ts';
+
+function groupOps(ops: RemovalOp[]): Map<string, RemovalOp[]> {
+ const groups = new Map<string, RemovalOp[]>();
+ for (const op of ops) {
+ const arr = groups.get(op.group) ?? [];
+ arr.push(op);
+ groups.set(op.group, arr);
+ }
+ return groups;
+}
+
+export function formatRemovalPlan(plan: RemovalPlan): string {
+ if (plan.ops.length === 0) return dim('Nothing to remove.');
+ const lines: string[] = [];
+ for (const [group, ops] of groupOps(plan.ops)) {
+ if (lines.length > 0) lines.push('');
+ lines.push(accent(`${group}:`));
+ for (const op of ops) {
+ lines.push(` ${warning('-')} ${op.label}`);
+ }
+ }
+ return lines.join('\n');
+}
+
+export function formatRemovalOutcome(outcome: RemovalOutcome): string {
+ const removed = outcome.removed.length;
+ const failed = outcome.failed.length;
+ const notPresent = outcome.results.filter((r) => r.status === 'not-present').length;
+ const skipped = outcome.results.filter((r) => r.status === 'skipped');
+
+ const lines: string[] = [];
+ lines.push(
+ failed > 0
+ ? warning(
+ `Removed ${removed} item${removed === 1 ? '' : 's'}, ${failed} could not be removed.`,
+ )
+ : success(`✓ Removed ${removed} item${removed === 1 ? '' : 's'}.`),
+ );
+ if (notPresent > 0) lines.push(dim(` ${notPresent} already absent.`));
+
+ for (const s of skipped) {
+ lines.push(
+ ` ${warning('·')} Left in place: ${s.op.label}${s.detail ? ` — ${dim(s.detail)}` : ''}`,
+ );
+ }
+ if (failed > 0) {
+ lines.push('');
+ lines.push(errorColor('Could not remove:'));
+ for (const f of outcome.failed) {
+ lines.push(` ${errorColor('✗')} ${f.op.label}${f.detail ? ` — ${f.detail}` : ''}`);
+ }
+ }
+ return lines.join('\n');
+}
+
+interface RemovalItem {
+ kind: string;
+ label: string;
+ detail?: string;
+}
+
+export type RemovalJson =
+ | { scope: 'uninstall' | 'deinit'; mode: 'dry-run'; planned: RemovalItem[] }
+ | {
+ scope: 'uninstall' | 'deinit';
+ mode: 'applied';
+ removed: RemovalItem[];
+ skipped: RemovalItem[];
+ failed: RemovalItem[];
+ };
+
+export function removalPlanToJson(plan: RemovalPlan): RemovalJson {
+ return {
+ scope: plan.scope,
+ mode: 'dry-run',
+ planned: plan.ops.map((op) => ({ kind: op.kind, label: op.label })),
+ };
+}
+
+export function removalOutcomeToJson(
+ scope: 'uninstall' | 'deinit',
+ outcome: RemovalOutcome,
+): RemovalJson {
+ return {
+ scope,
+ mode: 'applied',
+ removed: outcome.removed.map((r) => ({ kind: r.op.kind, label: r.op.label })),
+ skipped: outcome.results
+ .filter((r) => r.status === 'skipped')
+ .map((r) => ({ kind: r.op.kind, label: r.op.label, detail: r.detail })),
+ failed: outcome.failed.map((r) => ({ kind: r.op.kind, label: r.op.label, detail: r.detail })),
+ };
+}
diff --git a/packages/cli/src/commands/uninstall.test.ts b/packages/cli/src/commands/uninstall.test.ts
new file mode 100644
index 000000000..3f3dc5bb5
--- /dev/null
+++ b/packages/cli/src/commands/uninstall.test.ts
@@ -0,0 +1,293 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { Readable } from 'node:stream';
+import { detectInstallMethods, resolveRecentDeinitProjects, runUninstall } from './uninstall.ts';
+
+function write(path: string, content: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, content);
+}
+
+describe('detectInstallMethods', () => {
+ test('detects an app bundle, npm-global, and npx', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-detect-'));
+ try {
+ const userApp = join(home, 'Applications', 'OpenKnowledge.app');
+ const npmStub = (args: string[]) =>
+ args.includes('@inkeep/open-knowledge') ? '@inkeep/[email protected]\n' : null;
+ const methods = detectInstallMethods(
+ home,
+ '/Users/x/.npm/_npx/abcd/node_modules/.bin/ok',
+ npmStub,
+ (p) => p === userApp, // hermetic: only the injected user-app path "exists"
+ );
+ const kinds = methods.map((m) => m.method);
+ expect(kinds).toContain('app');
+ expect(kinds).toContain('npm-global');
+ expect(kinds).toContain('npx');
+ expect(methods.find((m) => m.method === 'npm-global')?.instruction).toContain(
+ 'npm uninstall -g',
+ );
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('returns nothing when no install is detected', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-detect-'));
+ try {
+ expect(
+ detectInstallMethods(
+ home,
+ '/usr/local/bin/ok',
+ () => null,
+ () => false,
+ ),
+ ).toEqual([]);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('resolveRecentDeinitProjects', () => {
+ function twoProjects(): { home: string; a: string; b: string } {
+ const home = mkdtempSync(join(tmpdir(), 'ok-recent-'));
+ const a = join(home, 'projA');
+ const b = join(home, 'projB');
+ write(join(a, '.ok', 'config.yml'), 'x\n');
+ write(join(b, '.ok', 'config.yml'), 'x\n');
+ return { home, a, b };
+ }
+
+ test('--yes alone selects NO projects (opt-in — global only)', async () => {
+ const { home, a, b } = twoProjects();
+ try {
+ const selected = await resolveRecentDeinitProjects({
+ home,
+ platform: 'darwin',
+ cwd: a, // standing in an OK project — still not auto-selected
+ lockDirs: [],
+ yes: true,
+ readRecents: () => [{ path: b }],
+ findRoot: () => ({ rootPath: a, distance: 0 }),
+ });
+ expect(selected).toEqual([]); // neither the current project nor recents
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('--all-projects selects current + recents', async () => {
+ const { home, a, b } = twoProjects();
+ try {
+ const selected = await resolveRecentDeinitProjects({
+ home,
+ platform: 'darwin',
+ cwd: a,
+ lockDirs: [],
+ yes: true,
+ allProjects: true,
+ readRecents: () => [{ path: b }],
+ findRoot: () => ({ rootPath: a, distance: 0 }),
+ });
+ expect(selected).toContain(a);
+ expect(selected).toContain(b);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('--dry-run selects nothing by default (opt-in preview)', async () => {
+ const { home, a, b } = twoProjects();
+ try {
+ const selected = await resolveRecentDeinitProjects({
+ home,
+ platform: 'darwin',
+ cwd: a,
+ lockDirs: [],
+ dryRun: true,
+ readRecents: () => [{ path: b }],
+ findRoot: () => ({ rootPath: a, distance: 0 }),
+ });
+ expect(selected).toEqual([]);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('interactive: only the ticked projects are selected (default is none)', async () => {
+ const { home, a, b } = twoProjects();
+ try {
+ const selected = await resolveRecentDeinitProjects({
+ home,
+ platform: 'darwin',
+ cwd: a,
+ lockDirs: [],
+ isTTY: true,
+ readRecents: () => [{ path: b }],
+ findRoot: () => ({ rootPath: a, distance: 0 }),
+ promptFn: async (candidates) => candidates.filter((c) => c.path === b).map((c) => c.path),
+ });
+ expect(selected).toEqual([b]); // only what the user ticked
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('--all-projects skips recent entries whose dir no longer exists / is not an OK project', async () => {
+ const { home, a } = twoProjects();
+ try {
+ const selected = await resolveRecentDeinitProjects({
+ home,
+ platform: 'darwin',
+ cwd: a,
+ lockDirs: [],
+ allProjects: true,
+ readRecents: () => [{ path: join(home, 'deleted-project') }],
+ findRoot: () => ({ rootPath: a, distance: 0 }),
+ });
+ expect(selected).toEqual([a]); // the non-existent recent is dropped
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('runUninstall', () => {
+ test('dry-run renders the plan + binary instructions, removing nothing', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));
+ try {
+ write(join(home, '.ok', 'auth.yml'), 'x\n');
+ const result = await runUninstall({
+ home,
+ platform: 'darwin',
+ cwd: home,
+ dryRun: true,
+ deps: {
+ discoverLockDirs: async () => [],
+ detectInstallMethods: () => [
+ { method: 'app', label: 'OK Desktop', instruction: 'Move to Trash' },
+ ],
+ },
+ });
+ expect(result.status).toBe('dry-run');
+ expect(result.message).toContain('Would remove');
+ expect(result.message).toContain('Move to Trash'); // binary instruction shown
+ expect(existsSync(join(home, '.ok'))).toBe(true); // nothing removed
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('refuses to run non-interactively without --yes', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));
+ try {
+ const result = await runUninstall({
+ home,
+ platform: 'darwin',
+ cwd: home,
+ isTTY: false,
+ deps: { discoverLockDirs: async () => [] },
+ });
+ expect(result.status).toBe('cancelled');
+ expect(result.exitCode).toBe(1);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('empty prompt input aborts and removes nothing', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));
+ try {
+ write(join(home, '.ok', 'auth.yml'), 'x\n');
+ const result = await runUninstall({
+ home,
+ platform: 'darwin',
+ cwd: home,
+ isTTY: true,
+ confirmStream: Readable.from(['\n']),
+ deps: { discoverLockDirs: async () => [] },
+ });
+ expect(result.status).toBe('cancelled');
+ expect(existsSync(join(home, '.ok'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('reports failed + exit 1 when an op fails (e.g. a server won’t stop)', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));
+ try {
+ write(join(home, '.ok', 'auth.yml'), 'x\n');
+ const result = await runUninstall({
+ home,
+ platform: 'darwin',
+ cwd: home,
+ yes: true,
+ deps: {
+ discoverLockDirs: async () => ['/some/proj/.ok/local'], // → a stop-server op
+ detectInstallMethods: () => [],
+ runRemovalDeps: {
+ clearToken: async () => ({ touched: [] }),
+ clearEmbeddingsKey: async () => ({ touched: [] }),
+ stopServer: () => ({ stopped: 0, failed: [{ pid: 99, error: 'EPERM' }] }),
+ },
+ },
+ });
+ expect(result.status).toBe('failed');
+ expect(result.exitCode).toBe(1);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('--json without --yes is rejected (no interactive prompt possible)', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));
+ try {
+ const result = await runUninstall({
+ home,
+ platform: 'darwin',
+ cwd: home,
+ json: true,
+ deps: { discoverLockDirs: async () => [] },
+ });
+ expect(result.status).toBe('failed');
+ expect(result.exitCode).toBe(1);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('--yes success path runs the removal and reports done (creds stubbed)', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));
+ try {
+ write(join(home, '.ok', 'auth.yml'), 'x\n');
+ write(join(home, '.agents', 'skills', 'open-knowledge-discovery', 'SKILL.md'), '# d\n');
+ const result = await runUninstall({
+ home,
+ platform: 'darwin',
+ cwd: home,
+ yes: true,
+ deps: {
+ discoverLockDirs: async () => [],
+ detectInstallMethods: () => [],
+ runRemovalDeps: {
+ clearToken: async () => ({ touched: ['file'] }),
+ clearEmbeddingsKey: async () => ({ touched: [] }),
+ stopServer: () => ({ stopped: 0, failed: [] }),
+ },
+ },
+ });
+ expect(result.status).toBe('done');
+ expect(result.exitCode).toBe(0);
+ expect(result.message).toContain('Removed');
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);
+ expect(existsSync(join(home, '.agents', 'skills', 'open-knowledge-discovery'))).toBe(false);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/uninstall.ts b/packages/cli/src/commands/uninstall.ts
new file mode 100644
index 000000000..1b94e5672
--- /dev/null
+++ b/packages/cli/src/commands/uninstall.ts
@@ -0,0 +1,371 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { findEnclosingProjectRoot } from '@inkeep/open-knowledge-server';
+import checkbox from '@inquirer/checkbox';
+import { Command } from 'commander';
+import { desktopUserDataDir, readDesktopRecentProjects } from '../integrations/desktop-state.ts';
+import { readPathInstallMarker } from '../integrations/path-shim.ts';
+import { accent, dim, error as errorColor, info, success, warning } from '../ui/colors.ts';
+import { confirmDestructive } from '../ui/confirm.ts';
+import { discoverLockDirs } from '../utils/process-scan.ts';
+import { buildUninstallPlan, type RunRemovalDeps, runRemoval } from './removal-plan.ts';
+import {
+ formatRemovalOutcome,
+ formatRemovalPlan,
+ removalOutcomeToJson,
+ removalPlanToJson,
+} from './removal-render.ts';
+
+export interface InstallMethod {
+ method: 'app' | 'npm-global' | 'npx';
+ label: string;
+ instruction: string;
+}
+
+export function detectInstallMethods(
+ home: string,
+ argv1: string | undefined,
+ runNpmLs: (args: string[]) => string | null = defaultNpmLs,
+ exists: (path: string) => boolean = existsSync,
+): InstallMethod[] {
+ const methods: InstallMethod[] = [];
+
+ for (const app of [
+ '/Applications/OpenKnowledge.app',
+ join(home, 'Applications', 'OpenKnowledge.app'),
+ ]) {
+ if (exists(app)) {
+ methods.push({
+ method: 'app',
+ label: `OK Desktop (${app})`,
+ instruction: `Move ${app} to the Trash (or: rm -rf "${app}")`,
+ });
+ }
+ }
+
+ const npmOut = runNpmLs(['ls', '-g', '--depth=0', '@inkeep/open-knowledge']);
+ if (npmOut?.includes('@inkeep/open-knowledge@')) {
+ methods.push({
+ method: 'npm-global',
+ label: 'npm global install',
+ instruction: 'npm uninstall -g @inkeep/open-knowledge',
+ });
+ }
+
+ if (argv1 && /[/\\]_npx[/\\]/.test(argv1)) {
+ methods.push({
+ method: 'npx',
+ label: 'npx (ephemeral)',
+ instruction:
+ 'Nothing to uninstall — npx runs from a temporary cache. (Optional: npm cache clean --force)',
+ });
+ }
+
+ return methods;
+}
+
+function defaultNpmLs(args: string[]): string | null {
+ try {
+ return execFileSync('npm', args, {
+ encoding: 'utf-8',
+ timeout: 5000,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ } catch {
+ return null;
+ }
+}
+
+/** A banner rule the app-removal callout is bracketed with, so the one manual
+ * step OK can't do for itself doesn't get lost in the removal log. */
+const CALLOUT_RULE = '━'.repeat(64);
+
+function formatInstallInstructions(methods: InstallMethod[]): string {
+ const lines: string[] = [
+ warning(CALLOUT_RULE),
+ accent(' One more step — remove the OpenKnowledge app itself'),
+ dim(" (OpenKnowledge can't delete its own running binary — do this by hand.)"),
+ '',
+ ];
+ if (methods.length === 0) {
+ lines.push(dim(' Install method not detected. If you installed it, remove it via:'));
+ lines.push(` ${info('OK Desktop')} — move /Applications/OpenKnowledge.app to the Trash`);
+ lines.push(` ${info('npm global')} — npm uninstall -g @inkeep/open-knowledge`);
+ lines.push(` ${info('npx')} — nothing to remove (runs from a temporary cache)`);
+ } else {
+ for (const m of methods) {
+ lines.push(` ${info(m.label)}`);
+ lines.push(` ${m.instruction}`);
+ }
+ }
+ lines.push(warning(CALLOUT_RULE));
+ return lines.join('\n');
+}
+
+interface ProjectCandidate {
+ path: string;
+ running: boolean;
+ current: boolean;
+}
+
+function projectRootFromLockDir(lockDir: string): string {
+ return resolve(lockDir, '..', '..');
+}
+
+function isDeinitableProject(dir: string): boolean {
+ return existsSync(join(dir, '.ok'));
+}
+
+export interface ResolveRecentProjectsInput {
+ home: string;
+ platform: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ cwd: string;
+ lockDirs: string[];
+ yes?: boolean;
+ allProjects?: boolean;
+ dryRun?: boolean;
+ isTTY?: boolean;
+ promptFn?: (candidates: ProjectCandidate[]) => Promise<string[]>;
+ readRecents?: (userDataDir: string) => Array<{ path: string }>;
+ findRoot?: typeof findEnclosingProjectRoot;
+}
+
+export async function resolveRecentDeinitProjects(
+ input: ResolveRecentProjectsInput,
+): Promise<string[]> {
+ const findRoot = input.findRoot ?? findEnclosingProjectRoot;
+ const readRecents = input.readRecents ?? readDesktopRecentProjects;
+
+ const currentRoot = findRoot(input.cwd)?.rootPath ?? null;
+ const userDataDir = desktopUserDataDir({
+ home: input.home,
+ platformName: input.platform,
+ env: input.env,
+ });
+
+ const recentPaths = new Set<string>();
+ for (const p of readRecents(userDataDir)) recentPaths.add(resolve(p.path));
+ const runningRoots = new Set(input.lockDirs.map(projectRootFromLockDir));
+ for (const r of runningRoots) recentPaths.add(r);
+ if (currentRoot) recentPaths.delete(currentRoot); // handled as the `current` candidate
+
+ const candidates: ProjectCandidate[] = [];
+ if (currentRoot && isDeinitableProject(currentRoot)) {
+ candidates.push({ path: currentRoot, running: runningRoots.has(currentRoot), current: true });
+ }
+ for (const p of recentPaths) {
+ if (!isDeinitableProject(p)) continue; // skip removed / non-OK dirs
+ candidates.push({ path: p, running: runningRoots.has(p), current: false });
+ }
+ if (candidates.length === 0) return [];
+
+ if (input.allProjects) return candidates.map((c) => c.path); // explicit: all
+ if (input.yes) return []; // `--yes` alone = global only; add `--all-projects` for projects
+ if (input.dryRun) return []; // a plain run selects nothing by default
+ const tty = input.isTTY ?? process.stdout.isTTY;
+ if (!tty) return []; // non-interactive without a flag: touch no project repo
+ const prompt = input.promptFn ?? defaultProjectCheckbox;
+ return prompt(candidates);
+}
+
+async function defaultProjectCheckbox(candidates: ProjectCandidate[]): Promise<string[]> {
+ return checkbox({
+ message:
+ 'Also remove OpenKnowledge from these projects? (space to toggle; none selected by default)\n' +
+ " Removes each project's .ok/ config, editor MCP entries, and OK edit-history\n" +
+ ' (.git/ok/). Your markdown content is kept — `ok start` re-adds OK later.\n',
+ required: false,
+ theme: { icon: { checked: '[x]', unchecked: '[ ]' } },
+ choices: candidates.map((c) => ({
+ name: `${c.path}${c.current ? ' (current)' : ''}${c.running ? ' (running — will be stopped)' : ''}`,
+ value: c.path,
+ checked: false,
+ })),
+ });
+}
+
+/** Injectable seams for `runUninstall` — a named interface (not an anonymous
+ * inline type), matching `RepairSkillsDeps` etc. */
+interface UninstallDeps {
+ discoverLockDirs?: () => Promise<string[]>;
+ resolveRecentProjects?: typeof resolveRecentDeinitProjects;
+ detectInstallMethods?: typeof detectInstallMethods;
+ runRemovalDeps?: RunRemovalDeps;
+}
+
+export interface UninstallOptions {
+ home?: string;
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ cwd?: string;
+ host?: string;
+ yes?: boolean;
+ dryRun?: boolean;
+ json?: boolean;
+ purgeContent?: boolean;
+ allProjects?: boolean;
+ isTTY?: boolean;
+ argv1?: string;
+ confirmStream?: NodeJS.ReadableStream;
+ deps?: UninstallDeps;
+}
+
+export interface UninstallResult {
+ status: 'dry-run' | 'cancelled' | 'done' | 'failed';
+ message: string;
+ exitCode: number;
+}
+
+const URL_SCHEME_NOTE = dim(
+ 'The openknowledge:// URL scheme deregisters itself once the app is removed — no action needed.',
+);
+
+export async function runUninstall(opts: UninstallOptions = {}): Promise<UninstallResult> {
+ const home = opts.home ?? homedir();
+ const platform = opts.platform ?? process.platform;
+ const env = opts.env ?? process.env;
+ const cwd = resolve(opts.cwd ?? process.cwd());
+ const host = opts.host ?? 'github.com';
+ const purgeContent = opts.purgeContent ?? false;
+
+ const discoverLocks = opts.deps?.discoverLockDirs ?? discoverLockDirs;
+ const resolveRecents = opts.deps?.resolveRecentProjects ?? resolveRecentDeinitProjects;
+ const detectInstall = opts.deps?.detectInstallMethods ?? detectInstallMethods;
+
+ const lockDirs = await discoverLocks();
+ const marker = readPathInstallMarker(home);
+ const recentDeinitProjectRoots = await resolveRecents({
+ home,
+ platform,
+ env,
+ cwd,
+ lockDirs,
+ yes: opts.yes,
+ allProjects: opts.allProjects,
+ dryRun: opts.dryRun,
+ isTTY: opts.isTTY,
+ });
+
+ const plan = buildUninstallPlan({
+ home,
+ platform,
+ env,
+ host,
+ lockDirs,
+ marker,
+ recentDeinitProjectRoots,
+ purgeContent,
+ });
+
+ const fallbackNote = dim(
+ 'Individual projects are only removed when you select them (or pass --all-projects). ' +
+ 'To remove OpenKnowledge from one project, run `ok deinit` inside it.',
+ );
+ const binaryBlock = (): string =>
+ formatInstallInstructions(detectInstall(home, opts.argv1 ?? process.argv[1]));
+
+ if (opts.dryRun) {
+ const body = opts.json
+ ? JSON.stringify(removalPlanToJson(plan), null, 2)
+ : [
+ accent('Would remove (dry-run — no changes made):'),
+ '',
+ formatRemovalPlan(plan),
+ '',
+ fallbackNote,
+ '',
+ binaryBlock(),
+ ].join('\n');
+ return { status: 'dry-run', message: body, exitCode: 0 };
+ }
+
+ if (opts.json && !opts.yes) {
+ return {
+ status: 'failed',
+ message: `${errorColor('Error:')} --json requires --yes (or --dry-run) so there is no interactive prompt.`,
+ exitCode: 1,
+ };
+ }
+
+ if (!opts.yes) {
+ const tty = opts.isTTY ?? process.stdout.isTTY;
+ if (!tty) {
+ return {
+ status: 'cancelled',
+ message: `${errorColor('Aborted:')} refusing to uninstall non-interactively without --yes.`,
+ exitCode: 1,
+ };
+ }
+ process.stderr.write(
+ `${accent('This will remove OpenKnowledge from your machine:')}\n\n${formatRemovalPlan(plan)}\n\n${warning('This cannot be undone.')}\n\n`,
+ );
+ const confirmed = await confirmDestructive(
+ `${accent('Remove all of the above?')} ${dim('[y/N] ')}`,
+ opts.confirmStream,
+ );
+ if (!confirmed) {
+ return { status: 'cancelled', message: dim('Cancelled. Nothing was removed.'), exitCode: 0 };
+ }
+ }
+
+ const outcome = await runRemoval(plan, opts.deps?.runRemovalDeps);
+
+ const parts = [
+ opts.json
+ ? JSON.stringify(removalOutcomeToJson('uninstall', outcome), null, 2)
+ : formatRemovalOutcome(outcome),
+ ];
+ if (!opts.json) {
+ parts.push('', fallbackNote, URL_SCHEME_NOTE);
+ if (outcome.failed.length === 0) {
+ parts.push('', success("OpenKnowledge's files have been removed from this machine."));
+ }
+ parts.push('', binaryBlock());
+ }
+
+ return {
+ status: outcome.failed.length > 0 ? 'failed' : 'done',
+ message: parts.join('\n'),
+ exitCode: outcome.failed.length > 0 ? 1 : 0,
+ };
+}
+
+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.',
+ )
+ .option(
+ '-y, --yes',
+ 'Skip the confirmation prompt (removes the global footprint only; add --all-projects to also deinit projects)',
+ )
+ .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(
+ '--all-projects',
+ 'Also deinit every recent/running project (by default no project is removed — you pick them interactively)',
+ )
+ .action(
+ async (options: {
+ yes?: boolean;
+ dryRun?: boolean;
+ json?: boolean;
+ purgeContent?: boolean;
+ allProjects?: boolean;
+ }) => {
+ const result = await runUninstall({
+ yes: options.yes,
+ dryRun: options.dryRun,
+ json: options.json,
+ purgeContent: options.purgeContent,
+ allProjects: options.allProjects,
+ });
+ process.stdout.write(`${result.message}\n`);
+ if (result.exitCode !== 0) process.exitCode = result.exitCode;
+ },
+ );
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index ff40f4ce7..565e6bd1a 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -60,6 +60,14 @@ export {
parseGitHubTreeUrl,
parseGitUrl,
} from './github/url.ts';
+export {
+ PATH_SHIM_BEGIN,
+ PATH_SHIM_BLOCK_RE,
+ PATH_SHIM_END,
+ type PathDiscovery,
+ type PathInstallMarker,
+ pathInstallMarkerPath,
+} from './integrations/path-shim.ts';
export type { IntegrationWriteOutcome } from './integrations/project-integration-writers.ts';
export {
type ResolveProjectRootOptions,
diff --git a/packages/cli/src/integrations/desktop-state.test.ts b/packages/cli/src/integrations/desktop-state.test.ts
new file mode 100644
index 000000000..c0d6d24ac
--- /dev/null
+++ b/packages/cli/src/integrations/desktop-state.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ DESKTOP_LEGACY_PRODUCT_NAME,
+ DESKTOP_PRODUCT_NAME,
+ desktopUserDataDir,
+ readDesktopRecentProjects,
+ stateDirIsOurs,
+} from './desktop-state.ts';
+
+describe('desktopUserDataDir', () => {
+ test('resolves the Electron userData path per platform', () => {
+ expect(desktopUserDataDir({ home: '/Users/x', platformName: 'darwin' })).toBe(
+ '/Users/x/Library/Application Support/OpenKnowledge',
+ );
+ expect(
+ desktopUserDataDir({
+ home: '/home/x',
+ platformName: 'linux',
+ env: { XDG_CONFIG_HOME: '/home/x/.config' },
+ }),
+ ).toBe('/home/x/.config/OpenKnowledge');
+ expect(
+ desktopUserDataDir({
+ home: 'C:\\Users\\x',
+ platformName: 'win32',
+ env: { APPDATA: 'C:\\Users\\x\\AppData\\Roaming' },
+ }),
+ ).toContain('OpenKnowledge');
+ });
+
+ test('the legacy product name resolves the space-named macOS dir', () => {
+ expect(
+ desktopUserDataDir({
+ home: '/Users/x',
+ platformName: 'darwin',
+ productName: DESKTOP_LEGACY_PRODUCT_NAME,
+ }),
+ ).toBe('/Users/x/Library/Application Support/Open Knowledge');
+ expect(DESKTOP_PRODUCT_NAME).not.toBe(DESKTOP_LEGACY_PRODUCT_NAME);
+ });
+});
+
+function writeState(dir: string, value: unknown): void {
+ writeFileSync(join(dir, 'state.json'), JSON.stringify(value));
+}
+
+describe('readDesktopRecentProjects', () => {
+ test('reads the recent-projects list, keeping only string path+name entries', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-state-'));
+ try {
+ writeState(dir, {
+ recentProjects: [
+ { path: '/a', name: 'A', lastOpenedAt: 't' },
+ { path: '/b', name: 'B' },
+ { path: 123, name: 'bad' }, // dropped — non-string path
+ 'garbage', // dropped
+ ],
+ lastOpenedProject: '/a',
+ });
+ expect(readDesktopRecentProjects(dir)).toEqual([
+ { path: '/a', name: 'A' },
+ { path: '/b', name: 'B' },
+ ]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('returns [] for an absent, malformed, or foreign-shaped state.json', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-state-'));
+ try {
+ expect(readDesktopRecentProjects(dir)).toEqual([]); // absent
+ writeFileSync(join(dir, 'state.json'), 'not json');
+ expect(readDesktopRecentProjects(dir)).toEqual([]); // malformed
+ writeState(dir, { somethingElse: true }); // foreign — no recentProjects array
+ expect(readDesktopRecentProjects(dir)).toEqual([]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('stateDirIsOurs', () => {
+ test('true only when state.json parses as our AppState shape', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-state-'));
+ try {
+ expect(stateDirIsOurs(dir)).toBe(false); // absent
+ writeState(dir, { recentProjects: [] }); // our shape (even if empty)
+ expect(stateDirIsOurs(dir)).toBe(true);
+ writeState(dir, { recentProjects: [{ path: '/p', name: 'P', lastOpenedAt: 't' }] });
+ expect(stateDirIsOurs(dir)).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('false for a FOREIGN vendor’s same-named dir (no recentProjects array)', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-state-'));
+ try {
+ writeState(dir, { windows: [], preferences: { theme: 'dark' } });
+ expect(stateDirIsOurs(dir)).toBe(false);
+ writeFileSync(join(dir, 'state.json'), '{ broken json');
+ expect(stateDirIsOurs(dir)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/integrations/desktop-state.ts b/packages/cli/src/integrations/desktop-state.ts
new file mode 100644
index 000000000..7a90644e2
--- /dev/null
+++ b/packages/cli/src/integrations/desktop-state.ts
@@ -0,0 +1,60 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { type AppSupportOptions, resolveAppSupportPath } from '../commands/editors.ts';
+
+export const DESKTOP_PRODUCT_NAME = 'OpenKnowledge';
+/** Pre-rename `productName` (macOS legacy `Open Knowledge`, with a space). A
+ * generic name we don't own by name alone — always identity-gate before
+ * deleting its dir. */
+export const DESKTOP_LEGACY_PRODUCT_NAME = 'Open Knowledge';
+
+interface DesktopUserDataOptions extends AppSupportOptions {
+ productName?: string;
+}
+
+export function desktopUserDataDir(options: DesktopUserDataOptions = {}): string {
+ const productName = options.productName ?? DESKTOP_PRODUCT_NAME;
+ return join(resolveAppSupportPath(options), productName);
+}
+
+export interface DesktopRecentProject {
+ path: string;
+ name: string;
+}
+
+function parseRecentProjects(raw: unknown): DesktopRecentProject[] | null {
+ if (typeof raw !== 'object' || raw === null) return null;
+ const recentRaw = (raw as Record<string, unknown>).recentProjects;
+ if (!Array.isArray(recentRaw)) return null;
+ const projects: DesktopRecentProject[] = [];
+ for (const entry of recentRaw) {
+ if (typeof entry !== 'object' || entry === null) continue;
+ const item = entry as Record<string, unknown>;
+ if (typeof item.path === 'string' && typeof item.name === 'string') {
+ projects.push({ path: item.path, name: item.name });
+ }
+ }
+ return projects;
+}
+
+export function readDesktopRecentProjects(userDataDir: string): DesktopRecentProject[] {
+ const stateFile = join(userDataDir, 'state.json');
+ if (!existsSync(stateFile)) return [];
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(readFileSync(stateFile, 'utf-8'));
+ } catch {
+ return [];
+ }
+ return parseRecentProjects(parsed) ?? [];
+}
+
+export function stateDirIsOurs(userDataDir: string): boolean {
+ const stateFile = join(userDataDir, 'state.json');
+ if (!existsSync(stateFile)) return false;
+ try {
+ return parseRecentProjects(JSON.parse(readFileSync(stateFile, 'utf-8'))) !== null;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/cli/src/integrations/path-shim.test.ts b/packages/cli/src/integrations/path-shim.test.ts
new file mode 100644
index 000000000..34bc43637
--- /dev/null
+++ b/packages/cli/src/integrations/path-shim.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ extraSymlinkStillOurs,
+ PATH_SHIM_BEGIN,
+ PATH_SHIM_END,
+ pathInstallMarkerPath,
+ readPathInstallMarker,
+ stripManagedPathBlock,
+} from './path-shim.ts';
+
+function block(inner = '[ -f "$HOME/.ok/env.sh" ] && . "$HOME/.ok/env.sh"'): string {
+ return `${PATH_SHIM_BEGIN}\n${inner}\n${PATH_SHIM_END}\n`;
+}
+
+describe('stripManagedPathBlock', () => {
+ test('strips the block from a user rc file, preserving every other line', () => {
+ const before = `export EDITOR=vim\n\n${block()}\nalias ll='ls -la'\n`;
+ const { text, changed, emptyAfter } = stripManagedPathBlock(before);
+ expect(changed).toBe(true);
+ expect(emptyAfter).toBe(false);
+ expect(text).toContain('export EDITOR=vim');
+ expect(text).toContain("alias ll='ls -la'");
+ expect(text).not.toContain(PATH_SHIM_BEGIN);
+ expect(text).not.toContain(PATH_SHIM_END);
+ });
+
+ test('reports emptyAfter for an OK-owned file whose only content is the block', () => {
+ const { text, changed, emptyAfter } = stripManagedPathBlock(block());
+ expect(changed).toBe(true);
+ expect(emptyAfter).toBe(true);
+ expect(text.trim()).toBe('');
+ });
+
+ test('is a no-op for a file with no managed block', () => {
+ const before = 'export PATH="$HOME/bin:$PATH"\n';
+ const { text, changed, emptyAfter } = stripManagedPathBlock(before);
+ expect(changed).toBe(false);
+ expect(emptyAfter).toBe(false);
+ expect(text).toBe(before);
+ });
+});
+
+describe('readPathInstallMarker', () => {
+ test('reads a valid v1 marker', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-marker-'));
+ try {
+ const markerPath = pathInstallMarkerPath(home);
+ const dir = markerPath.slice(0, markerPath.lastIndexOf('/'));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ markerPath,
+ JSON.stringify({
+ version: 1,
+ installedAt: 'x',
+ bundleVersion: '1.0.0',
+ bundleWrapperPath: '/w',
+ binDir: join(home, '.ok', 'bin'),
+ envShimPath: join(home, '.ok', 'env.sh'),
+ rcFiles: [join(home, '.zshrc')],
+ rcOptOuts: [],
+ pathDiscovery: null,
+ extraSymlinks: [],
+ }),
+ );
+ const marker = readPathInstallMarker(home);
+ expect(marker?.version).toBe(1);
+ expect(marker?.rcFiles).toEqual([join(home, '.zshrc')]);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('returns null for an absent, malformed, or wrong-version marker', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-marker-'));
+ try {
+ expect(readPathInstallMarker(home)).toBeNull();
+ const markerPath = pathInstallMarkerPath(home);
+ const dir = markerPath.slice(0, markerPath.lastIndexOf('/'));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(markerPath, 'not json');
+ expect(readPathInstallMarker(home)).toBeNull();
+ writeFileSync(markerPath, JSON.stringify({ version: 2 }));
+ expect(readPathInstallMarker(home)).toBeNull();
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('extraSymlinkStillOurs', () => {
+ test('true only when the path is a symlink still pointing at the recorded target', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-xsym-'));
+ try {
+ const target = join(dir, '.ok', 'bin', 'ok');
+ const link = join(dir, 'ok');
+ symlinkSync(target, link);
+ expect(extraSymlinkStillOurs(link, target)).toBe(true);
+ expect(extraSymlinkStillOurs(link, join(dir, 'somewhere-else'))).toBe(false);
+ const plain = join(dir, 'plain');
+ writeFileSync(plain, 'x');
+ expect(extraSymlinkStillOurs(plain, target)).toBe(false);
+ expect(extraSymlinkStillOurs(join(dir, 'missing'), target)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/integrations/path-shim.ts b/packages/cli/src/integrations/path-shim.ts
new file mode 100644
index 000000000..b0d3f0ab4
--- /dev/null
+++ b/packages/cli/src/integrations/path-shim.ts
@@ -0,0 +1,95 @@
+import {
+ existsSync as fsExistsSync,
+ lstatSync as fsLstatSync,
+ readFileSync as fsReadFileSync,
+ readlinkSync as fsReadlinkSync,
+} from 'node:fs';
+import { join } from 'node:path';
+
+export const PATH_SHIM_BEGIN = '# >>> open-knowledge cli >>>';
+export const PATH_SHIM_END = '# <<< open-knowledge cli <<<';
+export const PATH_SHIM_BLOCK_RE =
+ /^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;
+
+export interface PathDiscovery {
+ capturedAt: string;
+ pathEntries: string[];
+ shellUsed: string;
+ okBinAlreadyOnPath: boolean;
+}
+
+export interface PathInstallMarker {
+ version: 1;
+ installedAt: string;
+ bundleVersion: string;
+ bundleWrapperPath: string;
+ binDir: string;
+ envShimPath: string;
+ rcFiles: string[];
+ /** Rc files the user stripped the managed block from — never written to
+ * again by the installer. */
+ rcOptOuts: string[];
+ pathDiscovery: PathDiscovery | null;
+ extraSymlinks: Array<{
+ path: string;
+ target: string;
+ createdAt: string;
+ kind: 'created' | 'refreshed-our-own';
+ }>;
+}
+
+/** Absolute path to the PATH-install manifest (macOS layout — the shim is
+ * macOS-packaged-desktop only, so this path is where it is ever written). */
+export function pathInstallMarkerPath(home: string): string {
+ return join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json');
+}
+
+export interface PathShimFsOps {
+ existsSync(path: string): boolean;
+ readFileSync(path: string, encoding: 'utf8'): string;
+ lstatSync(path: string): { isSymbolicLink(): boolean };
+ readlinkSync(path: string): string;
+}
+
+const defaultFsOps: PathShimFsOps = {
+ existsSync: (path) => fsExistsSync(path),
+ readFileSync: (path, encoding) => fsReadFileSync(path, encoding),
+ lstatSync: (path) => fsLstatSync(path),
+ readlinkSync: (path) => fsReadlinkSync(path),
+};
+
+export function readPathInstallMarker(
+ home: string,
+ fs: PathShimFsOps = defaultFsOps,
+): PathInstallMarker | null {
+ const path = pathInstallMarkerPath(home);
+ if (!fs.existsSync(path)) return null;
+ try {
+ const parsed = JSON.parse(fs.readFileSync(path, 'utf8')) as PathInstallMarker;
+ return parsed?.version === 1 ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+export function stripManagedPathBlock(text: string): {
+ text: string;
+ changed: boolean;
+ emptyAfter: boolean;
+} {
+ const next = text.replace(PATH_SHIM_BLOCK_RE, '');
+ return { text: next, changed: next !== text, emptyAfter: next.trim() === '' };
+}
+
+export function extraSymlinkStillOurs(
+ path: string,
+ target: string,
+ fs: PathShimFsOps = defaultFsOps,
+): boolean {
+ try {
+ if (!fs.lstatSync(path).isSymbolicLink()) return false;
+ return fs.readlinkSync(path) === target;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/cli/src/integrations/skill-teardown.test.ts b/packages/cli/src/integrations/skill-teardown.test.ts
new file mode 100644
index 000000000..00822d0cc
--- /dev/null
+++ b/packages/cli/src/integrations/skill-teardown.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, test } from 'bun:test';
+import { join } from 'node:path';
+import { BUNDLE_SKILL_NAME, USER_GLOBAL_BUNDLE_IDS } from '@inkeep/open-knowledge-server';
+import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';
+import { userGlobalSkillBundleTargets } from './skill-teardown.ts';
+
+const HOME = '/home/tester';
+
+describe('userGlobalSkillBundleTargets', () => {
+ test('targets the central store + every per-host dir for each user-global bundle', () => {
+ const targets = userGlobalSkillBundleTargets(HOME);
+ const expectedCount = USER_GLOBAL_BUNDLE_IDS.length * (1 + HOSTS_WITH_USER_SKILL_DIR.length);
+ expect(targets.length).toBe(expectedCount);
+
+ for (const bundleId of USER_GLOBAL_BUNDLE_IDS) {
+ const name = BUNDLE_SKILL_NAME[bundleId];
+ expect(targets).toContainEqual({
+ path: join(HOME, '.agents', 'skills', name),
+ bundleId,
+ scope: 'central',
+ });
+ for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ expect(targets).toContainEqual({
+ path: join(HOME, host.hostDir, 'skills', name),
+ bundleId,
+ scope: 'host',
+ hostDir: host.hostDir,
+ });
+ }
+ }
+ });
+
+ test('includes both built-in bundles by name (discovery + write-skill)', () => {
+ const paths = userGlobalSkillBundleTargets(HOME).map((t) => t.path);
+ expect(paths.some((p) => p.endsWith('/open-knowledge-discovery'))).toBe(true);
+ expect(paths.some((p) => p.endsWith('/open-knowledge-write-skill'))).toBe(true);
+ });
+
+ test('never targets the shared ~/.agents/skills root itself', () => {
+ const paths = userGlobalSkillBundleTargets(HOME).map((t) => t.path);
+ expect(paths).not.toContain(join(HOME, '.agents', 'skills'));
+ for (const t of userGlobalSkillBundleTargets(HOME).filter((x) => x.scope === 'central')) {
+ expect(t.path.startsWith(`${join(HOME, '.agents', 'skills')}/`)).toBe(true);
+ }
+ });
+});
diff --git a/packages/cli/src/integrations/skill-teardown.ts b/packages/cli/src/integrations/skill-teardown.ts
new file mode 100644
index 000000000..7aa34b901
--- /dev/null
+++ b/packages/cli/src/integrations/skill-teardown.ts
@@ -0,0 +1,35 @@
+import { join } from 'node:path';
+import {
+ BUNDLE_SKILL_NAME,
+ type BundleId,
+ USER_GLOBAL_BUNDLE_IDS,
+} from '@inkeep/open-knowledge-server';
+import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';
+
+export interface SkillBundleTarget {
+ path: string;
+ bundleId: BundleId;
+ scope: 'central' | 'host';
+ hostDir?: string;
+}
+
+export function userGlobalSkillBundleTargets(home: string): SkillBundleTarget[] {
+ const targets: SkillBundleTarget[] = [];
+ for (const bundleId of USER_GLOBAL_BUNDLE_IDS) {
+ const name = BUNDLE_SKILL_NAME[bundleId];
+ targets.push({
+ path: join(home, '.agents', 'skills', name),
+ bundleId,
+ scope: 'central',
+ });
+ for (const host of HOSTS_WITH_USER_SKILL_DIR) {
+ targets.push({
+ path: join(home, host.hostDir, 'skills', name),
+ bundleId,
+ scope: 'host',
+ hostDir: host.hostDir,
+ });
+ }
+ }
+ return targets;
+}
diff --git a/packages/cli/src/native/toml-config-engine.test.ts b/packages/cli/src/native/toml-config-engine.test.ts
index a4d67b227..1dc52f92d 100644
--- a/packages/cli/src/native/toml-config-engine.test.ts
+++ b/packages/cli/src/native/toml-config-engine.test.ts
@@ -8,6 +8,11 @@ const NOOP_UPSERT: NativeTomlBinding['upsertMcpServer'] = () => ({
changed: false,
existed: false,
});
+const NOOP_REMOVE: NativeTomlBinding['removeMcpServer'] = () => ({
+ text: '',
+ changed: false,
+ existed: false,
+});
describe('createTomlConfigEngine', () => {
test('resolves the native backend and parses values smol-toml rejects', () => {
@@ -36,6 +41,7 @@ describe('createTomlConfigEngine', () => {
throw new Error('symbol not found');
},
upsertMcpServer: NOOP_UPSERT,
+ removeMcpServer: NOOP_REMOVE,
};
const engine = createTomlConfigEngine(() => abiMismatch);
expect(engine.backend).toBe('fallback');
@@ -45,6 +51,7 @@ describe('createTomlConfigEngine', () => {
const wrongOutput: NativeTomlBinding = {
parseTomlToJson: () => 'not json at all',
upsertMcpServer: NOOP_UPSERT,
+ removeMcpServer: NOOP_REMOVE,
};
expect(createTomlConfigEngine(() => wrongOutput).backend).toBe('fallback');
});
@@ -53,6 +60,7 @@ describe('createTomlConfigEngine', () => {
const fake: NativeTomlBinding = {
parseTomlToJson: (raw) => (raw.includes('probe') ? '{"probe":1}' : '{"injected":true}'),
upsertMcpServer: NOOP_UPSERT,
+ removeMcpServer: NOOP_REMOVE,
};
const engine = createTomlConfigEngine(() => fake);
expect(engine.backend).toBe('native');
@@ -67,6 +75,7 @@ describe('createTomlConfigEngine', () => {
captured = { toml, name, json };
return { text: 'edited', changed: true, existed: true };
},
+ removeMcpServer: NOOP_REMOVE,
};
const engine = createTomlConfigEngine(() => fake);
if (engine.backend !== 'native') throw new Error('expected the native engine');
@@ -79,6 +88,39 @@ describe('createTomlConfigEngine', () => {
});
});
+ test('removeEntry forwards to the binding and maps text + existed', () => {
+ let captured: { toml: string; name: string } | undefined;
+ const fake: NativeTomlBinding = {
+ parseTomlToJson: (raw) => (raw.includes('probe') ? '{"probe":1}' : '{}'),
+ upsertMcpServer: NOOP_UPSERT,
+ removeMcpServer: (toml, name) => {
+ captured = { toml, name };
+ return { text: 'trimmed', changed: true, existed: true };
+ },
+ };
+ const engine = createTomlConfigEngine(() => fake);
+ if (engine.backend !== 'native') throw new Error('expected the native engine');
+ const result = engine.removeEntry('x = 1\n', 'open-knowledge');
+ expect(result).toEqual({ text: 'trimmed', existed: true });
+ expect(captured).toEqual({ toml: 'x = 1\n', name: 'open-knowledge' });
+ });
+
+ test('the real native engine removes OK’s entry, preserving a sibling', () => {
+ const engine = createTomlConfigEngine();
+ if (engine.backend !== 'native') throw new Error('native addon must be built for this gate');
+ const input =
+ '# keep\n[mcp_servers.other]\ncommand = "node" # sibling\n\n[mcp_servers.open-knowledge]\ncommand = "/bin/sh"\n';
+ const removed = engine.removeEntry(input, 'open-knowledge');
+ expect(removed.existed).toBe(true);
+ expect(removed.text).toContain('# keep');
+ expect(removed.text).toContain('[mcp_servers.other]');
+ expect(removed.text).toContain('command = "node" # sibling');
+ expect(removed.text).not.toContain('[mcp_servers.open-knowledge]');
+ const again = engine.removeEntry(removed.text, 'open-knowledge');
+ expect(again.existed).toBe(false);
+ expect(again.text).toBe(removed.text);
+ });
+
test('the real native engine upserts OK’s entry, preserving a sibling', () => {
const engine = createTomlConfigEngine();
if (engine.backend !== 'native') throw new Error('native addon must be built for this gate');
@@ -108,6 +150,7 @@ describe('createTomlConfigEngine', () => {
const arrayRoot: NativeTomlBinding = {
parseTomlToJson: (raw) => (raw.includes('probe') ? '{"probe":1}' : '[1,2,3]'),
upsertMcpServer: NOOP_UPSERT,
+ removeMcpServer: NOOP_REMOVE,
};
expect(() => createTomlConfigEngine(() => arrayRoot).parseToObject('x')).toThrow();
});
diff --git a/packages/cli/src/native/toml-config-engine.ts b/packages/cli/src/native/toml-config-engine.ts
index 5a18f71a3..80081d9e2 100644
--- a/packages/cli/src/native/toml-config-engine.ts
+++ b/packages/cli/src/native/toml-config-engine.ts
@@ -11,6 +11,7 @@ interface NativeMcpEditResult {
export interface NativeTomlBinding {
parseTomlToJson(tomlText: string): string;
upsertMcpServer(tomlText: string, serverName: string, entryJson: string): NativeMcpEditResult;
+ removeMcpServer(tomlText: string, serverName: string): NativeMcpEditResult;
}
export interface TomlUpsertResult {
@@ -25,6 +26,7 @@ interface TomlConfigEngineBase {
interface NativeTomlConfigEngine extends TomlConfigEngineBase {
readonly backend: 'native';
upsertEntry(raw: string, serverName: string, entry: Record<string, unknown>): TomlUpsertResult;
+ removeEntry(raw: string, serverName: string): TomlUpsertResult;
}
interface FallbackTomlConfigEngine extends TomlConfigEngineBase {
@@ -65,6 +67,10 @@ function makeNativeEngine(binding: NativeTomlBinding): NativeTomlConfigEngine {
const result = binding.upsertMcpServer(raw, serverName, JSON.stringify(entry));
return { text: result.text, existed: result.existed };
},
+ removeEntry(raw, serverName) {
+ const result = binding.removeMcpServer(raw, serverName);
+ return { text: result.text, existed: result.existed };
+ },
};
}
diff --git a/packages/cli/src/project-anchor.ts b/packages/cli/src/project-anchor.ts
index 3e3142df8..5d24839f5 100644
--- a/packages/cli/src/project-anchor.ts
+++ b/packages/cli/src/project-anchor.ts
@@ -8,6 +8,7 @@ const PROJECT_ANCHORED_COMMANDS: ReadonlySet<string> = new Set([
'ui',
'mcp',
'preview',
+ 'deinit',
]);
export function resolveProjectAnchor(
diff --git a/packages/cli/src/ui/confirm.ts b/packages/cli/src/ui/confirm.ts
new file mode 100644
index 000000000..95018176c
--- /dev/null
+++ b/packages/cli/src/ui/confirm.ts
@@ -0,0 +1,14 @@
+import { createInterface } from 'node:readline/promises';
+
+export async function confirmDestructive(
+ prompt: string,
+ input?: NodeJS.ReadableStream,
+): Promise<boolean> {
+ const rl = createInterface({ input: input ?? process.stdin, output: process.stderr });
+ try {
+ const answer = (await rl.question(prompt)).trim().toLowerCase();
+ return answer === 'y' || answer === 'yes';
+ } finally {
+ rl.close();
+ }
+}
diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.ts
index 57b89e3f6..778870c0b 100644
--- a/packages/desktop/src/main/path-install.ts
+++ b/packages/desktop/src/main/path-install.ts
@@ -11,12 +11,19 @@ import {
writeFileSync as fsWriteFileSync,
} from 'node:fs';
import { dirname, join } from 'node:path';
+import {
+ PATH_SHIM_BEGIN as BEGIN,
+ PATH_SHIM_BLOCK_RE as BLOCK_RE,
+ PATH_SHIM_END as END,
+ type PathDiscovery,
+ type PathInstallMarker,
+ pathInstallMarkerPath,
+} from '@inkeep/open-knowledge';
import { wrapperPathInBundle } from './bundle-paths.ts';
+export { pathInstallMarkerPath };
+
const NAMES = ['ok', 'open-knowledge'] as const;
-const BEGIN = '# >>> open-knowledge cli >>>';
-const END = '# <<< open-knowledge cli <<<';
-const BLOCK_RE = /^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;
interface PathInstallFsOps {
existsSync(path: string): boolean;
@@ -50,34 +57,6 @@ const DEFAULT_LOGGER: PathInstallLogger = {
event: (payload) => console.warn(JSON.stringify(payload)),
};
-interface PathDiscovery {
- capturedAt: string;
- pathEntries: string[];
- shellUsed: string;
- okBinAlreadyOnPath: boolean;
-}
-
-interface PathInstallMarker {
- version: 1;
- installedAt: string;
- bundleVersion: string;
- bundleWrapperPath: string;
- binDir: string;
- envShimPath: string;
- rcFiles: string[];
- /** Rc files the user stripped the managed block from — never write to these
- * again. `~/.ok/*` self-heals forever; the user's own rc files get one shot
- * plus refreshes only while the block is still present. */
- rcOptOuts: string[];
- pathDiscovery: PathDiscovery | null;
- extraSymlinks: Array<{
- path: string;
- target: string;
- createdAt: string;
- kind: 'created' | 'refreshed-our-own';
- }>;
-}
-
export type EnsureCliOnPathResult =
| { status: 'skipped'; reason: string }
| { status: 'healthy-current'; marker: PathInstallMarker }
@@ -130,10 +109,6 @@ interface EnsureCliOnPathOpts {
now?: () => Date;
}
-export function pathInstallMarkerPath(home: string): string {
- return join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json');
-}
-
function readMarker(
home: string,
fs: PathInstallFsOps,