Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Restore Desktop silent PATH install — rc-block only, opt-out honored (#1788)
mike-inkeep110f01fbd6ee
diff --git a/.changeset/desktop-silent-path-install-restored.md b/.changeset/desktop-silent-path-install-restored.mdnew file mode 100644index 000000000..1ef6c449e--- /dev/null+++ b/.changeset/desktop-silent-path-install-restored.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++Open Knowledge Desktop again puts the `ok` command on your PATH automatically — politely. Launching the packaged app installs silent terminal shims (`~/.ok/bin/ok` and `~/.ok/bin/open-knowledge` symlinks into the app bundle, a `~/.ok/env.sh` PATH shim, and a clearly marked managed block in your shell rc files — `.zshrc`, plus `.bash_profile` and fish config where present) with no admin prompt. Any user who has run Desktop at least once can type `ok` in a new terminal.++Good-manners guarantees: the edit is disclosed in-app via a sticky toast that names the exact file(s) touched; the block is padded with blank lines and carries an inline opt-out hint; and deleting the block from an rc file is honored permanently — Open Knowledge records the opt-out and never re-adds it to that file. The `~/.ok/bin` shims themselves still self-heal on every startup, and `OK_RECLAIM_DISABLE=1` disables the whole mechanism.++Unlike the earlier incarnation of this feature, Desktop no longer seeds `ok` symlinks into other writable PATH directories (`~/.cargo/bin`, `~/.local/bin`, and the like) to make the command visible in already-open shells — that surprised users more than it helped. Startup now cleans up the symlinks earlier builds recorded, removing each one only while it still points at the recorded bundle target; anything re-pointed or foreign is left alone. The `/usr/local/bin` admin-prompt installer remains retired.diff --git a/packages/app/src/lib/install-onboarding-toast.ts b/packages/app/src/lib/install-onboarding-toast.tsindex 06f5f0fd1..fea989bd4 100644--- a/packages/app/src/lib/install-onboarding-toast.ts+++ b/packages/app/src/lib/install-onboarding-toast.ts@@ -5,7 +5,9 @@ import { relativeToProject } from '@/lib/project-paths';const TOAST_DURATION_MS = 4000;/** "Sticky" toast — large finite duration in lieu of `Infinity`. Used for- * failure outcomes that surface an action item the user must see.+ * failure outcomes that surface an action item the user must see, and for+ * PATH/rc-file edit disclosures — the user must get a real chance to notice+ * that Open Knowledge touched their shell config (and how to undo it).* 24h is long enough to span typical user idle windows; the close button* on the Toaster gives an immediate-dismiss escape hatch. */const STICKY_TOAST_DURATION_MS = 24 * 60 * 60 * 1000;@@ -38,8 +40,9 @@ export function installOnboardingToastListener(opts: {parts.push(`PATH install failed: ${payload.path.summary}`);const message = parts.length > 0 ? parts.join('; ') : 'Open Knowledge integrations checked.';const hasFailure = payload.mcp.status === 'failed' || payload.path.status === 'failed';+ const pathTouched = payload.path.status !== 'none';sonnerToast[hasFailure ? 'error' : 'success'](message, {- duration: hasFailure ? STICKY_TOAST_DURATION_MS : TOAST_DURATION_MS,+ duration: hasFailure || pathTouched ? STICKY_TOAST_DURATION_MS : TOAST_DURATION_MS,});return;}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 40da66e06..ab7654e95 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -166,6 +166,7 @@ import {recordCreateNewBannerShown,recordOnboardingFlow,} from './onboarding-telemetry.ts';+import { type EnsureCliOnPathResult, ensureCliOnPath } from './path-install.ts';import { installStdioBrokenPipeGuard } from './process-safety-net.ts';import {checkAndRepairProjectMcpOnProjectOpen,@@ -1271,21 +1272,35 @@ function armMcpWiring(opts: { forceShow?: boolean } = {}): RunMcpWiringHandle {return runMcpWiringOnFirstLaunch(createMcpWiringOpts(opts));}-function dispatchStartupReclaimToastWhenReady(results: { mcp: McpStartupRepairResult }): void {- const { mcp } = results;+function formatUnknownError(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++function dispatchStartupReclaimToastWhenReady(results: {+ mcp: McpStartupRepairResult;+ path: EnsureCliOnPathResult;+}): void {+ const { mcp, path } = results;+ const pathLeg =+ path.status === 'installed'+ ? ({ status: 'installed', summary: path.summary } as const)+ : path.status === 'failed-all'+ ? ({ status: 'failed', summary: path.error } as const)+ : ({ status: 'none' } as const);if (mcp.status === 'failed') {dispatchToastWhenReady({kind: 'startup-reclaim',mcp: { status: 'failed', editors: mcp.failedEditors.map((f) => f.editor) },- path: { status: 'none' },+ path: pathLeg,});return;}- if (mcp.status !== 'repaired') return;+ const hasMcp = mcp.status === 'repaired';+ if (!hasMcp && pathLeg.status === 'none') return;dispatchToastWhenReady({kind: 'startup-reclaim',- mcp: { status: 'repaired', editors: mcp.repairedEditors },- path: { status: 'none' },+ mcp: hasMcp ? { status: 'repaired', editors: mcp.repairedEditors } : { status: 'none' },+ path: pathLeg,});}@@ -2345,9 +2360,42 @@ function bootPrimaryInstance(): void {});mcpWiringHandle = armMcpWiring();- void checkAndRepairMcpWiringOnStartup(createMcpWiringOpts()).then((mcp) => {- dispatchStartupReclaimToastWhenReady({ mcp });- });+ void Promise.allSettled([+ checkAndRepairMcpWiringOnStartup(createMcpWiringOpts()),+ ensureCliOnPath({+ executablePath: app.getPath('exe'),+ isPackaged: app.isPackaged,+ platform: process.platform,+ forceEnv: process.env.OK_M6B_FORCE ?? null,+ reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,+ home: osHomedir(),+ bundleVersion: app.getVersion(),+ logger: {+ event: (payload) => getLogger('path-install').info(payload, payload.event),+ },+ }),+ ])+ .then(([mcpSettled, pathSettled]) => {+ if (mcpSettled.status === 'rejected') {+ console.warn('[main] MCP startup repair threw', {+ error: formatUnknownError(mcpSettled.reason),+ });+ }+ const mcp: McpStartupRepairResult =+ mcpSettled.status === 'fulfilled'+ ? mcpSettled.value+ : { status: 'failed', failedEditors: [] };+ const path: EnsureCliOnPathResult =+ pathSettled.status === 'fulfilled'+ ? pathSettled.value+ : { status: 'failed-all', error: formatUnknownError(pathSettled.reason) };+ dispatchStartupReclaimToastWhenReady({ mcp, path });+ })+ .catch((err) => {+ console.warn('[main] startup reclaim dispatch threw', {+ error: formatUnknownError(err),+ });+ });const decision = bootRestoreDecision({pendingRestore: appState.pendingWindowRestore,diff --git a/packages/desktop/src/main/path-install.test.ts b/packages/desktop/src/main/path-install.test.tsnew file mode 100644index 000000000..7d0098f21--- /dev/null+++ b/packages/desktop/src/main/path-install.test.ts@@ -0,0 +1,287 @@+import { describe, expect, test } from 'bun:test';+import {+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { ensureCliOnPath, pathInstallMarkerPath } from './path-install.ts';++const EXE = '/Applications/Open Knowledge.app/Contents/MacOS/Open Knowledge';+const WRAPPER = '/Applications/Open Knowledge.app/Contents/Resources/cli/bin/ok.sh';++function home() {+ return mkdtempSync(join(tmpdir(), 'ok-path-install-'));+}++describe('ensureCliOnPath', () => {+ test('installs canonical ~/.ok/bin links, env shim, zsh rc block, and marker without admin prompt', async () => {+ const h = home();+ const result = await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),+ });+ expect(result.status).toBe('installed');+ expect(readlinkSync(join(h, '.ok', 'bin', 'ok'))).toBe(WRAPPER);+ expect(readlinkSync(join(h, '.ok', 'bin', 'open-knowledge'))).toBe(WRAPPER);+ expect(readFileSync(join(h, '.ok', 'env.sh'), 'utf8')).toContain(+ 'export PATH="$' + '{HOME}/.ok/bin:$' + '{PATH}"',+ );+ const zshrc = readFileSync(join(h, '.zshrc'), 'utf8');+ expect(zshrc).toContain('# >>> open-knowledge cli >>>');+ expect(zshrc).toContain('Delete this whole block to opt out');+ expect(JSON.parse(readFileSync(pathInstallMarkerPath(h), 'utf8')).bundleWrapperPath).toBe(+ WRAPPER,+ );+ });++ test('healthy marker fast-path respects disk source of truth', async () => {+ const h = home();+ await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),+ });+ const healthy = await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),+ });+ expect(healthy.status).toBe('healthy-current');+ unlinkSync(join(h, '.ok', 'bin', 'ok'));+ const repaired = await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),+ });+ expect(repaired.status).toBe('installed');+ expect(readlinkSync(join(h, '.ok', 'bin', 'ok'))).toBe(WRAPPER);+ });++ test('honors removal of the managed block — records opt-out, never re-adds, summary discloses', async () => {+ const h = home();+ const run = () =>+ ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),+ });+ const first = await run();+ expect(first.status).toBe('installed');+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('# >>> open-knowledge cli >>>');+ if (first.status === 'installed') expect(first.summary).toContain('~/.zshrc');++ writeFileSync(join(h, '.zshrc'), 'export FOO=1\n');+ const second = await run();+ expect(second.status).toBe('installed');+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).not.toContain('# >>> open-knowledge cli >>>');+ if (second.status === 'installed') expect(second.summary).toContain("won't be re-added");+ const marker = JSON.parse(readFileSync(pathInstallMarkerPath(h), 'utf8'));+ expect(marker.rcOptOuts).toEqual([join(h, '.zshrc')]);++ const third = await run();+ expect(third.status).toBe('healthy-current');+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).not.toContain('# >>> open-knowledge cli >>>');+ });++ test('does not seed symlinks into other PATH dirs and pads the zshrc block with blank lines', async () => {+ const h = home();+ const bin = join(h, 'bin');+ mkdirSync(bin);+ writeFileSync(join(h, '.zshrc'), 'export FOO=1');+ const result = await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${bin}:/usr/bin`, stderr: '' }),+ });+ expect(result.status).toBe('installed');+ expect(() => lstatSync(join(bin, 'ok'))).toThrow();+ expect(() => lstatSync(join(bin, 'open-knowledge'))).toThrow();+ const zshrc = readFileSync(join(h, '.zshrc'), 'utf8');+ expect(zshrc).toContain('export FOO=1\n\n# >>> open-knowledge cli >>>');+ expect(zshrc.endsWith('# <<< open-knowledge cli <<<\n\n')).toBe(true);+ });++ test('removes legacy marker-recorded extra symlinks, leaves re-pointed ones, retries failures', async () => {+ const h = home();+ const bin = join(h, 'bin');+ mkdirSync(bin);+ symlinkSync(WRAPPER, join(bin, 'ok'));+ symlinkSync('/elsewhere/ok.sh', join(bin, 'open-knowledge'));+ const markerPath = pathInstallMarkerPath(h);+ mkdirSync(dirname(markerPath), { recursive: true });+ const entry = (path: string) => ({+ path,+ target: WRAPPER,+ createdAt: '2026-05-01T00:00:00.000Z',+ kind: 'created' as const,+ });+ writeFileSync(+ markerPath,+ JSON.stringify({+ version: 1,+ installedAt: '2026-05-01T00:00:00.000Z',+ bundleVersion: '0.4.0',+ bundleWrapperPath: WRAPPER,+ binDir: join(h, '.ok', 'bin'),+ envShimPath: join(h, '.ok', 'env.sh'),+ rcFiles: [],+ pathDiscovery: null,+ extraSymlinks: [+ entry(join(bin, 'ok')),+ entry(join(bin, 'open-knowledge')),+ entry(join(bin, 'gone')),+ ],+ }),+ );+ const events: Array<Record<string, unknown>> = [];+ const result = await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),+ logger: { event: (e) => events.push(e) },+ });+ expect(result.status).toBe('installed');+ expect(() => lstatSync(join(bin, 'ok'))).toThrow();+ expect(readlinkSync(join(bin, 'open-knowledge'))).toBe('/elsewhere/ok.sh');+ const marker = JSON.parse(readFileSync(markerPath, 'utf8'));+ expect(marker.extraSymlinks).toEqual([]);+ expect(events.some((e) => e.event === 'path-install-extra-symlink-removed')).toBe(true);+ });++ test('skips outside packaged darwin bundle contexts', async () => {+ const h = home();+ const base = {+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: '', stderr: '' }),+ };+ expect(await ensureCliOnPath({ ...base, reclaimDisableEnv: '1' })).toEqual({+ status: 'skipped',+ reason: 'reclaim-disabled',+ });+ expect(await ensureCliOnPath({ ...base, platform: 'linux' })).toEqual({+ status: 'skipped',+ reason: 'platform',+ });+ expect(await ensureCliOnPath({ ...base, isPackaged: false })).toEqual({+ status: 'skipped',+ reason: 'dev-mode',+ });+ expect(await ensureCliOnPath({ ...base, executablePath: '/usr/local/bin/electron' })).toEqual({+ status: 'skipped',+ reason: 'bad-executable-path',+ });+ });++ test('returns failed-all instead of throwing when an fs operation fails', async () => {+ const h = home();+ const enoent = () => Object.assign(new Error('ENOENT'), { code: 'ENOENT' });+ const result = await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),+ fs: {+ existsSync: () => false,+ readFileSync: () => '',+ writeFileSync: () => {},+ mkdirSync: () => {+ throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });+ },+ unlinkSync: () => {},+ symlinkSync: () => {},+ renameSync: () => {},+ readlinkSync: () => {+ throw enoent();+ },+ lstatSync: () => {+ throw enoent();+ },+ },+ logger: { event: () => {} },+ });+ expect(result.status).toBe('failed-all');+ if (result.status === 'failed-all') expect(result.error).toContain('EACCES');+ });++ test('fish conf.d block uses fish syntax, not POSIX export', async () => {+ const h = home();+ await ensureCliOnPath({+ executablePath: EXE,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),+ });+ const fish = readFileSync(join(h, '.config', 'fish', 'conf.d', 'open-knowledge.fish'), 'utf8');+ expect(fish).toContain('# >>> open-knowledge cli >>>');+ expect(fish).toContain('set -gx PATH');+ expect(fish).not.toContain('export PATH');+ });++ test('app update repoints canonical symlinks to the new bundle wrapper', async () => {+ const h = home();+ const opts = (exe: string) => ({+ executablePath: exe,+ isPackaged: true,+ platform: 'darwin',+ home: h,+ bundleVersion: '0.5.0-test',+ env: { HOME: h, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),+ });+ await ensureCliOnPath(opts(EXE));+ const newExe = '/Users/someone/Applications/Open Knowledge.app/Contents/MacOS/Open Knowledge';+ const newWrapper =+ '/Users/someone/Applications/Open Knowledge.app/Contents/Resources/cli/bin/ok.sh';+ const result = await ensureCliOnPath(opts(newExe));+ expect(result.status).toBe('installed');+ expect(readlinkSync(join(h, '.ok', 'bin', 'ok'))).toBe(newWrapper);+ expect(readlinkSync(join(h, '.ok', 'bin', 'open-knowledge'))).toBe(newWrapper);+ });+});diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.tsnew file mode 100644index 000000000..b5547d013--- /dev/null+++ b/packages/desktop/src/main/path-install.ts@@ -0,0 +1,496 @@+import { spawn as nodeSpawn } from 'node:child_process';+import {+ existsSync as fsExistsSync,+ lstatSync as fsLstatSync,+ mkdirSync as fsMkdirSync,+ readFileSync as fsReadFileSync,+ readlinkSync as fsReadlinkSync,+ renameSync as fsRenameSync,+ symlinkSync as fsSymlinkSync,+ unlinkSync as fsUnlinkSync,+ writeFileSync as fsWriteFileSync,+} from 'node:fs';+import { dirname, join } from 'node:path';+import { wrapperPathInBundle } from './bundle-paths.ts';++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;+ readFileSync(path: string, encoding: 'utf8'): string;+ writeFileSync(path: string, content: string): void;+ mkdirSync(path: string, options?: { recursive?: boolean }): void;+ unlinkSync(path: string): void;+ symlinkSync(target: string, path: string): void;+ renameSync(oldPath: string, newPath: string): void;+ readlinkSync(path: string): string;+ lstatSync(path: string): { isSymbolicLink(): boolean };+}++const defaultFsOps: PathInstallFsOps = {+ existsSync: (path) => fsExistsSync(path),+ readFileSync: (path, encoding) => fsReadFileSync(path, encoding),+ writeFileSync: (path, content) => fsWriteFileSync(path, content),+ mkdirSync: (path, options) => fsMkdirSync(path, options),+ unlinkSync: (path) => fsUnlinkSync(path),+ symlinkSync: (target, path) => fsSymlinkSync(target, path),+ renameSync: (oldPath, newPath) => fsRenameSync(oldPath, newPath),+ readlinkSync: (path) => fsReadlinkSync(path),+ lstatSync: (path) => fsLstatSync(path),+};++interface PathInstallLogger {+ event(payload: { event: string; [key: string]: unknown }): void;+}++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 }+ | { status: 'installed'; marker: PathInstallMarker; summary: string }+ | { status: 'failed-all'; error: string };++interface EnsureCliOnPathOpts {+ executablePath: string;+ isPackaged: boolean;+ platform: 'darwin' | 'win32' | 'linux' | string;+ forceEnv?: string | null | undefined;+ reclaimDisableEnv?: string | null | undefined;+ env?: Record<string, string | undefined>;+ home: string;+ bundleVersion: string;+ fs?: PathInstallFsOps;+ spawn?: (+ command: string,+ args: string[],+ opts: { timeoutMs: number; env: Record<string, string | undefined> },+ ) => Promise<{ code: number | null; stdout: string; stderr: string; timedOut?: boolean }>;+ logger?: PathInstallLogger;+ now?: () => Date;+}++export function pathInstallMarkerPath(home: string): string {+ return join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json');+}++function readMarker(+ home: string,+ fs: PathInstallFsOps,+ logger: PathInstallLogger,+): PathInstallMarker | null {+ const path = pathInstallMarkerPath(home);+ if (!fs.existsSync(path)) return null;+ try {+ const parsed = JSON.parse(fs.readFileSync(path, 'utf8')) as PathInstallMarker;+ if (parsed?.version !== 1) {+ logger.event({ event: 'path-install-marker-version-unknown', foundVersion: parsed?.version });+ return null;+ }+ return parsed;+ } catch (err) {+ logger.event({+ event: 'path-install-marker-read-failed',+ error: err instanceof Error ? err.message : String(err),+ });+ return null;+ }+}++function writeMarker(home: string, marker: PathInstallMarker, fs: PathInstallFsOps): void {+ const path = pathInstallMarkerPath(home);+ fs.mkdirSync(dirname(path), { recursive: true });+ fs.writeFileSync(path, `${JSON.stringify(marker, null, 2)}\n`);+}++function okBin(home: string): string {+ return join(home, '.ok', 'bin');+}++function envShim(home: string): string {+ return join(home, '.ok', 'env.sh');+}++const MANAGED_HINT =+ '# ! Contents within this block are managed by Open Knowledge. Do not edit.\n# ! Delete this whole block to opt out — Open Knowledge will not re-add it.';++function block(): string {+ return `${BEGIN}\n${MANAGED_HINT}\n[ -f "$HOME/.ok/env.sh" ] && . "$HOME/.ok/env.sh"\n${END}\n`;+}++function fishBlock(): string {+ return `${BEGIN}\n${MANAGED_HINT}\nif test -d "$HOME/.ok/bin"\n if not contains "$HOME/.ok/bin" $PATH\n set -gx PATH "$HOME/.ok/bin" $PATH\n end\nend\n${END}\n`;+}++function rcTargets(+ home: string,+ shell: string | undefined,+ fs: PathInstallFsOps,+): Array<{ path: string; create: boolean; content: string }> {+ const base = [+ { path: join(home, '.zshrc'), create: shell?.endsWith('/zsh') ?? false, content: block() },+ { path: join(home, '.bash_profile'), create: false, content: block() },+ {+ path: join(home, '.config', 'fish', 'conf.d', 'open-knowledge.fish'),+ create: true,+ content: fishBlock(),+ },+ ];+ return base.filter((t) => t.create || fs.existsSync(t.path));+}++function upsertBlock(path: string, content: string, fs: PathInstallFsOps): boolean {+ const prior = fs.existsSync(path) ? fs.readFileSync(path, 'utf8') : '';+ if (prior.includes(BEGIN) && prior.includes(END)) {+ const next = prior.replace(BLOCK_RE, content);+ if (next !== prior) fs.writeFileSync(path, next.endsWith('\n') ? next : `${next}\n`);+ return next !== prior;+ }+ fs.mkdirSync(dirname(path), { recursive: true });+ const sep =+ prior === '' ? '' : prior.endsWith('\n\n') ? '' : prior.endsWith('\n') ? '\n' : '\n\n';+ fs.writeFileSync(path, `${prior}${sep}${content}\n`);+ return true;+}++function rcBlockHealthy(path: string, fs: PathInstallFsOps): boolean {+ if (!fs.existsSync(path)) return false;+ const text = fs.readFileSync(path, 'utf8');+ return text.includes(BEGIN) && text.includes(END);+}++function linkPointsTo(+ path: string,+ target: string,+ fs: PathInstallFsOps,+ logger?: PathInstallLogger,+): boolean {+ try {+ return fs.readlinkSync(path) === target;+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT' && code !== 'EINVAL') {+ logger?.event({+ event: 'path-install-readlink-unexpected-error',+ path,+ code,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ return false;+ }+}++function canonicalHealthy(+ home: string,+ wrapper: string,+ fs: PathInstallFsOps,+ logger?: PathInstallLogger,+): boolean {+ return NAMES.every((name) => linkPointsTo(join(okBin(home), name), wrapper, fs, logger));+}++function replaceSymlinkAtomic(link: string, wrapper: string, fs: PathInstallFsOps): void {+ const tmp = `${link}.tmp-${process.pid}-${Date.now()}`;+ try {+ fs.unlinkSync(tmp);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;+ }+ fs.symlinkSync(wrapper, tmp);+ try {+ fs.renameSync(tmp, link);+ } catch (err) {+ try {+ fs.unlinkSync(tmp);+ } catch {}+ throw err;+ }+}++function installCanonical(home: string, wrapper: string, fs: PathInstallFsOps): void {+ const bin = okBin(home);+ fs.mkdirSync(bin, { recursive: true });+ for (const name of NAMES) {+ replaceSymlinkAtomic(join(bin, name), wrapper, fs);+ }+}++async function defaultSpawn(+ command: string,+ args: string[],+ opts: { timeoutMs: number; env: Record<string, string | undefined> },+) {+ return new Promise<{ code: number | null; stdout: string; stderr: string; timedOut?: boolean }>(+ (resolve) => {+ const child = nodeSpawn(command, args, {+ env: opts.env as NodeJS.ProcessEnv,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ child.unref();+ let stdout = '';+ let stderr = '';+ let hardKill: NodeJS.Timeout | undefined;+ const timer = setTimeout(() => {+ child.stdout.removeAllListeners('data');+ child.stderr.removeAllListeners('data');+ child.stdout.destroy();+ child.stderr.destroy();+ child.kill();+ hardKill = setTimeout(() => child.kill('SIGKILL'), 1000);+ hardKill.unref();+ resolve({ code: null, stdout, stderr, timedOut: true });+ }, opts.timeoutMs);+ timer.unref();+ child.stdout.on('data', (d) => {+ stdout += String(d);+ });+ child.stderr.on('data', (d) => {+ stderr += String(d);+ });+ child.on('error', (err) => {+ clearTimeout(timer);+ resolve({ code: 1, stdout, stderr: err.message });+ });+ child.on('close', (code) => {+ clearTimeout(timer);+ if (hardKill) clearTimeout(hardKill);+ resolve({ code, stdout, stderr });+ });+ },+ );+}++async function discoverRealInteractivePath(+ opts: EnsureCliOnPathOpts,+): Promise<PathDiscovery | null> {+ const env = opts.env ?? process.env;+ const shell = env.SHELL ?? '/bin/zsh';+ const spawn = opts.spawn ?? defaultSpawn;+ const logger = opts.logger ?? DEFAULT_LOGGER;+ try {+ const result = await spawn(shell, ['-ilc', 'printf %s "$PATH"'], { timeoutMs: 2000, env });+ if (result.code !== 0 || result.timedOut || !result.stdout) {+ logger.event({+ event: 'path-discovery-failed',+ shell,+ code: result.code,+ timedOut: result.timedOut ?? false,+ });+ return null;+ }+ const pathEntries = result.stdout.split(':').filter(Boolean);+ const binDir = okBin(opts.home);+ return {+ capturedAt: (opts.now?.() ?? new Date()).toISOString(),+ pathEntries,+ shellUsed: shell,+ okBinAlreadyOnPath: pathEntries.includes(binDir),+ };+ } catch (err) {+ logger.event({+ event: 'path-discovery-failed',+ shell,+ error: err instanceof Error ? err.message : String(err),+ });+ return null;+ }+}++function removeRecordedExtraSymlinks(+ recorded: PathInstallMarker['extraSymlinks'],+ fs: PathInstallFsOps,+ logger: PathInstallLogger,+): { remaining: PathInstallMarker['extraSymlinks']; removedCount: number } {+ const remaining: PathInstallMarker['extraSymlinks'] = [];+ let removedCount = 0;+ for (const entry of recorded) {+ try {+ const stat = fs.lstatSync(entry.path);+ if (!stat.isSymbolicLink() || fs.readlinkSync(entry.path) !== entry.target) continue;+ fs.unlinkSync(entry.path);+ removedCount += 1;+ logger.event({ event: 'path-install-extra-symlink-removed', path: entry.path });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;+ remaining.push(entry);+ logger.event({+ event: 'path-install-extra-symlink-remove-failed',+ path: entry.path,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ return { remaining, removedCount };+}++function markerHealthy(+ marker: PathInstallMarker,+ home: string,+ wrapper: string,+ fs: PathInstallFsOps,+ logger?: PathInstallLogger,+): boolean {+ if (marker.bundleWrapperPath !== wrapper) return false;+ if (!canonicalHealthy(home, wrapper, fs, logger)) return false;+ if (!marker.rcFiles.every((file) => rcBlockHealthy(file, fs))) return false;+ if (marker.extraSymlinks.length > 0) return false;+ return true;+}++export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<EnsureCliOnPathResult> {+ const {+ executablePath,+ isPackaged,+ platform,+ forceEnv,+ reclaimDisableEnv,+ home,+ bundleVersion,+ fs = defaultFsOps,+ logger = DEFAULT_LOGGER,+ } = opts;+ if (reclaimDisableEnv === '1') return { status: 'skipped', reason: 'reclaim-disabled' };+ if (platform !== 'darwin') return { status: 'skipped', reason: 'platform' };+ if (!isPackaged && forceEnv !== '1') return { status: 'skipped', reason: 'dev-mode' };+ if (!/\.app\/Contents\/MacOS\/[^/]+$/.test(executablePath))+ return { status: 'skipped', reason: 'bad-executable-path' };++ const wrapper = wrapperPathInBundle(executablePath);+ const prior = readMarker(home, fs, logger);+ if (prior && markerHealthy(prior, home, wrapper, fs, logger)) {+ logger.event({ event: 'path-install-healthy-current', binDir: prior.binDir });+ return { status: 'healthy-current', marker: prior };+ }++ let phase:+ | 'installCanonical'+ | 'writeEnvShim'+ | 'discoverPath'+ | 'checkRcHealth'+ | 'upsertRcBlocks'+ | 'cleanupExtraSymlinks'+ | 'writeMarker' = 'installCanonical';+ try {+ logger.event({ event: 'path-install-check-started' });+ installCanonical(home, wrapper, fs);+ phase = 'writeEnvShim';+ const shim = envShim(home);+ fs.mkdirSync(dirname(shim), { recursive: true });+ fs.writeFileSync(+ shim,+ '# Open Knowledge CLI environment — managed file, do not edit.\ncase ":$' ++ '{PATH}:" in\n *:"$' ++ '{HOME}/.ok/bin":*) ;;\n *) export PATH="$' ++ '{HOME}/.ok/bin:$' ++ '{PATH}" ;;\nesac\n',+ );++ phase = 'discoverPath';+ const discovery = await discoverRealInteractivePath(opts);+ phase = 'checkRcHealth';+ const priorOptOuts = prior?.rcOptOuts ?? [];+ const newOptOuts = (prior?.rcFiles ?? []).filter(+ (file) => !priorOptOuts.includes(file) && !rcBlockHealthy(file, fs),+ );+ const rcOptOuts = [...priorOptOuts, ...newOptOuts];+ for (const file of newOptOuts) {+ logger.event({ event: 'path-install-rc-opt-out', path: file });+ }+ const targets = rcTargets(home, (opts.env ?? process.env).SHELL, fs).filter(+ (target) => !rcOptOuts.includes(target.path),+ );+ const activePriorRcFiles = (prior?.rcFiles ?? []).filter((file) => !rcOptOuts.includes(file));+ const canSkipRc =+ prior != null &&+ discovery?.okBinAlreadyOnPath === true &&+ activePriorRcFiles.every((file) => rcBlockHealthy(file, fs));+ phase = 'upsertRcBlocks';+ const rcFiles: string[] = [];+ const changedRcFiles: string[] = [];+ if (canSkipRc && prior) {+ rcFiles.push(...activePriorRcFiles);+ } else {+ for (const target of targets) {+ if (upsertBlock(target.path, target.content, fs)) changedRcFiles.push(target.path);+ rcFiles.push(target.path);+ }+ }+ phase = 'cleanupExtraSymlinks';+ const cleanup = removeRecordedExtraSymlinks(prior?.extraSymlinks ?? [], fs, logger);+ phase = 'writeMarker';+ const marker: PathInstallMarker = {+ version: 1,+ installedAt: (opts.now?.() ?? new Date()).toISOString(),+ bundleVersion,+ bundleWrapperPath: wrapper,+ binDir: okBin(home),+ envShimPath: shim,+ rcFiles,+ rcOptOuts,+ pathDiscovery: discovery,+ extraSymlinks: cleanup.remaining,+ };+ writeMarker(home, marker, fs);+ logger.event({ event: 'path-install-symlink-success', binDir: marker.binDir });+ if (changedRcFiles.length > 0)+ logger.event({ event: 'path-install-rc-append-success', rcFiles: changedRcFiles });+ const tildify = (p: string) => (p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p);+ const parts: string[] = [];+ if (changedRcFiles.length > 0)+ parts.push(+ `Added ok to your PATH — managed block in ${changedRcFiles.map(tildify).join(', ')}.`,+ );+ if (newOptOuts.length > 0)+ parts.push(+ `You removed the Open Knowledge block from ${newOptOuts.map(tildify).join(', ')} — it won't be re-added.`,+ );+ if (cleanup.removedCount > 0)+ parts.push(+ `Removed ${cleanup.removedCount} leftover ok symlink(s) created by an older version.`,+ );+ return {+ status: 'installed',+ marker,+ summary: parts.length > 0 ? parts.join(' ') : 'Installed CLI shims.',+ };+ } catch (err) {+ const error = err instanceof Error ? err.message : String(err);+ const stack = err instanceof Error ? err.stack : undefined;+ logger.event({ event: 'path-install-failed-all', phase, error, stack });+ return { status: 'failed-all', error };+ }+}