Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(install): drive harness presence from toolscan discovery (#591)
Alot1z39d07342a7ae
diff --git a/.github/fixtures/harness-smoke/README.md b/.github/fixtures/harness-smoke/README.mdnew file mode 100644index 00000000..41567238--- /dev/null+++ b/.github/fixtures/harness-smoke/README.md@@ -0,0 +1,20 @@+# Harness smoke fixture++This fixture is intentionally small and offline. It is consumed by the+`harness-install-smoke` CI job through `TOOLSCAN_PATH`.++- `claude` — a fake `claude` binary the job copies to `$HOME/.local/bin/claude`+ (off PATH, exactly where toolscan's extra scan roots matter). Only the fake+ toolscan output names it, so the CLI must both decide presence from toolscan+ and *execute* the absolute path toolscan reported — if the seam regressed to+ PATH-only execution, `ix mcp install` would report a false `conflict`.+- `toolscan.mjs` — fake toolscan output naming `claude` at+ `/tmp/ix-harness-home/.local/bin/claude` (the job's HOME).+- The fixture HOME starts empty, so no config-directory probe can make an+ absent host look present. `codex`, `agents` and `cursor` are in the skills+ table but absent here; `openclaw`/`gemini`/`opencode`/`vscode` have no+ skills convention and must not appear as install targets at all.++`ix mcp install` is exercised with `--host claude codex openclaw` (the same+registry restriction the old `HARNESS_HOSTS_FILE` fixture provided; an unknown+host id fails loudly, so a renamed host cannot pass silently).\ No newline at end of filediff --git a/.github/fixtures/harness-smoke/claude b/.github/fixtures/harness-smoke/claudenew file mode 100755index 00000000..ea747608--- /dev/null+++ b/.github/fixtures/harness-smoke/claude@@ -0,0 +1,9 @@+#!/usr/bin/env node++if (process.argv[2] === "mcp" && process.argv[3] === "list") {+ process.stdout.write("configured servers:\n");+ process.exit(0);+}++process.stderr.write("unsupported fixture invocation\n");+process.exit(2);diff --git a/.github/fixtures/harness-smoke/claude.cmd b/.github/fixtures/harness-smoke/claude.cmdnew file mode 100644index 00000000..c0589767--- /dev/null+++ b/.github/fixtures/harness-smoke/claude.cmd@@ -0,0 +1,11 @@+@echo off+rem Windows twin of the `claude` fixture: a shebang script cannot be spawned+rem by CreateProcess, so on Windows the fake CLI is a .cmd shim that answers+rem the host's `mcp list` probe exactly like the POSIX fixture. Kept ASCII:+rem cmd and CP1252 consoles mangle anything else.+if "%~1"=="mcp" if "%~2"=="list" (+ echo configured servers:+ exit /b 0+)+echo unsupported fixture invocation 1>&2+exit /b 2\ No newline at end of filediff --git a/.github/fixtures/harness-smoke/toolscan.mjs b/.github/fixtures/harness-smoke/toolscan.mjsnew file mode 100644index 00000000..ba713144--- /dev/null+++ b/.github/fixtures/harness-smoke/toolscan.mjs@@ -0,0 +1,14 @@+#!/usr/bin/env node++// The smoke job installs the fake claude at $HOME/.local/bin and keeps it OFF+// PATH; only this scan names it. The path must match the job's HOME so the+// CLI can exec the discovered absolute path — resolve it from the environment+// rather than hardcoding the job's temp HOME, and report the .cmd twin on+// Windows (a shebang script cannot be spawned by CreateProcess; hosts.ts runs+// .cmd shims through cmd, which is exactly the branch this leg exercises).+const home = (process.env.HOME || "/tmp/ix-harness-home").replace(/\\/g, "/");+const claude = process.platform === "win32" ? `${home}/.local/bin/claude.cmd` : `${home}/.local/bin/claude`;+process.stdout.write(JSON.stringify({+ tools: [{ name: "claude", path: claude, source: "root" }],+ truncated: false,+}));\ No newline at end of filediff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 21034eba..d8df58f3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -315,6 +315,218 @@ jobs:working-directory: ix-clirun: node scripts/check-api-parity.mjs+ # ── Harness installer smoke ─────────────────────────────────────────────+ # Keep this in a clean container and feed both surfaces the same tiny fixture.+ # The real machine's PATH and home directory must not decide this test: if the+ # fixture disappears or the helper stops consuming toolscan output, the+ # positive/negative assertions below fail instead of silently passing.+ #+ # The fake claude lives at $HOME/.local/bin — deliberately NOT on PATH — and+ # only the fake toolscan knows it, so this job exercises the seam's motivating+ # case: presence decided by toolscan, and the off-PATH CLI invoked through+ # the absolute path toolscan reported. If that threading regressed, inspect+ # would ENOENT and the CLI would report a false conflict instead of+ # would-register.+ harness-install-smoke:+ name: Harness install smoke+ runs-on: ubuntu-latest+ container: node:22-bookworm+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Install Ix CLI dependencies+ working-directory: ix-cli+ run: npm ci --silent+ - name: Build Ix CLI+ working-directory: ix-cli+ run: npm run build+ - name: Exercise the skills table and shell installer+ shell: bash+ env:+ HOME: /tmp/ix-harness-home+ HARNESS_HOME: /tmp/ix-harness-home+ run: |+ set -euo pipefail+ # This job runs in a container, where the github.workspace context+ # resolves to the HOST path (/home/runner/work/...) that does not+ # exist inside the container. Resolve fixtures against the step cwd+ # (the checkout root) so the path is right on host and container.+ FIXTURE="$PWD/.github/fixtures/harness-smoke"+ test -f "$FIXTURE/claude" || { echo "fixture missing: $FIXTURE"; ls -la .github/fixtures/harness-smoke/ || true; exit 1; }+ rm -rf "$HOME"+ mkdir -p "$HOME/.local/bin"+ # Installed off PATH, exactly where toolscan's extra roots matter.+ cp "$FIXTURE/claude" "$HOME/.local/bin/claude"+ chmod +x "$HOME/.local/bin/claude"+ export TOOLSCAN_PATH="$FIXTURE/toolscan.mjs"++ rows=$(node ix-cli/scripts/skill-harnesses.mjs --probe)+ printf '%s\n' "$rows"+ grep -Fq 'claude|Claude Code|claude|~/.claude|~/.claude/skills|1|toolscan' <<<"$rows"+ grep -Fq 'codex|Codex CLI|codex|~/.codex|~/.codex/skills|0|none' <<<"$rows"+ grep -Fq 'agents|Agents (agents.md)||~/.agents|~/.agents/skills|0|none' <<<"$rows"+ grep -Fq 'cursor|Cursor|cursor|~/.cursor|~/.cursor/skills-cursor|0|none' <<<"$rows"+ # Harnesses without a skills convention must not be install targets.+ ! grep -Fq 'openclaw' <<<"$rows"+ ! grep -Fq 'gemini' <<<"$rows"++ install_out=$(bash scripts/install-skill.sh --dry-run)+ printf '%s\n' "$install_out"+ grep -Fq 'would install: /tmp/ix-harness-home/.claude/skills/ix' <<<"$install_out"+ test ! -e "$HOME/.claude/skills/ix"++ shell_json=$(bash scripts/install-skill.sh --dry-run --json)+ printf '%s\n' "$shell_json"+ node -e '+ const r = JSON.parse(require("node:fs").readFileSync(0, "utf8"));+ const byId = new Map(r.hosts.map((h) => [h.id, h]));+ const claude = byId.get("claude");+ if (claude?.action !== "would-install") throw new Error("claude not would-install in shell report");+ if (claude?.detectedVia !== "toolscan") throw new Error("claude detection source not toolscan in shell report");+ if (!claude?.dest.endsWith("/.claude/skills/ix")) throw new Error("claude dest wrong: " + claude?.dest);+ for (const id of ["codex", "agents", "cursor"]) {+ const h = byId.get(id);+ if (h?.action !== "skip") throw new Error(id + " not skipped in shell report");+ if (h?.detectedVia !== "none") throw new Error(id + " detection source not none in shell report");+ }+ ' <<<"$shell_json"+ - name: Exercise ix mcp install dry-run against the off-PATH fixture+ shell: bash+ env:+ HOME: /tmp/ix-harness-home+ working-directory: ix-cli+ run: |+ set -euo pipefail+ # Same container-path rationale as the step above: derive the fixture+ # from the step cwd (this step runs in ix-cli) instead of the+ # host-resolved github.workspace context.+ FIXTURE="$(cd .. && pwd)/.github/fixtures/harness-smoke"+ export TOOLSCAN_PATH="$FIXTURE/toolscan.mjs"+ test -f "$TOOLSCAN_PATH" || { echo "toolscan fixture missing: $TOOLSCAN_PATH"; exit 1; }+ # --host restricts the registry the same way the old env fixture did;+ # an unknown id fails loudly, so a renamed host cannot pass silently.+ node dist/cli/main.js mcp install --host claude codex openclaw --dry-run --format json | tee /tmp/mcp-install.json+ node -e '+ const r = require("/tmp/mcp-install.json");+ const byId = new Map(r.hosts.map((h) => [h.id, h]));+ // claude is NOT on PATH here — only the fake toolscan names it, and+ // inspect must run the absolute path toolscan reported. A would-+ // register proves the threading; a conflict would mean the seam+ // regressed to PATH-only execution.+ if (byId.get("claude")?.outcome !== "would-register")+ throw new Error("claude was not detected: " + JSON.stringify(byId.get("claude")));+ if (byId.get("claude")?.detectedVia !== "toolscan")+ throw new Error("claude was not detected via toolscan: " + byId.get("claude")?.detectedVia);+ if (byId.get("codex")?.outcome !== "not-installed") throw new Error("codex was detected unexpectedly");+ if (byId.get("codex")?.detectedVia !== "none") throw new Error("codex detection source not reported");+ if (byId.get("openclaw")?.outcome !== "not-installed") throw new Error("openclaw was detected unexpectedly");+ if (byId.get("openclaw")?.detectedVia !== "none") throw new Error("openclaw detection source not reported");+ '++ # Windows twin of the harness smoke: the Linux job runs in a clean container,+ # but the Windows branches of this surface — the `where` probe, the cmd-shim+ # execution path (hosts.ts run/quoteForCmd), and install-skill.sh under Git+ # Bash — are never executed there. This leg runs the same two batteries on a+ # real windows-2022 runner. The fake claude is the .cmd twin (shebang scripts+ # cannot be spawned by CreateProcess) and toolscan.mjs reports the platform+ # twin's path; everything else is byte-for-byte the Linux assertions. No+ # container (Linux-only), no mktemp: the hermetic HOME derives from+ # runner.temp, the platform temp API.+ harness-install-smoke-windows:+ name: Harness install smoke (Windows)+ runs-on: windows-2022+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: "22"+ cache: "npm"+ cache-dependency-path: ix-cli/package-lock.json+ - name: Install Ix CLI dependencies+ working-directory: ix-cli+ run: npm ci --silent+ - name: Build Ix CLI+ working-directory: ix-cli+ run: npm run build+ - name: Exercise the skills table and shell installer (Git Bash)+ shell: bash+ env:+ HOME: ${{ runner.temp }}/ix-harness-home+ HARNESS_HOME: ${{ runner.temp }}/ix-harness-home+ run: |+ set -euo pipefail+ FIXTURE="$PWD/.github/fixtures/harness-smoke"+ test -f "$FIXTURE/claude.cmd" || { echo "fixture missing: $FIXTURE"; ls -la .github/fixtures/harness-smoke/ || true; exit 1; }+ rm -rf "$HOME"+ mkdir -p "$HOME/.local/bin"+ # Installed off PATH, exactly where toolscan's extra roots matter.+ cp "$FIXTURE/claude.cmd" "$HOME/.local/bin/claude.cmd"+ export TOOLSCAN_PATH="$FIXTURE/toolscan.mjs"++ rows=$(node ix-cli/scripts/skill-harnesses.mjs --probe)+ printf '%s\n' "$rows"+ grep -Fq 'claude|Claude Code|claude|~/.claude|~/.claude/skills|1|toolscan' <<<"$rows"+ grep -Fq 'codex|Codex CLI|codex|~/.codex|~/.codex/skills|0|none' <<<"$rows"+ grep -Fq 'agents|Agents (agents.md)||~/.agents|~/.agents/skills|0|none' <<<"$rows"+ grep -Fq 'cursor|Cursor|cursor|~/.cursor|~/.cursor/skills-cursor|0|none' <<<"$rows"+ # Harnesses without a skills convention must not be install targets.+ ! grep -Fq 'openclaw' <<<"$rows"+ ! grep -Fq 'gemini' <<<"$rows"++ install_out=$(bash scripts/install-skill.sh --dry-run)+ printf '%s\n' "$install_out"+ dest="$HOME/.claude/skills/ix"+ grep -Fq "would install: $dest" <<<"$install_out"+ test ! -e "$dest"++ shell_json=$(bash scripts/install-skill.sh --dry-run --json)+ printf '%s\n' "$shell_json"+ node -e '+ const r = JSON.parse(require("node:fs").readFileSync(0, "utf8"));+ const byId = new Map(r.hosts.map((h) => [h.id, h]));+ const claude = byId.get("claude");+ if (claude?.action !== "would-install") throw new Error("claude not would-install in shell report");+ if (claude?.detectedVia !== "toolscan") throw new Error("claude detection source not toolscan in shell report");+ if (!claude?.dest.endsWith("/.claude/skills/ix")) throw new Error("claude dest wrong: " + claude?.dest);+ for (const id of ["codex", "agents", "cursor"]) {+ const h = byId.get(id);+ if (h?.action !== "skip") throw new Error(id + " not skipped in shell report");+ if (h?.detectedVia !== "none") throw new Error(id + " detection source not none in shell report");+ }+ ' <<<"$shell_json"+ - name: Exercise ix mcp install dry-run against the off-PATH fixture (Git Bash)+ shell: bash+ env:+ HOME: ${{ runner.temp }}/ix-harness-home+ working-directory: ix-cli+ run: |+ set -euo pipefail+ FIXTURE="$(cd .. && pwd)/.github/fixtures/harness-smoke"+ export TOOLSCAN_PATH="$FIXTURE/toolscan.mjs"+ test -f "$TOOLSCAN_PATH" || { echo "toolscan fixture missing: $TOOLSCAN_PATH"; exit 1; }+ # --host restricts the registry the same way the old env fixture did;+ # an unknown id fails loudly, so a renamed host cannot pass silently.+ node dist/cli/main.js mcp install --host claude codex openclaw --dry-run --format json | tee "$HOME/mcp-install.json"+ MCP_INSTALL_JSON="$HOME/mcp-install.json" node -e '+ const r = require(process.env.MCP_INSTALL_JSON);+ const byId = new Map(r.hosts.map((h) => [h.id, h]));+ // claude is NOT on PATH here — only the fake toolscan names it, and+ // inspect must run the absolute path toolscan reported through the+ // cmd shim. A would-register proves the threading; a conflict would+ // mean the seam regressed to PATH-only execution.+ if (byId.get("claude")?.outcome !== "would-register")+ throw new Error("claude was not detected: " + JSON.stringify(byId.get("claude")));+ if (byId.get("claude")?.detectedVia !== "toolscan")+ throw new Error("claude was not detected via toolscan: " + byId.get("claude")?.detectedVia);+ if (byId.get("codex")?.outcome !== "not-installed") throw new Error("codex was detected unexpectedly");+ if (byId.get("codex")?.detectedVia !== "none") throw new Error("codex detection source not reported");+ if (byId.get("openclaw")?.outcome !== "not-installed") throw new Error("openclaw was detected unexpectedly");+ if (byId.get("openclaw")?.detectedVia !== "none") throw new Error("openclaw detection source not reported");+ '+# ── Aggregate gate ───────────────────────────────────────────────────────# ── Link gate ────────────────────────────────────────────────────────────# Probes every external URL in the repo's markdown and fails on 404/410, so@@ -371,7 +583,7 @@ jobs:ci-success:name: CI Passedif: always()- needs: [static, test, e2e, api-parity, doc-parity, links]+ needs: [static, test, e2e, api-parity, doc-parity, links, harness-install-smoke, harness-install-smoke-windows]runs-on: ubuntu-lateststeps:- name: Verify all required jobs succeeded@@ -382,9 +594,13 @@ jobs:echo "api-parity=${{ needs.api-parity.result }}"echo "doc-parity=${{ needs.doc-parity.result }}"echo "links=${{ needs.links.result }}"+ echo "harness-install-smoke=${{ needs.harness-install-smoke.result }}"+ echo "harness-install-smoke-windows=${{ needs.harness-install-smoke-windows.result }}"[ "${{ needs.static.result }}" = "success" ] \&& [ "${{ needs.test.result }}" = "success" ] \&& [ "${{ needs.e2e.result }}" = "success" ] \&& [ "${{ needs.api-parity.result }}" = "success" ] \&& [ "${{ needs.doc-parity.result }}" = "success" ] \- && [ "${{ needs.links.result }}" = "success" ]+ && [ "${{ needs.links.result }}" = "success" ] \+ && [ "${{ needs.harness-install-smoke.result }}" = "success" ] \+ && [ "${{ needs.harness-install-smoke-windows.result }}" = "success" ]diff --git a/README.md b/README.mdindex 90b7a19c..ee656cfa 100644--- a/README.md+++ b/README.md@@ -219,18 +219,35 @@ Windows (PowerShell):irm https://raw.githubusercontent.com/ix-infrastructure/ix-cursor-plugin/main/install.ps1 | iex```-## Claude Code / .agents Skill--[`skills/ix/`](skills/ix/SKILL.md) is a self-contained **Claude Code skill** (also-loaded natively through the `.agents` surface) that teaches any LLM agent to drive the-`ix` CLI: build the graph, explain symbols, trace flows, analyze impact, and-detect smells — instead of grepping and guessing.--**Install it** (deploys to `~/.claude/skills/ix` and `~/.agents/skills/ix` so it-works in every project):+## Agent Skill (any harness)++[`skills/ix/`](skills/ix/SKILL.md) is a single, self-contained **agent skill** that+teaches any LLM agent to drive the `ix` CLI: build the graph, explain symbols,+trace flows, analyze impact, and detect smells — instead of grepping and+guessing. It follows the [Claude Code skill+format](https://code.claude.com/docs/en/skills) and the+[agents.md](https://agents.md) standard, and any skill-compatible harness loads+the same `skills/ix/` tree natively from its own skills directory — Claude Code+(`~/.claude/skills`), Agents (`~/.agents/skills`), Codex CLI, Gemini CLI,+Cursor, and more.++**Install it** — `scripts/install-skill.sh` probes which agent harnesses are+installed on this machine and deploys `skills/ix` to every one of them (Claude+Code's `~/.claude/skills`, Agents' `~/.agents/skills` per+[agents.md](https://agents.md), Codex's `~/.codex/skills`, Gemini's+`~/.gemini/skills`, Cursor's `~/.cursor/skills`, and more — the same detection+`ix mcp install` uses). Detection is embedded; when+[toolscan](https://github.com/Alot1z/toolscan) is available (`TOOLSCAN_PATH`+set — never a bare-name PATH lookup, so nothing is executed unless you opt in)+its discovery output additionally scans the common install roots beyond PATH+(`~/.local/bin`, `%LOCALAPPDATA%`, ...) — a purely additive seam: without it+the built-in probes decide, so a clean machine and CI behave exactly the same. Pass `--dry-run` to see the targets, or list+harness ids to install only those:```bash-bash scripts/install-skill.sh+bash scripts/install-skill.sh # every harness found+bash scripts/install-skill.sh --dry-run+bash scripts/install-skill.sh claude gemini```Then start a new session and ask your agent to set it up:@@ -251,8 +268,8 @@ powershell -ExecutionPolicy Bypass -File skills/ix/scripts/bootstrap.ps1 .The skill follows the progressive-disclosure layout — a lean `SKILL.md` with thefull command reference, output-format rules, and troubleshooting split into`references/`, plus `scripts/` for first-run setup — so it is portable to Claude-Code, the `.agents` surface, and any other skill-compatible agent. Edit `skills/ix/` and-re-run `scripts/install-skill.sh` to update your installed copy. To produce a+Code, Agents, and any other skill-compatible agent. Edit `skills/ix/` and+re-run `scripts/install-skill.sh` to update every installed copy. To produce adistributable zip:```bashdiff --git a/ix-cli/scripts/skill-harnesses.mjs b/ix-cli/scripts/skill-harnesses.mjsnew file mode 100644index 00000000..380c0e2c--- /dev/null+++ b/ix-cli/scripts/skill-harnesses.mjs@@ -0,0 +1,216 @@+#!/usr/bin/env node+/**+ * Harness registry reader for scripts/install-skill.sh.+ *+ * The skills table is explicit, small, and deliberate — a harness appears+ * here only once its skills directory has been verified against the harness's+ * actual convention (checked on a machine with every harness installed:+ * Cursor's skills live in `~/.cursor/skills-cursor`, and gemini, opencode,+ * openclaw and vscode have no skills convention at all, so they are not+ * install targets). This is *not* derived from the MCP host registry+ * (ix-cli/src/mcp/hosts.ts): that table answers "where does this harness read+ * its MCP config", which is a different question from "where does it load+ * skills" — deriving one from the other is a category error that produced+ * five install targets nothing reads. Adding a harness is a one-line edit+ * here, and a deliberate one, backed by having checked where that harness+ * actually looks.+ *+ * Output: one line per harness, `id|label|bin|config-dir|skill-dir`, with+ * `~` unexpanded (the shell expands it).+ *+ * `--probe` appends two more fields per line: `present` (`1`/`0`) and `via` —+ * the detection source that decided (toolscan | path | config-dir | none),+ * mirroring the CLI report's `detectedVia`. Presence: the bin is found (via+ * toolscan when TOOLSCAN_PATH is set, PATH otherwise) or the config directory+ * exists. The toolscan seam is optional and additive — TOOLSCAN_PATH is opt-in+ * (the helper never looks `toolscan` up on PATH) and when it is unset the+ * embedded PATH probe decides, so a clean machine behaves exactly as before+ * and CI never needs toolscan.+ *+ * node scripts/skill-harnesses.mjs # the table+ * node scripts/skill-harnesses.mjs --probe # + presence + detection source per row+ * HARNESS_HOME=P node scripts/skill-harnesses.mjs --probe # where ~ resolves (hermetic tests)+ */+import { execFileSync } from "node:child_process";+import { existsSync } from "node:fs";+import { homedir } from "node:os";+import { pathToFileURL } from "node:url";++/**+ * The installable harnesses and where each one reads skills.+ *+ * Verified per harness (2026-09-03, against a machine with all eight+ * candidates installed):+ * claude — ~/.claude/skills (correct)+ * agents — ~/.agents/skills (the agents.md surface)+ * codex — ~/.codex/skills (correct)+ * cursor — ~/.cursor/skills-cursor (NOT ~/.cursor/skills)+ * Deliberately absent: gemini/opencode/openclaw/vscode have no skills+ * convention (checked: ~/.gemini has extensions/commands only; ~/.config/+ * opencode has agents/commands/plugins; ~/.openclaw has agents/extensions/+ * flows; ~/.vscode has no skills concept and exists on every machine that+ * ever installed an extension — installing there would be inert, and probing+ * it would report a false positive).+ */+const SKILL_DIRS = {+ claude: { label: "Claude Code", bin: "claude", cfg: "~/.claude", skill: "~/.claude/skills" },+ agents: { label: "Agents (agents.md)", bin: "", cfg: "~/.agents", skill: "~/.agents/skills" },+ codex: { label: "Codex CLI", bin: "codex", cfg: "~/.codex", skill: "~/.codex/skills" },+ cursor: { label: "Cursor", bin: "cursor", cfg: "~/.cursor", skill: "~/.cursor/skills-cursor" },+};++/** A harness row as emitted by {@link readHarnesses} (cfg/skill `~`-unexpanded). */+export function readHarnesses() {+ return Object.entries(SKILL_DIRS).map(([id, entry]) => ({ id, ...entry }));+}++/** Whether a bare command resolves on PATH (the embedded fallback probe). */+export function binOnPath(bin) {+ if (!bin) return false;+ try {+ execFileSync(process.platform === "win32" ? "where" : "which", [bin], {+ stdio: "ignore",+ windowsHide: true,+ });+ return true;+ } catch {+ return false;+ }+}++/**+ * Resolve the toolscan command: `TOOLSCAN_PATH` only.+ * Returns null when it is unset — the seam degrades, it never fails the+ * install, and it never executes a bare `toolscan` name from PATH (an+ * attacker-plantable name; opt-in only).+ */+export function resolveToolscan() {+ const explicit = process.env.TOOLSCAN_PATH?.trim();+ if (!explicit) return null;+ return /\.m?js$/i.test(explicit)+ ? { cmd: process.execPath, args: [explicit] }+ : { cmd: explicit, args: [] };+}++/**+ * Mirror of hosts.ts `quoteForCmd` for the shell branch below.+ *+ * Canonical copy: ix-cli/src/mcp/hosts.ts (the .mjs cannot import TS). The+ * two must stay byte-identical — the drift guard is skill-harnesses.test.ts,+ * which asserts this function equals the TS implementation across a battery+ * of arguments. Wrapping in double quotes is what makes a path containing a+ * space — or a `&`, or parentheses — survive: cmd treats a quoted region as+ * literal. An argument carrying a double quote of its own cannot be encoded+ * this way and is refused by hosts.ts `run`.+ */+const SAFE_BARE_ARG = /^[A-Za-z0-9_@:.,=+\-\\/]+$/;+export function quoteForCmd(arg) {+ if (SAFE_BARE_ARG.test(arg)) return arg;+ let out = '"';+ let slashes = 0;+ for (const ch of arg) {+ if (ch === "\\") {+ slashes += 1;+ out += ch;+ continue;+ }+ if (ch === '"') {+ out += `${`\\`.repeat(slashes)}\\"`;+ slashes = 0;+ continue;+ }+ slashes = 0;+ out += ch;+ }+ return `${out}${`\\`.repeat(slashes)}"`;+}++/**+ * Run toolscan once and return the set of tool names it found with a usable+ * path (lowercased), or null when toolscan is unavailable or misbehaves.+ *+ * An entry that names a tool without a path is not usable evidence — mirror+ * the CLI's `hostInstalled`, which requires `discovery.paths` before it takes+ * the toolscan verdict — so name-only entries are ignored rather than+ * reported as a presence toolscan did not establish.+ */+export function runToolscanOnce(resolve = resolveToolscan) {+ const target = resolve();+ if (!target) return null;+ try {+ const useShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(target.cmd);+ // npm shims carry no executable bit and CreateProcess cannot launch them,+ // so the whole line goes through cmd, PRE-QUOTED (same as hosts.ts `run`+ // and discovery.ts `execSpawnable`): with `shell: true` and an args array+ // node joins them unquoted, so a shim path containing a space would be+ // split — the exact class hosts.ts::quoteForCmd exists for.+ const line = [target.cmd, ...target.args].map(quoteForCmd).join(" ");+ const out = execFileSync(useShell ? line : target.cmd, useShell ? {} : target.args, {+ encoding: "utf8",+ timeout: 20_000,+ windowsHide: true,+ stdio: ["ignore", "pipe", "ignore"],+ ...(useShell ? { shell: true } : {}),+ });+ const parsed = JSON.parse(out);+ const tools = Array.isArray(parsed?.tools) ? parsed.tools : [];+ const names = new Set();+ for (const tool of tools) {+ if (+ typeof tool?.name === "string" &&+ tool.name !== "" &&+ typeof tool?.path === "string" &&+ tool.path !== ""+ ) {+ names.add(tool.name.toLowerCase());+ }+ }+ return names;+ } catch {+ return null;+ }+}++/**+ * Whether one harness is present, and which probe decided.+ *+ * Precedence mirrors the CLI's `detectedVia` (install.ts): toolscan first+ * (purely additive evidence — a harness its scan found is present no matter+ * what the embedded probes say), then the bin on PATH, then the config+ * directory (a GUI-only install is still found), else absent. `deps` injects+ * the probe functions so tests stay hermetic; the defaults are the real+ * implementations (toolscan output when present, `where`/`which`, and the+ * filesystem).+ */+export function probePresent(row, deps = {}) {+ const { toolscanNames = null, binOnPath: which = binOnPath, exists = existsSync } = deps;+ const binFound = toolscanNames ? toolscanNames.has(row.bin.toLowerCase()) : false;+ if (binFound) return { present: true, via: "toolscan" };+ if (which(row.bin)) return { present: true, via: "path" };+ // `~` resolves to the user's home — overridable through HARNESS_HOME so a+ // hermetic run can point it at an empty temp dir (install-skill.sh expands+ // `~` itself with $HOME for the destination paths; this override exists so+ // the presence decision agrees with that view on Windows, where node's+ // os.homedir() does not follow $HOME).+ const cfgExpanded = row.cfg.replace(/^~/, process.env.HARNESS_HOME || homedir());+ return exists(cfgExpanded) ? { present: true, via: "config-dir" } : { present: false, via: "none" };+}++export function main(argv = process.argv.slice(2)) {+ const probe = argv.includes("--probe");+ const rows = readHarnesses();++ const toolscanNames = probe ? runToolscanOnce() : null;+ const out = rows.map((row) => {+ const base = [row.id, row.label, row.bin, row.cfg, row.skill];+ if (!probe) return base.join("|");+ const { present, via } = probePresent(row, { toolscanNames });+ return [...base, present ? "1" : "0", via].join("|");+ });+ process.stdout.write(`${out.join("\n")}\n`);+}++const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;+if (isMain) {+ main();+}diff --git a/ix-cli/src/cli/__tests__/discovery.test.ts b/ix-cli/src/cli/__tests__/discovery.test.tsnew file mode 100644index 00000000..da936aa1--- /dev/null+++ b/ix-cli/src/cli/__tests__/discovery.test.ts@@ -0,0 +1,139 @@+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it } from "vitest";++import { discoverTools, NO_DISCOVERY, parseToolscanOutput, resolveToolscan, type ToolDiscovery } from "../../mcp/discovery.js";++const scratch: string[] = [];++afterEach(() => {+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "ix-discovery-"));+ scratch.push(dir);+ return dir;+}++describe("parseToolscanOutput", () => {+ it("indexes tools by lowercased name, keeping the first reported path", () => {+ const { names, paths } = parseToolscanOutput(+ JSON.stringify({+ tools: [+ { name: "claude", path: "C:\\a\\claude.cmd", source: "PATH" },+ { name: "CODE", path: "C:\\b\\code.exe", source: "PATH" },+ { name: "claude", path: "C:\\later\\claude.cmd", source: "root" },+ ],+ }),+ );++ expect(names.has("claude")).toBe(true);+ expect(names.has("code")).toBe(true);+ expect(paths.get("claude")).toBe("C:\\a\\claude.cmd");+ expect(paths.get("code")).toBe("C:\\b\\code.exe");+ });++ it("degrades to empty on non-JSON output", () => {+ const { names, paths } = parseToolscanOutput("traceback noise, not JSON");++ expect(names.size).toBe(0);+ expect(paths.size).toBe(0);+ });++ it("skips malformed tool entries without failing the rest", () => {+ const { names } = parseToolscanOutput(+ JSON.stringify({ tools: [{ name: 42 }, {}, null, { name: "" }, { name: "ok", path: "p" }] }),+ );++ expect([...names]).toEqual(["ok"]);+ });+});++describe("discoverTools", () => {+ it("returns the empty discovery when toolscan cannot be resolved", async () => {+ const discovery = await discoverTools(async () => null);++ expect(discovery).toEqual(NO_DISCOVERY);+ });++ it("returns the empty discovery when the toolscan run fails", async () => {+ const discovery = await discoverTools(+ async () => ({ cmd: "definitely-not-toolscan", args: [] }),+ parseToolscanOutput,+ async () => {+ throw new Error("spawn ENOENT");+ },+ );++ expect(discovery).toEqual(NO_DISCOVERY);+ });++ it("returns the empty discovery when the output parses to nothing", async () => {+ const discovery = await discoverTools(+ async () => ({ cmd: "toolscan", args: [] }),+ parseToolscanOutput,+ async () => ({ stdout: "garbage" }),+ );++ expect(discovery).toEqual(NO_DISCOVERY);+ });++ it("indexes real toolscan output", async () => {+ const discovery = await discoverTools(+ async () => ({ cmd: "toolscan", args: [] }),+ parseToolscanOutput,+ async () => ({+ stdout: JSON.stringify({ tools: [{ name: "claude", path: "C:\\a\\claude.cmd" }], truncated: false }),+ }),+ );++ expect(discovery.source).toBe("toolscan");+ expect(discovery.names.has("claude")).toBe(true);+ });++ it("resolves TOOLSCAN_PATH scripts through node and consumes their output", async () => {+ const script = join(tempDir(), "fake-toolscan.mjs");+ writeFileSync(script, 'console.log(JSON.stringify({ tools: [{ name: "claude", path: "x" }] }));');++ const previous = process.env.TOOLSCAN_PATH;+ process.env.TOOLSCAN_PATH = script;+ try {+ const discovery: ToolDiscovery = await discoverTools();+ expect(discovery.source).toBe("toolscan");+ expect(discovery.names.has("claude")).toBe(true);+ } finally {+ if (previous === undefined) delete process.env.TOOLSCAN_PATH;+ else process.env.TOOLSCAN_PATH = previous;+ }+ });++ it("never executes a bare `toolscan` found on PATH", async () => {+ // Security pin: a PATH fallback would let any attacker-planted `toolscan`+ // decide which host config files `ix mcp install` writes. Discovery is+ // opt-in via TOOLSCAN_PATH only — a bare name on PATH is ignored even+ // though it resolves.+ const dir = tempDir();+ const name = process.platform === "win32" ? "toolscan.cmd" : "toolscan";+ writeFileSync(join(dir, name), process.platform === "win32" ? "@echo off\n" : "#!/bin/sh\n");+ if (process.platform !== "win32") chmodSync(join(dir, name), 0o755);++ const previousPath = process.env.PATH;+ const previousToolscan = process.env.TOOLSCAN_PATH;+ delete process.env.TOOLSCAN_PATH;+ process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${previousPath ?? ""}`;+ try {+ // The resolver itself must refuse the bare name even though it resolves.+ expect(await resolveToolscan()).toBeNull();+ const discovery = await discoverTools();+ expect(discovery).toEqual(NO_DISCOVERY);+ } finally {+ if (previousToolscan === undefined) delete process.env.TOOLSCAN_PATH;+ else process.env.TOOLSCAN_PATH = previousToolscan;+ if (previousPath === undefined) delete process.env.PATH;+ else process.env.PATH = previousPath;+ }+ });+});\ No newline at end of filediff --git a/ix-cli/src/cli/__tests__/mcp-install.test.ts b/ix-cli/src/cli/__tests__/mcp-install.test.tsindex 9bd71ab5..603ace13 100644--- a/ix-cli/src/cli/__tests__/mcp-install.test.ts+++ b/ix-cli/src/cli/__tests__/mcp-install.test.ts@@ -36,19 +36,28 @@ function tempDir(): string {function fakeHost(id: string,registration: Registration,- options: { installed?: boolean; fails?: boolean; detectInstalled?: () => Promise<boolean> } = {},-): McpHost & { registerCalls: number } {+ options: {+ installed?: boolean;+ fails?: boolean;+ detectInstalled?: () => Promise<boolean>;+ bin?: string;+ } = {},+): McpHost & { registerCalls: number; inspectBins: Array<string | undefined>; registerBins: Array<string | undefined> } {const host = {id,label: id,- bin: options.installed === false ? "definitely-not-a-real-binary-xyz" : "node",+ bin: options.bin ?? (options.installed === false ? "definitely-not-a-real-binary-xyz" : "node"),target: `${id}-config`,registerCalls: 0,+ inspectBins: [] as Array<string | undefined>,+ registerBins: [] as Array<string | undefined>,...(options.detectInstalled ? { detectInstalled: options.detectInstalled } : {}),- async inspect() {+ async inspect(execBin?: string) {+ host.inspectBins.push(execBin);return { registration };},- async register() {+ async register(execBin?: string) {+ host.registerBins.push(execBin);host.registerCalls += 1;if (options.fails) throw new Error("host CLI said no");},@@ -63,7 +72,7 @@ describe("ix mcp install", () => {const report = await runInstall({ hosts: [host] });expect(host.registerCalls).toBe(1);- expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true });+ expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true, detectedVia: "path" });expect(report.registered).toBe(1);});@@ -123,6 +132,116 @@ describe("ix mcp install", () => {expect(report.hosts[0]).toMatchObject({ outcome: "not-installed", installed: false });});+ it("runs the off-PATH CLI through the absolute path toolscan found", async () => {+ // The bin is deliberately not on PATH; only the toolscan seam names it —+ // and the seam must *execute* the discovered path, or inspect reads an+ // unreadable registration (conflict) and register fails (ENOENT). That is+ // the case this feature exists for.+ const resolved = "/opt/off-path/bin/definitely-not-a-real-binary-xyz";+ const host = fakeHost("found", "none", { installed: false });++ const report = await runInstall({+ hosts: [host],+ discover: async () => ({+ source: "toolscan",+ names: new Set(["definitely-not-a-real-binary-xyz"]),+ paths: new Map([["definitely-not-a-real-binary-xyz", resolved]]),+ }),+ });++ expect(host.inspectBins).toEqual([resolved]);+ expect(host.registerBins).toEqual([resolved]);+ expect(host.registerCalls).toBe(1);+ expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true, detectedVia: "toolscan" });+ });++ it("falls back to the bare bin when toolscan found no path", async () => {+ // Discovery may name a bin without reporting a path for it; execution must+ // then go through normal PATH resolution rather than a stale override.+ const host = fakeHost("found", "none");++ await runInstall({+ hosts: [host],+ discover: async () => ({+ source: "toolscan",+ names: new Set(["node"]),+ paths: new Map(),+ }),+ });++ expect(host.inspectBins).toEqual([undefined]);+ expect(host.registerBins).toEqual([undefined]);+ });++ it("degrades a name-only toolscan entry to the embedded probes when the bin is off PATH", async () => {+ // KageBinary #591 round-2 finding: a toolscan entry that names a bin but+ // carries no path would flip presence on the name alone, then fall through+ // to a bare-name PATH exec that cannot find an off-PATH CLI — a clean+ // `not-installed` became a false `conflict`. The presence verdict must+ // require the path toolscan reported, degrading to the embedded probes.+ const host = fakeHost("absent", "none", { installed: false });++ const report = await runInstall({+ hosts: [host],+ discover: async () => ({+ source: "toolscan",+ names: new Set(["definitely-not-a-real-binary-xyz"]),+ paths: new Map(),+ }),+ });++ expect(host.inspectBins).toEqual([]);+ expect(host.registerCalls).toBe(0);+ expect(report.hosts[0]).toMatchObject({+ outcome: "not-installed",+ installed: false,+ detectedVia: "none",+ });+ });++ it("falls back to the embedded probe when toolscan did not find the CLI", async () => {+ // toolscan ran but only found `node`; the fake bin is not on PATH either.+ const host = fakeHost("absent", "none", { installed: false });++ const report = await runInstall({+ hosts: [host],+ discover: async () => ({ source: "toolscan", names: new Set(["node"]), paths: new Map() }),+ });++ // The seam is additive evidence only — a toolscan miss must not flip a+ // genuinely absent host to installed.+ expect(host.registerCalls).toBe(0);+ expect(report.hosts[0]).toMatchObject({ outcome: "not-installed", installed: false, detectedVia: "none" });+ });++ it("keeps the config-dir probe for hosts toolscan does not name", async () => {+ // cursor-like: no CLI on PATH and toolscan did not find it, but the config+ // dir exists — the host must still read as installed.+ const host = fakeHost("cursor", "none", {+ bin: "definitely-not-a-real-binary-xyz",+ detectInstalled: async () => true,+ });++ const report = await runInstall({+ hosts: [host],+ discover: async () => ({ source: "toolscan", names: new Set(["claude"]), paths: new Map() }),+ });++ expect(host.registerCalls).toBe(1);+ expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true, detectedVia: "config-dir" });+ });++ it("reports a host whose CLI is on PATH as detected on PATH, not via its config dir", async () => {+ // cursor/vscode/opencode's combined check is on-PATH-or-config-dir; a host+ // found by the PATH half of it must not be mislabelled `config-dir`.+ const host = fakeHost("cursor", "none", { detectInstalled: async () => true });++ const report = await runInstall({ hosts: [host] });++ expect(host.registerCalls).toBe(1);+ expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true, detectedVia: "path" });+ });+it("reports a failing host without aborting the rest", async () => {const hosts = [fakeHost("broken", "none", { fails: true }), fakeHost("fine", "none")];@@ -173,11 +292,12 @@ describe("ix mcp install", () => {const report = await runInstall({ hosts: [host] });- expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true });+ expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true, detectedVia: "config-dir" });expect(host.registerCalls).toBe(1);});});+describe("ix mcp doctor", () => {it("separates a free name from one held by someone else", async () => {const report = await runDoctor({diff --git a/ix-cli/src/cli/__tests__/skill-harnesses.test.ts b/ix-cli/src/cli/__tests__/skill-harnesses.test.tsnew file mode 100644index 00000000..d42fefa6--- /dev/null+++ b/ix-cli/src/cli/__tests__/skill-harnesses.test.ts@@ -0,0 +1,206 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it } from "vitest";++import { quoteForCmd as tsQuoteForCmd } from "../../mcp/hosts.js";++const scratch: string[] = [];++afterEach(() => {+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });+});++/**+ * The helper is plain ESM (.mjs) that install-skill.sh runs without a build+ * step. Its public shape is declared here instead of in a hand-written+ * .d.mts, so a signature change in the helper surfaces as a runtime failure+ * in these tests rather than a typecheck that checks nothing.+ */+type HarnessRow = { id: string; label: string; bin: string; cfg: string; skill: string };+type ProbeResult = { present: boolean; via: string };++// @ts-expect-error — no .d.mts by design (review #591): the local interface+// below is the type contract, and a helper shape change fails here at runtime.+const helper = (await import("../../../scripts/skill-harnesses.mjs")) as unknown as {+ readHarnesses: () => HarnessRow[];+ probePresent: (+ row: HarnessRow,+ deps?: {+ toolscanNames?: Set<string> | null;+ binOnPath?: (bin: string) => boolean;+ exists?: (path: string) => boolean;+ },+ ) => ProbeResult;+ resolveToolscan: () => { cmd: string; args: string[] } | null;+ runToolscanOnce: (resolve?: () => { cmd: string; args: string[] } | null) => Set<string> | null;+ quoteForCmd: (arg: string) => string;+};++const { probePresent, readHarnesses, resolveToolscan, runToolscanOnce, quoteForCmd } = helper;++const row = (overrides: Partial<{ bin: string; cfg: string }> = {}) => ({+ id: "claude",+ label: "Claude Code",+ bin: "claude",+ cfg: "~/.claude",+ skill: "~/.claude/skills",+ ...overrides,+});++describe("probePresent", () => {+ it("counts a harness present when toolscan found its CLI, even off PATH", () => {+ const present = probePresent(row(), {+ toolscanNames: new Set(["claude"]),+ binOnPath: () => false,+ exists: () => false,+ });++ expect(present).toEqual({ present: true, via: "toolscan" });+ });++ it("counts a harness present when its config dir exists, even with no CLI", () => {+ // The GUI-only case: no bin anywhere, but ~/.agents exists.+ const present = probePresent(row({ bin: "cursor", cfg: "~/.cursor" }), {+ toolscanNames: new Set(["claude"]),+ binOnPath: () => false,+ exists: (path) => path.endsWith(".cursor"),+ });++ expect(present).toEqual({ present: true, via: "config-dir" });+ });++ it("counts a harness absent when neither toolscan, PATH, nor the config dir has it", () => {+ const present = probePresent(row({ bin: "codex", cfg: "~/.codex" }), {+ toolscanNames: new Set(["claude"]),+ binOnPath: () => false,+ exists: () => false,+ });++ expect(present).toEqual({ present: false, via: "none" });+ });++ it("falls back to the embedded PATH probe when toolscan is unavailable", () => {+ const present = probePresent(row(), {+ toolscanNames: null,+ binOnPath: () => true,+ exists: () => false,+ });++ expect(present).toEqual({ present: true, via: "path" });+ });++ it("matches toolscan names against the lowercased bin", () => {+ // runToolscanOnce lowercases at ingestion; the probe receives that shape.+ const present = probePresent(row(), {+ toolscanNames: new Set(["claude"]),+ binOnPath: () => false,+ exists: () => false,+ });++ expect(present).toEqual({ present: true, via: "toolscan" });+ });+});++describe("resolveToolscan (the security pin)", () => {+ it("never resolves a bare `toolscan` from PATH — TOOLSCAN_PATH is the only opt-in", () => {+ // KageBinary #591 round-2 finding: the TS copy of this resolver carries a+ // pin in discovery.test.ts; the shell-side copy must too. A PATH fallback+ // re-added here would execute any attacker-planted `toolscan`; planting one+ // on PATH and expecting null makes that regression go red.+ const dir = mkdtempSync(join(tmpdir(), "ix-skill-pin-"));+ scratch.push(dir);+ const plant = join(dir, process.platform === "win32" ? "toolscan.cmd" : "toolscan");+ writeFileSync(plant, process.platform === "win32" ? "@echo off\r\n" : "#!/bin/sh\nexit 0\n", "utf8");+ const previousPath = process.env.PATH;+ const previousTs = process.env.TOOLSCAN_PATH;+ delete process.env.TOOLSCAN_PATH;+ process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${previousPath ?? ""}`;+ try {+ expect(resolveToolscan()).toBeNull();+ } finally {+ if (previousTs === undefined) delete process.env.TOOLSCAN_PATH;+ else process.env.TOOLSCAN_PATH = previousTs;+ process.env.PATH = previousPath ?? "";+ }+ });+});++describe("quoteForCmd (drift guard vs hosts.ts)", () => {+ // The .mjs mirrors hosts.ts::quoteForCmd because it cannot import TS. This+ // battery keeps the two byte-identical — a divergence here is exactly the+ // "unquoted path with a space gets split" class the mirror exists to avoid.+ const cases = [+ ["C:\\node.exe", "C:\\node.exe"],+ ["C:\\Program Files\\bin\\toolscan.cmd", '"C:\\Program Files\\bin\\toolscan.cmd"'],+ ["C:\\a&b\\x.cmd", '"C:\\a&b\\x.cmd"'],+ // Backslash is in the safe-bare class, so a lone backslash path is bare.+ ["C:\\foo\\", "C:\\foo\\"],+ // A space forces quoting; trailing backslashes are doubled before the+ // closing quote so cmd does not eat it.+ ["C:\\Program Files\\foo\\", '"C:\\Program Files\\foo\\\\"'],+ // `~` is not in the safe-bare class (mirrors hosts.ts exactly).+ ["~/.local/bin/claude", '"~/.local/bin/claude"'],+ ["/opt/ix tools/bin/claude", '"/opt/ix tools/bin/claude"'],+ ["npm-run.cmd", "npm-run.cmd"],+ ] as const;++ for (const [input, expected] of cases) {+ it(`quotes ${JSON.stringify(input)}`, () => {+ expect(quoteForCmd(input)).toBe(expected);+ });+ }++ it("matches hosts.ts::quoteForCmd on every case", () => {+ for (const [input] of cases) {+ expect(quoteForCmd(input)).toBe(tsQuoteForCmd(input));+ }+ });+});++describe("runToolscanOnce", () => {+ it("ignores an entry that names a tool without a usable path", () => {+ const nameOnly = runToolscanOnce(() => ({+ cmd: process.execPath,+ args: ["-e", `process.stdout.write(JSON.stringify({ tools: [{ name: "claude" }], truncated: false }))`],+ }));++ expect(nameOnly).toEqual(new Set());+ });++ it("keeps an entry whose tool carries a path", () => {+ const withPath = runToolscanOnce(() => ({+ cmd: process.execPath,+ args: [+ "-e",+ `process.stdout.write(JSON.stringify({ tools: [{ name: "claude", path: "/x/claude" }], truncated: false }))`,+ ],+ }));++ expect(withPath).toEqual(new Set(["claude"]));+ });+});++describe("readHarnesses", () => {+ it("lists exactly the harnesses with a verified skills convention", () => {+ const rows = readHarnesses();++ // Deliberately small and explicit: only harnesses whose skills directory+ // is verified to be read belong here. gemini/opencode/openclaw/vscode+ // have no skills convention, so they must not be install targets.+ expect(rows.map((r) => r.id)).toEqual(["claude", "agents", "codex", "cursor"]);+ });++ it("points cursor at skills-cursor, the directory Cursor actually reads", () => {+ const cursor = readHarnesses().find((r) => r.id === "cursor");++ expect(cursor).toMatchObject({ cfg: "~/.cursor", skill: "~/.cursor/skills-cursor" });+ });++ it("appends the agents.md surface as a documented supplement", () => {+ const agents = readHarnesses().find((r) => r.id === "agents");++ expect(agents).toMatchObject({ bin: "", cfg: "~/.agents", skill: "~/.agents/skills" });+ });+});\ No newline at end of filediff --git a/ix-cli/src/cli/commands/mcp.ts b/ix-cli/src/cli/commands/mcp.tsindex 0a17ef5a..5100242f 100644--- a/ix-cli/src/cli/commands/mcp.ts+++ b/ix-cli/src/cli/commands/mcp.ts@@ -39,6 +39,7 @@ function hostFields(host: HostReport): Array<[string, LlmValue]> {["host", host.id],["outcome", host.outcome],["installed", host.installed],+ ["detectedVia", host.detectedVia],["registration", host.registration],["note", host.note],];diff --git a/ix-cli/src/mcp/discovery.ts b/ix-cli/src/mcp/discovery.tsnew file mode 100644index 00000000..13f16ef0--- /dev/null+++ b/ix-cli/src/mcp/discovery.ts@@ -0,0 +1,125 @@+import { execFile } from "node:child_process";+import { promisify } from "node:util";++import { quoteForCmd } from "./hosts.js";++const execFileAsync = promisify(execFile);++/**+ * Tool discovery seam for `ix mcp install` / `ix mcp doctor`.+ *+ * The embedded presence checks (hosts.ts's `detectInstalled` / `isOnPath`)+ * probe PATH only. toolscan (https://github.com/Alot1z/toolscan) scans PATH+ * *and* the common install roots beyond it — `~/.local/bin`, `~/.npm-global`,+ * `%LOCALAPPDATA%\Programs`, ... — which is exactly where a harness CLI ends+ * up when the user installed it outside their shell PATH. When toolscan is+ * available its discovery output feeds the presence decision; when it is not+ * (a clean machine, CI) the embedded checks decide, so nothing breaks and no+ * dependency is introduced. The relationship is a soft seam by design: Ix+ * stays zero-hard-dep, and toolscan is purely additive evidence.+ */+export interface ToolDiscovery {+ /** Where the tool list came from. */+ source: "toolscan" | "none";+ /** Tool names toolscan reported, lowercased (additive evidence only). */+ names: Set<string>;+ /** First reported path per name, for diagnostics. */+ paths: Map<string, string>;+}++/** The empty discovery: no toolscan, embedded checks decide. */+export const NO_DISCOVERY: ToolDiscovery = { source: "none", names: new Set(), paths: new Map() };++/** How long a toolscan scan may take before we give up on it. */+const TOOLSCAN_TIMEOUT_MS = 20_000;++/** A spawnable command line, as resolved from TOOLSCAN_PATH or PATH. */+interface Spawnable {+ cmd: string;+ args: string[];+}++/** Run a command on Windows through cmd when its shim needs it (.cmd/.bat). */+function execSpawnable(target: Spawnable): Promise<{ stdout: string }> {+ const useShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(target.cmd);+ const options = {+ encoding: "utf8" as const,+ timeout: TOOLSCAN_TIMEOUT_MS,+ windowsHide: true,+ ...(useShell ? { shell: true } : {}),+ };+ if (useShell) {+ // npm shims carry no executable bit and CreateProcess cannot launch them,+ // so the whole line goes through cmd, pre-quoted (same approach as+ // hosts.ts's `run` — an unquoted path containing a space would be split).+ return execFileAsync([target.cmd, ...target.args].map(quoteForCmd).join(" "), options);+ }+ return execFileAsync(target.cmd, target.args, options);+}++/**+ * Resolve the toolscan command: `TOOLSCAN_PATH` only, never a bare-name PATH+ * lookup.+ *+ * A PATH fallback would make `ix mcp install` execute *any* program named+ * `toolscan` that an attacker can plant on PATH, and let its JSON decide+ * which host config files get written — a widening this CLI deliberately+ * avoids (the same care as the bounded-read and symlink work). Opt-in only:+ * unset means no toolscan, and the embedded probes decide.+ */+export async function resolveToolscan(): Promise<Spawnable | null> {+ const explicit = process.env.TOOLSCAN_PATH?.trim();+ if (!explicit) return null;+ // A script path runs under node (that is how this repo invokes toolscan);+ // anything else is treated as an executable the user pointed at.+ return /\.m?js$/i.test(explicit)+ ? { cmd: process.execPath, args: [explicit] }+ : { cmd: explicit, args: [] };+}++/** Turn toolscan's JSON scan output into a name/path index. */+export function parseToolscanOutput(stdout: string): Pick<ToolDiscovery, "names" | "paths"> {+ const names = new Set<string>();+ const paths = new Map<string, string>();+ let parsed: unknown;+ try {+ parsed = JSON.parse(stdout);+ } catch {+ return { names, paths };+ }+ const tools = (parsed as { tools?: unknown })?.tools;+ if (!Array.isArray(tools)) return { names, paths };+ for (const entry of tools) {+ if (typeof entry !== "object" || entry === null) continue;+ const tool = entry as { name?: unknown; path?: unknown };+ if (typeof tool.name !== "string" || tool.name === "") continue;+ const key = tool.name.toLowerCase();+ names.add(key);+ if (typeof tool.path === "string" && !paths.has(key)) paths.set(key, tool.path);+ }+ return { names, paths };+}++/**+ * Probe toolscan once and index what it found.+ *+ * Any failure — TOOLSCAN_PATH unset, unreadable, timed out, or emitting+ * something that is not the scan shape — degrades to the embedded checks+ * rather than failing the install. A broken optional seam must never break+ * the command it augments.+ */+export async function discoverTools(+ resolve: () => Promise<Spawnable | null> = resolveToolscan,+ parse: (stdout: string) => Pick<ToolDiscovery, "names" | "paths"> = parseToolscanOutput,+ run: (target: Spawnable) => Promise<{ stdout: string }> = execSpawnable,+): Promise<ToolDiscovery> {+ try {+ const target = await resolve();+ if (!target) return NO_DISCOVERY;+ const { stdout } = await run(target);+ const { names, paths } = parse(stdout);+ return names.size === 0 ? NO_DISCOVERY : { source: "toolscan", names, paths };+ } catch {+ return NO_DISCOVERY;+ }+}\ No newline at end of filediff --git a/ix-cli/src/mcp/hosts.ts b/ix-cli/src/mcp/hosts.tsindex ef1026a1..2fbafd23 100644--- a/ix-cli/src/mcp/hosts.ts+++ b/ix-cli/src/mcp/hosts.ts@@ -49,10 +49,22 @@ export interface McpHost {* editor sitting right there and wrote nothing.*/detectInstalled?(): Promise<boolean>;- /** Read-only look at what holds {@link SERVER_NAME} today. */- inspect(): Promise<Pick<HostStatus, "registration" | "detail">>;- /** Register `ix mcp`. Only called once inspect reports it is safe. */- register(): Promise<void>;+ /**+ * Read-only look at what holds {@link SERVER_NAME} today.+ *+ * `execBin` overrides the CLI to invoke: the caller may have discovered an+ * absolute path out-of-band (toolscan's scan of the install roots beyond+ * PATH). Without it, a host whose CLI is *not* on PATH reads as an unreadable+ * registration — `unknown` — which `install` reports as a conflict and+ * `--force` then turns into a failed registration, so the seam's own+ * motivating case fails. Config-file hosts ignore it (they never shell out).+ */+ inspect(execBin?: string): Promise<Pick<HostStatus, "registration" | "detail">>;+ /**+ * Register `ix mcp`. Only called once inspect reports it is safe.+ * `execBin` has the same meaning as in {@link McpHost.inspect}.+ */+ register(execBin?: string): Promise<void>;/** Where the registration lands, shown in the report. */target: string;}@@ -411,13 +423,16 @@ function cliHost(spec: {label: spec.label,bin: spec.bin,target: spec.target,- async inspect() {+ async inspect(execBin?: string) {+ // execBin is the caller's absolute path (toolscan's discovery); falling+ // back to the bare name keeps PATH resolution for the embedded probes.+ const bin = execBin ?? spec.bin;if (spec.showArgs) {- const shown = await run(spec.bin, spec.showArgs);+ const shown = await run(bin, spec.showArgs);return classifyShown(`${shown.stdout}\n${shown.stderr}`, shown.ok);}- const result = await run(spec.bin, spec.listArgs);+ const result = await run(bin, spec.listArgs);// A host that cannot answer is treated as occupied rather than empty:// guessing "none" here is the one wrong guess that overwrites something.if (!result.ok && !result.stdout.includes(SERVER_NAME)) {@@ -425,13 +440,14 @@ function cliHost(spec: {}return classifyListing(`${result.stdout}\n${result.stderr}`);},- async register() {+ async register(execBin?: string) {+ const bin = execBin ?? spec.bin;const launcher = await resolveLauncher();if (spec.windowsFallback && platform() === "win32") {spec.windowsFallback(launcher);return;}- const result = await run(spec.bin, spec.addArgs(launcher));+ const result = await run(bin, spec.addArgs(launcher));if (!result.ok) {throw new Error(firstLine(result.stderr) || firstLine(result.stdout) || "registration failed");}@@ -634,10 +650,11 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<sttarget: vsCodeUserConfig(),detectInstalled: fileHostInstalled("code", vsCodeUserConfig()),// No list subcommand, so the user-profile file is the only read path.- async inspect() {+ // Config-file hosts never shell out, so they ignore the exec-bin override.+ async inspect(_execBin?: string) {return inspectJsonFile(vsCodeUserConfig(), "servers");},- async register() {+ async register(_execBin?: string) {const ix = await resolveLauncher();// Written rather than handed to `code --add-mcp`, so the write lands in// the same file `inspect` reads. Shelling out needed `code` on PATH —@@ -655,10 +672,10 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<stbin: "cursor",target: cursorConfigPath(),detectInstalled: fileHostInstalled("cursor", cursorConfigPath()),- async inspect() {+ async inspect(_execBin?: string) {return inspectJsonFile(cursorConfigPath(), "mcpServers");},- async register() {+ async register(_execBin?: string) {const ix = await resolveLauncher();writeJson(cursorConfigPath(), (config) => {const servers = (config.mcpServers ??= {}) as Record<string, unknown>;@@ -672,10 +689,10 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<stbin: "opencode",target: opencodeConfigPath(),detectInstalled: fileHostInstalled("opencode", opencodeConfigPath()),- async inspect() {+ async inspect(_execBin?: string) {return inspectJsonFile(opencodeConfigPath(), "mcp");},- async register() {+ async register(_execBin?: string) {const ix = await resolveLauncher();writeJson(opencodeConfigPath(), (config) => {const servers = (config.mcp ??= {}) as Record<string, unknown>;diff --git a/ix-cli/src/mcp/install.ts b/ix-cli/src/mcp/install.tsindex 996e7d79..224b60d4 100644--- a/ix-cli/src/mcp/install.ts+++ b/ix-cli/src/mcp/install.ts@@ -10,6 +10,7 @@ import {type McpHost,type Registration,} from "./hosts.js";+import { discoverTools, type ToolDiscovery } from "./discovery.js";import { IX_MCP_OSS_TOOL_NAMES, IX_MCP_PRO_TOOL_NAMES } from "./server.js";import { detectPro } from "./runner.js";@@ -26,9 +27,19 @@ export type Outcome =/** Doctor only: ours, but the launcher path it records is gone. */| "stale";+/** Which probe decided a host's presence. */+type DetectionVia = "toolscan" | "path" | "config-dir" | "none";+export interface HostReport extends HostStatus {outcome: Outcome;target: string;+ /**+ * Which probe decided presence: toolscan's scan, the PATH probe, a config+ * directory, or `none` when the host is absent. Makes the toolscan seam+ * auditable: a host toolscan found reads `toolscan` even when its CLI also+ * happens to be on PATH.+ */+ detectedVia: DetectionVia;/** Why it was skipped, or how it failed. */note?: string;}@@ -53,6 +64,11 @@ export interface InstallOptions {dryRun?: boolean;/** Replace a name held by something else. Off by default: never clobber. */force?: boolean;+ /**+ * Tool discovery (toolscan when available, embedded checks otherwise).+ * Injectable so tests can feed a fixed discovery.+ */+ discover?: () => Promise<ToolDiscovery>;}/**@@ -146,9 +162,57 @@ function selectHosts(all: McpHost[], only?: string[]): McpHost[] {return all.filter((host) => only.includes(host.id));}-/** Whether the host is present. Falls back to the PATH probe. */-async function hostInstalled(host: McpHost): Promise<boolean> {- return host.detectInstalled ? host.detectInstalled() : isOnPath(host.bin);+/**+ * Whether the host is present, and which probe decided.+ *+ * The toolscan seam only ever adds evidence: a harness whose CLI toolscan+ * found is present no matter what the embedded probe says. It never overrides+ * a negative — a config-dir host (cursor, vscode, opencode) is present with+ * no CLI on PATH, and toolscan's bounded scan can truncate — so the embedded+ * check still runs whenever toolscan does not name the bin.+ *+ * Probe order is also the honesty order for `detectedVia`: PATH is checked+ * before the config-dir probe, so a host whose CLI resolves on PATH is+ * reported as found *on PATH* rather than misattributed to its config+ * directory (which cursor/vscode/opencode's combined check would otherwise+ * claim).+ */+async function hostInstalled(+ host: McpHost,+ discovery: ToolDiscovery,+): Promise<{ installed: boolean; via: DetectionVia }> {+ // A toolscan entry must carry the path that makes its verdict executable:+ // `inspect`/`register` run whatever `paths` names for an off-PATH harness,+ // so a name-only entry (truncated scan) that flips presence here would fall+ // through to a bare-name PATH exec that ENOENTs into a false `conflict`.+ // Requiring the path degrades such entries to the embedded probes instead+ // of inventing a presence toolscan did not actually establish.+ if (+ discovery.names.has(host.bin.toLowerCase()) &&+ discovery.paths.has(host.bin.toLowerCase())+ ) {+ return { installed: true, via: "toolscan" };+ }+ if (await isOnPath(host.bin)) return { installed: true, via: "path" };+ if (host.detectInstalled) {+ return (await host.detectInstalled())+ ? { installed: true, via: "config-dir" }+ : { installed: false, via: "none" };+ }+ return { installed: false, via: "none" };+}++/**+ * The absolute CLI path toolscan found for a host, if any.+ *+ * Without this, a harness whose CLI is installed off PATH (the seam's own+ * motivating case) reads as an unreadable registration — `unknown`, which+ * `install` reports as a conflict and `--force` turns into a failed+ * registration. Toolscan's scan covers the install roots beyond PATH, so its+ * reported path is exactly the command `inspect`/`register` must execute.+ */+function toolscanBin(host: McpHost, discovery: ToolDiscovery): string | undefined {+ return discovery.paths.get(host.bin.toLowerCase());}function noteFor(registration: Registration, detail?: string): string | undefined {@@ -170,35 +234,52 @@ function noteFor(registration: Registration, detail?: string): string | undefineexport async function runInstall(options: InstallOptions = {}): Promise<InstallReport> {const hosts = selectHosts(options.hosts ?? createHosts(writeJsonConfig), options.only);+ const discovery = await (options.discover ?? discoverTools)();const reports: HostReport[] = [];for (const host of hosts) {const base = { id: host.id, label: host.label, target: host.target };+ const presence = await hostInstalled(host, discovery);- if (!(await hostInstalled(host))) {- reports.push({ ...base, installed: false, registration: "none", outcome: "not-installed" });+ if (!presence.installed) {+ reports.push({+ ...base,+ detectedVia: presence.via,+ installed: false,+ registration: "none",+ outcome: "not-installed",+ });continue;}- const { registration, detail } = await host.inspect();+ const execBin = toolscanBin(host, discovery);+ const { registration, detail } = await host.inspect(execBin);const blocked = outcomeFor(registration, options.force === true);if (blocked) {- reports.push({ ...base, installed: true, registration, outcome: blocked, note: noteFor(registration, detail) });+ reports.push({+ ...base,+ detectedVia: presence.via,+ installed: true,+ registration,+ outcome: blocked,+ note: noteFor(registration, detail),+ });continue;}if (options.dryRun) {- reports.push({ ...base, installed: true, registration, outcome: "would-register" });+ reports.push({ ...base, detectedVia: presence.via, installed: true, registration, outcome: "would-register" });continue;}try {- await host.register();- reports.push({ ...base, installed: true, registration, outcome: "registered" });+ await host.register(execBin);+ reports.push({ ...base, detectedVia: presence.via, installed: true, registration, outcome: "registered" });} catch (error) {reports.push({...base,+ detectedVia: presence.via,installed: true,registration,outcome: "failed",@@ -223,19 +304,30 @@ const DOCTOR_OUTCOME: Record<Registration, Outcome> = {unknown: "conflict",};-export async function runDoctor(options: { hosts?: McpHost[]; only?: string[] } = {}): Promise<DoctorReport> {+export async function runDoctor(+ options: { hosts?: McpHost[]; only?: string[]; discover?: () => Promise<ToolDiscovery> } = {},+): Promise<DoctorReport> {const hosts = selectHosts(options.hosts ?? createHosts(writeJsonConfig), options.only);+ const discovery = await (options.discover ?? discoverTools)();const reports: HostReport[] = [];for (const host of hosts) {const base = { id: host.id, label: host.label, target: host.target };- if (!(await hostInstalled(host))) {- reports.push({ ...base, installed: false, registration: "none", outcome: "not-installed" });+ const presence = await hostInstalled(host, discovery);+ if (!presence.installed) {+ reports.push({+ ...base,+ detectedVia: presence.via,+ installed: false,+ registration: "none",+ outcome: "not-installed",+ });continue;}- const { registration, detail } = await host.inspect();+ const { registration, detail } = await host.inspect(toolscanBin(host, discovery));reports.push({...base,+ detectedVia: presence.via,installed: true,registration,outcome: DOCTOR_OUTCOME[registration],diff --git a/scripts/install-skill.sh b/scripts/install-skill.shindex e0adb776..fcce8d1a 100644--- a/scripts/install-skill.sh+++ b/scripts/install-skill.sh@@ -1,16 +1,34 @@#!/usr/bin/env bash#-# Install the Ix skill for Claude Code and the .agents skill surface.+# Install the Ix skill for every agent harness found on this machine.#-# Deploys skills/ix to:-# ~/.claude/skills/ix — Claude Code (global)-# ~/.agents/skills/ix — the .agents skill surface (global)+# skills/ix is a single, harness-agnostic skill (SKILL.md + references/ ++# scripts/). Each agent harness loads skills from its own directory, so this+# script probes for installed harnesses and deploys the same tree to each one+# that is present.#-# Skill loaders search ~/.claude/skills, ~/.agents/skills, and the-# project's .claude/skills and .agents/skills, so a global install makes the-# skill available in every project. Re-run after editing skills/ix.+# The harness table is NOT maintained here: it lives as an explicit, small+# registry in ix-cli/scripts/skill-harnesses.mjs (claude, agents, codex,+# cursor), where each entry's skill directory has been verified against the+# harness's actual convention — Cursor reads ~/.cursor/skills-cursor, and+# gemini/opencode/openclaw/vscode have no skills convention, so they are not+# install targets. Adding a harness is a deliberate one-line edit there.#-# Usage: bash scripts/install-skill.sh+# Presence is decided by the helper (`--probe`): a harness is present when its+# CLI is found or its config directory exists, so a GUI-only install is still+# found. When TOOLSCAN_PATH is set (opt-in — this script never executes a+# bare `toolscan` name from PATH), its discovery output scans the common+# install roots beyond PATH; otherwise the embedded PATH probe decides —+# toolscan is optional and purely additive, so a clean machine behaves+# exactly the same. Re-run after editing skills/ix to update every installed+# copy.+#+# Usage:+# bash scripts/install-skill.sh # install to every harness found+# bash scripts/install-skill.sh --dry-run # show the targets, write nothing+# bash scripts/install-skill.sh --force # overwrite a same-name foreign skill+# bash scripts/install-skill.sh claude codex # explicit harness ids only+# bash scripts/install-skill.sh --dry-run --json # machine-readable report (see below)set -euo pipefail@@ -19,31 +37,173 @@ SRC="$ROOT/skills/ix"[ -f "$SRC/SKILL.md" ] || { echo "error: $SRC/SKILL.md not found" >&2; exit 1; }FORCE=0-[ "${1:-}" = "--force" ] && FORCE=1+DRY_RUN=0+JSON=0+EXPLICIT=()+for arg in "$@"; do+ case "$arg" in+ --force) FORCE=1 ;;+ --dry-run) DRY_RUN=1 ;;+ --json) JSON=1 ;;+ -*) echo "error: unknown option $arg" >&2; exit 1 ;;+ *) EXPLICIT+=("$arg") ;;+ esac+done++# A machine-readable report replaces the human output: one object per harness+# with the action this run takes (would-install | would-refuse | installed |+# refused | skip) and `detectedVia` — the probe that decided presence+# (toolscan | path | config-dir | none), mirroring `ix mcp install`'s report.+# CI asserts the JSON fields instead of grepping the human lines.++# --- Read the harness registry (hosts.ts via the helper, no built CLI) ------+HELPER="$ROOT/ix-cli/scripts/skill-harnesses.mjs"+if [ ! -f "$HELPER" ]; then+ echo "error: $HELPER not found (the harness registry helper)" >&2+ exit 1+fi+if ! command -v node >/dev/null 2>&1; then+ echo "error: node is required to read the harness registry (ix-cli/src/mcp/hosts.ts)" >&2+ exit 1+fi++HELPER_OUT="$(node "$HELPER" --probe)" || {+ echo "error: harness registry helper failed — see its stderr above" >&2+ exit 1+}+IDS=() LABELS=() BINS=() CFGS=() DESTS=() PRESENT=() VIAS=()+while IFS= read -r row; do+ IFS='|' read -r id label bin cfg skill present via <<<"$row"+ [ -z "$cfg" ] && { echo "error: harness '$id' has no config-dir convention" >&2; exit 1; }+ cfg="${cfg//\~/$HOME}"+ skill="${skill//\~/$HOME}"+ IDS+=("$id"); LABELS+=("$label"); BINS+=("$bin"); CFGS+=("$cfg"); DESTS+=("$skill/ix"); PRESENT+=("$present"); VIAS+=("$via")+done <<<"$HELPER_OUT"+if [ "${#IDS[@]}" = "0" ]; then+ echo "error: harness registry produced no entries" >&2+ exit 1+fi++# --- Explicit harness id selection (unknown ids are an error, not a no-op) ---+if [ "${#EXPLICIT[@]}" -gt 0 ]; then+ all="${IDS[*]}"+ for id in "${EXPLICIT[@]}"; do+ case " $all " in+ *" $id "*) ;;+ *) echo "error: unknown harness id '$id'" >&2+ echo " valid ids:${all}" >&2+ exit 1 ;;+ esac+ done+ want=" ${EXPLICIT[*]} "+ o_ids=("${IDS[@]}"); o_labels=("${LABELS[@]}"); o_bins=("${BINS[@]}")+ o_cfgs=("${CFGS[@]}"); o_dests=("${DESTS[@]}"); o_present=("${PRESENT[@]}"); o_vias=("${VIAS[@]}")+ IDS=(); LABELS=(); BINS=(); CFGS=(); DESTS=(); PRESENT=(); VIAS=()+ for ((i = 0; i < ${#o_ids[@]}; i++)); do+ case "$want" in+ *" ${o_ids[$i]} "*)+ IDS+=("${o_ids[$i]}"); LABELS+=("${o_labels[$i]}"); BINS+=("${o_bins[$i]}")+ CFGS+=("${o_cfgs[$i]}"); DESTS+=("${o_dests[$i]}"); PRESENT+=("${o_present[$i]}"); VIAS+=("${o_vias[$i]}") ;;+ esac+ done+fi++# --- Install to every selected harness that is present -----------------------+# DECISIONS accumulates one `id<TAB>action<TAB>dest<TAB>via` record per host so+# the --json report can be emitted without re-deriving anything. Human lines+# go through `say`, which is silent in --json mode so stdout stays parseable.+say() {+ [ "$JSON" = "1" ] || echo "$@"+}installed=0-for dest in "$HOME/.claude/skills/ix" "$HOME/.agents/skills/ix"; do- mkdir -p "$(dirname "$dest")"- if [ -e "$dest" ]; then+conflicts=0+DECISIONS=()+for ((i = 0; i < ${#IDS[@]}; i++)); do+ id="${IDS[$i]}"; bin="${BINS[$i]}"; cfg="${CFGS[$i]}"; dest="${DESTS[$i]}"; via="${VIAS[$i]}"+ if [ "${PRESENT[$i]}" != "1" ]; then+ if [ -n "$bin" ]; then+ say "skip: $id — no $bin CLI or config at $cfg"+ else+ say "skip: $id — no config at $cfg"+ fi+ DECISIONS+=("$id"$'\t'"skip"$'\t'""$'\t'"$via")+ continue+ fi+ if [ -e "$dest" ] && [ "$FORCE" != "1" ] && ! grep -qs '^name: ix$' "$dest/SKILL.md"; then# Refuse to delete something that is not a previous install of this skill.# `ix` is a short name, and the unconditional `rm -rf` this replaces would# silently destroy a hand-written skill that happened to share it — with no- # prompt, no backup, and nothing in the output to say it had happened.- if [ "$FORCE" != "1" ] && ! grep -qs '^name: ix$' "$dest/SKILL.md"; then+ # prompt, no backup, and nothing in the output to say it had happened. The+ # check runs in dry-run too, so the preview and the real run agree.+ if [ "$DRY_RUN" = "1" ]; then+ say "would refuse: $dest — exists and is not an Ix skill install (use --force)"+ DECISIONS+=("$id"$'\t'"would-refuse"$'\t'"$dest"$'\t'"$via")+ elseecho "error: $dest exists and is not an Ix skill install." >&2echo " Move it aside, or re-run with --force to overwrite it." >&2- exit 1+ DECISIONS+=("$id"$'\t'"refused"$'\t'"$dest"$'\t'"$via")fi+ conflicts=$((conflicts + 1))+ continue+ fi+ if [ "$DRY_RUN" = "1" ]; then+ say "would install: $dest"+ DECISIONS+=("$id"$'\t'"would-install"$'\t'"$dest"$'\t'"$via")+ installed=$((installed + 1))+ continue+ fi+ mkdir -p "$(dirname "$dest")"+ if [ -e "$dest" ]; thenrm -rf "$dest"ficp -R "$SRC" "$dest"- echo "Installed: $dest"- installed=1+ say "Installed: $dest"+ DECISIONS+=("$id"$'\t'"installed"$'\t'"$dest"$'\t'"$via")+ installed=$((installed + 1))done-if [ "$installed" = "1" ]; then+if [ "$JSON" = "1" ]; then+ printf '%s\n' "${DECISIONS[@]:-}" | IX_DRY_RUN="$DRY_RUN" node -e '+ const lines = require("node:fs").readFileSync(0, "utf8").split("\n").filter(Boolean);+ const hosts = lines.map((line) => {+ const [id, action, dest, via] = line.split("\t");+ return { id, action, dest: dest || null, detectedVia: via };+ });+ process.stdout.write(JSON.stringify({+ dryRun: process.env.IX_DRY_RUN === "1",+ hosts,+ }, null, 2) + "\n");+ '+ # Same agreement as the human dry-run: a would-refuse predicts the real+ # run's exit 1.+ [ "$conflicts" = "0" ] || exit 1+ exit 0+fi++if [ "$DRY_RUN" = "1" ]; then+ echo+ echo "Dry run: $installed harness(es) would receive the skill."+ # The preview and the real run must agree: a conflict in the real run+ # exits 1, so a preview that predicts a refusal exits 1 too.+ [ "$conflicts" = "0" ] || exit 1+ exit 0+ fi++if [ "$installed" = "0" ] && [ "$conflicts" = "0" ]; thenecho- echo "Ix skill installed for Claude Code and the .agents surface."- echo "Start a new session so the agent picks it up, then ask it to use Ix:"- echo " \"Set up Ix and map this repo\""+ echo "No agent harness found. Install one of: ${IDS[*]} — or pass ids:"+ echo " bash scripts/install-skill.sh ${IDS[0]}"+ exit 0fi++echo+if [ "$conflicts" = "0" ]; then+ echo "Ix skill installed for $installed harness(es)."+else+ echo "Ix skill installed for $installed harness(es); $conflicts destination(s) refused."+fi+echo "Start a new session so the agent picks it up, then ask it to use Ix:"+echo " \"Set up Ix and map this repo\""++[ "$conflicts" = "0" ] || exit 1\ No newline at end of filediff --git a/skills/ix/SKILL.md b/skills/ix/SKILL.mdindex ae2370fe..35a0a363 100644--- a/skills/ix/SKILL.md+++ b/skills/ix/SKILL.md@@ -71,6 +71,38 @@ Map → Explain → Trace → Impact4. Immediately after modifying code, run `ix map --silent` to re-ingest.5. When Ix reports low confidence, mention the uncertainty to the user, suggest re-running `ix map`, and never present low-confidence data as established fact.+## Harness install seam++The skill installer (`scripts/install-skill.sh`) reads an explicit, small harness table from `ix-cli/scripts/skill-harnesses.mjs` — claude, agents, codex and cursor only. Each entry's skills directory is verified against what that harness actually reads (Cursor uses `~/.cursor/skills-cursor`, not `~/.cursor/skills`); gemini, opencode, openclaw and vscode have no skills convention, so they are deliberately not install targets. Adding a harness is a one-line edit in that table, after checking where the harness really looks. `ix mcp install` uses the separate MCP host registry (`ix-cli/src/mcp/hosts.ts`) — a different table answering a different question.++When `TOOLSCAN_PATH` is set, both surfaces consult its discovery output so a harness CLI installed outside `PATH` can still be found — and `ix mcp install` executes the absolute path toolscan reports, so the off-PATH harness is inspected and registered through the binary toolscan found. Toolscan is optional and additive: if it is unset or fails, the embedded `PATH` and config-directory probes remain authoritative. `TOOLSCAN_PATH` is opt-in: neither surface ever looks `toolscan` up on `PATH` (the CLI executes whatever `TOOLSCAN_PATH` names, so only set it to a binary you trust).++The probe battery has two environment seams:++| Seam | Used by | Default |+|---|---|---|+| `TOOLSCAN_PATH` | `skill-harnesses.mjs --probe`, `ix mcp install` | Unset — no toolscan, embedded probes decide |+| `HARNESS_HOME` | `skill-harnesses.mjs --probe` | `os.homedir()`; `install-skill.sh` uses the shell's `$HOME` |++For a hermetic probe with no real user configuration:++```bash+HARNESS_HOME="$(mktemp -d)" \+ node ix-cli/scripts/skill-harnesses.mjs --probe+```++To drive the same probe with a local or npm-installed toolscan bundle:++```bash+TOOLSCAN_PATH=/path/to/toolscan/dist/toolscan.mjs \+ HARNESS_HOME="$(mktemp -d)" \+ node ix-cli/scripts/skill-harnesses.mjs --probe+```++`--probe` emits `id|label|bin|config-dir|skill-dir|present|detectedVia`, where `present` is `1` or `0` and `detectedVia` names the probe that decided (`toolscan` | `path` | `config-dir` | `none`). `scripts/install-skill.sh --dry-run --json` emits the same per-harness view as machine-readable JSON: one object per host with `action` (`would-install` | `would-refuse` | `installed` | `refused` | `skip`), `dest`, and `detectedVia` — so CI can assert *how* a harness was found, not just that it was. A `would-refuse` in the preview exits 1, matching the real run's conflict exit, so scripts can rely on the two agreeing.++The install report's `--format json|llm` output carries `detectedVia` per host (`toolscan` | `path` | `config-dir` | `none`), so a consumer can see which probe decided presence — a host toolscan found reads `toolscan` even when its CLI also happens to be on PATH, and a host found by the PATH probe reads `path` rather than being misattributed to its config directory.+## References- **references/commands.md** — full command routing tables, decomposition recipes, best practices, and the do-not-use list. Load before running any command beyond the core four above.diff --git a/skills/ix/references/troubleshooting.md b/skills/ix/references/troubleshooting.mdindex dc179ab1..cba30428 100644--- a/skills/ix/references/troubleshooting.md+++ b/skills/ix/references/troubleshooting.md@@ -50,6 +50,60 @@ again.stops sending more (default 5). `0` sends every patch regardless, which isthe pre-#560 behaviour.+## Harness presence (hermetic reproduction)++The skill installer reads the explicit harness table in+`ix-cli/scripts/skill-harnesses.mjs` (claude, agents, codex, cursor — each+entry's skills directory verified against what that harness actually reads;+`ix mcp install` uses the separate MCP host registry in+`ix-cli/src/mcp/hosts.ts`). The helper's `--probe` emits one row per harness+with a `1`/`0` presence field and the detection source. When `TOOLSCAN_PATH`+is set, its discovery output is consumed as additive evidence for binaries+installed outside `PATH`; otherwise the embedded `PATH` and config-directory+probes decide.++Use these environment variables to reproduce the decision without using the+real user configuration:++| Variable | Scope | Purpose | Default |+|---|---|---|---|+| `TOOLSCAN_PATH` | helper and `ix mcp install` | An executable, script, or `dist/toolscan.mjs` to query. Opt-in only — the CLI never looks `toolscan` up on `PATH`, and it executes whatever this names, so point it only at a binary you trust. | Unset — no toolscan; embedded probes decide. |+| `HARNESS_HOME` | `skill-harnesses.mjs --probe` | Replaces Node's home directory when expanding `~` for config-directory presence checks. | `os.homedir()` |++A no-write local probe is:++```bash+HARNESS_HOME="$(mktemp -d)" \+ node ix-cli/scripts/skill-harnesses.mjs --probe+```++To include a local checkout or an npm-installed toolscan bundle:++```bash+TOOLSCAN_PATH=/path/to/toolscan/dist/toolscan.mjs \+ HARNESS_HOME="$(mktemp -d)" \+ node ix-cli/scripts/skill-harnesses.mjs --probe+```++To exercise the CLI surface against a fixture, restrict it with `--host` (an+unknown id fails loudly, so a renamed host cannot pass silently):++```bash+HOME="$(mktemp -d)" \+TOOLSCAN_PATH=/path/to/toolscan/dist/toolscan.mjs \+node ix-cli/dist/cli/main.js mcp install --host claude codex openclaw --dry-run --format json+```++The CI smoke job repeats this in a clean `node:22-bookworm` container with a+fake `toolscan` result naming only `claude`. The fake `claude` is installed at+`$HOME/.local/bin` — off PATH — so the job proves both directions of the seam:+presence decided by toolscan, and the off-PATH CLI invoked through the absolute+path toolscan reported. It asserts `claude` is present and `codex`/`agents`/+`cursor` are absent through the shell installer, and `claude` registers+(not a false conflict) plus `codex`/`openclaw` absent through `ix mcp install`;+the fake command and temporary home prevent host-machine state from making the+check pass accidentally.+## Re-mappingThe graph persists between sessions but goes stale as code changes. Re-run