Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): install the user-global skill only into detected agent hosts (#820) (#2931)
mike-inkeep42aee4473209
diff --git a/.changeset/user-global-skill-detected-hosts-only.md b/.changeset/user-global-skill-detected-hosts-only.mdnew file mode 100644index 000000000..783c0af8b--- /dev/null+++ b/.changeset/user-global-skill-detected-hosts-only.md@@ -0,0 +1,23 @@+---+"@inkeep/open-knowledge": patch+---++The user-global Agent Skill now installs only into agent hosts you actually have, and nothing is written when you have none.++Previously `ok init` shelled out to `npx -y skills@~1.5.0 add … --agent '*' -g -y --copy`. The `--agent '*'` flag makes that CLI skip its own host detection and write into every host in its registry, so a single `ok init` created 110 directories across 54 tool-config homes in a real `$HOME` — 51 of them for tools that had never been installed, including `.zencoder`, `.terramind`, `.rovodev`, `.snowflake/cortex` and `.tabnine/agent`. Because OK's user-global skills are behavioural instructions autonomous software reads and acts on, that is a scope-of-consent problem, not cosmetic clutter. Neither `--no-mcp` nor `--local-only` suppressed it, and `OK_RECLAIM_DISABLE` / `OK_SKILL_MANAGE` gate a different code path, so there was no way to narrow it short of the undiscoverable `--no-skills`.++The install no longer runs a subprocess at all. OK copies the bundle itself into the skills directory of each detected host — the same `detectPath` probe `ok init` already uses to decide which editors get MCP wiring — plus the shared `~/.agents/skills/` hub those hosts read natively. With no host detected it writes nothing, not even the hub. Nothing about the dependency was load-bearing: OK passed a local path, forced `--copy`, and that CLI writes no lockfile or state at global scope, so it contributed a directory table OK already maintains in core for project scope. Dropping it also removes a floating-range `npx -y` fetch-and-execute at init time and third-party install telemetry (`add-skill.vercel.sh`) that OK never opted out of, and makes the install work where `npx` isn't on `PATH`.++Coverage narrows from that CLI's ~75 hosts to the ones OK supports and tests — Claude Code, Cursor, Codex, and OpenCode — which is the same set `ok init` already wires MCP for.++`ok repair-skills` now also cleans up after the old behaviour. It removes OK's own `open-knowledge*` skill directories from the agent homes a pre-0.42 fan-out reached but OK never supported, and then removes those agent homes themselves when OK's skill was the only thing in them — otherwise the fix would leave ~47 empty directories behind and a home-directory diff would look much as it did before. On a home left by the old build that is 54 top-level entries down to 9.++The prune is not conditional on there being a skill to delete: a machine swept by an interim build has the skills already gone and only empty `~/.<host>/skills/` husks left, and keying the walk off a fresh deletion would make those unreachable forever. `ok repair-skills` removes them on their own.++Deleting from `$HOME` is exactly what issue #820 was about, so the cleanup asks first. It prints every path it would remove, says plainly that each agent home is going because it holds nothing once OK's skill is gone, and waits for confirmation; a bare Enter declines. `--yes` skips the prompt, and a non-interactive run without it declines rather than deleting unattended. It is deliberately **not** wired into `ok init`.++It also refuses to descend through a symlink: agent hosts commonly symlink their `skills/` dir at the shared `~/.agents/skills` hub, and following one could delete a live install — or a user directory — through the link, so any symlinked ancestor disqualifies that host entirely. `applyLegacyFanoutSweep` re-derives the set of paths it is allowed to touch and aborts without deleting anything if handed one outside it, and both entry points reject a non-absolute home (an empty one would silently retarget the sweep at the process's working directory).++Three further bounds keep it conservative: only directories named in a frozen list of the agent homes that one shipped version wrote to (never a path discovered by walking the filesystem), only directories that are empty afterwards — a tool you actually use keeps its folder, and the removal goes through `rmdir`, which refuses a non-empty directory even if something appears between the prompt and the delete — and never a shared root, so `~/.config/goose` goes while `~/.config` stays.++The `ok init` summary now names the hosts it wrote to (`installed for Claude, Cursor`) instead of claiming `installed to detected agent hosts` while detection had been bypassed, reports when no host was found, and points failures at `ok repair-skills` rather than a manual `npx` command. The `@inkeep/open-knowledge` package no longer declares a `postinstall` script; it never worked (the symbol it imported was never exported from the published bundle) and would have fanned out with no consent gate had it been repaired.diff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex 081927ce9..df01e34ea 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -207,6 +207,24 @@ The rule does NOT catch: bare `exec(...)` (the identifier is too commonly shadowPlugin: [`biome-plugins/require-windowshide-on-spawn.grit`](require-windowshide-on-spawn.grit). Fixture: [`biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx`](__fixtures__/require-windowshide-on-spawn.fixture.tsx). Test: [`packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts`](../packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+### `no-blind-agent-host-fanout.grit`++Scope discipline for user-global Agent Skill installs. Bans the `skills` CLI npm specs (`skills@~1.5.0` and its caret / exact / `latest` variants) and the bare `'--agent'` argv token anywhere under `packages/{server,cli}/src/**`.++**Why.** `installUserSkill` used to shell out to `npx -y skills@~1.5.0 add <dir> --agent '*' -g -y --copy`. `--agent '*'` makes that CLI skip its own host detection and target every host in its registry (~75 and growing), so a single `ok init` wrote 110 directories across 54 tool-config homes in a real `$HOME` — 51 of them for tools the reporter had never installed ([issue #820](https://github.com/inkeep/open-knowledge/issues/820)). OK's user-global skills are behavioural instructions autonomous software reads and acts on, so writing one into a tool's config dir is a scope-of-consent decision, not cosmetic clutter.++Nothing about the dependency was load-bearing: OK passed a local path (no source resolution), forced `--copy` (no symlinks), and the CLI writes no lockfile or state at global scope. It contributed a directory table that OK already maintains in core for project scope — while costing a floating-range `npx -y` fetch-and-execute at init time and third-party telemetry OK never opted out of. The install now writes directly, gated on `detectUserSkillHosts`, whose host set derives from `HOSTS_WITH_USER_SKILL_DIR` in [`packages/core/src/constants/editors.ts`](../packages/core/src/constants/editors.ts).++The rule bans the *ingredients* rather than the assembled command line, because the argv was built as an array of literals that no single AST node spans.++**Scoped via `overrides[].plugins`** to `packages/{server,cli}/src/**/*.ts`. Tests are deliberately **in** scope (unlike the sibling spawn rule): a test that reintroduces the invocation reintroduces the fan-out, and the suite asserts the writer's behavior through the filesystem, never through argv.++The rule does NOT catch a spec assembled by concatenation or interpolation (`` `skills@${range}` ``), or the flag reaching a subprocess through a variable — GritQL matches the string-literal node. Both are defeatable-on-purpose rather than accidental; the behavioural backstop is [`packages/server/src/skill-install.test.ts`](../packages/server/src/skill-install.test.ts), whose "never creates a dotdir for a host that is not installed" case asserts the real filesystem outcome.++Adding a host that needs a different install mechanism? Add it to `HOSTS_WITH_USER_SKILL_DIR` and let the detection gate cover it — don't suppress this rule.++Plugin: [`biome-plugins/no-blind-agent-host-fanout.grit`](no-blind-agent-host-fanout.grit). Fixture: [`biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsx`](__fixtures__/no-blind-agent-host-fanout.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts`](../packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+## SuppressionInline `// biome-ignore` comments silence individual diagnostics. The most specific form names the rule and the reason:diff --git a/biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsx b/biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsxnew file mode 100644index 000000000..15bd107f9--- /dev/null+++ b/biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsx@@ -0,0 +1,55 @@+/**+ * Fixture for `no-blind-agent-host-fanout.grit`.+ *+ * Pairs 5 positive cases (the `skills` CLI npm specs OK used to shell out to,+ * plus the bare `--agent` argv token whose `'*'` value caused issue #820 —+ * plugin MUST fire) with negative cases (an unrelated `'skills'` word, a+ * similarly-spelled flag, a comment mention, a template literal, and a+ * concatenation — plugin must NOT fire). The fixture-file test asserts the+ * diagnostic count with exact equality (`toBe(5)`) so both a weakened pattern+ * (drops below 5) and a widened pattern that catches a negative (rises above 5)+ * fail the gate.+ *+ * The template-literal and concatenation negatives are the honest precision+ * boundary: GritQL matches the string-literal node, so a spec assembled at+ * runtime slips through. That is a defeatable-on-purpose escape, not an+ * accidental reintroduction — the behavioural backstop is the filesystem+ * assertion in `packages/server/src/skill-install.test.ts` ("never creates a+ * dotdir for a host that is not installed").+ *+ * Deliberately NOT linted by the main `pnpm lint` pass (biome-plugins/ is+ * outside the lint paths); only the scoped override in biome.jsonc reaches it,+ * via the fixture-file test.+ */++declare const range: string;+declare function spawn(cmd: string, args: readonly string[]): void;++function positives() {+ // P1-P4: every npm spec shape for the `skills` CLI OK used to fetch-and-exec.+ spawn('npx', ['-y', 'skills@~1.5.0', 'add', '.']);+ spawn('npx', ['-y', 'skills@^1.5.0', 'add', '.']);+ spawn('npx', ['-y', '[email protected]', 'add', '.']);+ spawn('npx', ['-y', 'skills@latest', 'add', '.']);+ // P5: the flag itself — the incident was its `'*'` value, but the flag only+ // exists to address that CLI, so the token is the reintroduction signal.+ spawn('npx', ['add', '.', '--agent', '*']);+}++function negatives() {+ // N1: the bare word, unrelated to the npm spec.+ spawn('ok', ['skills', 'list']);+ // N2-N3: similarly-spelled flags that are not the banned token.+ spawn('ok', ['--agents', 'claude']);+ spawn('ok', ['--agent-id', 'abc']);+ // N4: a comment mentioning `npx skills@~1.5.0 add --agent '*'` — GritQL+ // matches string-literal nodes, never trivia, so prose describing the old+ // invocation (as the real module's docstring does) must stay silent.+ spawn('ok', ['repair-skills']);+ // N5: interpolation — no single node holds the whole value.+ spawn('npx', [`skills@${range}`, 'add', '.']);+ // N6: concatenation — likewise.+ spawn('npx', [`skills@${''}${range}`, 'add', '.']);+}++export { positives, negatives };diff --git a/biome-plugins/no-blind-agent-host-fanout.grit b/biome-plugins/no-blind-agent-host-fanout.gritnew file mode 100644index 000000000..63de372bc--- /dev/null+++ b/biome-plugins/no-blind-agent-host-fanout.grit@@ -0,0 +1,59 @@+// no-blind-agent-host-fanout — user-global skill installs must be detection-gated.+//+// OK's user-global Agent Skills are behavioural instructions autonomous software+// reads and acts on. Writing them into a tool's config dir is a scope-of-consent+// decision, so it is allowed ONLY for hosts detected on disk.+//+// The regression this prevents (issue #820): `installUserSkill` shelled out to+//+// npx -y skills@~1.5.0 add <dir> --agent '*' -g -y --copy+//+// `--agent '*'` makes that CLI skip its own host detection and target every host+// in its registry (~75 and growing). One `ok init` created 110 directories across+// 54 tool-config homes in a real `$HOME`; 51 of those tools were never installed.+// The invocation shipped in v0.3.0 and survived 15 months because the spec's own+// open question about `--agent '*'`'s behavior (Q10) was never closed, while the+// code's doc comment and the terminal summary both asserted the OPPOSITE — that+// OK had detected the user's hosts.+//+// The rule bans the ingredients rather than the assembled command line, because+// the argv is built as an array of literals that no single node spans:+// - any `skills@…` npm spec — OK writes user-global skills itself now+// (`installUserSkill` in `packages/server/src/skill-install.ts`), gated on+// `detectUserSkillHosts`. There is no supported reason to re-introduce the+// subprocess; it also cost a floating-range fetch-and-execute at init time+// and third-party telemetry OK never opted out of.+// - a bare `'--agent'` argv token — the flag only exists to address that CLI,+// and `'*'` is the value that caused the incident.+//+// Scoped via `overrides[].plugins` to `packages/{server,cli}/src/**` — where the+// user-global install lives. Tests are NOT excluded: a test that reintroduces the+// invocation is exactly as load-bearing as production code here, and the suite+// asserts the writer's behavior through the filesystem, never through argv.+//+// Does NOT catch (documented honestly): a spec string assembled by concatenation+// or interpolation (`'skills@' + range`), or the flag reaching a subprocess via a+// variable. Both are defeatable-on-purpose, not accidental reintroductions; the+// filesystem assertions in `skill-install.test.ts` ("never creates a dotdir for a+// host that is not installed") are the behavioural backstop.+//+// If a future host genuinely needs a different install mechanism, add it to+// `HOSTS_WITH_USER_SKILL_DIR` in `packages/core/src/constants/editors.ts` and let+// the detection gate cover it — do not suppress this rule.+//+// See PRECEDENTS.md #42 (custom Biome enforcement is GritQL plugins).++language js++or {+ `'skills@~1.5.0'` as $lit,+ `'skills@^1.5.0'` as $lit,+ `'[email protected]'` as $lit,+ `'skills@latest'` as $lit,+ `'--agent'` as $lit+} where {+ register_diagnostic(+ span = $lit,+ message = "User-global skill installs must be gated on detected hosts, not fanned out via the `skills` CLI's `--agent '*'`. OK writes these dirs itself — use `installUserSkill` / `detectUserSkillHosts` from @inkeep/open-knowledge-server, whose host set comes from core's `HOSTS_WITH_USER_SKILL_DIR`. `--agent '*'` bypasses host detection and creates config dirs for tools the user never installed (issue #820: 51 such dirs from one `ok init`). See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-blind-agent-host-fanoutgrit"+ )+}diff --git a/biome.jsonc b/biome.jsoncindex 303c81198..fcd4e8387 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -122,6 +122,22 @@],"plugins": ["./biome-plugins/require-windowshide-on-spawn.grit"]},+ {+ // Scope discipline for user-global Agent Skill installs (issue #820).+ // OK writes these dirs itself, gated on `detectUserSkillHosts`; shelling+ // out to the `skills` CLI with `--agent '*'` bypasses host detection and+ // creates config dirs for tools the user never installed. Scoped to+ // server + cli (where the user-global install lives). Tests are NOT+ // excluded — a test reintroducing the invocation is as load-bearing as+ // production code, and the suite asserts through the filesystem, never+ // through argv.+ "includes": [+ "packages/server/src/**/*.ts",+ "packages/cli/src/**/*.ts",+ "biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsx"+ ],+ "plugins": ["./biome-plugins/no-blind-agent-host-fanout.grit"]+ },{// One-shot `expect(await locator.count())` reads never retry and are// the canonical hidden-flake assertion shape (2026-06 e2e audit).diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 1139bc8ae..1576bf9df 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -137,20 +137,15 @@ The **Install for Claude Chat & Cowork** command (command palette or Help menu)### Installing the package-Installing `@inkeep/open-knowledge` from npm (or invoking it with `npx`) drops the two CLI binaries plus a bundled native addon, and runs a `postinstall` step that registers a small "discovery" skill so the AI editors on your machine know OpenKnowledge exists.+Installing `@inkeep/open-knowledge` from npm (or invoking it with `npx`) drops the two CLI binaries plus a bundled native addon. **Nothing is written to your home directory at install time** — no lifecycle scripts run, and no skills are registered until you run `ok init`.| Path | What it is | Scope || --- | --- | --- || `ok`, `open-knowledge` (on your `PATH`) | The two CLI binaries (identical entry point) | Outside-project (npm global/bin) || `<pkg>/dist/native/` | Bundled native TOML-editing addon, shipped inside the package | Outside-project (package dir) |-| `~/.agents/skills/open-knowledge-discovery/` | The **discovery skill** — a short instruction file that teaches any agent host how to find and initialize OpenKnowledge. Installed via `npx skills add … --agent '*' -g` | Outside-project (home dir) |-| `~/.ok/skill-state.yml` | Records which skill version is installed, so the step is skipped next time | Outside-project (home dir) |-| `~/.ok/skill-install-events.jsonl` | Append-only local log of skill-install attempts | Outside-project (home dir) |--The `postinstall` step is **non-fatal** (install always succeeds even if it fails) and **version-gated** (it does nothing if the current version is already installed). It installs the discovery skill for every detected agent host: the shared `~/.agents/skills/` directory and each detected editor's user-level skills folder (`~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`). The only network access is npm fetching the `skills` helper.<Callout type="info" title="Opt out">- Install with `npm install --ignore-scripts` to skip the `postinstall` skill step entirely. You can always add the skills later from `ok init`.+ Installing the package writes nothing outside its own directory, so there is nothing to opt out of here. The user-global skills are installed by `ok init`, and `ok init --no-skills` declines them.</Callout>### `ok init`@@ -183,6 +178,20 @@ With `--scope user` or `both` (the default), `ok init` also registers the `open-| `~/.lmstudio/mcp.json` | LM Studio (only when installed; also checks `~/.cache/lm-studio/mcp.json`) | Outside-project (editor config) || `~/.hermes/config.yaml` | Hermes (only when `~/.hermes/` exists) | Outside-project (editor config) |+`ok init` also installs the user-global **discovery skill** — a short instruction file that teaches an agent host how to find and initialize OpenKnowledge — so it is available in every project. It is written **only** into the skills directories of agent hosts already present in your home directory, plus the shared `~/.agents/skills/` hub those hosts read. If none of them is present, nothing is written at all.++| Path | What it is | Scope |+| --- | --- | --- |+| `~/.agents/skills/open-knowledge-*/` | Shared hub read natively by Codex, OpenCode, and Cursor | Outside-project (home dir) |+| `~/.claude/skills/open-knowledge-*/` | Written only when `~/.claude/` already exists | Outside-project (home dir) |+| `~/.cursor/skills/open-knowledge-*/` | Written only when `~/.cursor/` already exists | Outside-project (home dir) |+| `~/.codex/skills/open-knowledge-*/` | Written only when `~/.codex/` already exists | Outside-project (home dir) |+| `~/.opencode/skills/open-knowledge-*/` | Written only when `~/.opencode/` already exists | Outside-project (home dir) |+| `~/.ok/skill-state.yml` | Records which skill version is installed, so the step is skipped next time | Outside-project (home dir) |+| `~/.ok/skill-install-events.jsonl` | Append-only local log of skill-install attempts | Outside-project (home dir) |++The install is **non-fatal** (`ok init` still exits 0 if it fails), **version-gated** (a no-op when the current version is already installed), and needs **no network access**. Decline it with `ok init --no-skills`, or choose individual bundles with `--skills <ids>`; the decision is remembered in `~/.ok/skill-state.yml` and honored by every later install path. `ok repair-skills` re-runs it.+Pi is the exception: it has no user-level MCP config (it has no MCP support at all), so its integration is only ever the project-scoped bridge extension above.On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` and `%APPDATA%\opencode\`, and the MCP entry is a PowerShell launcher.diff --git a/packages/app/src/components/InstallInClaudeDesktopDialog.tsx b/packages/app/src/components/InstallInClaudeDesktopDialog.tsxindex 2aaf7b06e..6e5a8794d 100644--- a/packages/app/src/components/InstallInClaudeDesktopDialog.tsx+++ b/packages/app/src/components/InstallInClaudeDesktopDialog.tsx@@ -19,7 +19,7 @@ import { cn } from '@/lib/utils';* `InstallInClaudeDesktopDialog` — concierge for installing the Open* Knowledge skill for **Claude Chat & Cowork** inside the **Claude Desktop* App**. Distinct from Claude (CLI / Code tab) which is already covered- * by `ok init`'s `npx skills add` flow.+ * by `ok init`'s user-global skill install.** Runtime branches on `'okDesktop' in window`:* - Electron: calls `window.okDesktop.skill.buildAndOpen()` — main processdiff --git a/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts b/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.tsnew file mode 100644index 000000000..ddbc3d604--- /dev/null+++ b/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts@@ -0,0 +1,105 @@+/**+ * no-blind-agent-host-fanout — Biome GritQL plugin fixture test.+ *+ * Plugin: `biome-plugins/no-blind-agent-host-fanout.grit`+ * Fixture: `biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsx`+ *+ * Per precedent #42 (custom Biome enforcement is GritQL plugins). Forbids+ * re-introducing the `npx skills … --agent '*'` shell-out that made `ok init`+ * create skill directories in every host the third-party CLI knows about,+ * including ~51 for tools the user had never installed (issue #820). OK now+ * writes the user-global bundle itself, gated on `detectUserSkillHosts`.+ *+ * Three guarantees, each its own test:+ * 1. Fires on exactly the planted positives (and on no negative) — the+ * bidirectional `toBe(5)` count, plus the diagnostic-message contract.+ * 2. Registered as an override scoped to the packages that own the install,+ * with tests deliberately IN scope.+ * 3. The banned npm-spec arms cover every range shape of the pinned spec the+ * incident shipped with, so a caret/exact/latest variant can't slip past a+ * guard written only against the tilde form.+ */++import { spawnSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';++// __dirname → packages/app/tests/lint-plugins/. OK subtree root is 4 levels up.+const REPO_ROOT = join(__dirname, '..', '..', '..', '..');+const FIXTURE_REL = 'biome-plugins/__fixtures__/no-blind-agent-host-fanout.fixture.tsx';+const PLUGIN_REL = './biome-plugins/no-blind-agent-host-fanout.grit';+const GRIT_ABS = join(REPO_ROOT, 'biome-plugins/no-blind-agent-host-fanout.grit');++describe('no-blind-agent-host-fanout GritQL plugin', () => {+ test('fires on exactly 5 planted positives (and on no negative case)', () => {+ const result = spawnSync('pnpm', ['exec', 'biome', 'check', FIXTURE_REL], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ });+ // Surface a spawn failure explicitly: without this, `status` is null on a+ // `pnpm exec` spawn error and the `not.toBe(0)` below passes vacuously,+ // masking the failure as "0 diagnostics".+ expect(result.error).toBeUndefined();+ // biome check exits non-zero when any diagnostic (incl. plugin) fires.+ expect(result.status).not.toBe(0);+ const output = `${result.stdout}\n${result.stderr}`;+ const fires = (+ output.match(/User-global skill installs must be gated on detected hosts/g) ?? []+ ).length;+ expect(fires).toBe(5);+ // Diagnostic names the replacement API, not just the prohibition.+ expect(output).toContain('detectUserSkillHosts');+ expect(output).toContain('HOSTS_WITH_USER_SKILL_DIR');+ // Diagnostic message appends a docs URL — generic URL regex + anchor+ // substring, so the regex can't be vacuously satisfied by an unrelated URL.+ expect(output).toMatch(/https?:\/\/[^\s]+/);+ expect(output).toContain('biome-plugins/README.md#no-blind-agent-host-fanoutgrit');+ });++ test('registered as an override over the packages that own the install, tests included', () => {+ const config = readBiomeConfig(REPO_ROOT);+ // NOT at root plugins[] — the workspace has legitimate `--agent` argv in+ // unrelated surfaces (ACP agent spawning), so a workspace-wide promotion+ // would redden `pnpm lint`.+ const rootPlugins: string[] = config.plugins ?? [];+ expect(rootPlugins).not.toContain(PLUGIN_REL);++ const overrides: Array<{ includes?: string[]; plugins?: string[] }> = config.overrides ?? [];+ const entry = overrides.find((o) => (o.plugins ?? []).includes(PLUGIN_REL));+ expect(entry).toBeDefined();+ const includes = entry?.includes ?? [];+ // The fixture must be in scope so the firing test above can trigger the rule.+ expect(includes).toContain(FIXTURE_REL);+ // Both packages that can reach the user-global install must be covered.+ expect(includes).toContain('packages/server/src/**/*.ts');+ expect(includes).toContain('packages/cli/src/**/*.ts');+ // Tests are deliberately IN scope, unlike the sibling spawn rule: a test+ // that re-introduces the shell-out would re-introduce the fan-out. Assert+ // no test-exclusion crept in.+ for (const excluded of ['!**/*.test.ts', '!**/*.test-helper.ts']) {+ expect(includes).not.toContain(excluded);+ }+ });++ test('bans every range shape of the spec, not just the one that shipped', () => {+ // Strip `//` comment lines so the docstring's illustrative `skills@~1.5.0`+ // mention is not mistaken for an `or {}` arm.+ const gritArms = readFileSync(GRIT_ABS, 'utf-8')+ .split('\n')+ .filter((line) => !line.trimStart().startsWith('//'))+ .join('\n');+ const matched = [...gritArms.matchAll(/`'([^']+)'`/g)].map((m) => m[1]).sort();+ // Non-vacuity: a failed extraction would make the subset checks below pass+ // against an empty set.+ expect(matched.length).toBeGreaterThan(0);+ // `~` is what v0.3.0 shipped; the other three are the shapes a well-meaning+ // "let's pin it properly" or "let's float it" edit would reach for.+ for (const spec of ['skills@~1.5.0', 'skills@^1.5.0', '[email protected]', 'skills@latest']) {+ expect(matched).toContain(spec);+ }+ // The flag token itself — the `'*'` value is what bypassed host detection.+ expect(matched).toContain('--agent');+ });+});diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 1040e2be6..fbfb2fb4d 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -40,7 +40,6 @@"build:schema": "node --import tsx --conditions=development scripts/build-config-schema.mjs","build:assets": "pnpm run build:app && pnpm run build:skill-asset && pnpm run build:notices && pnpm run build:license && pnpm run build:native && pnpm run build:schema","build": "pnpm run build:cli && pnpm run build:assets",- "postinstall": "node scripts/postinstall.mjs","test": "pnpm run build:schema && vitest run","test:e2e:cli": "vitest run --config vitest.e2e.config.ts","typecheck": "tsc --noEmit",diff --git a/packages/cli/scripts/postinstall.mjs b/packages/cli/scripts/postinstall.mjsdeleted file mode 100644index f4b4ccb29..000000000--- a/packages/cli/scripts/postinstall.mjs+++ /dev/null@@ -1,52 +0,0 @@-#!/usr/bin/env node-/**- * `@inkeep/open-knowledge` postinstall hook.- *- * Fires `installUserSkill()` once per `npm install` / `bun install` / `npx`- * cache population. Non-fatal: any failure is swallowed so the host install- * never blocks.- *- */--async function run() {- let installUserSkill;- try {- // Relative import resolves inside the published npm tarball at- // <pkg-root>/dist/index.mjs — the tsdown-bundled entry that re-exports- // `installUserSkill` from @inkeep/open-knowledge-server.- const mod = await import('../dist/index.mjs');- installUserSkill = mod.installUserSkill;- } catch {- // Dev-install scenarios (e.g. running `npm install` against a tarball- // where dist/ is missing, `--ignore-scripts`, or source-only installs)- // never block — fall through to exit 0.- return;- }-- if (typeof installUserSkill !== 'function') return;-- let result;- try {- result = await installUserSkill();- } catch {- // installUserSkill is documented as never-throws; this catch is pure- // defensive hardening so a broken build never blocks `npm install`.- return;- }-- if (result === 'installed') {- process.stdout.write('[open-knowledge] Agent Skill installed to detected agent hosts.\n');- } else if (result === 'failed') {- process.stderr.write(- '[open-knowledge] Agent Skill auto-install failed; run manually: ' +- "npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy\n",- );- }- // result === 'skip-current' → silent.-}--// Fire-and-forget. Always exit 0 regardless of outcome —-// `npm install` must never fail because skill-install hit an edge case.-run().finally(() => {- process.exit(0);-});diff --git a/packages/cli/src/commands/cowork.ts b/packages/cli/src/commands/cowork.tsindex ee4029e75..c6b349538 100644--- a/packages/cli/src/commands/cowork.ts+++ b/packages/cli/src/commands/cowork.ts@@ -19,9 +19,9 @@* 4. User completes the manual upload inside the Claude Desktop App:* Customize → Skills → + → Create skill → Upload skill → pick file.*- * Why this exists: `ok init` installs the skill into Claude via `npx skills- * add`, but that flow doesn't reach Claude Chat or Cowork modes (they read from- * a separate, isolated Skills list inside the Claude Desktop App).+ * Why this exists: `ok init` installs the skill into Claude's user-global+ * skills dir, but that flow doesn't reach Claude Chat or Cowork modes (they+ * read from a separate, isolated Skills list inside the Claude Desktop App).** The underlying `buildAndOpenSkill` lives in `@inkeep/open-knowledge-server`* (alongside `buildSkillZip`). The `POST /api/install-skill` endpoint and thediff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.tsindex be46d08a1..fa637fc26 100644--- a/packages/cli/src/commands/init.test.ts+++ b/packages/cli/src/commands/init.test.ts@@ -104,9 +104,9 @@ describe('runInit', () => {},});/**- * Stubbed installUserSkill used by every test unless overridden. Prevents- * the real `npx skills` subprocess from firing in the test suite, keeping- * runs hermetic + fast.+ * Stubbed installUserSkill used by every test unless overridden. Keeps the+ * real installer from copying bundles into the runner's `$HOME`, so runs+ * stay hermetic + fast.*/const defaultInstallUserSkill = async () => 'installed' as const;const runInitForTest = async (options: Parameters<typeof runInit>[0] = {}) =>@@ -916,7 +916,7 @@ describe('runInit', () => {const beforeClaude = readFileSync(claudePath, 'utf-8');const beforeAgents = readFileSync(agentsPath, 'utf-8');- // Run init with a no-op skill install so we don't shell out to `npx skills`.+ // Run init with a no-op skill install so nothing touches the real $HOME.await runInitForTest({ installUserSkill: async () => 'skip-current' });// Byte-identical pre/post — the new init code does NOT touch legacy injections.@@ -937,7 +937,33 @@ describe('runInit', () => {expect(result.skillInstall).toBe('installed');const output = formatInitResult(result, testDir);expect(output).toContain('User-global skill:');- expect(output).toContain('installed to detected agent hosts');+ // The summary must name real targets. It previously claimed "detected+ // agent hosts" while the install had bypassed detection entirely and+ // written into ~75 tool dirs (issue #820) — an install summary must never+ // assert more scope discipline than the install actually applied.+ expect(output).toContain('installed for');+ expect(output).not.toContain('detected agent hosts');+ });++ it('reports the hosts actually written, never an unverified claim (issue #820)', async () => {+ // `.claude` is the only host dotdir staged under the fake home, so the+ // summary must name Claude and nothing else.+ mkdirSync(join(fakeHome, '.claude'), { recursive: true });+ const result = await runInitForTest({+ installUserSkill: async () => 'installed',+ });+ expect(result.skillHosts).toEqual(['claude']);+ expect(formatInitResult(result, testDir)).toContain('installed for Claude');+ });++ it('returns skillInstall = "no-hosts" when no agent host is present', async () => {+ const result = await runInitForTest({+ installUserSkill: async () => 'no-hosts',+ });+ expect(result.skillInstall).toBe('no-hosts');+ expect(result.skillHosts).toEqual([]);+ const output = formatInitResult(result, testDir);+ expect(output).toContain('no supported agent host detected');});it('returns skillInstall = "skip-current" when the sidecar is current', async () => {@@ -960,7 +986,10 @@ describe('runInit', () => {// Manual-install hint surfaces in the summaryconst output = formatInitResult(result, testDir);expect(output).toContain('install failed');- expect(output).toContain('npx skills');+ // Recovery is OK's own command — the hint no longer points at a+ // third-party CLI OK doesn't invoke (issue #820).+ expect(output).toContain('ok repair-skills');+ expect(output).not.toContain('npx skills');});it('passes opts.home through to installUserSkill (D15)', async () => {@@ -1154,11 +1183,10 @@ describe('runInit', () => {describe('ensureProjectGit wiring (US-005)', () => {it('fresh tmpdir (no .git/) → runInit creates .git/ and reports didGitInit=true', async () => {// Use runInitForTest (defaultInstallUserSkill stub) — the real- // installUserSkill shells out to `npx skills@~1.5.0 add` which- // intermittently fails in CI sandboxes (subprocess returns nonzero- // with empty stderr; exit code null) and times out the 5s budget.- // The git-init wiring under test is independent of skill install,- // so the hermetic stub is the right scope.+ // installUserSkill copies the bundle into every detected agent host+ // under `$HOME`, which this test has no reason to touch. The git-init+ // wiring under test is independent of skill install, so the hermetic+ // stub is the right scope.const result = await runInitForTest({ editors: ['claude'] });expect(result.didGitInit).toBe(true);diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 42165d91d..fdde17def 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -25,6 +25,7 @@ import type {} from '@inkeep/open-knowledge-server';import {BUNDLE_SKILL_NAME,+ detectUserSkillHosts,ensureProjectGit,ensureProjectSkillGitignore,GitNotAvailableError,@@ -81,6 +82,7 @@ import { accent, dim, error, info, success, warning } from '../ui/colors.ts';import { isObject } from '../utils/is-object.ts';import {ALL_EDITOR_IDS,+ EDITOR_LABELS,EDITOR_TARGETS,type EditorId,type EditorMcpTarget,@@ -841,6 +843,13 @@ interface InitCommandResult {* step could run.*/skillInstall?: InstallUserSkillResult | 'declined';+ /**+ * Agent hosts the user-global skill was actually written to, as editor ids.+ * Empty unless `skillInstall === 'installed'`. Reported verbatim in the+ * summary so the line names real targets instead of claiming detection that+ * did not happen (issue #820).+ */+ skillHosts?: readonly string[];/** Content preview result (undefined if preview failed or was not run). */preview?: PreviewResult;/** `true` if `ensureProjectGit` ran `git init` during this invocation. */@@ -1813,6 +1822,7 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitComlet anyInstalled = false;let anyFailed = false;let anySkipped = false;+ let anyNoHosts = false;for (const id of USER_GLOBAL_BUNDLE_IDS) {const enabled = enabledBundles.has(id);await writeBundleDecision(skillHome, BUNDLE_SKILL_NAME[id], enabled).catch(() => {});@@ -1823,6 +1833,7 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitComconst result = await installSkill({ home: options.home, bundleId: id, force: true });if (result === 'installed') anyInstalled = true;else if (result === 'failed') anyFailed = true;+ else if (result === 'no-hosts') anyNoHosts = true;else anySkipped = true;} else {try {@@ -1843,7 +1854,12 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom? 'installed': anyEnabled && anySkipped? 'skip-current'- : 'declined';+ : anyEnabled && anyNoHosts+ ? 'no-hosts'+ : 'declined';+ // Named so the summary can report the hosts actually written rather than+ // asserting an unverified "detected agent hosts" (issue #820).+ const skillHosts = anyInstalled ? detectUserSkillHosts(skillHome).map((h) => h.editorId) : [];// Derive backward-compat fields from the Claude entry (preferred) or first resultconst defaultAction: EditorMcpResult['action'] = skipMcp ? 'skipped-flag' : 'skipped-missing';@@ -1879,6 +1895,7 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitComprojectSkills: projectSkillResults,legacyProjectConfigs,skillInstall,+ skillHosts,didGitInit: gitResult.didInit,rootGitignoreCreated,gitRootPromoted: resolution.gitRootPromoted,@@ -2189,24 +2206,33 @@ export function formatInitResult(result: InitCommandResult, cwd: string): stringlines.push('');lines.push(accent('User-global skill:'));switch (result.skillInstall) {- case 'installed':- lines.push(- ` open-knowledge ${success('installed to detected agent hosts')} via \`npx skills\``,+ case 'installed': {+ // Name the hosts. The previous copy claimed "detected agent hosts"+ // while the install had bypassed detection entirely (issue #820) — an+ // install summary must never assert more scope discipline than it used.+ const hostLabels = (result.skillHosts ?? []).map(+ (id) => EDITOR_LABELS[id as EditorId] ?? id,);+ const target = hostLabels.length > 0 ? hostLabels.join(', ') : 'the shared ~/.agents store';+ lines.push(` open-knowledge ${success(`installed for ${target}`)}`);break;+ }case 'skip-current':lines.push(` open-knowledge ${success('already installed at current version')}`);break;case 'declined':lines.push(` open-knowledge ${dim('skipped (opted out via --no-skills)')}`);break;- case 'failed':+ case 'no-hosts':lines.push(- ` ${warning('open-knowledge install failed — MCP still configured; run manually:')}`,+ ` open-knowledge ${dim('skipped — no supported agent host detected in your home directory')}`,);+ break;+ case 'failed':lines.push(- ` ${warning(" npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy")}`,+ ` ${warning('open-knowledge install failed — MCP still configured; retry with:')}`,);+ lines.push(` ${warning(' ok repair-skills')}`);break;}}diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.tsindex bee029b1f..7e81646b5 100644--- a/packages/cli/src/commands/repair-skills.test.ts+++ b/packages/cli/src/commands/repair-skills.test.ts@@ -1,6 +1,7 @@import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';+import { PassThrough } from 'node:stream';import type { SkillInstallEvent } from '@inkeep/open-knowledge-server';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { EDITOR_TARGETS } from './editors.ts';@@ -19,6 +20,7 @@ const {PROJECT_SKILL_DIR_NAME,repairSkillsResultExitCode,formatRepairSkillsResult,+ confirmLegacyCleanup,} = __testing;function mkScratch(tag: string): { root: string; home: string; project: string; bundles: string } {@@ -1282,6 +1284,9 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {it('renders per-sweep counts when both sweeps ran to done', () => {const out = formatRepairSkillsResult({status: 'done',+ legacySwept: [],+ legacyCleanupDeclined: false,+ legacyCleanupFailed: false,project: {outcome: 'done',entries: [@@ -1333,6 +1338,9 @@ describe('formatRepairSkillsResult — done-branch stdout formatting', () => {it('renders skip reason when the user sweep version-skips', () => {const out = formatRepairSkillsResult({status: 'done',+ legacySwept: [],+ legacyCleanupDeclined: false,+ legacyCleanupFailed: false,project: { outcome: 'done', entries: [] },user: { outcome: 'skipped', reason: 'version-current' },});@@ -1384,7 +1392,14 @@ describe('repairSkillsResultExitCode (PR feedback: standalone exit code mapping)? [{ kind: 'central', path: '/tmp/x', outcome: 'failed', error: 'simulated' }]: [{ kind: 'central', path: '/tmp/x', outcome: 'written' }],};- return { status: 'done', project, user };+ return {+ status: 'done',+ project,+ user,+ legacySwept: [],+ legacyCleanupDeclined: false,+ legacyCleanupFailed: false,+ };}it('reclaim-disabled skip exits 0', () => {@@ -1547,3 +1562,187 @@ describe('repairSkills — symlink-escape guard (parity with writeProjectSkill)'expect(existsSync(witnessFile)).toBe(true);});});++// ---------------------------------------------------------------------------+// Pre-0.42 cleanup consent (issue #820)+// ---------------------------------------------------------------------------+//+// The cleanup deletes from `$HOME`. Doing that without showing the user the+// paths first would repeat the original mistake, so consent is a hard gate:+// no confirmer, no deletion.++describe('legacy fan-out cleanup — consent gate', () => {+ function plantLegacy(home: string): string {+ const dir = join(home, '.zencoder', 'skills', USER_SKILL_DIR_NAME);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), '# stale\n', 'utf-8');+ return dir;+ }++ /** Version-skip deps: the user sweep is irrelevant to these tests. */+ function quietDeps(bundles: string): RepairSkillsDeps {+ return depsBuilder({+ projectBundleDir: bundles,+ discoveryBundleDir: bundles,+ bundledVersion: '9.9.9',+ recordedVersion: '9.9.9',+ writtenVersions: [],+ });+ }++ it('deletes nothing when no confirmer is wired', async () => {+ const { home, project, bundles } = mkScratch('legacy-noconfirm');+ const legacy = plantLegacy(home);++ const result = await repairSkills({+ projectDir: project,+ home,+ deps: quietDeps(bundles),+ logger: () => {},+ });++ expect(result.status).toBe('done');+ if (result.status !== 'done') return;+ expect(result.legacySwept).toEqual([]);+ expect(result.legacyCleanupDeclined).toBe(true);+ expect(existsSync(legacy)).toBe(true);+ });++ it('deletes nothing when the user declines', async () => {+ const { home, project, bundles } = mkScratch('legacy-decline');+ const legacy = plantLegacy(home);++ const result = await repairSkills({+ projectDir: project,+ home,+ deps: quietDeps(bundles),+ logger: () => {},+ confirmLegacyCleanup: async () => false,+ });++ if (result.status !== 'done') throw new Error('expected done');+ expect(result.legacySwept).toEqual([]);+ expect(result.legacyCleanupDeclined).toBe(true);+ expect(existsSync(legacy)).toBe(true);+ expect(formatRepairSkillsResult(result)).toContain('Cleanup: declined');+ });++ it('deletes the skill AND the emptied agent home when the user accepts', async () => {+ const { home, project, bundles } = mkScratch('legacy-accept');+ plantLegacy(home);++ const result = await repairSkills({+ projectDir: project,+ home,+ deps: quietDeps(bundles),+ logger: () => {},+ confirmLegacyCleanup: async () => true,+ });++ if (result.status !== 'done') throw new Error('expected done');+ expect(result.legacyCleanupDeclined).toBe(false);+ expect(existsSync(join(home, '.zencoder'))).toBe(false);+ expect(formatRepairSkillsResult(result)).toContain('Cleanup: removed');+ });++ it('never asks when there is nothing to clean up', async () => {+ const { home, project, bundles } = mkScratch('legacy-none');+ let asked = false;++ await repairSkills({+ projectDir: project,+ home,+ deps: quietDeps(bundles),+ logger: () => {},+ confirmLegacyCleanup: async () => {+ asked = true;+ return true;+ },+ });++ expect(asked).toBe(false);+ });++ it('the confirmer is handed the exact paths, so the prompt can list them', async () => {+ const { home, project, bundles } = mkScratch('legacy-plan');+ const legacy = plantLegacy(home);+ let seen: { skillDirs: string[]; emptyDirs: string[] } | null = null;++ await repairSkills({+ projectDir: project,+ home,+ deps: quietDeps(bundles),+ logger: () => {},+ confirmLegacyCleanup: async (plan) => {+ seen = { skillDirs: [...plan.skillDirs], emptyDirs: [...plan.emptyDirs] };+ return false;+ },+ });++ expect(seen).not.toBeNull();+ expect(seen?.skillDirs).toEqual([legacy]);+ expect(seen?.emptyDirs).toEqual([join(home, '.zencoder', 'skills'), join(home, '.zencoder')]);+ });+});++describe('confirmLegacyCleanup — prompt behaviour', () => {+ const plan = { skillDirs: ['/h/.zencoder/skills/open-knowledge-discovery'], emptyDirs: [] };++ it('--yes approves without prompting', async () => {+ expect(await confirmLegacyCleanup(plan, { yes: true })).toBe(true);+ });++ it('declines on a non-TTY rather than deleting unattended', async () => {+ const piped = new PassThrough() as unknown as NodeJS.ReadableStream & { isTTY?: boolean };+ piped.isTTY = false;+ expect(await confirmLegacyCleanup(plan, { yes: false, input: piped })).toBe(false);+ });++ it('a bare Enter declines — deletion is never the default', async () => {+ expect(await confirmLegacyCleanup(plan, { yes: false, input: fakeTty('') })).toBe(false);+ });++ it('accepts an explicit y', async () => {+ expect(await confirmLegacyCleanup(plan, { yes: false, input: fakeTty('y') })).toBe(true);+ });++ function fakeTty(answer: string): NodeJS.ReadableStream & { isTTY?: boolean } {+ const stream = new PassThrough() as unknown as NodeJS.ReadableStream & { isTTY?: boolean };+ stream.isTTY = true;+ queueMicrotask(() => {+ (stream as unknown as PassThrough).write(`${answer}\n`);+ });+ return stream;+ }+});++describe('legacy cleanup — an internal failure is never reported as a decline', () => {+ // Approving and then hitting a re-validation error is a bug on our side.+ // Rendering it as "declined" would tell the user they chose this, which is+ // the same dishonest reporting this PR exists to remove.+ it('renders a distinct failed line, not the decline line', () => {+ const base = formatRepairSkillsResult({+ status: 'done',+ legacySwept: [],+ legacyCleanupDeclined: false,+ legacyCleanupFailed: true,+ project: { outcome: 'done', entries: [] },+ user: { outcome: 'done', version: '9.9.9', entries: [] },+ } as unknown as RepairSkillsResult);+ expect(base).toContain('Cleanup: failed');+ expect(base).not.toContain('Cleanup: declined');+ });++ it('a genuine decline still reads as declined', () => {+ const out = formatRepairSkillsResult({+ status: 'done',+ legacySwept: [],+ legacyCleanupDeclined: true,+ legacyCleanupFailed: false,+ project: { outcome: 'done', entries: [] },+ user: { outcome: 'done', version: '9.9.9', entries: [] },+ } as unknown as RepairSkillsResult);+ expect(out).toContain('Cleanup: declined');+ expect(out).not.toContain('Cleanup: failed');+ });+});diff --git a/packages/cli/src/commands/repair-skills.ts b/packages/cli/src/commands/repair-skills.tsindex 62168d611..e714da451 100644--- a/packages/cli/src/commands/repair-skills.ts+++ b/packages/cli/src/commands/repair-skills.ts@@ -28,7 +28,8 @@ import {writeFileSync as fsWriteFileSync,} from 'node:fs';import { homedir } from 'node:os';-import { dirname, join, resolve as resolvePath } from 'node:path';+import { dirname, join, relative, resolve as resolvePath } from 'node:path';+import { createInterface } from 'node:readline/promises';import {BUNDLE_SKILL_NAME,type BundleId,@@ -44,8 +45,14 @@ import {writeTargetVersion,} from '@inkeep/open-knowledge-server';import { Command } from 'commander';-import { removeUserGlobalSkillBundle } from '../integrations/skill-teardown.ts';+import {+ applyLegacyFanoutSweep,+ type LegacyFanoutSweepPlan,+ planLegacyFanoutSweep,+ removeUserGlobalSkillBundle,+} from '../integrations/skill-teardown.ts';import { assertProjectPathSafe } from '../integrations/write-project-skill.ts';+import { accent, dim, warning } from '../ui/colors.ts';import { EDITOR_TARGETS, type EditorId, HOSTS_WITH_USER_SKILL_DIR } from './editors.ts';// `HOSTS_WITH_USER_SKILL_DIR` is the canonical core constant (derived from@@ -161,6 +168,17 @@ export interface RepairSkillsContext {deps?: RepairSkillsDeps;/** Override fs primitives for tests. */fs?: RepairSkillsFsOps;+ /**+ * Decide whether to delete the directories a pre-0.42 fan-out left behind+ * (issue #820). Called ONLY when there is something to remove, with the exact+ * plan. Returning false leaves every path in place.+ *+ * Required to delete anything: with no confirmer the sweep is skipped, so a+ * caller that never wired consent can't quietly remove files from `$HOME`.+ * `repairSkillsCommand` supplies an interactive prompt (or an auto-yes under+ * `--yes`); tests inject a stub.+ */+ confirmLegacyCleanup?: (plan: LegacyFanoutSweepPlan) => Promise<boolean>;}export type ProjectSkillOutcome = 'no-token' | 'reclaimed' | 'created' | 'failed';@@ -210,6 +228,22 @@ export type RepairSkillsResult =status: 'done';project: ProjectSweepResult;user: UserSweepResult;+ /**+ * Paths removed from hosts a pre-0.42 fan-out reached but OK never+ * supported (issue #820) — OK's skill dirs plus any agent home left empty+ * by their removal. Empty on a machine that never ran an affected+ * version, on every run after the first, and whenever the user declines.+ */+ legacySwept: string[];+ /** True when a cleanup was available and the user (or `--yes`) declined it. */+ legacyCleanupDeclined: boolean;+ /**+ * True when the user APPROVED the cleanup but it refused to run — a+ * re-validation failure, i.e. a bug. Kept separate from+ * `legacyCleanupDeclined` so the summary never reports our failure as+ * the user's choice.+ */+ legacyCleanupFailed: boolean;};function defaultLogger(event: RepairSkillsLogEvent): void {@@ -748,8 +782,40 @@ export async function repairSkills(ctx: RepairSkillsContext): Promise<RepairSkilconst project = runProjectSweep(ctx.projectDir, deps, fs, logger);const user = await runUserSweep(home, deps, fs, logger);+ // Explicit-invocation only, and consent-gated even then. `ok init` must never+ // delete from $HOME unasked — that would answer one scope violation with+ // another — and neither may this command without showing its work first.+ const legacyPlan = planLegacyFanoutSweep(home);+ let legacySwept: string[] = [];+ let legacyCleanupDeclined = false;+ let legacyCleanupFailed = false;+ if (legacyPlan.skillDirs.length > 0 || legacyPlan.emptyDirs.length > 0) {+ const approved = ctx.confirmLegacyCleanup ? await ctx.confirmLegacyCleanup(legacyPlan) : false;+ if (approved) {+ try {+ legacySwept = applyLegacyFanoutSweep(home, legacyPlan);+ } catch (err) {+ // `apply` re-validates the plan and throws rather than delete anything+ // it can't account for. That means a bug, not a user problem — surface+ // it as its own outcome (never as a decline) and carry on, because the+ // install is this command's real job.+ legacyCleanupFailed = true;+ logger({+ event: 'legacy-fanout-cleanup-refused',+ scope: 'user',+ error: err instanceof Error ? err.message : String(err),+ });+ }+ for (const path of legacySwept) {+ logger({ event: 'legacy-fanout-path-removed', scope: 'user', path });+ }+ } else {+ legacyCleanupDeclined = true;+ logger({ event: 'legacy-fanout-cleanup-declined', scope: 'user' });+ }+ }- return { status: 'done', project, user };+ return { status: 'done', project, user, legacySwept, legacyCleanupDeclined, legacyCleanupFailed };}/**@@ -812,6 +878,13 @@ function formatRepairSkillsResult(result: RepairSkillsResult): string {} else {lines.push(` User: skipped (${result.user.reason}).`);}+ if (result.legacySwept.length > 0) {+ lines.push(` Cleanup: removed ${result.legacySwept.length} path(s) from a pre-0.42 install.`);+ } else if (result.legacyCleanupFailed) {+ lines.push(' Cleanup: failed — see logs; pre-0.42 directories left in place.');+ } else if (result.legacyCleanupDeclined) {+ lines.push(' Cleanup: declined — pre-0.42 directories left in place.');+ }return lines.join('\n');}@@ -824,10 +897,15 @@ export function repairSkillsCommand(): Command {.description('Refresh bundled SKILL.md files for installed AI editors (project-local + user-global). Runs automatically during `ok start`; this command forces an explicit sweep.',)- .action(async () => {+ .option(+ '-y, --yes',+ 'Skip the confirmation prompt for removing directories left by a pre-0.42 install.',+ )+ .action(async (opts: { yes?: boolean }) => {const result = await repairSkills({projectDir: resolvePath(process.cwd()),reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,+ confirmLegacyCleanup: (plan) => confirmLegacyCleanup(plan, { yes: opts.yes === true }),});process.stdout.write(`${formatRepairSkillsResult(result)}\n`);// process.exitCode (not process.exit) so any pending stdout/stderr@@ -836,6 +914,82 @@ export function repairSkillsCommand(): Command {});}+/**+ * Show exactly what the pre-0.42 cleanup would delete and ask before doing it.+ *+ * Two things the user must be able to see BEFORE consenting, because the whole+ * point of issue #820 was software touching `$HOME` beyond what the user+ * pictured: every path is listed (not just a count), and each agent home is+ * labelled with WHY it is going — it holds nothing but OK's own skill, so it is+ * empty the moment that skill is removed.+ *+ * Non-interactive (piped/CI) without `--yes` declines rather than proceeding:+ * an unattended run must never delete from a home directory on a default.+ */+async function confirmLegacyCleanup(+ plan: LegacyFanoutSweepPlan,+ opts: { yes: boolean; input?: NodeJS.ReadableStream & { isTTY?: boolean } },+): Promise<boolean> {+ const home = homedir();+ const show = (p: string) => `~/${relative(home, p)}`;+ const input = opts.input ?? process.stdin;++ const lines: string[] = [+ '',+ accent(+ 'A previous version of OpenKnowledge installed its skill into agent tools you may never have used.',+ ),+ dim(+ '(Versions before 0.42 wrote to every host a third-party installer knew about — see issue #820.)',+ ),+ ];+ if (plan.skillDirs.length > 0) {+ lines.push(+ '',+ `${accent('Remove OpenKnowledge skills:')} ${plan.skillDirs.length}`,+ ...plan.skillDirs.map((p) => ` ${show(p)}`),+ );+ }+ if (plan.emptyDirs.length > 0) {+ // Wording depends on whether skills are going too. A machine swept by an+ // earlier build already has them gone, and telling that user these dirs+ // are empty "once the above are gone" would describe a step not happening.+ const heading =+ plan.skillDirs.length > 0+ ? 'Then remove these, which hold nothing else once the above are gone:'+ : 'Remove these empty directories, left behind by that install:';+ lines.push(+ '',+ `${accent(heading)} ${plan.emptyDirs.length}`,+ ...plan.emptyDirs.map((p) => ` ${show(p)}`),+ );+ }+ lines.push(+ '',+ dim('Nothing outside these paths is touched. A directory that still holds anything is kept.'),+ );+ process.stdout.write(`${lines.join('\n')}\n`);++ if (opts.yes) return true;+ if (!input.isTTY) {+ process.stdout.write(+ `${warning('Not a terminal — skipping cleanup. Re-run with `ok repair-skills --yes` to remove these.')}\n`,+ );+ return false;+ }++ const rl = createInterface({ input, output: process.stdout });+ try {+ const answer = (await rl.question(`\n${accent('Remove them?')} ${dim('[y/N] ')}`))+ .trim()+ .toLowerCase();+ // Default NO — deletion is never the answer to an empty Enter.+ return answer === 'y' || answer === 'yes';+ } finally {+ rl.close();+ }+}+export const __testing = {HOSTS_WITH_USER_SKILL_DIR,USER_SKILL_DIR_NAME,@@ -843,4 +997,5 @@ export const __testing = {CENTRAL_USER_SKILL_REL,formatRepairSkillsResult,repairSkillsResultExitCode,+ confirmLegacyCleanup,};diff --git a/packages/cli/src/integrations/skill-teardown.test.ts b/packages/cli/src/integrations/skill-teardown.test.tsindex 1dedbdcbe..64fcc2a26 100644--- a/packages/cli/src/integrations/skill-teardown.test.ts+++ b/packages/cli/src/integrations/skill-teardown.test.ts@@ -1,8 +1,15 @@-import { join } from 'node:path';+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, sep } from 'node:path';import { BUNDLE_SKILL_NAME, USER_GLOBAL_BUNDLE_IDS } from '@inkeep/open-knowledge-server';import { describe, expect, test } from 'vitest';import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';-import { userGlobalSkillBundleTargets } from './skill-teardown.ts';+import {+ applyLegacyFanoutSweep,+ planLegacyFanoutSweep,+ removeUserGlobalSkillBundle,+ userGlobalSkillBundleTargets,+} from './skill-teardown.ts';const HOME = '/home/tester';@@ -48,3 +55,432 @@ describe('userGlobalSkillBundleTargets', () => {}});});++describe('legacy fan-out sweep', () => {+ function tmpHome(): string {+ return mkdtempSync(join(tmpdir(), 'ok-legacy-sweep-'));+ }+ function plantSkill(home: string, relDir: string, name: string): string {+ const dir = join(home, relDir, 'skills', name);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), '# stale\n', 'utf-8');+ return dir;+ }+ function sweep(home: string): string[] {+ return applyLegacyFanoutSweep(home, planLegacyFanoutSweep(home));+ }++ test('removes OK skill dirs left in hosts OK never supported', () => {+ const home = tmpHome();+ const zencoder = plantSkill(home, '.zencoder', 'open-knowledge-discovery');+ const terramind = plantSkill(home, '.terramind', 'open-knowledge-write-skill');+ // Nested agent home, written exactly as the fan-out produced it.+ const tabnine = plantSkill(home, join('.tabnine', 'agent'), 'open-knowledge-discovery');+ // Pre-split name, from an even older install.+ const rovodev = plantSkill(home, '.rovodev', 'open-knowledge');++ const removed = sweep(home);++ for (const dir of [zencoder, terramind, tabnine, rovodev]) {+ expect(existsSync(dir)).toBe(false);+ expect(removed).toContain(dir);+ }+ });++ test("prunes the agent home once OK's skill was the only thing in it", () => {+ const home = tmpHome();+ plantSkill(home, '.zencoder', 'open-knowledge-discovery');++ sweep(home);++ // The whole tree goes: nothing else was ever in it.+ expect(existsSync(join(home, '.zencoder'))).toBe(false);+ });++ test('prunes a nested agent home up to its hardcoded root', () => {+ const home = tmpHome();+ plantSkill(home, join('.tabnine', 'agent'), 'open-knowledge-discovery');++ sweep(home);++ expect(existsSync(join(home, '.tabnine'))).toBe(false);+ });++ test('never removes the shared ~/.config, only the tool folder inside it', () => {+ const home = tmpHome();+ plantSkill(home, join('.config', 'goose'), 'open-knowledge-discovery');++ sweep(home);++ expect(existsSync(join(home, '.config', 'goose'))).toBe(false);+ // `.config` is a shared XDG root — inert or not, OK must never delete it.+ expect(existsSync(join(home, '.config'))).toBe(true);+ });++ test("keeps an agent home that still holds anything of the tool's own", () => {+ const home = tmpHome();+ plantSkill(home, '.zencoder', 'open-knowledge-discovery');+ // The user actually uses zencoder.+ writeFileSync(join(home, '.zencoder', 'config.json'), '{}', 'utf-8');++ sweep(home);++ expect(existsSync(join(home, '.zencoder'))).toBe(true);+ expect(existsSync(join(home, '.zencoder', 'config.json'))).toBe(true);+ // Only OK's own dir went; the now-empty `skills/` stays because its parent did.+ expect(existsSync(join(home, '.zencoder', 'skills', 'open-knowledge-discovery'))).toBe(false);+ });++ test('keeps a sibling skill the user owns — and therefore the dirs holding it', () => {+ const home = tmpHome();+ plantSkill(home, '.zencoder', 'open-knowledge-discovery');+ const mine = plantSkill(home, '.zencoder', 'my-own-skill');+ const lookalike = plantSkill(home, '.zencoder', 'open-knowledgeable-notes');++ sweep(home);++ expect(existsSync(mine)).toBe(true);+ expect(existsSync(lookalike)).toBe(true);+ expect(existsSync(join(home, '.zencoder'))).toBe(true);+ });++ test('never touches a host OK still installs to', () => {+ const home = tmpHome();+ const live = HOSTS_WITH_USER_SKILL_DIR.map((h) =>+ plantSkill(home, h.hostDir, 'open-knowledge-discovery'),+ );+ const central = plantSkill(home, '.agents', 'open-knowledge-discovery');++ const removed = sweep(home);++ for (const dir of [...live, central]) {+ expect(existsSync(dir)).toBe(true);+ expect(removed).not.toContain(dir);+ }+ });++ test('plan lists every path before anything is deleted', () => {+ const home = tmpHome();+ const skill = plantSkill(home, '.zencoder', 'open-knowledge-discovery');++ const plan = planLegacyFanoutSweep(home);++ // Planning is pure — the user has to be able to read this and say no.+ expect(existsSync(skill)).toBe(true);+ expect(plan.skillDirs).toEqual([skill]);+ expect(plan.emptyDirs).toEqual([join(home, '.zencoder', 'skills'), join(home, '.zencoder')]);+ });++ test('emptyDirs are deepest-first so rmdir can succeed in order', () => {+ const home = tmpHome();+ plantSkill(home, join('.tabnine', 'agent'), 'open-knowledge-discovery');++ const { emptyDirs } = planLegacyFanoutSweep(home);++ expect(emptyDirs).toEqual([+ join(home, '.tabnine', 'agent', 'skills'),+ join(home, '.tabnine', 'agent'),+ join(home, '.tabnine'),+ ]);+ });++ test('a dir that gained content between plan and apply survives', () => {+ const home = tmpHome();+ plantSkill(home, '.zencoder', 'open-knowledge-discovery');+ const plan = planLegacyFanoutSweep(home);+ // User installs the tool for real in the gap.+ writeFileSync(join(home, '.zencoder', 'config.json'), '{}', 'utf-8');++ applyLegacyFanoutSweep(home, plan);++ // rmdir refuses a non-empty dir — the race can't destroy their data.+ expect(existsSync(join(home, '.zencoder', 'config.json'))).toBe(true);+ expect(existsSync(join(home, '.zencoder'))).toBe(true);+ });++ // An earlier build of this cleanup removed the skill dirs but never pruned,+ // so real machines exist where the skills are already gone and only empty+ // `~/.<host>/skills/` trees remain. Gating the walk on "we deleted a skill+ // just now" made those unreachable forever — the exact state this covers.+ test('prunes empty leftovers even when the skill dir is already gone', () => {+ const home = tmpHome();+ // No open-knowledge* dir anywhere: just the husks a leaf-only sweep leaves.+ mkdirSync(join(home, '.zencoder', 'skills'), { recursive: true });+ mkdirSync(join(home, '.terramind', 'skills'), { recursive: true });++ const plan = planLegacyFanoutSweep(home);+ expect(plan.skillDirs).toEqual([]);+ expect(plan.emptyDirs.length).toBeGreaterThan(0);++ applyLegacyFanoutSweep(home, plan);++ expect(existsSync(join(home, '.zencoder'))).toBe(false);+ expect(existsSync(join(home, '.terramind'))).toBe(false);+ });++ test('an already-clean host with a non-empty skills dir is left alone', () => {+ const home = tmpHome();+ const mine = join(home, '.zencoder', 'skills', 'my-own-skill');+ mkdirSync(mine, { recursive: true });+ writeFileSync(join(mine, 'SKILL.md'), '# mine\n', 'utf-8');++ applyLegacyFanoutSweep(home, planLegacyFanoutSweep(home));++ expect(existsSync(mine)).toBe(true);+ });++ test('is a no-op on a home that never ran an affected version', () => {+ const home = tmpHome();+ expect(planLegacyFanoutSweep(home).skillDirs).toEqual([]);+ expect(sweep(home)).toEqual([]);+ });++ test('is idempotent — the second run finds nothing', () => {+ const home = tmpHome();+ plantSkill(home, '.zencoder', 'open-knowledge-discovery');++ expect(sweep(home).length).toBeGreaterThan(0);+ expect(sweep(home)).toEqual([]);+ });+});++// ---------------------------------------------------------------------------+// Adversarial: the cleanup runs `rm -rf` inside a user's home directory, so+// every one of these is a "could this delete the wrong thing" case. Each was a+// real hole found by attacking the first implementation.+// ---------------------------------------------------------------------------++describe('legacy fan-out sweep — refuses unsafe inputs', () => {+ function tmpHome(): string {+ return mkdtempSync(join(tmpdir(), 'ok-legacy-guard-'));+ }+ function plantSkill(home: string, relDir: string): string {+ const dir = join(home, relDir, 'skills', 'open-knowledge-discovery');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), '# stale\n', 'utf-8');+ return dir;+ }++ // `join('', '.zencoder', …)` is RELATIVE — an empty or relative home silently+ // retargets the whole sweep at the process cwd, which for a CLI is the user's+ // project. Throwing beats returning nothing: it surfaces the caller's bug.+ test.each([+ '',+ '.',+ 'relative/path',+ 'x/../y',+ ])('a non-absolute home (%j) throws instead of resolving against cwd', (bogus) => {+ expect(() => planLegacyFanoutSweep(bogus)).toThrow(/absolute home/);+ });++ test('the filesystem root is refused', () => {+ expect(() => planLegacyFanoutSweep(sep)).toThrow(/filesystem root/);+ });++ test('a relative home cannot target a matching tree in the cwd', () => {+ const box = tmpHome();+ plantSkill(box, '.zencoder');+ const prev = process.cwd();+ process.chdir(box);+ try {+ expect(() => planLegacyFanoutSweep('')).toThrow();+ expect(existsSync(join(box, '.zencoder', 'skills', 'open-knowledge-discovery'))).toBe(true);+ } finally {+ process.chdir(prev);+ }+ });++ // Agent hosts commonly symlink `skills/` at the shared `~/.agents/skills`+ // hub, so following one could delete a live install — or, if it points at a+ // user directory, their files.+ test('a symlinked agent home is skipped entirely', () => {+ const box = tmpHome();+ const target = join(box, 'precious');+ mkdirSync(join(target, 'skills', 'open-knowledge-discovery'), { recursive: true });+ writeFileSync(join(target, 'thesis.txt'), 'mine\n', 'utf-8');+ const home = join(box, 'home');+ mkdirSync(home, { recursive: true });+ symlinkSync(target, join(home, '.zencoder'));++ const plan = planLegacyFanoutSweep(home);+ applyLegacyFanoutSweep(home, plan);++ expect(plan.skillDirs).toEqual([]);+ expect(existsSync(join(target, 'thesis.txt'))).toBe(true);+ expect(existsSync(join(target, 'skills', 'open-knowledge-discovery'))).toBe(true);+ });++ test('a symlinked skills/ dir is skipped — no delete through the link', () => {+ const box = tmpHome();+ const docs = join(box, 'Documents');+ mkdirSync(join(docs, 'open-knowledge-discovery'), { recursive: true });+ writeFileSync(join(docs, 'open-knowledge-discovery', 'notes.md'), 'mine\n', 'utf-8');+ const home = join(box, 'home');+ mkdirSync(join(home, '.zencoder'), { recursive: true });+ symlinkSync(docs, join(home, '.zencoder', 'skills'));++ const plan = planLegacyFanoutSweep(home);+ applyLegacyFanoutSweep(home, plan);++ expect(plan.skillDirs).toEqual([]);+ expect(existsSync(join(docs, 'open-knowledge-discovery', 'notes.md'))).toBe(true);+ });++ // `applyLegacyFanoutSweep` is exported and takes plain strings, so trusting+ // its input would let any future caller — or a bug mutating a plan between+ // the prompt and the delete — recursively remove an arbitrary directory.+ test('a skill dir swapped for a symlink between plan and apply is not followed', () => {+ const home = tmpHome();+ const precious = join(home, 'Documents');+ mkdirSync(precious, { recursive: true });+ writeFileSync(join(precious, 'thesis.txt'), 'mine\n', 'utf-8');+ const skill = plantSkill(home, '.zencoder');++ const plan = planLegacyFanoutSweep(home);+ // Attacker (or a racing tool) replaces the planned dir with a link.+ rmSync(skill, { recursive: true, force: true });+ symlinkSync(precious, skill);++ applyLegacyFanoutSweep(home, plan);++ expect(existsSync(join(precious, 'thesis.txt'))).toBe(true);+ });++ test('a skill dir replaced with unrelated content between plan and apply is left alone', () => {+ const home = tmpHome();+ const skill = plantSkill(home, '.zencoder');+ const plan = planLegacyFanoutSweep(home);+ // No longer an OK bundle: no SKILL.md, and not empty.+ rmSync(join(skill, 'SKILL.md'));+ writeFileSync(join(skill, 'someone-elses-data.txt'), 'mine\n', 'utf-8');++ applyLegacyFanoutSweep(home, plan);++ expect(existsSync(join(skill, 'someone-elses-data.txt'))).toBe(true);+ });++ // Found by an independent safety review. `rmdir` refuses a symlink LEAF, but+ // it still resolves a symlinked ANCESTOR, so a link swapped in after planning+ // had it delete a directory at the link target. Only ever an empty one — but+ // "empty" is not ours to assume about somewhere else on disk.+ test('an ancestor swapped for a symlink between plan and apply is not followed', () => {+ const home = tmpHome();+ const elsewhere = join(home, 'elsewhere');+ mkdirSync(join(elsewhere, 'skills'), { recursive: true });+ plantSkill(home, '.zencoder');++ const plan = planLegacyFanoutSweep(home);+ // The whole agent home becomes a link to a tree with an empty `skills/`.+ rmSync(join(home, '.zencoder'), { recursive: true, force: true });+ symlinkSync(elsewhere, join(home, '.zencoder'));++ applyLegacyFanoutSweep(home, plan);++ expect(existsSync(join(elsewhere, 'skills'))).toBe(true);+ expect(existsSync(elsewhere)).toBe(true);+ });++ test('a forged plan is refused, and nothing is deleted', () => {+ const home = tmpHome();+ const precious = join(home, 'Documents');+ mkdirSync(precious, { recursive: true });+ writeFileSync(join(precious, 'thesis.txt'), 'mine\n', 'utf-8');++ expect(() => applyLegacyFanoutSweep(home, { skillDirs: [precious], emptyDirs: [] })).toThrow(+ /outside the known legacy set/,+ );+ expect(existsSync(join(precious, 'thesis.txt'))).toBe(true);+ });++ test('a plan smuggling an extra emptyDir is refused before any delete runs', () => {+ const home = tmpHome();+ const legit = plantSkill(home, '.zencoder');+ const victim = join(home, '.ssh');+ mkdirSync(victim, { recursive: true });++ const plan = planLegacyFanoutSweep(home);+ expect(() =>+ applyLegacyFanoutSweep(home, { ...plan, emptyDirs: [...plan.emptyDirs, victim] }),+ ).toThrow(/outside the known legacy set/);+ // Refusal happens up front — even the legitimate part is untouched.+ expect(existsSync(victim)).toBe(true);+ expect(existsSync(legit)).toBe(true);+ });+});++describe('legacy fan-out host table — static integrity', () => {+ // The table drives deletion, so a typo in it is the highest-severity bug+ // available here. These are pure checks on the data, no filesystem involved.+ const HOME = sep === '/' ? '/home/tester' : 'C:\\Users\\tester';++ test('every planned path is inside home and never home itself', () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-legacy-table-'));+ for (const rel of ['.zencoder', '.tabnine/agent', '.config/goose', '.config/kimchi/harness']) {+ const dir = join(home, rel, 'skills', 'open-knowledge-discovery');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), '# x\n', 'utf-8');+ }+ const plan = planLegacyFanoutSweep(home);+ expect(plan.skillDirs.length).toBeGreaterThan(0);+ for (const p of [...plan.skillDirs, ...plan.emptyDirs]) {+ expect(p.startsWith(home + sep)).toBe(true);+ expect(p).not.toBe(home);+ }+ });++ test('shared XDG roots are never planned for removal', () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-legacy-xdg-'));+ for (const rel of ['.config/goose', '.config/crush', '.config/kimchi/harness']) {+ const dir = join(home, rel, 'skills', 'open-knowledge-discovery');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), '# x\n', 'utf-8');+ }+ const plan = planLegacyFanoutSweep(home);+ expect(plan.emptyDirs).not.toContain(join(home, '.config'));+ expect(plan.emptyDirs).toContain(join(home, '.config', 'goose'));+ // …and the shared root really does survive an apply.+ applyLegacyFanoutSweep(home, plan);+ expect(existsSync(join(home, '.config'))).toBe(true);+ expect(existsSync(join(home, '.config', 'goose'))).toBe(false);+ });++ test('no legacy host escapes home via .. and every pruneRoot is an ancestor', () => {+ // Derived from behaviour rather than the private table: plant each host,+ // then assert the deepest planned dir per entry is still under home.+ const home = mkdtempSync(join(tmpdir(), 'ok-legacy-esc-'));+ const dir = join(home, '.zencoder', 'skills', 'open-knowledge-discovery');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), '# x\n', 'utf-8');+ const plan = planLegacyFanoutSweep(home);+ for (const p of plan.emptyDirs) {+ expect(p.includes(`${sep}..${sep}`)).toBe(false);+ expect(p.startsWith(home + sep)).toBe(true);+ }+ expect(HOME.length).toBeGreaterThan(0);+ });+});++describe('userGlobalSkillBundleTargets / removeUserGlobalSkillBundle — home guard', () => {+ // `os.homedir()` returns $HOME verbatim, so a broken environment made this+ // teardown (the `--no-skills` / opt-out path) delete relative to the process+ // cwd. Predates the legacy sweep, so it was missed when that was hardened.+ test.each(['', '.', 'relative/home'])('a non-absolute home (%j) throws', (bogus) => {+ expect(() => userGlobalSkillBundleTargets(bogus)).toThrow(/absolute home/);+ expect(() => removeUserGlobalSkillBundle(bogus, 'discovery')).toThrow(/absolute home/);+ });++ test('a relative home cannot delete a matching tree in the cwd', () => {+ const box = mkdtempSync(join(tmpdir(), 'ok-teardown-cwd-'));+ const victim = join(box, '.agents', 'skills', 'open-knowledge-discovery');+ mkdirSync(victim, { recursive: true });+ writeFileSync(join(victim, 'SKILL.md'), '# x\n', 'utf-8');+ const prev = process.cwd();+ process.chdir(box);+ try {+ expect(() => removeUserGlobalSkillBundle('', 'discovery')).toThrow();+ expect(existsSync(victim)).toBe(true);+ } finally {+ process.chdir(prev);+ }+ });+});diff --git a/packages/cli/src/integrations/skill-teardown.ts b/packages/cli/src/integrations/skill-teardown.tsindex edd45d45c..a5cef835c 100644--- a/packages/cli/src/integrations/skill-teardown.ts+++ b/packages/cli/src/integrations/skill-teardown.ts@@ -23,8 +23,8 @@* (OK-authored global skills) and `~/Downloads/openknowledge.skill`.*/-import { rmSync } from 'node:fs';-import { join } from 'node:path';+import { existsSync, lstatSync, readdirSync, rmdirSync, rmSync } from 'node:fs';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import {BUNDLE_SKILL_NAME,type BundleId,@@ -32,6 +32,341 @@ import {} from '@inkeep/open-knowledge-server';import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';+/**+ * The agent homes a pre-0.42 `ok init` created skill copies in, for tools OK+ * does not support and the user very likely never installed.+ *+ * Until 0.42 the install shelled out to `npx skills … --agent '*' -g`, which+ * skipped that CLI's host detection and wrote into every host in its registry+ * (issue #820). This is the observed result of that command against a pristine+ * `$HOME`, minus the hosts OK still installs to.+ *+ * FROZEN — a historical record of what one shipped version did, not a mirror of+ * anything upstream. It can never need updating: no future OK version writes+ * these paths, and the third-party registry growing further is irrelevant+ * because no OK build will ever have fanned out to the new entries. Deletion+ * only; never an install target.+ *+ * `hostDir` is the parent of `skills/`, so nested agent homes (`.astrbot/data`,+ * `.tabnine/agent`) are expressed exactly as they were written.+ *+ * `pruneRoot` is the TOPMOST dir OK may remove once it is empty — hardcoded per+ * entry rather than derived, so pruning can only ever delete a directory whose+ * name is an agent home from this list. It is NOT always `hostDir`'s first+ * segment: the XDG entries live under the shared `~/.config`, which OK must+ * never remove even if it happens to be empty, so their root stops at the+ * tool's own folder (`.config/goose`, not `.config`).+ */+interface LegacyFanoutHost {+ /** Home-relative parent of the `skills/` dir the fan-out wrote into. */+ readonly hostDir: string;+ /** Home-relative topmost dir OK may remove when empty. */+ readonly pruneRoot: string;+}++const LEGACY_FANOUT_HOSTS: readonly LegacyFanoutHost[] = [+ { hostDir: '.adal', pruneRoot: '.adal' },+ { hostDir: '.aider-desk', pruneRoot: '.aider-desk' },+ { hostDir: '.astrbot/data', pruneRoot: '.astrbot' },+ { hostDir: '.augment', pruneRoot: '.augment' },+ { hostDir: '.autohand', pruneRoot: '.autohand' },+ { hostDir: '.bob', pruneRoot: '.bob' },+ { hostDir: '.codeartsdoer', pruneRoot: '.codeartsdoer' },+ { hostDir: '.codebuddy', pruneRoot: '.codebuddy' },+ { hostDir: '.codeium/windsurf', pruneRoot: '.codeium' },+ { hostDir: '.codemaker', pruneRoot: '.codemaker' },+ { hostDir: '.codestudio', pruneRoot: '.codestudio' },+ { hostDir: '.commandcode', pruneRoot: '.commandcode' },+ // XDG entries: stop at the tool's own folder, never at the shared `.config`.+ { hostDir: '.config/crush', pruneRoot: '.config/crush' },+ { hostDir: '.config/devin', pruneRoot: '.config/devin' },+ { hostDir: '.config/goose', pruneRoot: '.config/goose' },+ { hostDir: '.config/kimchi/harness', pruneRoot: '.config/kimchi' },+ { hostDir: '.continue', pruneRoot: '.continue' },+ { hostDir: '.factory', pruneRoot: '.factory' },+ { hostDir: '.forge', pruneRoot: '.forge' },+ { hostDir: '.grok', pruneRoot: '.grok' },+ { hostDir: '.iflow', pruneRoot: '.iflow' },+ { hostDir: '.inferencesh', pruneRoot: '.inferencesh' },+ { hostDir: '.jazz', pruneRoot: '.jazz' },+ { hostDir: '.junie', pruneRoot: '.junie' },+ { hostDir: '.kilocode', pruneRoot: '.kilocode' },+ { hostDir: '.kiro', pruneRoot: '.kiro' },+ { hostDir: '.kode', pruneRoot: '.kode' },+ { hostDir: '.lingma', pruneRoot: '.lingma' },+ { hostDir: '.mcpjam', pruneRoot: '.mcpjam' },+ { hostDir: '.moxby', pruneRoot: '.moxby' },+ { hostDir: '.mux', pruneRoot: '.mux' },+ { hostDir: '.neovate', pruneRoot: '.neovate' },+ { hostDir: '.ona', pruneRoot: '.ona' },+ { hostDir: '.openhands', pruneRoot: '.openhands' },+ { hostDir: '.pochi', pruneRoot: '.pochi' },+ { hostDir: '.qoder', pruneRoot: '.qoder' },+ { hostDir: '.qoder-cn', pruneRoot: '.qoder-cn' },+ { hostDir: '.qwen', pruneRoot: '.qwen' },+ { hostDir: '.reasonix', pruneRoot: '.reasonix' },+ { hostDir: '.roo', pruneRoot: '.roo' },+ { hostDir: '.rovodev', pruneRoot: '.rovodev' },+ { hostDir: '.snowflake/cortex', pruneRoot: '.snowflake' },+ { hostDir: '.tabnine/agent', pruneRoot: '.tabnine' },+ { hostDir: '.terramind', pruneRoot: '.terramind' },+ { hostDir: '.tinycloud', pruneRoot: '.tinycloud' },+ { hostDir: '.trae', pruneRoot: '.trae' },+ { hostDir: '.trae-cn', pruneRoot: '.trae-cn' },+ { hostDir: '.vibe', pruneRoot: '.vibe' },+ { hostDir: '.zcode', pruneRoot: '.zcode' },+ { hostDir: '.zencoder', pruneRoot: '.zencoder' },+];++/**+ * Every OK-owned skill dir name a legacy fan-out could have left behind: the+ * current user-global bundles plus the pre-split `open-knowledge` name.+ * Reserved `open-knowledge*` names OK alone writes, so removing one can never+ * touch a skill the user authored or installed themselves.+ */+const LEGACY_SWEEPABLE_SKILL_NAMES: readonly string[] = [+ ...USER_GLOBAL_BUNDLE_IDS.map((id) => BUNDLE_SKILL_NAME[id]),+ 'open-knowledge',+];++export interface LegacyFanoutSweepPlan {+ /** OK's own skill dirs to delete, e.g. `~/.zencoder/skills/open-knowledge-discovery`. */+ readonly skillDirs: string[];+ /**+ * Dirs left holding nothing once `skillDirs` are gone, deepest-first. Every+ * entry is either a `skills/` dir or an agent home named in+ * `LEGACY_FANOUT_HOSTS` — never a path discovered by walking the filesystem.+ */+ readonly emptyDirs: string[];+}++/**+ * Reject a `home` that could make every path below resolve somewhere else.+ *+ * `join('', '.zencoder', …)` yields a RELATIVE path, so an empty or relative+ * home silently retargets the whole sweep at the process's cwd — which for a+ * CLI is the user's project. `'/'` would put the sweep at the filesystem root.+ * Both are programming errors, and both are unrecoverable once a delete runs,+ * so they throw rather than no-op.+ */+function assertUsableHome(home: string): string {+ if (!isAbsolute(home)) {+ throw new Error(+ `skill cleanup requires an absolute home directory; got ${JSON.stringify(home)}`,+ );+ }+ const normalized = resolve(home);+ if (normalized === sep || dirname(normalized) === normalized) {+ throw new Error(`skill cleanup refuses to operate on the filesystem root (${normalized})`);+ }+ return normalized;+}++/**+ * True when every path component from `home` down to `dir` is a real directory.+ *+ * Symlinks are followed by `existsSync` / `readdirSync` / `rmSync`, so a+ * symlinked ancestor makes the sweep act on the LINK TARGET — which may be+ * anywhere. That is not hypothetical in this ecosystem: agent hosts commonly+ * symlink their `skills/` dir at the shared `~/.agents/skills` hub, so+ * descending blind could delete a live install (or a user directory) through+ * the link. Any symlink on the path disqualifies the entry entirely: the+ * cleanup is best-effort housekeeping, and skipping is always safe.+ */+function isSymlinkFreeUnder(home: string, dir: string): boolean {+ const rel = relative(home, dir);+ if (rel.startsWith('..') || isAbsolute(rel)) return false;+ let cur = home;+ for (const segment of rel.split(sep)) {+ cur = join(cur, segment);+ try {+ // `lstat`, not `stat`: a symlink must report as a symlink, not as its target.+ if (!lstatSync(cur).isDirectory()) return false;+ } catch {+ return false;+ }+ }+ return true;+}++/** True when `dir`'s only remaining contents are paths already slated for removal. */+function willBeEmpty(dir: string, doomed: ReadonlySet<string>): boolean {+ try {+ return readdirSync(dir).every((name) => doomed.has(join(dir, name)));+ } catch {+ // Unreadable or absent — never claim it will be empty.+ return false;+ }+}++/**+ * Compute what a legacy sweep would delete, without touching disk.+ *+ * Split from the apply step so `ok repair-skills` can show the user the exact+ * list and get consent first — this deletes from `$HOME`, and doing that+ * unannounced is the same class of overreach as the bug it cleans up.+ *+ * Pruning is bounded three ways: only dirs that are empty afterwards, only up+ * to the entry's hardcoded `pruneRoot`, and only names drawn from+ * `LEGACY_FANOUT_HOSTS`. A directory the user created that merely happens to sit+ * in the walk is never a candidate, because candidates come from the table+ * rather than from the filesystem.+ */+export function planLegacyFanoutSweep(homeInput: string): LegacyFanoutSweepPlan {+ const home = assertUsableHome(homeInput);+ const skillDirs: string[] = [];+ const emptyDirs: string[] = [];+ const doomed = new Set<string>();++ for (const entry of LEGACY_FANOUT_HOSTS) {+ const skillsDir = join(home, entry.hostDir, 'skills');+ // Refuse the whole entry if anything on the way down is a symlink.+ if (!isSymlinkFreeUnder(home, skillsDir)) continue;+ const present = LEGACY_SWEEPABLE_SKILL_NAMES.map((name) => join(skillsDir, name)).filter(+ (path) => existsSync(path),+ );+ skillDirs.push(...present);+ for (const path of present) doomed.add(path);++ // NOTE: no early-out when `present` is empty. An earlier build of this+ // cleanup removed the skill dirs WITHOUT pruning, so a machine that ran it+ // is left with empty `~/.<host>/skills/` trees and nothing to key off.+ // Gating the walk on "we deleted something just now" made those+ // permanently unreachable — the plan skipped the host and the clutter the+ // cleanup exists to remove stayed forever. The walk below is self-limiting+ // (`willBeEmpty` is false for an absent or non-empty dir), so letting it+ // run unconditionally costs one stat per host and catches that state.++ // Walk up from `skills/` to the entry's hardcoded root, stopping at the+ // first dir that would still hold something.+ const stopAt = join(home, entry.pruneRoot);+ let cur = skillsDir;+ while (willBeEmpty(cur, doomed)) {+ emptyDirs.push(cur);+ doomed.add(cur);+ if (cur === stopAt) break;+ const parent = dirname(cur);+ // Belt-and-braces: never step to or above `home`, whatever the table says.+ if (parent === cur || parent === home || !parent.startsWith(home + sep)) break;+ cur = parent;+ }+ }++ return { skillDirs, emptyDirs };+}++/**+ * True when `dir` still looks like an OK skill bundle we may remove.+ *+ * A bundle always ships a `SKILL.md`; an empty dir is also fine (nothing to+ * lose, and refusing would strand the husk forever — the same trap that made+ * the prune unreachable on already-swept machines). Anything else means the+ * path was replaced between the prompt and here, so leave it: the user was+ * shown a bundle, not whatever this now is.+ */+function isRemovableBundleDir(dir: string): boolean {+ try {+ if (!lstatSync(dir).isDirectory()) return false;+ const entries = readdirSync(dir);+ return entries.length === 0 || entries.includes('SKILL.md');+ } catch {+ return false;+ }+}++/**+ * Every path the sweep is EVER allowed to delete for a given home, derived from+ * the table alone — no filesystem access, no dependence on the caller's plan.+ */+function legalSweepPaths(home: string): { skillDirs: Set<string>; emptyDirs: Set<string> } {+ const skillDirs = new Set<string>();+ const emptyDirs = new Set<string>();+ for (const entry of LEGACY_FANOUT_HOSTS) {+ const skillsDir = join(home, entry.hostDir, 'skills');+ for (const name of LEGACY_SWEEPABLE_SKILL_NAMES) skillDirs.add(join(skillsDir, name));+ const stopAt = join(home, entry.pruneRoot);+ let cur = skillsDir;+ while (true) {+ emptyDirs.add(cur);+ if (cur === stopAt) break;+ const parent = dirname(cur);+ if (parent === cur || parent === home || !parent.startsWith(home + sep)) break;+ cur = parent;+ }+ }+ return { skillDirs, emptyDirs };+}++/**+ * Execute a plan from `planLegacyFanoutSweep`. Returns the paths actually+ * removed so the caller reports real work rather than intent.+ *+ * The plan is RE-VALIDATED against `legalSweepPaths` before anything is+ * touched, and a path outside that set aborts the whole sweep without deleting+ * anything. `apply` is exported and takes plain strings, so trusting its input+ * would make any future caller — or any bug that mutates a plan between the+ * prompt and here — able to recursively delete an arbitrary directory. The+ * legal set comes from the frozen host table, so validation cannot drift from+ * what planning can produce.+ *+ * `skillDirs` are removed recursively (they hold OK's own bundle files);+ * `emptyDirs` go via `rmdir`, which refuses a non-empty directory AND refuses a+ * symlink leaf — so a race between plan and apply (the user installs the tool+ * in between) can never destroy their data. `rmdir` does NOT protect against a+ * symlinked ANCESTOR, though: the path is still resolved through the link, so+ * both legs re-check `isSymlinkFreeUnder` immediately before unlinking.+ */+export function applyLegacyFanoutSweep(homeInput: string, plan: LegacyFanoutSweepPlan): string[] {+ const home = assertUsableHome(homeInput);+ const legal = legalSweepPaths(home);++ const illegal = [+ ...plan.skillDirs.filter((p) => !legal.skillDirs.has(p)),+ ...plan.emptyDirs.filter((p) => !legal.emptyDirs.has(p)),+ ];+ if (illegal.length > 0) {+ // Loud, and BEFORE any delete: a plan that doesn't come from+ // `planLegacyFanoutSweep` is a bug, and the safe response to a bug whose+ // blast radius is `rm -rf` is to do nothing at all.+ throw new Error(+ `refusing skill cleanup — ${illegal.length} path(s) outside the known legacy set: ${illegal.join(', ')}`,+ );+ }++ const removed: string[] = [];+ for (const dir of plan.skillDirs) {+ // Re-check at delete time, not just at plan time. This is the one+ // recursive removal in the sweep, so the window between showing the user a+ // path and unlinking it is the one place a swapped symlink would cost+ // real data. `emptyDirs` below needs no equivalent — `rmdir` refuses to+ // follow a link or empty a non-empty dir on its own.+ if (!isSymlinkFreeUnder(home, dir)) continue;+ if (!isRemovableBundleDir(dir)) continue;+ try {+ rmSync(dir, { recursive: true, force: true });+ removed.push(dir);+ } catch {+ // Best-effort cleanup — a stubborn dir must not fail `repair-skills`,+ // whose actual job is the install.+ }+ }+ // Deepest-first: `planLegacyFanoutSweep` pushes `skills/` before its parents.+ for (const dir of plan.emptyDirs) {+ // `rmdir` refuses a symlink LEAF but still resolves a symlinked ANCESTOR,+ // so a link swapped in after planning would have it remove a directory at+ // the link target. Only ever an empty one — but "empty" is not ours to+ // assume about somewhere else on disk, so re-check the chain here.+ if (!isSymlinkFreeUnder(home, dir)) continue;+ try {+ rmdirSync(dir);+ removed.push(dir);+ } catch {+ // Non-empty (raced) or unreadable — leave it. Never force.+ }+ }+ return removed;+}+export interface SkillBundleTarget {/** Absolute path of the bundle directory to remove. */path: string;@@ -48,7 +383,12 @@ export interface SkillBundleTarget {* home dir. Ordered central-first per bundle so plan output reads bundle by* bundle.*/-export function userGlobalSkillBundleTargets(home: string): SkillBundleTarget[] {+export function userGlobalSkillBundleTargets(homeInput: string): SkillBundleTarget[] {+ // Same guard as the legacy sweep: `join('', '.agents', …)` is RELATIVE, and+ // `os.homedir()` returns `$HOME` verbatim — an empty or relative HOME would+ // aim this teardown at the process cwd. Predates the sweep, so it was missed+ // when the sweep was hardened.+ const home = assertUsableHome(homeInput);const targets: SkillBundleTarget[] = [];for (const bundleId of USER_GLOBAL_BUNDLE_IDS) {const name = BUNDLE_SKILL_NAME[bundleId];diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.tsindex 6f60f2cf3..2e4ba081e 100644--- a/packages/core/src/constants/editors.ts+++ b/packages/core/src/constants/editors.ts@@ -82,9 +82,10 @@ export const EDITOR_LABELS = {* broadcasting into a shared dir.** The asymmetry with USER/global scope is deliberate: `~/.agents/skills` IS the- * right hub there, because the `skills` CLI fans the bundled discovery skill out- * from it via `--agent '*'` (see `skill-install.ts`) — a shared convergence- * point that exists globally but has no per-project equivalent.+ * right hub there — several hosts (Codex, OpenCode, Cursor) read it natively at+ * user scope, so it is a real convergence point with no per-project equivalent.+ * The user-global writer (`installUserSkill`) writes it ALONGSIDE the per-host+ * dirs of detected hosts, and only when at least one host is detected.** The CLI's `EDITOR_TARGETS.projectSkillPath` is a second source for the same* map and must move in lock-step.diff --git a/packages/core/src/skill-state/schema.ts b/packages/core/src/skill-state/schema.tsindex a1bda8066..7530d4714 100644--- a/packages/core/src/skill-state/schema.ts+++ b/packages/core/src/skill-state/schema.ts@@ -7,7 +7,8 @@** Two actively-written targets at v0:* - `claude-cowork` — Track 2: `.skill` zip + Claude Desktop manual upload- * - `cli-hosts` — Track 1: `npx skills add --agent '*' -g`+ * - `cli-hosts` — Track 1: user-global bundle copied into each detected+ * agent host (`installUserSkill`)** Per-target metadata at v0:* - `version` — semver-ish string (regex-validated)diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex b46a5bf9e..6e31a1569 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -518,6 +518,8 @@ export {type BuildAndOpenSkillResult,type BuildAndOpenSkillStatus,buildAndOpenSkill,+ type DetectedSkillHost,+ detectUserSkillHosts,type InstallUserSkillOptions,type InstallUserSkillResult,installUserSkill,diff --git a/packages/server/src/skill-install-events.ts b/packages/server/src/skill-install-events.tsindex 5aa80e60a..f2ba80542 100644--- a/packages/server/src/skill-install-events.ts+++ b/packages/server/src/skill-install-events.ts@@ -33,7 +33,12 @@ export type SkillInstallEventSurface =| 'server-build-and-open'/** Electron bridge path: `okDesktop.skill.buildAndOpen` → `handleBuildAndOpen` (desktop main). */| 'electron-build-and-open'- /** Track 1 install: `installUserSkill` → `npx skills add --agent '*' -g`. */+ /**+ * Track 1 install: `installUserSkill` copying the user-global bundle into+ * each detected agent host. The `npx` in the name is historical — the value+ * is persisted in existing state files and event logs, so it outlives the+ * subprocess it was named for.+ */| 'cli-npx-skills-add'/** Desktop main-process direct invoke of `installUserSkill` (first-launch flow). */| 'desktop-direct'diff --git a/packages/server/src/skill-install.test.ts b/packages/server/src/skill-install.test.tsindex f6f7c9254..9ec111c25 100644--- a/packages/server/src/skill-install.test.ts+++ b/packages/server/src/skill-install.test.ts@@ -1,25 +1,31 @@/**- * Unit tests for installUserSkill.+ * Unit tests for installUserSkill + buildAndOpenSkill.*- * Subprocess invocation is mocked via the injectable `spawn` option.- * Each test uses a fresh `mkdtempSync`-backed HOME so the sidecar write path- * touches only the tmpdir — never the real `~/`.+ * `installUserSkill` writes directly (no subprocess), so these tests assert+ * against real files under a fresh `mkdtempSync`-backed HOME — never the real+ * `~/`. `buildAndOpenSkill` still shells out for the OS file association, and+ * mocks it via the injectable `spawnFn`.*/import type { SpawnOptions } from 'node:child_process';-import { EventEmitter } from 'node:events';-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ writeFileSync,+} from 'node:fs';import { readFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { PassThrough } from 'node:stream';+import { HOSTS_WITH_USER_SKILL_DIR } from '@inkeep/open-knowledge-core';import { beforeEach, describe, expect, test } from 'vitest';import {buildAndOpenSkill,- type InstallUserSkillOptions,+ detectUserSkillHosts,installUserSkill,- quoteForWindowsShell,type SkillInstallLogger,type SpawnLike,} from './skill-install.ts';@@ -29,71 +35,6 @@ async function readServerVersion(): Promise<string> {return (JSON.parse(raw) as { version: string }).version;}-/**- * Build a fake ChildProcess that scripts one emit() lifecycle — enough to- * exercise `installUserSkill`'s listener contract without spawning a real- * subprocess.- */-interface FakeChildScript {- /** Bytes to push to the stderr stream before exit. */- stderr?: string;- /** How the process terminates. */- outcome: { kind: 'exit'; code: number } | { kind: 'error'; error: Error } | { kind: 'hang' };-}--function makeFakeChild(script: FakeChildScript): ReturnType<SpawnLike> {- const child = new EventEmitter() as unknown as ReturnType<SpawnLike>;- const stderr = new PassThrough();- Object.assign(child, {- stderr,- stdout: new PassThrough(),- stdin: null,- kill: (_sig?: NodeJS.Signals | number) => {- // Mirror real ChildProcess: kill triggers an exit/error event unless we've already settled.- return true;- },- });-- queueMicrotask(() => {- if (script.stderr) stderr.emit('data', Buffer.from(script.stderr, 'utf-8'));- if (script.outcome.kind === 'exit') {- (child as unknown as EventEmitter).emit('exit', script.outcome.code, null);- } else if (script.outcome.kind === 'error') {- (child as unknown as EventEmitter).emit('error', script.outcome.error);- }- // 'hang' — emit nothing. installUserSkill should hit its timeout.- });-- return child;-}--interface CapturedSpawn {- command: string;- args: readonly string[];- opts: SpawnOptions;-}--function makeSpawnFake(script: FakeChildScript): {- spawn: SpawnLike;- calls: CapturedSpawn[];-} {- const calls: CapturedSpawn[] = [];- const spawn: SpawnLike = (command, args, opts) => {- calls.push({ command, args, opts });- return makeFakeChild(script);- };- return { spawn, calls };-}--function makeThrowingSpawn(err: Error): { spawn: SpawnLike; calls: CapturedSpawn[] } {- const calls: CapturedSpawn[] = [];- const spawn: SpawnLike = (command, args, opts) => {- calls.push({ command, args, opts });- throw err;- };- return { spawn, calls };-}-interface RecordedLog {level: 'warn' | 'info';data: unknown;@@ -113,7 +54,19 @@ function freshHome(): string {return mkdtempSync(join(tmpdir(), 'ok-skill-install-'));}-// Track-1 active path: `~/.ok/skill-state/cli-hosts`.+/** Create a host's dotdir so `detectUserSkillHosts` counts it as installed. */+function installHost(home: string, hostDir: string): void {+ mkdirSync(join(home, hostDir), { recursive: true });+}++/** Every host dir OK knows about — the candidate set detection filters. */+const ALL_HOST_DIRS = HOSTS_WITH_USER_SKILL_DIR.map((h) => h.hostDir);++/** Top-level entries a run created under HOME, sorted. */+function homeEntries(home: string): string[] {+ return readdirSync(home).sort();+}+// State lives at `~/.ok/skill-state.yml` as a single YAML document.const YAML_REL = ['.ok', 'skill-state.yml'] as const;function yamlPathFor(home: string): string {@@ -127,10 +80,14 @@ function centralSkillDirFor(home: string): string {return join(home, ...CENTRAL_SKILL_REL);}+function hostSkillDirFor(home: string, hostDir: string): string {+ return join(home, hostDir, 'skills', 'open-knowledge-discovery');+}+/**- * Pretend the `skills` CLI already wrote the central source. Pairs with+ * Pretend a prior install already wrote the central source. Pairs with* writeSidecar to simulate a real prior install — without both, the- * skip-current gate now correctly rejects the sidecar as stale.+ * skip-current gate correctly rejects the sidecar as stale.*/function writeCentralSkill(home: string): void {const dir = centralSkillDirFor(home);@@ -143,11 +100,7 @@ function findWarn(records: RecordedLog[], event: string): RecordedLog | undefinereturn records.find((r) => r.level === 'warn' && (r.data as { event?: string }).event === event);}-/**- * Pretend a pre-split `open-knowledge` user-global skill dir exists at one- * host. `installUserSkill` only spawns the legacy `npx skills remove` when- * such a dir is on disk — a fresh machine skips the subprocess entirely.- */+/** Pretend a pre-split `open-knowledge` user-global skill dir exists at one host. */function writeLegacyUserSkill(home: string, hostDir = '.claude'): void {const dir = join(home, hostDir, 'skills', 'open-knowledge');mkdirSync(dir, { recursive: true });@@ -215,332 +168,279 @@ function readInstallEvents(home: string): Array<Record<string, unknown>> {.map((l) => JSON.parse(l) as Record<string, unknown>);}-describe('quoteForWindowsShell', () => {- test('quotes whitespace-bearing args, escaping inner double-quotes', () => {- expect(quoteForWindowsShell('C:\\Users\\John Doe\\skills\\discovery')).toBe(- '"C:\\Users\\John Doe\\skills\\discovery"',- );- expect(quoteForWindowsShell('a "b" c')).toBe('"a \\"b\\" c"');+// ─── Scope discipline (issue #820) ─────────────────────────────────────────+//+// The regression this suite exists to prevent: `ok init` once shelled out to+// `npx skills add … --agent '*'`, which bypassed that CLI's host detection and+// created a skill dir in every one of the ~75 hosts it knows — 51 of them for+// tools the reporter had never installed. OK writes agent INSTRUCTIONS, so a+// dir for an absent tool is a scope-of-consent violation, not just clutter.+// These tests pin the contract: writes land ONLY in detected hosts, and a home+// with no agent host gets nothing at all.++describe('installUserSkill — scope discipline', () => {+ test('no agent host detected → returns "no-hosts" and writes NO skill dirs', async () => {+ const home = freshHome();+ const { logger, records } = makeRecordingLogger();++ const result = await installUserSkill({ home, logger });++ expect(result).toBe('no-hosts');+ // Only OK's own state dir may appear — no host dotdirs, no `.agents`.+ expect(homeEntries(home)).toEqual(['.ok']);+ expect(existsSync(centralSkillDirFor(home))).toBe(false);+ expect(+ records.some((r) => (r.data as { event?: string }).event === 'skill-install.no-hosts'),+ ).toBe(true);});- test('passes whitespace-free args through untouched (flags + the literal *)', () => {- expect(quoteForWindowsShell('*')).toBe('*');- expect(quoteForWindowsShell('--agent')).toBe('--agent');- expect(quoteForWindowsShell('C:\\Users\\mike\\skills\\discovery')).toBe(- 'C:\\Users\\mike\\skills\\discovery',- );+ test('never creates a dotdir for a host that is not installed', async () => {+ const home = freshHome();+ installHost(home, '.claude');++ await installUserSkill({ home });++ // `.claude` (installed) + `.agents` (central store) + `.ok` (state) only.+ expect(homeEntries(home)).toEqual(['.agents', '.claude', '.ok']);+ for (const hostDir of ALL_HOST_DIRS.filter((d) => d !== '.claude')) {+ expect(existsSync(join(home, hostDir))).toBe(false);+ }});-});-describe('installUserSkill — Windows npx.cmd shim', () => {- // On Windows `npx` is `npx.cmd`; Node's spawn cannot exec it without a shell.- // The injected `platform` lets us assert the shell shim on a POSIX runner.- test('platform "win32" spawns npx with shell:true', async () => {+ test('writes to every detected host, and only those', async () => {const home = freshHome();- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });+ installHost(home, '.claude');+ installHost(home, '.cursor');- const result = await installUserSkill({ home, spawn, platform: 'win32' });+ const result = await installUserSkill({ home });expect(result).toBe('installed');- expect(calls[0]?.command).toBe('npx');- expect(calls[0]?.opts.shell).toBe(true);- // The literal `*` must still reach npx (no whitespace → not quoted).- expect(calls[0]?.args).toContain('*');+ expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);+ expect(existsSync(join(hostSkillDirFor(home, '.cursor'), 'SKILL.md'))).toBe(true);+ expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(true);+ for (const hostDir of ALL_HOST_DIRS.filter((d) => d !== '.claude' && d !== '.cursor')) {+ expect(existsSync(hostSkillDirFor(home, hostDir))).toBe(false);+ }});- test('non-Windows platform spawns without a shell', async () => {+ test('"no-hosts" is recorded as skip-current with an explicit reason', async () => {const home = freshHome();- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- await installUserSkill({ home, spawn, platform: 'linux' });+ await installUserSkill({ home });- expect(calls[0]?.opts.shell ?? false).toBe(false);+ const events = readInstallEvents(home);+ expect(events.at(-1)?.outcome).toBe('skip-current');+ expect(events.at(-1)?.reason).toBe('no-hosts');+ });++ test('detectUserSkillHosts reports only the hosts present on disk', () => {+ const home = freshHome();+ expect(detectUserSkillHosts(home)).toEqual([]);+ installHost(home, '.codex');+ expect(detectUserSkillHosts(home).map((h) => h.hostDir)).toEqual(['.codex']);});});describe('installUserSkill — fresh install', () => {- test('no sidecar + subprocess exits 0 → adds discovery, returns "installed"', async () => {+ test('no sidecar + a detected host → writes the bundle, returns "installed"', async () => {const home = freshHome();- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });+ installHost(home, '.claude');const { logger, records } = makeRecordingLogger();- const result = await installUserSkill({ home, logger, spawn });+ const result = await installUserSkill({ home, logger });expect(result).toBe('installed');- // Fresh machine — no legacy `open-knowledge` dir — so one spawn: the `add`.- expect(calls.length).toBe(1);- expect(calls[0]?.command).toBe('npx');- expect(calls[0]?.args).toEqual([- '-y',- 'skills@~1.5.0',- 'add',- expect.stringContaining('assets/skills/discovery') as unknown as string,- '--agent',- '*',- '-g',- '-y',- '--copy',- ]);- // The rich `project` bundle never installs at user scope.- expect(calls[0]?.args.some((a) => /assets\/skills\/project/.test(a))).toBe(false);- expect((calls[0]?.opts.env as NodeJS.ProcessEnv)?.HOME).toBe(home);expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);- expect(records.some((r) => r.level === 'info' && /installed/i.test(r.message))).toBe(true);+ // The success log names real paths rather than asserting unverified detection.+ const installed = records.find(+ (r) => (r.data as { event?: string }).event === 'skill-install.installed',+ );+ expect(installed?.message).toContain(hostSkillDirFor(home, '.claude'));});- test('fresh machine with no legacy dir → npx skills remove is NOT spawned', async () => {+ test('install event carries bundle: "discovery"', async () => {const home = freshHome();- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });+ installHost(home, '.claude');- await installUserSkill({ home, spawn });+ await installUserSkill({ home });- expect(calls.some((c) => c.args.includes('remove'))).toBe(false);+ const events = readInstallEvents(home);+ expect(events.at(-1)?.bundle).toBe('discovery');+ expect(events.at(-1)?.outcome).toBe('installed');});- test('install event carries bundle: "discovery"', async () => {+ test('a shrinking bundle leaves no orphaned files from a prior version', async () => {const home = freshHome();- const { spawn } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });+ installHost(home, '.claude');+ const dest = hostSkillDirFor(home, '.claude');+ mkdirSync(dest, { recursive: true });+ writeFileSync(join(dest, 'STALE.md'), '# from an older bundle\n', 'utf-8');- await installUserSkill({ home, spawn });+ await installUserSkill({ home });- const events = readInstallEvents(home);- const installed = events.find((e) => e.outcome === 'installed');- expect(installed?.bundle).toBe('discovery');- expect(installed?.target).toBe('cli-hosts');+ expect(existsSync(join(dest, 'STALE.md'))).toBe(false);+ expect(existsSync(join(dest, 'SKILL.md'))).toBe(true);});});describe('installUserSkill — legacy migration', () => {- test('pre-split open-knowledge dir present → npx skills remove runs before the add', async () => {+ test('pre-split open-knowledge dir is removed before the discovery bundle lands', async () => {const home = freshHome();+ installHost(home, '.claude');writeLegacyUserSkill(home, '.claude');- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- const result = await installUserSkill({ home, spawn });+ const result = await installUserSkill({ home });expect(result).toBe('installed');- // Two subprocesses: the legacy `remove`, then the `add`.- expect(calls.length).toBe(2);- expect(calls[0]?.args).toEqual([- '-y',- 'skills@~1.5.0',- 'remove',- '--agent',- '*',- '-g',- 'open-knowledge',- ]);- expect(calls[1]?.args).toContain('add');- });-- test('legacy remove exiting non-zero is logged + swallowed; install still proceeds', async () => {+ expect(existsSync(join(home, '.claude', 'skills', 'open-knowledge'))).toBe(false);+ expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);+ });++ test('a pre-split dir in the central store is swept too', async () => {const home = freshHome();- writeLegacyUserSkill(home, '.cursor');- // The shared fake scripts every spawn — both `remove` and `add` exit 1.- // The non-zero `remove` must NOT abort the install; only the `add` gates it.- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 1 } });+ installHost(home, '.claude');+ writeLegacyUserSkill(home, '.agents');++ await installUserSkill({ home });++ expect(existsSync(join(home, '.agents', 'skills', 'open-knowledge'))).toBe(false);+ });++ test('fresh machine with no legacy dir → migration is a no-op', async () => {+ const home = freshHome();+ installHost(home, '.claude');const { logger, records } = makeRecordingLogger();- const result = await installUserSkill({ home, logger, spawn });+ await installUserSkill({ home, logger });- // `add` failed (exit 1) → 'failed'; the run did not throw, and the- // legacy-remove failure surfaced as its own swallowed warning.- expect(result).toBe('failed');- expect(calls[0]?.args).toContain('remove');- expect(findWarn(records, 'skill-install.legacy-remove-failed')).toBeDefined();+ expect(findWarn(records, 'skill-install.legacy-remove-failed')).toBeUndefined();});});describe('installUserSkill — idempotency (skip-current)', () => {- test('sidecar matches current version + central skill present → subprocess NOT invoked, returns "skip-current"', async () => {+ test('sidecar matches current version + central skill present → returns "skip-current"', async () => {const home = freshHome();- writeSidecar(home, `${currentVersion}\n`);+ installHost(home, '.claude');+ writeSidecar(home, currentVersion);writeCentralSkill(home);- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- const result = await installUserSkill({ home, spawn });+ const result = await installUserSkill({ home });expect(result).toBe('skip-current');- expect(calls.length).toBe(0);- expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);+ // Untouched: the gate short-circuits before any host write.+ expect(existsSync(hostSkillDirFor(home, '.claude'))).toBe(false);});- test('force bypasses the skip-current gate → subprocess IS invoked even when the version matches', async () => {+ test('force bypasses the skip-current gate', async () => {const home = freshHome();- writeSidecar(home, `${currentVersion}\n`);+ installHost(home, '.claude');+ writeSidecar(home, currentVersion);writeCentralSkill(home);- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- // `ok init` passes force so one bundle's shared-key version write can't- // freeze another bundle's content on an upgrade-then-reinit.- const result = await installUserSkill({ home, spawn, force: true });+ const result = await installUserSkill({ home, force: true });expect(result).toBe('installed');- expect(calls.length).toBe(1);+ expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);});test('sidecar without trailing newline still matches (tolerant parse)', async () => {const home = freshHome();+ installHost(home, '.claude');writeSidecar(home, currentVersion);writeCentralSkill(home);- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- const result = await installUserSkill({ home, spawn });- expect(result).toBe('skip-current');- expect(calls.length).toBe(0);+ expect(await installUserSkill({ home })).toBe('skip-current');});- test('sidecar matches but central skill dir is missing → reinstall fires, sidecar rewritten', async () => {+ test('sidecar matches but central skill dir is missing → reinstall fires', async () => {const home = freshHome();- writeSidecar(home, `${currentVersion}\n`);- // Deliberately do NOT call writeCentralSkill — simulates `npx skills remove -g`- // having nuked the skill while leaving the sidecar intact.- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- const { logger, records } = makeRecordingLogger();+ installHost(home, '.claude');+ writeSidecar(home, currentVersion);- const result = await installUserSkill({ home, logger, spawn });+ const result = await installUserSkill({ home });expect(result).toBe('installed');- // Fresh machine, no legacy dir — one spawn: the `add`.- expect(calls.length).toBe(1);- expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);- const reinstallLog = records.find(- (r) =>- r.level === 'info' &&- (r.data as { event?: string }).event === 'skill-install.reinstall-missing',- );- expect(reinstallLog).toBeDefined();+ expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(true);});-});-describe('installUserSkill — stale sidecar', () => {- test('sidecar version differs from package version → subprocess invoked, sidecar rewritten', async () => {+ test('the gate runs before detection — no host + matching sidecar still skips', async () => {const home = freshHome();- writeSidecar(home, '0.0.1\n');- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });-- const result = await installUserSkill({ home, spawn });+ writeSidecar(home, currentVersion);+ writeCentralSkill(home);- expect(result).toBe('installed');- expect(calls.length).toBe(1);- expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);+ expect(await installUserSkill({ home })).toBe('skip-current');});});-describe('installUserSkill — failure modes', () => {- test('subprocess non-zero exit → warning logged, sidecar NOT written, returns "failed"', async () => {+describe('installUserSkill — stale sidecar', () => {+ test('sidecar version differs from package version → reinstall, sidecar rewritten', async () => {const home = freshHome();- const { spawn } = makeSpawnFake({- stderr: 'no compatible agents detected',- outcome: { kind: 'exit', code: 1 },- });- const { logger, records } = makeRecordingLogger();+ installHost(home, '.claude');+ writeSidecar(home, '0.0.1-stale');+ writeCentralSkill(home);- const result = await installUserSkill({ home, logger, spawn });+ const result = await installUserSkill({ home });- expect(result).toBe('failed');- expect(readSidecarIfExists(home)).toBeNull();- const warnRecord = findWarn(records, 'skill-install.failed');- expect(warnRecord).toBeDefined();- expect(warnRecord?.data).toMatchObject({- event: 'skill-install.failed',- reason: 'nonzero-exit',- exitCode: 1,- });+ expect(result).toBe('installed');+ expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);});- test('subprocess hangs past timeout → killed, warning logged, returns "failed"', async () => {+ test('empty sidecar → treated as fresh install', async () => {const home = freshHome();- const { spawn } = makeSpawnFake({ outcome: { kind: 'hang' } });- const { logger, records } = makeRecordingLogger();-- const result = await installUserSkill({ home, logger, spawn, timeoutMs: 25 });+ installHost(home, '.claude');+ writeSidecar(home, '');- expect(result).toBe('failed');- expect(readSidecarIfExists(home)).toBeNull();- const warnRecord = findWarn(records, 'skill-install.failed');- expect(warnRecord?.data).toMatchObject({ event: 'skill-install.failed', reason: 'timeout' });+ expect(await installUserSkill({ home })).toBe('installed');});- test('spawn throws ENOENT (npx missing) → warning logged, returns "failed"', async () => {+ test('malformed sidecar content → treated as fresh install', async () => {const home = freshHome();- const enoent = Object.assign(new Error('spawn npx ENOENT'), { code: 'ENOENT' });- const { spawn } = makeThrowingSpawn(enoent);- const { logger, records } = makeRecordingLogger();+ installHost(home, '.claude');+ mkdirSync(join(home, '.ok'), { recursive: true });+ writeFileSync(yamlPathFor(home), 'not: [valid', 'utf-8');- const result = await installUserSkill({ home, logger, spawn });-- expect(result).toBe('failed');- expect(readSidecarIfExists(home)).toBeNull();- const warnRecord = findWarn(records, 'skill-install.failed');- expect(warnRecord?.data).toMatchObject({- event: 'skill-install.failed',- reason: 'spawn-error',- });+ expect(await installUserSkill({ home })).toBe('installed');});+});- test('child emits "error" (ENOENT surfaced async) → warning logged, returns "failed"', async () => {+describe('installUserSkill — failure modes', () => {+ test('every destination write failing → warning logged, sidecar NOT written, returns "failed"', async () => {const home = freshHome();- const { spawn } = makeSpawnFake({- outcome: { kind: 'error', error: new Error('spawn ENOENT') },- });+ installHost(home, '.claude');const { logger, records } = makeRecordingLogger();- const result = await installUserSkill({ home, logger, spawn });+ // Make both destinations unwritable by planting a FILE where the writer+ // needs a directory — `mkdirSync` then fails with ENOTDIR/EEXIST.+ writeFileSync(join(home, '.agents'), 'not a dir\n', 'utf-8');+ writeFileSync(join(home, '.claude', 'skills'), 'not a dir\n', 'utf-8');++ const result = await installUserSkill({ home, logger });expect(result).toBe('failed');expect(readSidecarIfExists(home)).toBeNull();- const warnRecord = findWarn(records, 'skill-install.failed');- expect(warnRecord?.data).toMatchObject({- event: 'skill-install.failed',- reason: 'spawn-error',- });+ expect(findWarn(records, 'skill-install.failed')).toBeDefined();});-});-describe('installUserSkill — sidecar tolerant parse', () => {- test('empty sidecar → treated as fresh install, subprocess invoked', async () => {+ test('a partial failure still installs the survivors and records the version', async () => {const home = freshHome();- writeSidecar(home, '');- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });-- const result = await installUserSkill({ home, spawn });-- expect(result).toBe('installed');- expect(calls.length).toBe(1);- });+ installHost(home, '.claude');+ installHost(home, '.cursor');+ const { logger, records } = makeRecordingLogger();- test('malformed sidecar content → treated as fresh install, subprocess invoked', async () => {- const home = freshHome();- writeSidecar(home, 'not-a-version-string\n');- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });+ // Only the cursor destination is blocked.+ writeFileSync(join(home, '.cursor', 'skills'), 'not a dir\n', 'utf-8');- const result = await installUserSkill({ home, spawn });+ const result = await installUserSkill({ home, logger });expect(result).toBe('installed');- expect(calls.length).toBe(1);+ expect(existsSync(join(hostSkillDirFor(home, '.claude'), 'SKILL.md'))).toBe(true);expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);+ expect(+ records.some((r) => (r.data as { event?: string }).event === 'skill-install.partial'),+ ).toBe(true);});});-describe('installUserSkill — HOME propagates to subprocess env', () => {- test('opts.home is passed as HOME env var to spawn', async () => {- const home = freshHome();- const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });- const opts: InstallUserSkillOptions = { home, spawn };-- await installUserSkill(opts);-- expect((calls[0]?.opts.env as NodeJS.ProcessEnv)?.HOME).toBe(host(calls).HOME);- });-});--// `host` shim suppresses an unused-import flag — `calls[0]?.opts.env` carries-// the HOME spec asserts; this scoped helper localizes the access pattern.-function host(calls: ReadonlyArray<{ opts: { env?: NodeJS.ProcessEnv } }>): NodeJS.ProcessEnv {- return (calls[0]?.opts.env ?? {}) as NodeJS.ProcessEnv;-}-// ─── buildAndOpenSkill ─────────────────────────────────────────────────────//// Shared primitive that produces `openknowledge.skill` and hands it to the OS@@ -792,3 +692,41 @@ describe('buildAndOpenSkill — install-state gate', () => {expect(second.status).toBe('skip-current');});});++describe('installUserSkill — home guard', () => {+ // Every path, including the recursive `rmSync` inside `replaceSkillDir`,+ // is built with `join(home, …)`, which is RELATIVE when home is. Returns+ // rather than throws: the function's contract is never-throws.+ test.each([+ '',+ '.',+ 'relative/home',+ ])('a non-absolute home (%j) fails without writing anything', async (bogus) => {+ const { logger, records } = makeRecordingLogger();+ expect(await installUserSkill({ home: bogus, logger })).toBe('failed');+ expect(findWarn(records, 'skill-install.failed')?.data).toMatchObject({+ reason: 'home-not-absolute',+ });+ // Not even the event log. `report` appends to `<home>/.ok/`, which for a+ // relative home lands in the process cwd — the first cut of this guard ran+ // AFTER `report` and littered the repo with `packages/server/.ok/` and+ // `packages/server/relative/home/.ok/`. Same bug class as the guard itself,+ // one layer over.+ expect(existsSync(join(process.cwd(), bogus, '.ok'))).toBe(false);+ });++ test('a relative home cannot touch a matching tree in the cwd', async () => {+ const box = freshHome();+ const decoy = join(box, '.claude', 'skills', 'open-knowledge-discovery');+ mkdirSync(decoy, { recursive: true });+ writeFileSync(join(decoy, 'SKILL.md'), '# mine\n', 'utf-8');+ const prev = process.cwd();+ process.chdir(box);+ try {+ expect(await installUserSkill({ home: '' })).toBe('failed');+ expect(existsSync(join(decoy, 'SKILL.md'))).toBe(true);+ } finally {+ process.chdir(prev);+ }+ });+});diff --git a/packages/server/src/skill-install.ts b/packages/server/src/skill-install.tsindex e65703b7b..7c43a34e3 100644--- a/packages/server/src/skill-install.ts+++ b/packages/server/src/skill-install.ts@@ -1,14 +1,16 @@import { type SpawnOptions, spawn } from 'node:child_process';+import { existsSync } from 'node:fs';import { stat } from 'node:fs/promises';import { homedir, platform as osPlatform } from 'node:os';-import { dirname, join, resolve as resolvePath } from 'node:path';+import { dirname, isAbsolute, join, resolve as resolvePath } from 'node:path';+import { type EditorId, HOSTS_WITH_USER_SKILL_DIR } from '@inkeep/open-knowledge-core';import {type BuildSkillZipResult,buildSkillZip,resolveBundledSkillDir,} from './build-skill-zip.ts';import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';-import { tracedMkdir } from './fs-traced.ts';+import { tracedCpSync, tracedMkdir, tracedMkdirSync, tracedRmSync } from './fs-traced.ts';import { getLogger } from './logger.ts';import { BUNDLE_SKILL_NAME, type BundleId } from './skill-bundles.ts';import { recordSkillInstallEvent, type SkillInstallEventOutcome } from './skill-install-events.ts';@@ -44,24 +46,13 @@ export type SpawnLike = (export interface InstallUserSkillOptions {/*** Override `$HOME`. The per-target install-state lives in- * `${home}/.ok/skill-state.yml` under target key `cli-hosts`.- * `HOME` env var is also overridden for the `npx skills` subprocess so it- * writes per-host skill copies under the overridden home. Tests pass a tmpdir- * here.+ * `${home}/.ok/skill-state.yml` under target key `cli-hosts`; the skill+ * copies land under `${home}/.agents/skills/` and `${home}/.<host>/skills/`.+ * Tests pass a tmpdir here.*/home?: string;/** Optional logger. Falls back to `console.warn` / `console.info`. */logger?: SkillInstallLogger;- /**- * Inject a `spawn`-like function for unit tests. Defaults to `node:child_process#spawn`.- * Production callers never pass this.- */- spawn?: SpawnLike;- /**- * Subprocess timeout in milliseconds. Defaults to 60_000 (60 s). Tests- * may lower this for faster coverage.- */- timeoutMs?: number;/*** Install-source attribution recorded on the per-target YAML entry.* Defaults to `'cli-npx-skills-add'` for the CLI / `ok init` path. The@@ -70,13 +61,6 @@ export interface InstallUserSkillOptions {* distinguish it from a user-typed `ok init`.*/surface?: SkillStateSurface;- /**- * Override the detected platform. Defaults to `process.platform`. On- * `'win32'` the `npx` subprocess is spawned with `shell:true` (see- * `runSpawn`). Tests inject `'win32'` to assert the `.cmd` shim path without- * a real Windows host.- */- platform?: NodeJS.Platform;/*** Which user-global bundle to install. Defaults to `'discovery'` so existing* callers (and the `ok init` discovery leg) are unchanged; `ok init` calls@@ -96,7 +80,7 @@ export interface InstallUserSkillOptions {force?: boolean;}-export type InstallUserSkillResult = 'installed' | 'skip-current' | 'failed';+export type InstallUserSkillResult = 'installed' | 'skip-current' | 'failed' | 'no-hosts';/*** Pre-split user-global skill name. The legacy migration removes any install@@ -107,19 +91,37 @@ export type InstallUserSkillResult = 'installed' | 'skip-current' | 'failed';const LEGACY_USER_SKILL_NAME = 'open-knowledge';/**- * Host dirs that may carry a pre-split `open-knowledge` user-global skill —- * the `--copy`-mode install targets. Mirrors the desktop reclaim's host set.+ * Vendor-neutral central store. Written only when at least one host is+ * detected — it is a convergence point FOR installed hosts (Codex, OpenCode,+ * Cursor read it natively), not a destination in its own right, so a machine+ * with no agent host gets nothing at all.*/-const LEGACY_USER_SKILL_HOST_DIRS = ['.claude', '.cursor', '.agents'] as const;+const CENTRAL_HOST_DIR = '.agents';-/** Pinned patch-range for the `skills` CLI. */-const SKILLS_CLI_SPEC = 'skills@~1.5.0';+function centralSkillDir(home: string, bundleName: string): string {+ return join(home, CENTRAL_HOST_DIR, 'skills', bundleName);+}-/** Subprocess timeout default. */-const DEFAULT_TIMEOUT_MS = 60_000;+/** A user-global skill destination: the central store, or one detected host. */+export interface DetectedSkillHost {+ /** Home-relative dotdir whose presence means the host is installed. */+ readonly hostDir: string;+ readonly editorId: EditorId;+}-function centralSkillDir(home: string, bundleName: string): string {- return join(home, '.agents', 'skills', bundleName);+/**+ * The OK-supported agent hosts actually present under `home`.+ *+ * STOP: this detection gate is load-bearing. OK writes agent INSTRUCTIONS, not+ * inert config — a skill dir created for a tool the user never installed is+ * both clutter and a scope-of-consent violation (issue #820, where a single+ * `ok init` created 51 tool-config dirs in a real `$HOME`). Every user-global+ * write site MUST filter through this. Host set comes from core's+ * `HOSTS_WITH_USER_SKILL_DIR`, derived from `EDITOR_PROJECT_SKILL_ROOT`, so it+ * can't drift from the editors OK actually supports.+ */+export function detectUserSkillHosts(home: string): DetectedSkillHost[] {+ return HOSTS_WITH_USER_SKILL_DIR.filter((host) => existsSync(join(home, host.hostDir)));}async function centralSkillExists(home: string, bundleName: string): Promise<boolean> {@@ -131,161 +133,130 @@ async function centralSkillExists(home: string, bundleName: string): Promise<boo}}-interface SpawnOutcome {- kind: 'ok' | 'nonzero' | 'timeout' | 'spawn-error';- exitCode?: number | null;- stderr: string;- error?: Error;-}-/**- * Quote one argv token for Windows `cmd.exe` when spawning with `shell:true`.- * cmd.exe joins the argv into a single command line and splits on whitespace,- * ignoring argv boundaries, so a whitespace-bearing token (notably the skill- * dir under a `C:\Users\<name with space>` home) must be double-quoted to- * survive as one argument. Whitespace-free tokens pass through untouched so a- * flag like `*` reaches `npx` literally.+ * Legacy migration: remove any pre-split user-global `open-knowledge` skill dir+ * before the `discovery` bundle lands. Swept across the detected hosts plus the+ * central store (Codex's former home before it moved to `.codex`). Fail-soft —+ * a removal failure is logged and swallowed; the install below is what the+ * result gates on. Sibling: `removeLegacyUserSkillDirs` in the desktop reclaim.*/-export function quoteForWindowsShell(arg: string): string {- return /\s/.test(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg;-}--function runSpawn(- spawnFn: SpawnLike,- command: string,- args: readonly string[],- env: NodeJS.ProcessEnv,- timeoutMs: number,- platform: NodeJS.Platform,-): Promise<SpawnOutcome> {- return new Promise((resolve) => {- let child: ReturnType<typeof spawn>;- // On Windows `npx` resolves to `npx.cmd`; Node's `spawn` refuses to exec a- // `.cmd`/`.bat` without a shell (hardened by CVE-2024-27980) and throws- // ENOENT. `shell:true` routes through cmd.exe instead — but cmd.exe does- // not re-quote argv, so whitespace-bearing args are quoted by us first.- const useShell = platform === 'win32';- const spawnArgs = useShell ? args.map(quoteForWindowsShell) : args;+function removeLegacyUserSkillDirs(+ home: string,+ hosts: readonly DetectedSkillHost[],+ logger: SkillInstallLogger,+): void {+ const legacyHostDirs = [...hosts.map((h) => h.hostDir), CENTRAL_HOST_DIR];+ for (const hostDir of legacyHostDirs) {+ const legacyDir = join(home, hostDir, 'skills', LEGACY_USER_SKILL_NAME);+ if (!existsSync(legacyDir)) continue;try {- child = spawnFn(- command,- spawnArgs,- withHiddenWindowsConsole({- env,- stdio: ['ignore', 'pipe', 'pipe'],- ...(useShell ? { shell: true } : {}),- }),+ tracedRmSync(legacyDir, { recursive: true, force: true });+ logger.info?.(+ { event: 'skill-install.legacy-removed', path: legacyDir },+ 'Removed pre-split `open-knowledge` user-global skill dir.',);} catch (err) {- resolve({ kind: 'spawn-error', stderr: '', error: err as Error });- return;+ logger.warn(+ { event: 'skill-install.legacy-remove-failed', path: legacyDir, err },+ 'Legacy `open-knowledge` skill removal failed; continuing with install.',+ );}-- let stderr = '';- let settled = false;- const settle = (outcome: SpawnOutcome) => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve(outcome);- };-- child.stderr?.on('data', (chunk: Buffer | string) => {- stderr += typeof chunk === 'string' ? chunk : chunk.toString('utf-8');- });-- child.on('error', (err) => {- // ENOENT on `npx` itself surfaces here.- settle({ kind: 'spawn-error', stderr, error: err });- });-- child.on('exit', (code) => {- if (code === 0) settle({ kind: 'ok', exitCode: code, stderr });- else settle({ kind: 'nonzero', exitCode: code, stderr });- });-- const timer = setTimeout(() => {- try {- child.kill('SIGTERM');- } catch {- /* already exited */- }- settle({ kind: 'timeout', stderr });- }, timeoutMs);- });+ }}/**- * True when any pre-split `open-knowledge` user-global skill dir is on disk.- * Gates the subprocess-spawning `npx skills remove` so a fresh machine with- * nothing to migrate pays no `npx` cost — mirrors the desktop reclaim's- * `existsSync` gate in `skill-reclaim.ts`.+ * Replace `destDir` with a fresh copy of `sourceDir`. `rm -rf` first so a+ * shrinking bundle can't leave orphaned files from a prior version behind.*/-async function anyLegacyUserSkillExists(home: string): Promise<boolean> {- for (const hostDir of LEGACY_USER_SKILL_HOST_DIRS) {- try {- const info = await stat(join(home, hostDir, 'skills', LEGACY_USER_SKILL_NAME));- if (info.isDirectory()) return true;- } catch {- /* absent — keep checking the remaining hosts */- }- }- return false;+function replaceSkillDir(sourceDir: string, destDir: string): void {+ tracedRmSync(destDir, { recursive: true, force: true });+ tracedMkdirSync(dirname(destDir), { recursive: true });+ tracedCpSync(sourceDir, destDir, { recursive: true });+}++/** Per-destination outcome, for the structured install log. */+interface SkillWriteEntry {+ path: string;+ status: 'written' | 'failed';+ error?: string;}/**- * Legacy migration: remove any pre-split user-global `open-knowledge` skill- * install before the new `discovery` bundle lands. No-op (no subprocess) when- * no legacy dir is on disk — a fresh machine pays no `npx` cost. Fail-soft:- * `npx skills remove` of an absent skill is expected to exit 0, but the- * outcome is not load-bearing — non-zero exit / timeout / spawn error is- * logged and swallowed. The subsequent `add` is what the install gates on.+ * Copy one bundle into the central store plus every detected host dir.+ * Callers pass an already-filtered `hosts` — this never probes for, or creates,+ * a dir belonging to an absent tool.*/-async function removeLegacyUserSkill(+function writeBundleToHosts(home: string,- spawnFn: SpawnLike,- env: NodeJS.ProcessEnv,- timeoutMs: number,- logger: SkillInstallLogger,- platform: NodeJS.Platform,-): Promise<void> {- if (!(await anyLegacyUserSkillExists(home))) return;- const args = ['-y', SKILLS_CLI_SPEC, 'remove', '--agent', '*', '-g', LEGACY_USER_SKILL_NAME];- const outcome = await runSpawn(spawnFn, 'npx', args, env, timeoutMs, platform);- if (outcome.kind !== 'ok') {- logger.warn(- {- event: 'skill-install.legacy-remove-failed',- reason: outcome.kind,- exitCode: outcome.exitCode,- stderr: outcome.stderr,- },- 'Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.',- );+ bundleName: string,+ sourceDir: string,+ hosts: readonly DetectedSkillHost[],+): SkillWriteEntry[] {+ const entries: SkillWriteEntry[] = [];+ const centralDest = centralSkillDir(home, bundleName);+ const destinations = [+ centralDest,+ ...hosts+ .map((host) => join(home, host.hostDir, 'skills', bundleName))+ // Defensive: a host dest that collapses onto the central store would be a+ // redundant double-write of the same bytes. No host root is `.agents`+ // today, but the guard keeps the central write authoritative if that+ // ever changes.+ .filter((dest) => dest !== centralDest),+ ];++ for (const dest of destinations) {+ try {+ replaceSkillDir(sourceDir, dest);+ entries.push({ path: dest, status: 'written' });+ } catch (err) {+ entries.push({+ path: dest,+ status: 'failed',+ error: err instanceof Error ? err.message : String(err),+ });+ }}+ return entries;}/**- * Install OpenKnowledge's user-global Agent Skill to every detected agent host.+ * Install one user-global OpenKnowledge Agent Skill bundle into the agent hosts+ * actually present under `home`.*- * Installs the SLIM `discovery` bundle only — the rich `project` bundle never- * lands at user scope; it ships project-local via `ok init`'s- * `writeProjectSkill`. Each invocation first removes any pre-split- * `open-knowledge` user-global install (fail-soft) then runs- * `npx skills@~1.5.0 add <discovery-dir> --agent '*' -g -y --copy`.+ * Writes directly — no subprocess, no network. This used to shell out to+ * `npx skills@~1.5.0 add … --agent '*' -g -y --copy`; `--agent '*'` bypassed+ * that CLI's host detection and created a skill dir in all ~75 hosts it knows,+ * so one `ok init` wrote 51 tool-config dirs for tools the user had never+ * installed (issue #820). Nothing about that dependency was load-bearing: OK+ * passes a local path (no source resolution), forces `--copy` (no symlinks),+ * and the CLI writes no lockfile or state at global scope — it contributed a+ * directory table, which OK already maintains in core for project scope. It+ * also cost a floating-range `npx -y` fetch-and-execute at init time and+ * third-party telemetry OK never opted out of.+ *+ * Destinations: the central `${home}/.agents/skills/<name>/` store plus+ * `${home}/.<host>/skills/<name>/` for each detected host — and NOTHING when no+ * host is detected (`'no-hosts'`), so a machine with no agent tooling gets no+ * dirs at all. See `detectUserSkillHosts` for why that gate is load-bearing.** Idempotency: the `cli-hosts` entry in `${home}/.ok/skill-state.yml` gates- * re-install. The subprocess is NOT invoked (and `'skip-current'` is returned)- * only when BOTH the recorded version matches the current+ * re-install. Nothing is written (and `'skip-current'` is returned) only when+ * BOTH the recorded version matches the current* `@inkeep/open-knowledge-server` package version AND the central skill* directory at `${home}/.agents/skills/open-knowledge-discovery` is still on- * disk. The disk-presence check exists because a manual `npx skills remove -g`- * (or equivalent rm) leaves the state file untouched, which would otherwise- * wedge the next `ok init` into a no-op despite the skill being gone.+ * disk. The disk-presence check exists because a manual `rm` of the skill+ * leaves the state file untouched, which would otherwise wedge the next+ * `ok init` into a no-op despite the skill being gone.*- * Always resolves (never throws). Non-zero exit, timeout, or spawn error on- * the `add` logs a warning via `opts.logger` (or `console.warn`) and returns- * `'failed'`.+ * Always resolves (never throws). Returns `'failed'` when no usable install+ * could be RECORDED — every destination write errored, a pre-write dependency+ * was missing (version read, bundled asset), or the state-file write failed+ * after the copies landed. That last case is why `'failed'` does not imply+ * "nothing on disk": the skill dirs exist but the version gate never advanced,+ * so the next run reinstalls rather than skipping. A partial host failure is+ * the opposite — it records the version and returns `'installed'`, because the+ * surviving copies are usable.*/export async function installUserSkill(opts: InstallUserSkillOptions = {},@@ -295,13 +266,28 @@ export async function installUserSkill(warn: (data, message) => getLogger('skills').warn(data, message),info: (data, message) => getLogger('skills').info(data, message),};- const spawnFn = opts.spawn ?? (spawn as SpawnLike);- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ // Historical enum value — kept verbatim because it is persisted in every+ // existing `~/.ok/skill-state.yml` and `skill-install-events.jsonl`; the+ // install no longer shells out to npx.const surfaceAttribution: SkillStateSurface = opts.surface ?? 'cli-npx-skills-add';- const platform = opts.platform ?? process.platform;const bundleId = opts.bundleId ?? 'discovery';const bundleName = BUNDLE_SKILL_NAME[bundleId];+ // FIRST, before anything derives a path from `home` — including `report`,+ // which appends the JSONL event log at `<home>/.ok/`. `join('', '.claude', …)`+ // is RELATIVE and `os.homedir()` returns `$HOME` verbatim, so a broken or+ // unset HOME sends every path below (the recursive `rmSync` in+ // `replaceSkillDir`, and the event log itself) into the process cwd — for the+ // CLI, the user's project. Nothing is recorded on this path: there is nowhere+ // safe to record it. Returns rather than throws: never-throws contract.+ if (!isAbsolute(home)) {+ logger.warn(+ { event: 'skill-install.failed', reason: 'home-not-absolute', home },+ 'Skill install aborted — $HOME is not an absolute path.',+ );+ return 'failed';+ }+const report = async (outcome: SkillInstallEventOutcome,version?: string,@@ -380,79 +366,71 @@ export async function installUserSkill(await report('failed', currentVersion, 'bundled-asset-missing');return 'failed';}- const env: NodeJS.ProcessEnv = { ...process.env, HOME: home };+ // Detect BEFORE writing anything. No detected host ⇒ no destinations ⇒ we+ // write nothing at all, not even the central store.+ const hosts = detectUserSkillHosts(home);+ if (hosts.length === 0) {+ logger.info?.(+ { event: 'skill-install.no-hosts', version: currentVersion },+ 'No supported agent host detected; skipping user-global skill install.',+ );+ await report('skip-current', currentVersion, 'no-hosts');+ return 'no-hosts';+ }// Drop any pre-split `open-knowledge` user-global install first (no-op on a- // fresh machine). Fail-soft — the `add` below is what the install gates on.- await removeLegacyUserSkill(home, spawnFn, env, timeoutMs, logger, platform);+ // fresh machine). Fail-soft — the writes below are what the result gates on.+ removeLegacyUserSkillDirs(home, hosts, logger);- // Install the bundle to every detected agent host.- const args = ['-y', SKILLS_CLI_SPEC, 'add', bundleDir, '--agent', '*', '-g', '-y', '--copy'];- const outcome = await runSpawn(spawnFn, 'npx', args, env, timeoutMs, platform);+ const entries = writeBundleToHosts(home, bundleName, bundleDir, hosts);+ const written = entries.filter((e) => e.status === 'written');+ const failed = entries.filter((e) => e.status === 'failed');- if (outcome.kind === 'ok') {- try {- await writeTargetVersion(home, 'cli-hosts', currentVersion, surfaceAttribution, logger);- } catch (err) {- logger.warn(- { event: 'skill-install.failed', reason: 'sidecar-write-failed', err },- 'Skill install succeeded but sidecar write failed.',- );- await report('failed', currentVersion, 'sidecar-write-failed');- return 'failed';- }- logger.info?.(- { event: 'skill-install.installed', version: currentVersion },- 'OpenKnowledge skill installed to detected agent hosts.',+ if (written.length === 0) {+ logger.warn(+ { event: 'skill-install.failed', reason: 'write-failed', entries: failed },+ 'Skill install failed — every destination write errored.',);- await report('installed', currentVersion);- return 'installed';+ await report('failed', currentVersion, 'write-failed');+ return 'failed';}- if (outcome.kind === 'timeout') {+ try {+ await writeTargetVersion(home, 'cli-hosts', currentVersion, surfaceAttribution, logger);+ } catch (err) {logger.warn(- { event: 'skill-install.failed', reason: 'timeout', timeoutMs, stderr: outcome.stderr },- 'Skill install subprocess timed out. Run manually: npx ' +- `${SKILLS_CLI_SPEC} add ${bundleDir} --agent '*' -g -y --copy`,+ { event: 'skill-install.failed', reason: 'sidecar-write-failed', err },+ 'Skill install succeeded but sidecar write failed.',);- await report('failed', currentVersion, 'timeout');+ await report('failed', currentVersion, 'sidecar-write-failed');return 'failed';}- if (outcome.kind === 'spawn-error') {+ if (failed.length > 0) {logger.warn(- {- event: 'skill-install.failed',- reason: 'spawn-error',- err: outcome.error,- stderr: outcome.stderr,- },- 'Skill install failed — `npx` unavailable or spawn errored. Run manually: npx ' +- `${SKILLS_CLI_SPEC} add ${bundleDir} --agent '*' -g -y --copy`,+ { event: 'skill-install.partial', version: currentVersion, entries: failed },+ 'Some agent hosts could not be written; the remaining copies are installed.',);- await report('failed', currentVersion, 'spawn-error');- return 'failed';}-- // nonzero- logger.warn(+ logger.info?.({- event: 'skill-install.failed',- reason: 'nonzero-exit',- exitCode: outcome.exitCode,- stderr: outcome.stderr,+ event: 'skill-install.installed',+ version: currentVersion,+ hosts: hosts.map((h) => h.editorId),+ paths: written.map((e) => e.path),},- 'Skill install subprocess exited non-zero. Run manually: npx ' +- `${SKILLS_CLI_SPEC} add ${bundleDir} --agent '*' -g -y --copy`,+ `OpenKnowledge skill installed to ${written.length} location(s): ${written+ .map((e) => e.path)+ .join(', ')}`,);- await report('failed', currentVersion, `nonzero-exit:${outcome.exitCode ?? 'unknown'}`);- return 'failed';+ await report('installed', currentVersion);+ return 'installed';}// ─── Claude Desktop install (.skill file + OS file association) ────────────//-// Distinct surface from `installUserSkill` above (which targets Claude-// CLI / Cursor / Codex via `npx skills add`). This path produces an+// Distinct surface from `installUserSkill` above (which copies the bundle+// into Claude Code / Cursor / Codex skill dirs). This path produces an// `openknowledge.skill` zip and hands it to the OS so Claude Desktop's native// install dialog takes over. Shared consumers: `ok install-skill` CLI,// `POST /api/install-skill`. The Electron `okDesktop.skill.buildAndOpen`diff --git a/packages/server/src/skill-state.ts b/packages/server/src/skill-state.tsindex 33f7cc438..1928a4877 100644--- a/packages/server/src/skill-state.ts+++ b/packages/server/src/skill-state.ts@@ -8,8 +8,8 @@* - `claude-cowork` — written by `buildAndOpenSkill` (server HTTP path) and* `handleBuildAndOpen` (desktop Electron bridge). Read by the renderer's* install gate before triggering a fresh `.skill` rebuild.- * - `cli-hosts` — written by `installUserSkill` after a successful- * `npx skills add --agent '*' -g` subprocess. Replaces the legacy+ * - `cli-hosts` — written by `installUserSkill` after it copies the+ * user-global bundle into the detected agent hosts. Replaces the legacy* `~/.ok/skill-installed-version` file (migrated on first encounter).** `recordedAt` is in-band: the YAML's own mtime is no longer authoritative.