diff --git a/CHANGELOG.md b/CHANGELOG.md index 232dadb0..e3de86a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,56 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Added + +- **`kit tools list` — the inventory that did not exist**, and the measurement three surfaces + were missing (#500). Per tool: the resolved path, the installer that owns it (classified from + the path, never assumed), the installed version, and with `--latest` how far behind it is. + Covers the declared `[tools]` **and** the undeclared CLIs an agent decides from — `gh`, `op`, + `jq`, `mise`, `docker`, `gcloud`, `kubectl`, `supabase`, `stripe`, `psql`, … — which were + invisible precisely because nothing declared them. + + Measured on the machine that filed the report, first run: `trivy 0.72.0 → 0.74.0`, + `trufflehog 3.95.9 → 3.97.0`, `gh 2.96.0 → 2.97.0`, `mise 2026.6.11 → 2026.8.9`, + `npm 10.9.8 → 12.0.2`, `op 2.34.0 → 2.39.0`. Cold 12s, warm 4s. + +- **`latest` is now checked against the installer that would satisfy it.** `versionSatisfies` + answered `if (required === "latest") return true;`, so `✓ vercel 53.1.1 (need latest)` printed + while the registry had 59.1.4 — six majors. The tools table now shows the installer in brackets + and, for a `latest` pin, `!` with `53.1.1 → 59.1.4 available`. A pin of `any` / `present` / `*` + asserts presence only, and says so, for repos that genuinely mean "whatever is installed". + + Lookups are per-installer (`npm view`, `mise latest`, `brew info --json=v2`, `pip index`), + cached per machine in `~/.kit/tool-latest.json` with a TTL (`KIT_TOOL_LATEST_TTL_H`, default + 24h), so the gate makes no network call once warm. A failed lookup is **not** cached — a flaky + network must not become a day-long policy. + +### Fixed + +- **`cli-lock.json` recorded a provenance it never measured, and the check called it `in sync`.** + Both writers did the same thing: + + ```ts + tools[name] = { version, source: "mise" }; // version = the DECLARED string + ``` + + so an entry read `{"vercel":{"version":"latest","source":"mise"}}` for a binary in + `/opt/homebrew/bin` that mise does not manage, and the lock check compared **names only**. + Now the version is the resolved one, the source is classified from the path, `sourceDetail` + carries installers the lock's four-value vocabulary cannot name (`brew`, `system`, `cargo`, + `kit-shim`), and a recorded source that contradicts the PATH winner fails the row with + `provenance drift: vercel: lock says mise, but /opt/homebrew/bin/vercel comes from brew`. + +- **An unrunnable currency check now reports why, instead of passing.** Air-gap makes no outbound + call and says so; an installer kit cannot query (`system`, `cargo`, `go`, a kit PATH shim) says + which; a timeout or an unparseable answer says that. Same rule as the scanners: coverage that + could not run is UNKNOWN, never clean. + +- **Prefixed declarations were reported as not installed.** `[tools]` carries backend prefixes + (`aqua:aquasecurity/trivy`, `npm:@socketsecurity/cli`), and the probe used the raw declaration + rather than the executable name — the same false statement as the one above, pointed the other + way. + ### Fixed - **The install-gate's refusal described its own machinery instead of the hazard it caught.** diff --git a/contracts/kit.opencli.json b/contracts/kit.opencli.json index ba60b2f5..8a10e492 100644 --- a/contracts/kit.opencli.json +++ b/contracts/kit.opencli.json @@ -1136,6 +1136,14 @@ "x-kit-mcp": false, "x-kit-stability": "experimental" }, + "tools": { + "kind": "command", + "summary": "Inventory the CLIs on this machine — path, installer, installed version, and (with --latest) how far behind each one is", + "x-kit-args-modeled": false, + "x-kit-audience": "all", + "x-kit-mcp": false, + "x-kit-stability": "experimental" + }, "triage": { "kind": "command", "summary": "Security evaluation before installing packages, images, or skills", diff --git a/contracts/public-surface.json b/contracts/public-surface.json index 7b0baf83..ac39f8f4 100644 --- a/contracts/public-surface.json +++ b/contracts/public-surface.json @@ -79,6 +79,7 @@ "statusline": "stable", "supply-chain": "stable", "team": "experimental", + "tools": "experimental", "triage": "stable", "upgrade": "stable", "verify-provenance": "stable", @@ -255,6 +256,7 @@ "statusline", "supply-chain", "team", + "tools", "triage", "upgrade", "verify-provenance", diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 5bd0d43c..352ef1b0 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -26,6 +26,15 @@ written before or after the command word — `kit --read-only check` and `kit check --read-only` are equivalent. Every command accepts them; a command that rejects unknown flags allows these on top of its own. +**`[tools]` pins say what they check.** An exact pin (`bun = "1.3.10"`) is a prefix match on +the installed version. `latest` now means *current*: kit resolves the newest version the tool's +own installer would give and reports drift — `!` with `53.1.1 → 59.1.4 available` in the tools +table — instead of passing because the binary answered `--version`, which is how +`✓ vercel 53.1.1 (need latest)` stood for six majors. When the newest version cannot be +determined (air-gap, an installer with no registry kit can query, a lookup that timed out) the +row is `− currency unchecked: ` — never a pass. A pin of `any`, `present` or `*` +asserts presence only, and says so. + **Unknown flags are rejected.** Every command validates its flags at dispatch against a declared table (`src/flag-surface.ts`), prints what it accepts, and exits 1 — a flag that silently does nothing is indistinguishable from a working @@ -355,6 +364,7 @@ Deterministic, zero-LLM code map: load only the relevant slice of a growing repo | Command | Purpose | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `kit tools list [--latest] [--json]` | Inventory the CLIs on this machine: resolved path, the installer that owns it (measured from the path, never assumed), installed version, and — with `--latest` — how far behind each one is. Covers the declared `[tools]` **and** the undeclared CLIs an agent decides from (`gh`, `op`, `docker`, `gcloud`, `kubectl`, `psql`, …). An installer kit cannot query (`system`, `cargo`, a kit PATH shim) reports `unchecked` **with the reason**; air-gap reports `unchecked`, never a version it did not verify. Answers are cached per machine (`~/.kit/tool-latest.json`, TTL `KIT_TOOL_LATEST_TTL_H`, default 24h), so the normal path makes no network call. `KIT_TOOLS_PATHS=1` prints paths. | | `kit map ` | The files connected to the seed(s) within `--depth` import hops (both directions) + external packages. TS/JS + Python. | | `kit map --depth N` | Widen the neighborhood (default 1). | | `kit map --budget N` | Keep only the N nearest-to-seed files; every drop is logged (never silent truncation). | diff --git a/docs/MCP_TOOLS_GUIDE.md b/docs/MCP_TOOLS_GUIDE.md index 613acafa..d38593f2 100644 --- a/docs/MCP_TOOLS_GUIDE.md +++ b/docs/MCP_TOOLS_GUIDE.md @@ -6,7 +6,7 @@ tool-by-tool reference lives in [MCP_TOOLS_REFERENCE.md](MCP_TOOLS_REFERENCE.md) this guide covers how to wire it up and how the surface is meant to be used. **The CLI-first rule.** An agent with shell access should run `kit ` -directly: the CLI covers all ~71 commands, costs zero standing context, and +directly: the CLI covers all ~72 commands, costs zero standing context, and `kit --help` self-documents. The server's own `instructions` field (sent in the MCP `initialize` result) says exactly this, so well-behaved clients route accordingly. The MCP tools exist for clients that cannot shell diff --git a/src/check-lock.ts b/src/check-lock.ts index f3b0c709..6b448e4a 100644 --- a/src/check-lock.ts +++ b/src/check-lock.ts @@ -91,13 +91,25 @@ export async function checkLockFiles(config: kitConfig, cwd?: string): Promise 0 + ? ` — provenance drift: ${drifted.join("; ")} (re-run \`kit fix\` to re-record)` + : ""; results.push({ category: "cli-lock", exists: true, - inSync: missing.length === 0, + // Drift counts against sync: the lock is a provenance record, and a record that names + // the wrong installer is not in sync with the machine it describes. + inSync: missing.length === 0 && drifted.length === 0, missing, authRequired, detail: - missing.length === 0 + missing.length === 0 && drifted.length === 0 ? `all tools locked${authDetails}` - : `${missing.length} tool(s) not in lock file${authDetails}`, + : missing.length > 0 + ? `${missing.length} tool(s) not in lock file${authDetails}${driftDetail}` + : `${drifted.length} tool(s) with wrong recorded provenance${authDetails}${driftDetail}`, }); } } diff --git a/src/check-run.ts b/src/check-run.ts index 7fc1255a..b12909b6 100644 --- a/src/check-run.ts +++ b/src/check-run.ts @@ -130,7 +130,15 @@ export async function runCheckGate(opts: RunCheckOptions = {}): Promise checkTools(config.tools!)) : []; + wants("tools") && config.tools + ? await step("tools", async () => { + // Currency from the cache only: the gate reports drift it already knows about and + // never makes the network a dependency of `kit check` (#500, requirement 6). + const { cachedCurrencyChecker } = await import("./tool-inventory.js"); + const { resolveToolBin } = await import("./utils/resolveTool.js"); + return checkTools(config.tools!, resolveToolBin, await cachedCurrencyChecker()); + }) + : []; const services = wants("services") && config.services ? await step("services", () => checkServices(config.services!)) diff --git a/src/check-tools.ts b/src/check-tools.ts index 82d0de14..2f9d413e 100644 --- a/src/check-tools.ts +++ b/src/check-tools.ts @@ -1,6 +1,10 @@ import type { ToolConfig } from "./config.js"; import { exec } from "./utils/exec.js"; import { resolveToolBin } from "./utils/resolveTool.js"; +import { homedir } from "node:os"; +import { classifyToolPath, type ToolSource } from "./tool-provenance.js"; +import { probeName } from "./tool-inventory.js"; +import type { DriftVerdict } from "./tool-latest.js"; /** Resolve a tool name to its executable path (mise-first), or null. */ export type ToolResolver = (tool: string) => Promise; @@ -9,9 +13,30 @@ export interface ToolStatus { name: string; required: string; installed: string | null; + /** Satisfies the declared pin. Unchanged meaning — every existing consumer reads this. */ ok: boolean; + /** Resolved executable path, when known. */ + path?: string; + /** Which installer owns that path (measured, never assumed). */ + source?: ToolSource; + /** + * Currency, for a pin that promises it (`latest`). `undefined` when the pin does not ask: + * an exact pin is about matching, not about being newest. + * + * `behind` is a WARNING, not a failure — the tool works, it is just old. But it must be + * visible: `✓ vercel 53.1.1 (need latest)` was printed for six majors of drift (#500). + * `unknown` carries the reason the lookup could not answer, and never reads as current. + */ + currency?: DriftVerdict; } +/** How a `latest` pin gets its answer. Injected so `checkTools` stays offline in tests. */ +export type CurrencyChecker = ( + tool: string, + source: ToolSource, + installed: string | null, +) => Promise; + async function getToolVersion(tool: string, resolve: ToolResolver): Promise { // Fast path: `mise current` gives the project-pinned version directly when the // tool is declared in the project's mise config. @@ -42,8 +67,27 @@ async function getToolVersion(tool: string, resolve: ToolResolver): Promise { const results: ToolStatus[] = []; for (const [name, required] of Object.entries(tools)) { const installed = await getToolVersion(name, resolve); const ok = installed !== null && versionSatisfies(installed, required); - results.push({ name, required, installed, ok }); + // The executable, not the declaration: `aqua:aquasecurity/trivy` resolves as `trivy`. + const path = (await resolve(probeName(name))) ?? undefined; + const source = path ? classifyToolPath(path, { home: homedir() }).source : undefined; + // Only a pin that PROMISES currency pays for a lookup. An exact pin says nothing about + // being newest, and asking anyway would put the network on the gate's critical path. + const drift = + currency && required === "latest" + ? await currency(name, source ?? "unknown", installed) + : undefined; + results.push({ name, required, installed, ok, path, source, currency: drift }); } return results; diff --git a/src/cli.ts b/src/cli.ts index 40655444..28552bf2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -76,6 +76,7 @@ import { cmdMcp } from "./commands/mcp.js"; import { cmdHooks } from "./commands/hooks.js"; import { cmdPlugin } from "./plugins-cli.js"; import { cmdTriage } from "./commands/triage.js"; +import { cmdTools } from "./commands/tools.js"; import { cmdSlopsquat } from "./commands/slopsquat.js"; import { cmdMemory } from "./commands/memory.js"; import { escapeWorkflowCmd, xmlEscape } from "./utils/ci-escape.js"; @@ -763,6 +764,11 @@ const COMMAND_REGISTRY: Record = { // layer cannot perform. mcp: true, }, + tools: { + handler: cmdTools, + stability: "experimental", + help: "Inventory the CLIs on this machine — path, installer, installed version, and (with --latest) how far behind each one is", + }, slopsquat: { handler: cmdSlopsquat, stability: "experimental", diff --git a/src/commands/setup.ts b/src/commands/setup.ts index 8b6ffdf1..2ebd82bc 100644 --- a/src/commands/setup.ts +++ b/src/commands/setup.ts @@ -942,9 +942,10 @@ export async function cmdInit(): Promise { { version: string; source: "mise" | "npm" | "pip" | "manual"; auth?: string } > = {}; if (config.tools) { - for (const [name, version] of Object.entries(config.tools)) { - tools[name] = { version, source: "mise" }; - } + // See fix.ts: the version and source are measured, not the declared string and a + // hardcoded "mise" (#500). + const { resolveLockEntries } = await import("../tool-inventory.js"); + Object.assign(tools, await resolveLockEntries(config.tools)); } await updateCliLock(tools); diff --git a/src/commands/tools.test.ts b/src/commands/tools.test.ts new file mode 100644 index 00000000..df936692 --- /dev/null +++ b/src/commands/tools.test.ts @@ -0,0 +1,97 @@ +/** + * The inventory command, driven end to end. + * + * `kit tools list` exists because nothing inventoried the CLIs an agent decides from (#500), so + * the thing worth testing is the OUTPUT an operator and a machine read: a source for everything + * installed, an explicit "not checked" rather than an implied pass, and a `--json` shape a script + * can rely on. + * + * No registry is contacted: `--latest` is never passed, and the gate-side reader is cache-only by + * construction. Each spawn walks the real PATH, so the assertions are about shape, not versions. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "..", "cli.js"); + +function run( + args: string[], + env: Record = {}, +): { exitCode: number; stdout: string; stderr: string } { + const r = spawnSync(process.execPath, [CLI_PATH, ...args], { + encoding: "utf-8", + env: { + ...process.env, + KIT_HIDE_HOOK_SKIP_BANNER: "1", + KIT_AUDIT_ANCHOR: "0", + ...env, + }, + timeout: 180_000, + }); + return { exitCode: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" }; +} + +describe("kit tools", () => { + it("lists by default, with the header, a source column and the summary", () => { + const r = run(["tools"]); + assert.equal(r.exitCode, 0, r.stderr); + assert.match(r.stdout, /kit tools list/); + // Every machine running this suite has git, and it comes from somewhere. + assert.match(r.stdout, /\bgit\b/); + assert.match(r.stdout, /declared in \.kit\.toml/); + // The currency hint must be present when --latest was NOT passed: silence would read as + // "checked and fine", which is the defect this command was built for. + assert.match(r.stdout, /Currency not checked/); + }); + + it("refuses an unknown subcommand instead of silently listing", () => { + const r = run(["tools", "bogus"]); + assert.equal(r.exitCode, 1); + assert.match(r.stderr, /unknown subcommand: kit tools bogus/); + assert.match(r.stderr, /kit tools list/); + }); + + it("emits a --json shape a script can rely on, with currency null until asked", () => { + const r = run(["tools", "list", "--json"]); + assert.equal(r.exitCode, 0, r.stderr); + const out = JSON.parse(r.stdout) as { + checkedCurrency: boolean; + tools: Array<{ + name: string; + declared: string | null; + path: string | null; + source: string | null; + shimmed: boolean | null; + installed: string | null; + currency: unknown; + }>; + }; + assert.equal(out.checkedCurrency, false); + assert.ok(Array.isArray(out.tools) && out.tools.length > 0); + for (const t of out.tools) { + assert.equal(typeof t.name, "string"); + assert.ok("declared" in t && "path" in t && "source" in t && "installed" in t); + assert.equal(t.currency, null, `${t.name}: currency must be null without --latest`); + if (t.path !== null) assert.ok(t.source, `${t.name}: a resolved path must carry a source`); + } + // stdout must be pure JSON — a machine reader is the point of the flag. + assert.doesNotMatch(r.stdout, /kit tools list/); + }); + + it("prints paths only when asked, so the default stays readable", () => { + const plain = run(["tools", "list"]); + const withPaths = run(["tools", "list"], { KIT_TOOLS_PATHS: "1" }); + assert.equal(withPaths.exitCode, 0, withPaths.stderr); + // Strip ANSI first: the path line is dim, so the escape sits between the indent and the `/`. + const stripAnsi = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, ""); + const countSlashes = (s: string): number => (stripAnsi(s).match(/^\s{4,}\/\S+/gm) ?? []).length; + assert.ok( + countSlashes(withPaths.stdout) > countSlashes(plain.stdout), + "KIT_TOOLS_PATHS=1 must add the resolved paths", + ); + }); +}); diff --git a/src/commands/tools.ts b/src/commands/tools.ts new file mode 100644 index 00000000..fdb37664 --- /dev/null +++ b/src/commands/tools.ts @@ -0,0 +1,120 @@ +/** + * `kit tools list` — what is actually installed, where it came from, and whether it is current. + * + * The inventory nobody had. `[tools]` covered five declared pins; the tools an agent actually + * decides from (`gh`, `op`, `docker`, `gcloud`, `psql`, …) were not declared, therefore not + * checked, therefore invisible — and the declared ones were reported without their source or + * their currency, so `✓ vercel 53.1.1 (need latest)` sat next to a registry that said 59.1.4 + * (#500). + * + * Currency lookups are opt-in per run (`--latest`) and cached with a TTL, because putting a + * registry call per tool on the default path is how a check becomes something people skip. + * Air-gap reports `unchecked` with the reason, never a version it did not verify. + */ + +import { c } from "../utils/colors.js"; +import { hasFlag } from "../utils/flags.js"; +import { loadConfig } from "../config.js"; +import { resolveConfigPath } from "../cli-shared.js"; + +function pad(s: string, n: number): string { + return s.length >= n ? s : s + " ".repeat(n - s.length); +} + +export async function cmdTools(): Promise { + const args = process.argv.slice(3); + const sub = args[0] && !args[0].startsWith("--") ? args[0] : "list"; + if (sub !== "list") { + console.error(`${c.red}unknown subcommand: kit tools ${sub}${c.reset}`); + console.error(`${c.dim}available: kit tools list [--latest] [--json]${c.reset}`); + return false; + } + + const jsonMode = hasFlag(process.argv, "--json"); + const withCurrency = hasFlag(process.argv, "--latest"); + + let declared: Record = {}; + try { + const config = await loadConfig(resolveConfigPath()); + declared = (config.tools ?? {}) as Record; + } catch { + /* no config here — the undeclared inventory is still worth printing */ + } + + const { inventoryTools } = await import("../tool-inventory.js"); + const facts = await inventoryTools(declared, { withCurrency }); + + if (jsonMode) { + console.log( + JSON.stringify( + { + checkedCurrency: withCurrency, + tools: facts.map((f) => ({ + name: f.name, + declared: f.declared ?? null, + path: f.path, + source: f.provenance?.source ?? null, + shimmed: f.provenance?.shimmed ?? null, + installed: f.installed, + currency: f.currency ?? null, + })), + }, + null, + 2, + ), + ); + return true; + } + + console.log(`${c.bold}${c.cyan}kit tools list${c.reset}`); + console.log(`${c.dim}${"─".repeat(64)}${c.reset}`); + const nameW = Math.max(10, ...facts.map((f) => f.name.length)) + 2; + const srcW = 10; + + for (const f of facts) { + const declaredMark = f.declared ? `${c.dim}(pin ${f.declared})${c.reset}` : ""; + if (!f.path) { + console.log( + ` ${c.red}✗${c.reset} ${pad(f.name, nameW)} ${c.red}not installed${c.reset} ${declaredMark}`, + ); + continue; + } + const source = f.provenance?.source ?? "unknown"; + const shim = f.provenance?.shimmed ? `${c.dim}(shim)${c.reset}` : ""; + const version = f.installed ?? `${c.yellow}version unreadable${c.reset}`; + const drift = f.currency; + const icon = + drift?.drift === "behind" + ? `${c.yellow}!${c.reset}` + : drift?.drift === "unknown" + ? `${c.dim}−${c.reset}` + : `${c.green}✓${c.reset}`; + const note = + drift?.drift === "behind" + ? ` ${c.yellow}→ ${drift.latest} available${c.reset}` + : drift?.drift === "ahead" + ? ` ${c.dim}ahead of ${drift.latest}${c.reset}` + : drift?.drift === "unknown" + ? ` ${c.dim}unchecked: ${drift.reason}${c.reset}` + : ""; + console.log( + ` ${icon} ${pad(f.name, nameW)} ${pad(String(version), 14)} ${c.dim}${pad(source, srcW)}${c.reset} ${shim} ${declaredMark}${note}`, + ); + if (f.path && process.env.KIT_TOOLS_PATHS === "1") { + console.log(` ${c.dim}${f.path}${c.reset}`); + } + } + + console.log(); + const declaredCount = facts.filter((f) => f.declared).length; + console.log( + `${c.dim}${facts.length} tool(s): ${declaredCount} declared in .kit.toml, ${facts.length - declaredCount} found on PATH.${c.reset}`, + ); + if (!withCurrency) { + console.log( + `${c.dim}Currency not checked — pass ${c.bold}--latest${c.reset}${c.dim} to compare against each installer's newest version (cached ${process.env.KIT_TOOL_LATEST_TTL_H ?? 24}h).${c.reset}`, + ); + } + console.log(`${c.dim}Paths: KIT_TOOLS_PATHS=1${c.reset}`); + return true; +} diff --git a/src/fix.ts b/src/fix.ts index 41e57637..7bc20d73 100644 --- a/src/fix.ts +++ b/src/fix.ts @@ -302,9 +302,13 @@ export async function cmdFix(cwd: string = process.cwd()): Promise { { version: string; source: "mise" | "npm" | "pip" | "manual"; auth?: string } > = {}; if (config.tools) { - for (const [name, version] of Object.entries(config.tools)) { - tools[name] = { version, source: "mise" }; - } + // Measured, not assumed. Both lock writers used to record the DECLARED string as the + // version and hardcode `source: "mise"`, so a lock entry read + // `{"vercel":{"version":"latest","source":"mise"}}` for a binary in + // /opt/homebrew/bin that mise does not manage — and `kit check` called it in sync + // (#500). `resolveLockEntries` reads the resolved version and classifies the path. + const { resolveLockEntries } = await import("./tool-inventory.js"); + Object.assign(tools, await resolveLockEntries(config.tools)); } await updateCliLock(tools, cwd); diff --git a/src/flag-surface.ts b/src/flag-surface.ts index ee3d6e9e..b8174754 100644 --- a/src/flag-surface.ts +++ b/src/flag-surface.ts @@ -580,6 +580,7 @@ export const COMMAND_FLAGS: Record = { statusline: ["--broker-gate", "--help", "--limit", "--mode", "--no-install-gate"], "supply-chain": ["--attest", "--json", "--mode", "--no-auto-install", "--non-interactive"], team: ["--broker-gate", "--help", "--limit", "--mode", "--no-install-gate", "--role"], + tools: ["--json", "--latest"], triage: [ "--cached", "--deep", diff --git a/src/lock.ts b/src/lock.ts index 4c3dcd03..bc31d7b1 100644 --- a/src/lock.ts +++ b/src/lock.ts @@ -35,6 +35,14 @@ export interface CliLock { export interface CliLockEntry { version: string; source: "mise" | "npm" | "pip" | "manual"; + /** + * The installer kit actually measured, when it has no name in `source`'s four-value + * vocabulary (`brew`, `system`, `cargo`, `kit-shim`, …). Added because the lock said `mise` + * for `/opt/homebrew/bin/vercel` and had no way to say otherwise (#500). + */ + sourceDetail?: string; + /** The resolved executable the version was read from — the evidence behind the entry. */ + path?: string; auth?: string; installedAt: string; } @@ -286,7 +294,16 @@ export async function updateSkillsLock( * Update CLI lock with installed tools */ export async function updateCliLock( - tools: Record, + tools: Record< + string, + { + version: string; + source: CliLockEntry["source"]; + sourceDetail?: string; + path?: string; + auth?: string; + } + >, cwd?: string, ): Promise { const existing = await readCliLock(cwd); @@ -306,6 +323,8 @@ export async function updateCliLock( lock.tools[name] = { version: info.version, source: info.source, + sourceDetail: info.sourceDetail, + path: info.path, auth: info.auth, installedAt: new Date().toISOString(), }; diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 75b22717..f41914b0 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -56,7 +56,7 @@ export const KIT_MCP_TOOLS: readonly string[] = [ * Server-level instructions (MCP `initialize` result). Clients like Claude Code * surface this to route tool selection, so it carries the one decision that * matters most for context economy: an agent WITH shell access should prefer the - * CLI (zero standing context cost, `--help` self-documents all 71 commands); + * CLI (zero standing context cost, `--help` self-documents all 72 commands); * these MCP tools exist for shell-less clients. Kept well under the ~2KB * truncation limit clients apply. */ diff --git a/src/output.ts b/src/output.ts index 093e4bac..7ebfd815 100644 --- a/src/output.ts +++ b/src/output.ts @@ -96,13 +96,32 @@ export function printToolsTable(tools: ToolStatus[]): void { const nameWidth = Math.max(12, ...tools.map((t) => t.name.length)) + 2; for (const tool of tools) { - const icon = tool.ok ? CHECK : CROSS; + // Currency is its own axis: a tool can satisfy its pin and still be six majors old, which + // is exactly what `✓ vercel 53.1.1 (need latest)` hid (#500). `behind` shows as a warning + // icon; `unknown` says why it could not be checked rather than borrowing the pass icon. + const drift = tool.currency; + const icon = !tool.ok + ? CROSS + : drift?.drift === "behind" + ? `${c.yellow}!${c.reset}` + : drift?.drift === "unknown" + ? `${c.dim}−${c.reset}` + : CHECK; const name = pad(tool.name, nameWidth); const version = tool.installed ? `${c.dim}${tool.installed}${c.reset}` : `${c.red}not installed${c.reset}`; const required = `${c.gray}(need ${tool.required})${c.reset}`; - console.log(` ${icon} ${name} ${version} ${required}`); + const note = + drift?.drift === "behind" + ? ` ${c.yellow}${drift.installed} → ${drift.latest} available${c.reset}` + : drift?.drift === "ahead" + ? ` ${c.dim}ahead of ${drift.latest}${c.reset}` + : drift?.drift === "unknown" + ? ` ${c.dim}currency unchecked: ${drift.reason}${c.reset}` + : ""; + const from = tool.source ? ` ${c.gray}[${tool.source}]${c.reset}` : ""; + console.log(` ${icon} ${name} ${version} ${required}${from}${note}`); } } diff --git a/src/tool-inventory.test.ts b/src/tool-inventory.test.ts new file mode 100644 index 00000000..942ad561 --- /dev/null +++ b/src/tool-inventory.test.ts @@ -0,0 +1,137 @@ +/** + * The inventory that did not exist, and the two mappings it needs to get right. + * + * `probeName` exists because a declared tool is not the same string as its executable: + * `[tools]` carries backend prefixes (`aqua:aquasecurity/trivy`, `npm:@socketsecurity/cli`), and + * probing the raw declaration reported installed tools as "not installed" — the same false + * statement #500 is about, pointed the other way. Measured before the fix: `kit tools list` said + * `✗ aqua:aquasecurity/trivy not installed` while trivy 0.72.0 was on PATH via mise. + * + * `toLockSource` exists because `cli-lock.json`'s vocabulary is four values wide and the machine + * has more installers than that. Rather than keep guessing `mise` (the defect), an installer + * without a lock word maps to `manual` and the measured name is kept alongside in `sourceDetail`. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { probeName, toLockSource, AGENT_RELEVANT_TOOLS } from "./tool-inventory.js"; + +const CLI_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "cli.js"); + +describe("probeName", () => { + it("strips the backend prefix and takes the executable name", () => { + assert.equal(probeName("aqua:aquasecurity/trivy"), "trivy"); + assert.equal(probeName("aqua:trufflesecurity/trufflehog"), "trufflehog"); + assert.equal(probeName("npm:@socketsecurity/cli"), "cli"); + assert.equal(probeName("pipx:lizard"), "lizard"); + assert.equal(probeName("go:github.com/x/y/cmd/tool"), "tool"); + }); + + it("leaves a plain name alone", () => { + for (const name of ["bun", "vercel", "semgrep", "python3"]) { + assert.equal(probeName(name), name); + } + }); + + it("drops a leading @ so a bare scope does not become the probe", () => { + assert.equal(probeName("npm:@scope"), "scope"); + }); +}); + +describe("toLockSource", () => { + it("maps the installers the lock can name", () => { + assert.equal(toLockSource("mise"), "mise"); + assert.equal(toLockSource("asdf"), "mise"); + assert.equal(toLockSource("npm-global"), "npm"); + assert.equal(toLockSource("pipx"), "pip"); + }); + + it("maps everything else to manual instead of guessing mise", () => { + // The defect: brew binaries were recorded as `mise`, and the check agreed (#500). + for (const source of ["brew", "system", "cargo", "go", "kit-shim", "unknown"] as const) { + assert.equal(toLockSource(source), "manual", source); + } + assert.equal(toLockSource(undefined), "manual"); + }); +}); + +describe("the agent-relevant list", () => { + it("covers the tools the report named as invisible", () => { + for (const t of ["gh", "op", "jq", "mise", "docker", "gcloud", "kubectl", "psql"]) { + assert.ok( + (AGENT_RELEVANT_TOOLS as readonly string[]).includes(t), + `${t} was named in #500 as a tool agents decide from`, + ); + } + }); + + it("has no duplicates — the inventory is a set, not a list that grew", () => { + const seen = new Set(AGENT_RELEVANT_TOOLS); + assert.equal(seen.size, AGENT_RELEVANT_TOOLS.length); + }); +}); + +/** + * End-to-end, against this machine. Deliberately does NOT assert versions — the point is the + * shape of the answer: every installed tool gets a measured path and source, and nothing claims + * `mise` for a binary outside mise. `--latest` is not passed, so no registry is queried. + */ +describe("kit tools list --json (compiled CLI)", () => { + const run = (): { + checkedCurrency: boolean; + tools: Array<{ + name: string; + declared: string | null; + path: string | null; + source: string | null; + installed: string | null; + currency: unknown; + }>; + } => { + const r = spawnSync(process.execPath, [CLI_PATH, "tools", "list", "--json"], { + encoding: "utf-8", + env: { ...process.env, KIT_HIDE_HOOK_SKIP_BANNER: "1", KIT_AUDIT_ANCHOR: "0" }, + timeout: 120_000, + }); + assert.equal(r.status, 0, r.stderr); + return JSON.parse(r.stdout) as never; + }; + + it("reports a path and a source for every tool it lists", () => { + const out = run(); + assert.ok(out.tools.length > 0, "this machine has tools on PATH"); + for (const t of out.tools) { + if (t.path === null) { + // Only a DECLARED tool may appear without a path — that absence is the finding. + assert.notEqual( + t.declared, + null, + `${t.name} is undeclared and missing; it should be omitted`, + ); + continue; + } + assert.ok(t.source, `${t.name} has a path but no measured source`); + } + }); + + it("does not claim mise for a binary outside mise", () => { + for (const t of run().tools) { + if (t.source !== "mise" || !t.path) continue; + assert.match( + t.path, + /mise/, + `${t.name} is reported as mise-installed but its path is ${t.path}`, + ); + } + }); + + it("leaves currency unchecked unless --latest is passed", () => { + const out = run(); + assert.equal(out.checkedCurrency, false); + for (const t of out.tools) assert.equal(t.currency, null, `${t.name} was checked unasked`); + }); +}); diff --git a/src/tool-inventory.ts b/src/tool-inventory.ts new file mode 100644 index 00000000..a649d6db --- /dev/null +++ b/src/tool-inventory.ts @@ -0,0 +1,237 @@ +/** + * One place that answers, per tool: where it is, who installed it, what version is there, and + * what the newest version would be. + * + * Three surfaces needed the same four facts and none of them had them (#500): + * + * - `cli-lock.json` recorded the DECLARED pin as the version and a hardcoded `source: "mise"`, + * so it said `mise` for `/opt/homebrew/bin/vercel`; + * - `kit check`'s tools table printed `✓ … (need latest)` without ever asking what latest is; + * - nothing at all inventoried the tools agents actually decide from (`gh`, `op`, `jq`, + * `docker`, `gcloud`, …) because they are not in `[tools]`. + * + * So the facts live here, measured once, and the surfaces render them. The undeclared list is + * deliberately opinionated rather than "everything on PATH": it is the set whose output an agent + * treats as authority, which is the reason an unnoticed six-major drift costs a wrong decision + * rather than a slow build. + */ + +import { homedir } from "node:os"; +import { join } from "node:path"; +import { readFile, writeFile, mkdir } from "node:fs/promises"; +import { resolveToolBin } from "./utils/resolveTool.js"; +import { classifyToolPath, type ToolProvenance, type ToolSource } from "./tool-provenance.js"; +import { + latestVersion, + judgeDrift, + type DriftVerdict, + type LatestCache, + type LatestDeps, +} from "./tool-latest.js"; +import { execFileNoThrow } from "./utils/execFileNoThrow.js"; + +/** + * Tools whose output an agent treats as authority, beyond whatever `[tools]` declares. + * + * Not "everything on PATH": an inventory nobody reads is the failure mode one level up. These + * are the ones that answer questions a session then acts on — identity, deploy state, secrets, + * cluster state, data. + */ +export const AGENT_RELEVANT_TOOLS = [ + "gh", + "op", + "jq", + "mise", + "docker", + "gcloud", + "kubectl", + "supabase", + "stripe", + "psql", + "git", + "node", + "npm", + "python3", + "vercel", + "convex", +] as const; + +export interface ToolFacts { + name: string; + /** The pin from `[tools]`, when the tool is declared. */ + declared?: string; + path: string | null; + provenance: ToolProvenance | null; + installed: string | null; + /** Only computed when asked for — a lookup per tool is not free. */ + currency?: DriftVerdict; +} + +/** + * The binary name to probe for a declared tool. + * + * `[tools]` declarations carry a backend prefix — `aqua:aquasecurity/trivy`, + * `npm:@socketsecurity/cli`, `pipx:lizard` — and the executable is named after the last path + * segment, not the declaration. Probing the raw string reported installed tools as + * "not installed", which is the same false statement as the one this arc is closing, pointed + * the other way. + */ +export function probeName(declaration: string): string { + const withoutBackend = declaration.includes(":") + ? declaration.slice(declaration.indexOf(":") + 1) + : declaration; + const last = withoutBackend.split("/").filter(Boolean).pop() ?? withoutBackend; + return last.replace(/^@/, ""); +} + +/** Read a tool's version the way the check does: run it and take the first version token. */ +export async function readToolVersion(bin: string): Promise { + const r = await execFileNoThrow(bin, ["--version"], { timeout: 10_000 }); + if (!r.ok) return null; + const m = (r.stdout || r.stderr || "").match(/(\d+[\d.]*)/); + return m ? m[1] : null; +} + +/** Where the latest-version cache lives. Per machine, not per repo: the answer is machine-wide. */ +export function latestCachePath(): string { + return join(process.env.KIT_AUDIT_ANCHOR_DIR ?? join(homedir(), ".kit"), "tool-latest.json"); +} + +/** Real dependencies for the latest lookups: subprocess, clock, on-disk TTL cache, air-gap. */ +export async function realLatestDeps(): Promise { + const { isAirGapPosture } = await import("./update-check.js"); + const offline = await isAirGapPosture(); + const path = latestCachePath(); + return { + offline, + now: () => Date.now(), + ttlHours: Number.parseFloat(process.env.KIT_TOOL_LATEST_TTL_H ?? "") || undefined, + run: async (cmd, args) => { + const r = await execFileNoThrow(cmd, [...args], { timeout: 20_000 }); + return { ok: r.ok, stdout: r.stdout ?? "" }; + }, + readCache: async () => { + try { + return JSON.parse(await readFile(path, "utf-8")) as LatestCache; + } catch { + return {}; + } + }, + writeCache: async (cache) => { + try { + await mkdir(join(path, ".."), { recursive: true }); + await writeFile(path, JSON.stringify(cache, null, 2) + "\n", { mode: 0o600 }); + } catch { + /* a cache we cannot write is a slower check, not a failed one */ + } + }, + }; +} + +/** + * A currency checker for the GATE: reads the cache, never fills it. + * + * `kit check` must not shell out to four registries — requirement 6 of #500 is that the check + * stays fast and offline-safe. So the gate reports drift the moment the cache knows about it + * (warmed by `kit tools list --latest`, or a cron), and otherwise says it has not been looked up. + * Silence would be the old false green with extra steps. + */ +export async function cachedCurrencyChecker(): Promise< + (tool: string, source: ToolSource, installed: string | null) => Promise +> { + const deps = { ...(await realLatestDeps()), cacheOnly: true }; + return async (tool, source, installed) => + judgeDrift(installed, await latestVersion(probeName(tool), source, deps)); +} + +/** Measure one tool. `withCurrency` gates the (possibly networked) latest lookup. */ +export async function describeTool( + name: string, + opts: { declared?: string; withCurrency?: boolean; deps?: LatestDeps } = {}, +): Promise { + const path = await resolveToolBin(probeName(name)); + const provenance = path ? classifyToolPath(path, { home: homedir() }) : null; + const installed = path ? await readToolVersion(path) : null; + const facts: ToolFacts = { name, declared: opts.declared, path, provenance, installed }; + if (opts.withCurrency && provenance) { + const deps = opts.deps ?? (await realLatestDeps()); + facts.currency = judgeDrift( + installed, + await latestVersion(probeName(name), provenance.source, deps), + ); + } + return facts; +} + +/** + * The full inventory: declared tools plus the agent-relevant ones found on PATH. + * + * Declared tools win on name collision — the pin is the interesting fact about them. + */ +export async function inventoryTools( + declared: Record = {}, + opts: { withCurrency?: boolean; deps?: LatestDeps } = {}, +): Promise { + const names = new Set([...Object.keys(declared), ...AGENT_RELEVANT_TOOLS]); + const out: ToolFacts[] = []; + for (const name of [...names].sort()) { + const facts = await describeTool(name, { + declared: declared[name], + withCurrency: opts.withCurrency, + deps: opts.deps, + }); + // An undeclared tool that is not installed is not news; a declared one that is missing is. + if (facts.path === null && declared[name] === undefined) continue; + out.push(facts); + } + return out; +} + +/** The lock's narrower source vocabulary. */ +export type LockSource = "mise" | "npm" | "pip" | "manual"; + +/** Map a measured installer onto what `cli-lock.json` can express. */ +export function toLockSource(source: ToolSource | undefined): LockSource { + switch (source) { + case "mise": + case "asdf": + return "mise"; + case "npm-global": + return "npm"; + case "pipx": + return "pip"; + case undefined: + return "manual"; + default: + // brew / system / cargo / go / kit-shim / unknown have no lock vocabulary of their own. + return "manual"; + } +} + +/** + * Lock entries for the declared tools, with the version and source MEASURED. + * + * The resolved version is recorded when the tool is installed; when it is not, the declared pin + * is kept so the entry still says what was asked for. `sourceDetail` carries the installer kit + * actually saw, because the lock's four-value vocabulary cannot say "brew". + */ +export async function resolveLockEntries( + declared: Record, +): Promise< + Record +> { + const out: Record< + string, + { version: string; source: LockSource; sourceDetail?: string; path?: string } + > = {}; + for (const [name, pin] of Object.entries(declared)) { + const facts = await describeTool(name); + out[name] = { + version: facts.installed ?? pin, + source: toLockSource(facts.provenance?.source), + sourceDetail: facts.provenance?.source, + path: facts.path ?? undefined, + }; + } + return out; +} diff --git a/src/tool-latest.test.ts b/src/tool-latest.test.ts new file mode 100644 index 00000000..61f7e2a1 --- /dev/null +++ b/src/tool-latest.test.ts @@ -0,0 +1,184 @@ +/** + * The lookup that `latest` never made. + * + * `check-tools.ts` answered `if (required === "latest") return true;`, so `✓ vercel 53.1.1 + * (need latest)` printed while npm had 59.1.4 (#500). These tests pin the three properties that + * make the replacement safe rather than merely present: a lookup that cannot run says so, an + * installer kit cannot query says which, and a warm cache means the gate makes no network call. + * + * Nothing here touches a registry — the runner, clock and cache are injected. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; + +import { + latestVersion, + judgeDrift, + compareVersions, + parseBrewInfoVersion, + firstVersion, + latestCacheKey, + type LatestCache, + type LatestDeps, +} from "./tool-latest.js"; + +/** A fixed, realistic clock: TTL arithmetic has to happen on plausible epoch values. */ +const NOW = 1_800_000_000_000; +const HOUR = 3_600_000; + +function deps( + over: Partial = {}, +): LatestDeps & { cache: LatestCache; calls: string[] } { + const cache: LatestCache = {}; + const calls: string[] = []; + const inner = over.run ?? (async () => ({ ok: true, stdout: "1.2.3\n" })); + const base: LatestDeps = { + now: () => NOW, + readCache: async () => cache, + writeCache: async (c) => { + for (const k of Object.keys(c)) cache[k] = c[k]; + }, + offline: false, + ...over, + // Wrap whatever runner the case supplied, so `calls` records every invocation — an + // override used to bypass the recorder and made "did this shell out?" untestable. + run: async (cmd, args) => { + calls.push(`${cmd} ${args.join(" ")}`); + return inner(cmd, args); + }, + }; + return Object.assign(base, { cache, calls }); +} + +describe("latestVersion", () => { + it("asks npm for an npm-global tool and caches the answer", async () => { + const d = deps({ run: async () => ({ ok: true, stdout: "6.7.0\n" }) }); + const r = await latestVersion("sandstream-kit", "npm-global", d); + assert.deepEqual(r, { status: "known", version: "6.7.0", via: "npm", cached: false }); + assert.equal(d.cache[latestCacheKey("sandstream-kit", "npm-global")]?.version, "6.7.0"); + }); + + it("serves a warm cache without running anything — the gate must not need the network", async () => { + const d = deps(); + d.cache["brew:vercel"] = { version: "59.1.4", at: NOW - HOUR, via: "brew" }; + const r = await latestVersion("vercel", "brew", d); + assert.deepEqual(r, { status: "known", version: "59.1.4", via: "brew", cached: true }); + assert.deepEqual(d.calls, [], "a cache hit must not shell out"); + }); + + it("re-asks once the TTL has passed", async () => { + const d = deps({ run: async () => ({ ok: true, stdout: "59.1.4\n" }) }); + d.cache["mise:semgrep"] = { version: "1.167.0", at: NOW - 25 * HOUR, via: "mise" }; + const r = await latestVersion("semgrep", "mise", d); + assert.equal(r.status === "known" && r.version, "59.1.4"); + assert.equal(r.status === "known" && r.cached, false); + assert.deepEqual(d.calls, ["mise latest semgrep"]); + }); + + it("air-gap reports unavailable with a reason — never current", async () => { + const d = deps({ offline: true }); + const r = await latestVersion("vercel", "brew", d); + assert.equal(r.status, "unavailable"); + assert.match(r.status === "unavailable" ? r.reason : "", /air-gap\/offline/); + assert.deepEqual(d.calls, [], "air-gap must make no outbound call"); + }); + + it("air-gap says the cached answer is stale rather than serving it silently", async () => { + const d = deps({ offline: true }); + d.cache["brew:vercel"] = { version: "58.0.0", at: NOW - 25 * HOUR, via: "brew" }; + const r = await latestVersion("vercel", "brew", d); + assert.equal(r.status, "unavailable"); + assert.match(r.status === "unavailable" ? r.reason : "", /58\.0\.0/); + }); + + it("an installer with no registry is unsupported, and names itself", async () => { + for (const source of ["system", "cargo", "go", "unknown"] as const) { + const r = await latestVersion("git", source, deps()); + assert.equal(r.status, "unsupported", source); + assert.match(r.status === "unsupported" ? r.reason : "", new RegExp(source)); + } + }); + + it("a kit shim is unsupported and says to resolve what it wraps", async () => { + const r = await latestVersion("bun", "kit-shim", deps()); + assert.equal(r.status, "unsupported"); + assert.match(r.status === "unsupported" ? r.reason : "", /delegates/); + }); + + it("a failed lookup is unavailable and is NOT cached — a transient must not become policy", async () => { + const d = deps({ run: async () => ({ ok: false, stdout: "" }) }); + const r = await latestVersion("vercel", "brew", d); + assert.equal(r.status, "unavailable"); + assert.match(r.status === "unavailable" ? r.reason : "", /did not answer/); + assert.deepEqual(Object.keys(d.cache), []); + }); + + it("an answer with no version in it is unavailable, not a pass", async () => { + const d = deps({ run: async () => ({ ok: true, stdout: "Warning: nothing to report\n" }) }); + const r = await latestVersion("vercel", "brew", d); + assert.equal(r.status, "unavailable"); + assert.match(r.status === "unavailable" ? r.reason : "", /no version could be read/); + }); + + it("reads brew's JSON rather than the first number in its chatter", () => { + const json = JSON.stringify({ + formulae: [{ versions: { stable: "59.1.4" } }], + }); + assert.equal(parseBrewInfoVersion(json), "59.1.4"); + assert.equal(parseBrewInfoVersion("not json"), null); + assert.equal(firstVersion("mise 2026.8.9 something"), "2026.8.9"); + }); +}); + +describe("compareVersions / judgeDrift", () => { + it("compares numerically, not as strings", () => { + // The case that mattered, and the one a string compare gets backwards. + assert.equal(compareVersions("53.1.1", "59.1.4"), -1); + assert.equal(compareVersions("9.0.0", "10.0.0"), -1); + assert.equal(compareVersions("1.173.0", "1.167.0"), 1); + assert.equal(compareVersions("1.2.3", "1.2.3"), 0); + assert.equal(compareVersions("1.2", "1.2.0"), 0); + assert.equal(compareVersions("v6.7.0", "6.7.0"), 0); + assert.equal(compareVersions("weird-build", "1.0.0"), null); + }); + + it("behind is the six-majors case, reported with both numbers", () => { + const v = judgeDrift("53.1.1", { + status: "known", + version: "59.1.4", + via: "brew", + cached: true, + }); + assert.deepEqual(v, { drift: "behind", installed: "53.1.1", latest: "59.1.4" }); + }); + + it("ahead is a warning, not an error — a newer local build is not a defect", () => { + const v = judgeDrift("2.0.0", { status: "known", version: "1.9.0", via: "npm", cached: false }); + assert.equal(v.drift, "ahead"); + }); + + it("carries the lookup's own reason through when it could not run", () => { + const v = judgeDrift("1.0.0", { + status: "unavailable", + reason: "air-gap/offline: nothing cached", + }); + assert.deepEqual(v, { drift: "unknown", reason: "air-gap/offline: nothing cached" }); + }); + + it("a missing tool is unknown drift, not behind", () => { + const v = judgeDrift(null, { status: "known", version: "1.0.0", via: "npm", cached: true }); + assert.deepEqual(v, { drift: "unknown", reason: "tool not installed" }); + }); + + it("an unparseable installed version does not pass as current", () => { + const v = judgeDrift("nightly", { + status: "known", + version: "1.0.0", + via: "npm", + cached: true, + }); + assert.equal(v.drift, "unknown"); + assert.match(v.drift === "unknown" ? v.reason : "", /cannot compare/); + }); +}); diff --git a/src/tool-latest.ts b/src/tool-latest.ts new file mode 100644 index 00000000..11f2aa18 --- /dev/null +++ b/src/tool-latest.ts @@ -0,0 +1,230 @@ +/** + * What the latest version of a tool is — per installer, cached, and honest when it cannot say. + * + * `latest` in `[tools]` was compared against nothing: `check-tools.ts` returned `true` for it + * before looking at anything, so `✓ vercel 53.1.1 (need latest)` was printed while the registry + * had 59.1.4 — six majors on (#500). The fix needs a source of truth per installer, because + * "latest" is a different question for brew, mise and npm. + * + * Three hard rules, from kit's own no-false-green stance: + * + * 1. **A lookup that could not run is `unavailable`, never "current".** Offline, air-gapped, a + * missing installer, a timeout — all report a reason and leave the verdict unknown. The old + * behaviour (assume fine) is exactly the false green this closes. + * 2. **An installer kit cannot query is `unsupported`, and says which.** `/usr/bin/git` has no + * registry to ask; pretending it is current would be the same lie in a smaller font. + * 3. **Never let the check become a network dependency.** Results are cached with a TTL + * (default 24h, `KIT_TOOL_LATEST_TTL_H`), and air-gap posture skips the lookups entirely, so + * a normal `kit check` makes no outbound call once warm. + * + * Everything is injected — the runner, the clock, the cache — so the tests never touch a + * registry or the real `~/.kit`. + */ + +import type { ToolSource } from "./tool-provenance.js"; + +export type LatestOutcome = + /** The installer answered: this is the newest version it would install. */ + | { status: "known"; version: string; via: string; cached: boolean } + /** kit has no way to ask this installer. Not a finding, and not a pass either. */ + | { status: "unsupported"; reason: string } + /** kit could not ask right now (offline, air-gap, installer missing, timeout). */ + | { status: "unavailable"; reason: string }; + +export interface LatestCacheEntry { + version: string; + /** Epoch ms when the answer was recorded. */ + at: number; + via: string; +} + +export type LatestCache = Record; + +export interface LatestDeps { + /** Run an installer command. Must never throw; `ok:false` means "could not ask". */ + run: (cmd: string, args: readonly string[]) => Promise<{ ok: boolean; stdout: string }>; + now: () => number; + readCache: () => Promise; + writeCache: (cache: LatestCache) => Promise; + /** Air-gap / offline posture: skip every lookup, report why. */ + offline: boolean; + /** + * Read the cache, never fill it. `kit check` runs on this: requirement 6 of #500 is that the + * gate must not become slow or network-dependent, and a gate that quietly shells out to four + * registries is exactly that. Drift still surfaces the moment something else warmed the cache + * (`kit tools list --latest`), and until then the row says so instead of passing. + */ + cacheOnly?: boolean; + /** Cache lifetime in hours. */ + ttlHours?: number; +} + +const DEFAULT_TTL_HOURS = 24; + +/** Cache key: the answer depends on the installer as much as on the name. */ +export function latestCacheKey(tool: string, source: ToolSource): string { + return `${source}:${tool}`; +} + +/** First version-looking token, so `mise latest node` / `brew info` chatter is tolerated. */ +export function firstVersion(text: string): string | null { + const m = text.match(/\b(\d+\.\d+(?:\.\d+)?(?:[-.][A-Za-z0-9.]+)?)\b/); + return m ? m[1] : null; +} + +/** + * How to ask each installer. Returning null means "kit has no query for this source" — + * `system`, `cargo`, `go`, `unknown`: the binary exists, nothing kit can compare it to. + * + * `kit-shim` deliberately has no query: the shim delegates, so asking about the shim would + * answer about the wrong thing. The caller resolves what it wraps first, or gets `unsupported`. + */ +function queryFor( + tool: string, + source: ToolSource, +): { cmd: string; args: string[]; via: string } | null { + switch (source) { + case "npm-global": + return { cmd: "npm", args: ["view", tool, "version"], via: "npm" }; + case "mise": + return { cmd: "mise", args: ["latest", tool], via: "mise" }; + case "brew": + return { cmd: "brew", args: ["info", "--json=v2", "--formula", tool], via: "brew" }; + case "pipx": + return { cmd: "pip", args: ["index", "versions", tool], via: "pip" }; + default: + return null; + } +} + +/** Pull the stable version out of `brew info --json=v2` without pulling in a JSON schema. */ +export function parseBrewInfoVersion(stdout: string): string | null { + try { + const parsed = JSON.parse(stdout) as { + formulae?: Array<{ versions?: { stable?: string | null } }>; + casks?: Array<{ version?: string | null }>; + }; + const stable = parsed.formulae?.[0]?.versions?.stable ?? parsed.casks?.[0]?.version; + return stable ?? null; + } catch { + return null; + } +} + +/** + * The newest version `source` would install for `tool`. + * + * Cache-first, then one command, then written back. A failed lookup is NOT cached: a flaky + * network would otherwise pin "unavailable" for a day, which turns a transient into a policy. + */ +export async function latestVersion( + tool: string, + source: ToolSource, + deps: LatestDeps, +): Promise { + const query = queryFor(tool, source); + if (!query) { + return { + status: "unsupported", + reason: + source === "kit-shim" + ? "kit PATH shim — resolve what it delegates to before asking for a latest version" + : `no registry kit can query for a ${source} install`, + }; + } + + const key = latestCacheKey(tool, source); + const ttlMs = (deps.ttlHours ?? DEFAULT_TTL_HOURS) * 3_600_000; + const cache = await deps.readCache(); + const hit = cache[key]; + if (hit && deps.now() - hit.at < ttlMs) { + return { status: "known", version: hit.version, via: hit.via, cached: true }; + } + + if (deps.cacheOnly) { + return { + status: "unavailable", + reason: hit + ? `cached answer is older than the TTL (${hit.version}) — run \`kit tools list --latest\` to refresh` + : "not looked up yet — run `kit tools list --latest` (this gate does not call registries)", + }; + } + + if (deps.offline) { + return { + status: "unavailable", + reason: hit + ? `air-gap/offline: cached answer from this machine is older than the TTL (${hit.version})` + : "air-gap/offline: no registry lookup made, and nothing cached", + }; + } + + const res = await deps.run(query.cmd, query.args); + if (!res.ok) { + return { + status: "unavailable", + reason: `\`${query.cmd} ${query.args.join(" ")}\` did not answer (installer missing, offline, or timed out)`, + }; + } + + const version = + query.via === "brew" + ? (parseBrewInfoVersion(res.stdout) ?? firstVersion(res.stdout)) + : firstVersion(res.stdout); + if (!version) { + return { + status: "unavailable", + reason: `\`${query.cmd} ${query.args.join(" ")}\` answered, but no version could be read from it`, + }; + } + + cache[key] = { version, at: deps.now(), via: query.via }; + await deps.writeCache(cache); + return { status: "known", version, via: query.via, cached: false }; +} + +export type DriftVerdict = + | { drift: "current" } + | { drift: "behind"; installed: string; latest: string } + /** Installed is NEWER than what the installer offers — a warning, not an error. */ + | { drift: "ahead"; installed: string; latest: string } + | { drift: "unknown"; reason: string }; + +/** + * Compare an installed version to a latest outcome. + * + * Numeric-segment comparison, not string compare: `53.1.1` vs `59.1.4` is the case that + * mattered, and `9.0.0` vs `10.0.0` is the one a naive compare gets backwards. Anything + * unparseable is `unknown` with a reason — never silently "current". + */ +export function compareVersions(installed: string, latest: string): -1 | 0 | 1 | null { + const parse = (v: string): number[] | null => { + const core = v.trim().replace(/^v/, "").split(/[-+]/)[0]; + if (!/^\d+(\.\d+)*$/.test(core)) return null; + return core.split(".").map((n) => Number.parseInt(n, 10)); + }; + const a = parse(installed); + const b = parse(latest); + if (!a || !b) return null; + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i] ?? 0; + const y = b[i] ?? 0; + if (x !== y) return x < y ? -1 : 1; + } + return 0; +} + +export function judgeDrift(installed: string | null, latest: LatestOutcome): DriftVerdict { + if (installed === null) return { drift: "unknown", reason: "tool not installed" }; + if (latest.status !== "known") return { drift: "unknown", reason: latest.reason }; + const cmp = compareVersions(installed, latest.version); + if (cmp === null) { + return { + drift: "unknown", + reason: `cannot compare installed ${installed} with latest ${latest.version}`, + }; + } + if (cmp < 0) return { drift: "behind", installed, latest: latest.version }; + if (cmp > 0) return { drift: "ahead", installed, latest: latest.version }; + return { drift: "current" }; +} diff --git a/src/tool-provenance.test.ts b/src/tool-provenance.test.ts new file mode 100644 index 00000000..9c2417bc --- /dev/null +++ b/src/tool-provenance.test.ts @@ -0,0 +1,119 @@ +/** + * Provenance has to be measured, because the lock used to guess it. + * + * `fix.ts` and `commands/setup.ts` both wrote `source: "mise"` for every declared tool, so a + * lock entry said `mise` for `/opt/homebrew/bin/vercel` — a binary mise does not manage — and + * `kit check` reported `in sync`, because the only thing it compared was whether an entry with + * that name existed (#500). + * + * The paths below are the real ones from the machine where that was found, which is why the + * ordering cases exist at all: the kit shim and mise's shims both live under `$HOME`, and + * Homebrew is reached through `/opt/homebrew/bin` symlinks rather than the Cellar path. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; + +import { classifyToolPath, provenanceMismatch } from "./tool-provenance.js"; + +const HOME = "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/Users/dev"; +const env = { home: HOME }; + +describe("classifyToolPath", () => { + it("classifies the installers measured on a real machine", () => { + const cases: Array<[string, string]> = [ + ["/opt/homebrew/bin/vercel", "brew"], + ["/opt/homebrew/bin/gh", "brew"], + ["/usr/local/Cellar/jq/1.7.1/bin/jq", "brew"], + ["/home/linuxbrew/.linuxbrew/bin/gh", "brew"], + [`${HOME}/.local/share/mise/shims/semgrep`, "mise"], + [`${HOME}/.local/share/mise/installs/node/25.8.0/bin/node`, "mise"], + [`${HOME}/.kit/shims/bun`, "kit-shim"], + [`${HOME}/.npm-global/bin/kit`, "npm-global"], + [`${HOME}/.cargo/bin/rg`, "cargo"], + [`${HOME}/.asdf/shims/ruby`, "asdf"], + ["/usr/bin/jq", "system"], + ["/usr/bin/git", "system"], + ["/bin/sh", "system"], + ["/opt/weird/place/tool", "unknown"], + ]; + for (const [path, expected] of cases) { + assert.equal(classifyToolPath(path, env).source, expected, path); + } + }); + + it("marks shims as shims — a shim delegates, so its source is not the origin", () => { + const kit = classifyToolPath(`${HOME}/.kit/shims/bun`, env); + assert.equal(kit.shimmed, true); + assert.match(kit.detail ?? "", /delegates/); + + // mise's shims dir is a shim; an installs path is the real binary. + assert.equal(classifyToolPath(`${HOME}/.local/share/mise/shims/node`, env).shimmed, true); + assert.equal( + classifyToolPath(`${HOME}/.local/share/mise/installs/node/25.8.0/bin/node`, env).shimmed, + false, + ); + assert.equal(classifyToolPath("/opt/homebrew/bin/vercel", env).shimmed, false); + }); + + it("prefers the kit shim over the home-dir rules it also matches", () => { + // Ordering regression: both this and mise live under $HOME. + assert.equal(classifyToolPath(`${HOME}/.kit-shims/pnpm`, env).source, "kit-shim"); + }); + + it("uses an explicit npm prefix when one is known", () => { + const p = "/opt/custom-npm/bin/kit"; + assert.equal(classifyToolPath(p, env).source, "unknown"); + assert.equal( + classifyToolPath(p, { ...env, npmPrefix: "/opt/custom-npm" }).source, + "npm-global", + ); + }); + + it("hedges on ~/.local/bin instead of claiming pipx outright", () => { + const r = classifyToolPath(`${HOME}/.local/bin/whatever`, env); + assert.equal(r.source, "pipx"); + assert.match(r.detail ?? "", /not exclusive/); + }); + + it("handles win32 paths case-insensitively", () => { + const w = { home: "C:\\Users\\dev", platform: "win32" as const }; + assert.equal(classifyToolPath("C:\\Users\\Dev\\.kit\\shims\\bun.exe", w).source, "kit-shim"); + assert.equal(classifyToolPath("C:\\Windows\\System32\\where.exe", w).source, "system"); + }); +}); + +describe("provenanceMismatch", () => { + const brew = classifyToolPath("/opt/homebrew/bin/vercel", env); + + it("catches the exact defect: lock says mise, binary comes from brew", () => { + const r = provenanceMismatch("mise", brew); + assert.equal(r.mismatch, true); + assert.match(r.reason ?? "", /lock says mise/); + assert.match(r.reason ?? "", /comes from brew/); + }); + + it("agrees when the lock is right", () => { + assert.equal(provenanceMismatch("brew", brew).mismatch, false); + }); + + it("says nothing when there is nothing recorded to contradict", () => { + assert.equal(provenanceMismatch(undefined, brew).mismatch, false); + }); + + it("never contradicts a shim — the shim delegates, so the lock may name the real installer", () => { + const shim = classifyToolPath(`${HOME}/.kit/shims/bun`, env); + assert.equal(provenanceMismatch("mise", shim).mismatch, false); + assert.equal(provenanceMismatch("npm", shim).mismatch, false); + }); + + it("does not alarm on an unclassifiable path — unknown is not evidence of a mismatch", () => { + const weird = classifyToolPath("/opt/weird/place/tool", env); + assert.equal(provenanceMismatch("mise", weird).mismatch, false); + }); + + it("treats the lock's 'manual' catch-all as unknown, not as a source", () => { + assert.equal(provenanceMismatch("manual", classifyToolPath("/opt/x/y", env)).mismatch, false); + assert.equal(provenanceMismatch("manual", brew).mismatch, true); + }); +}); diff --git a/src/tool-provenance.ts b/src/tool-provenance.ts new file mode 100644 index 00000000..f9babfd7 --- /dev/null +++ b/src/tool-provenance.ts @@ -0,0 +1,173 @@ +/** + * Which installer actually owns the binary on PATH. + * + * `cli-lock.json` claimed provenance it never measured. Both writers — `fix.ts` and + * `commands/setup.ts` — did this, identically: + * + * tools[name] = { version, source: "mise" }; // version = the DECLARED string + * + * so a lock entry read `{ "vercel": { "version": "latest", "source": "mise" } }` while the + * binary was `/opt/homebrew/bin/vercel` and `mise ls` did not mention it. `kit check` then said + * `✓ cli-lock.json in sync`, because the only comparison it made was "does an entry exist for + * this name" (#500). A lock file whose purpose is provenance was recording a guess. + * + * This module measures it instead, from the resolved path. Pure and injectable so every branch + * is testable without the machine it was written on: the classifier takes the path plus the few + * environment facts it needs (home dir, npm global prefix), never reading them itself. + * + * It answers WHERE FROM, not whether that is good. A tool coming from `system` is not a finding; + * a lock that says `mise` for it is. + */ + +import { posix, win32 } from "node:path"; + +/** + * Installers kit can recognise. `kit-shim` is kit's own PATH shim (the install gate) and is a + * WRAPPER, not an origin — see `shimmed` below. + */ +export type ToolSource = + | "brew" + | "mise" + | "asdf" + | "npm-global" + | "pipx" + | "cargo" + | "go" + | "kit-shim" + | "system" + | "unknown"; + +export interface ToolProvenance { + /** The resolved executable path, as given. */ + path: string; + source: ToolSource; + /** + * True when the path is a kit PATH shim: the real installer is whatever the shim delegates to, + * which this classifier cannot see from the path alone. Reported rather than guessed. + */ + shimmed: boolean; + /** Short human note — why this classification, when it is not obvious from the path. */ + detail?: string; +} + +export interface ClassifyEnv { + /** The user's home directory. */ + home: string; + /** `npm prefix -g`, when known: its `bin` is where `npm i -g` puts binaries. */ + npmPrefix?: string; + /** Windows paths use backslashes; the caller says which separator applies. */ + platform?: "posix" | "win32"; +} + +/** Case-insensitive on win32, exact elsewhere — mirrors how the two filesystems behave. */ +function contains(haystack: string, needle: string, win: boolean): boolean { + return win ? haystack.toLowerCase().includes(needle.toLowerCase()) : haystack.includes(needle); +} + +/** + * Classify a resolved executable path to the installer that owns it. + * + * Ordering matters and is deliberate: the kit shim and the mise shims dir both sit under `$HOME` + * and would both match a naive "in home dir" rule, and Homebrew's Cellar is reached through + * `/opt/homebrew/bin` symlinks, so the bin dir has to count as brew too. + */ +export function classifyToolPath(path: string, env: ClassifyEnv): ToolProvenance { + const win = env.platform === "win32"; + const p = win ? path : path; + const sep = win ? win32.sep : posix.sep; + const home = env.home.endsWith(sep) ? env.home.slice(0, -sep.length) : env.home; + const under = (...parts: string[]): string => [home, ...parts].join(sep); + + // kit's own shim first: it is the PATH entry kit installs to gate installs, and it wraps + // whatever the real installer is. Classifying it as "unknown" would hide that a shim exists. + if (contains(p, under(".kit", "shims"), win) || contains(p, under(".kit-shims"), win)) { + return { + path, + source: "kit-shim", + shimmed: true, + detail: "kit PATH shim — the real installer is whatever the shim delegates to", + }; + } + + if ( + contains(p, under(".local", "share", "mise"), win) || + contains(p, under(".mise"), win) || + contains(p, `${sep}mise${sep}installs${sep}`, win) || + contains(p, `${sep}mise${sep}shims${sep}`, win) + ) { + return { path, source: "mise", shimmed: contains(p, `${sep}shims${sep}`, win) }; + } + + if (contains(p, under(".asdf"), win)) return { path, source: "asdf", shimmed: true }; + + // Homebrew: /opt/homebrew (Apple Silicon), /usr/local/Cellar (Intel), linuxbrew. + if ( + contains(p, `${sep}opt${sep}homebrew${sep}`, win) || + contains(p, `${sep}Cellar${sep}`, win) || + contains(p, `linuxbrew`, win) + ) { + return { path, source: "brew", shimmed: false }; + } + + if (env.npmPrefix && contains(p, env.npmPrefix, win)) { + return { path, source: "npm-global", shimmed: false }; + } + // Common npm -g layouts when the prefix was not resolvable. + if ( + contains(p, under(".npm-global"), win) || + contains(p, under(".npm", "bin"), win) || + contains(p, `${sep}lib${sep}node_modules${sep}`, win) + ) { + return { path, source: "npm-global", shimmed: false, detail: "npm global layout" }; + } + + if (contains(p, under(".local", "pipx"), win)) return { path, source: "pipx", shimmed: false }; + if (contains(p, under(".cargo", "bin"), win)) return { path, source: "cargo", shimmed: false }; + if (contains(p, under("go", "bin"), win)) return { path, source: "go", shimmed: false }; + + // ~/.local/bin is pipx's default target but also a general dumping ground, so it is reported + // as pipx only with the hedge in `detail` — a wrong-but-confident source is what this module + // exists to stop. + if (contains(p, under(".local", "bin"), win)) { + return { + path, + source: "pipx", + shimmed: false, + detail: "~/.local/bin — pipx's default target, but not exclusive to it", + }; + } + + if ( + p.startsWith(`${sep}usr${sep}bin${sep}`) || + p.startsWith(`${sep}bin${sep}`) || + p.startsWith(`${sep}usr${sep}sbin${sep}`) || + p.startsWith(`${sep}sbin${sep}`) || + (win && contains(p, `${sep}Windows${sep}`, win)) + ) { + return { path, source: "system", shimmed: false }; + } + + return { path, source: "unknown", shimmed: false }; +} + +/** + * Does a lock entry's recorded source contradict the measured one? + * + * `kit-shim` never contradicts: the shim delegates, so the lock naming the underlying installer + * is right. Everything else is compared exactly — that comparison is the whole point, since the + * old lock said `mise` for a brew binary and nothing looked. + */ +export function provenanceMismatch( + recorded: string | undefined, + measured: ToolProvenance, +): { mismatch: boolean; reason?: string } { + if (!recorded) return { mismatch: false }; + if (measured.source === "unknown" || measured.source === "kit-shim") return { mismatch: false }; + // The lock's vocabulary is narrower than the classifier's ("manual" is its catch-all). + const normalised = recorded === "manual" ? "unknown" : recorded; + if (normalised === measured.source) return { mismatch: false }; + return { + mismatch: true, + reason: `lock says ${recorded}, but ${measured.path} comes from ${measured.source}`, + }; +}