Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion src/agent-sbom.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { agentToolchainComponents, mcpServersFromConfig } from "./agent-sbom.js";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { agentToolchainComponents, mcpServersFromConfig, discoverPlugins } from "./agent-sbom.js";
import { toCycloneDX, toSpdx, type Component } from "./sbom.js";

describe("agentToolchainComponents", () => {
Expand Down Expand Up @@ -53,6 +56,44 @@ describe("mcpServersFromConfig", () => {
});
});

describe("discoverPlugins", () => {
it("reads kitPlugins from package.json and resolves installed versions", () => {
const dir = mkdtempSync(join(tmpdir(), "kit-plugins-"));
try {
writeFileSync(
join(dir, "package.json"),
JSON.stringify({ kitPlugins: ["@acme/kit-railway", "kit-plugin-x"] }),
);
// one plugin installed (version resolvable), one not
mkdirSync(join(dir, "node_modules/@acme/kit-railway"), { recursive: true });
writeFileSync(
join(dir, "node_modules/@acme/kit-railway/package.json"),
JSON.stringify({ name: "@acme/kit-railway", version: "2.3.0" }),
);
const plugins = discoverPlugins(dir);
const byName = Object.fromEntries(plugins.map((p) => [p.name, p]));
assert.equal(byName["@acme/kit-railway"].version, "2.3.0");
assert.equal(byName["@acme/kit-railway"].source, "package.json:kitPlugins");
assert.equal(byName["kit-plugin-x"].version, undefined); // declared but not installed
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it("returns [] when there is no package.json or no kitPlugins (never throws)", () => {
const dir = mkdtempSync(join(tmpdir(), "kit-plugins-"));
try {
assert.deepEqual(discoverPlugins(dir), []);
writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "p" }));
assert.deepEqual(discoverPlugins(dir), []);
writeFileSync(join(dir, "package.json"), "{ not json");
assert.deepEqual(discoverPlugins(dir), []);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

describe("SBOM emitters honor Component.type / purl (backward-compatible)", () => {
const npm: Component = { name: "lodash", version: "4.17.21" };
const skill: Component = {
Expand Down
36 changes: 36 additions & 0 deletions src/agent-sbom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,39 @@ export function discoverAgentToolchain(cwd: string): {
}
return { skills, mcpServers };
}

/**
* Best-effort discovery of the plugins a project loads: the `kitPlugins` array in
* `package.json` (npm package names; the same list `loadPluginAdapters` consumes). When the
* plugin is installed, its version is read from `node_modules/<name>/package.json`. Pure
* filesystem read; missing/malformed inputs yield `[]`, never throw — matching
* `discoverAgentToolchain`'s defensive posture. Kept separate so it can be composed without
* changing `discoverAgentToolchain`'s shape (and its `kit sbom --agent` / `kit insight` callers).
*/
export function discoverPlugins(cwd: string): AgentComponentInput[] {
let names: string[];
try {
const pkg = JSON.parse(readFileSync(resolve(cwd, "package.json"), "utf8")) as Record<
string,
unknown
>;
const raw = pkg.kitPlugins;
names = Array.isArray(raw) ? raw.filter((p): p is string => typeof p === "string") : [];
} catch {
return [];
}
const out: AgentComponentInput[] = [];
for (const name of names) {
let version: string | undefined;
try {
const dep = JSON.parse(
readFileSync(resolve(cwd, "node_modules", name, "package.json"), "utf8"),
) as Record<string, unknown>;
if (typeof dep.version === "string") version = dep.version;
} catch {
/* plugin not installed — declared name only */
}
out.push({ name, version, source: "package.json:kitPlugins" });
}
return out;
}
13 changes: 7 additions & 6 deletions src/commands/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
*/
import { c } from "../utils/colors.js";
import { hasFlag } from "../utils/flags.js";
import { discoverAgentToolchain } from "../agent-sbom.js";
import { discoverAgentToolchain, discoverPlugins } from "../agent-sbom.js";
import {
loadProfile,
saveProfile,
Expand Down Expand Up @@ -165,16 +165,17 @@ async function profileFreeze(jsonMode: boolean): Promise<boolean> {
const { skills, mcpServers } = discoverAgentToolchain(cwd);
const actual = await discoverActualState(cwd);

// Snapshot the discoverable dimensions; preserve operator-authored sections verbatim.
// Snapshot the discoverable dimensions (skills/mcp/plugins/vault); preserve the
// non-discoverable, operator-authored sections (workflows/gates/scope) verbatim.
const next: KitProfile = {
version: existing?.version ?? 1,
generated: existing?.generated ?? new Date(0).toISOString(),
skills: toComponents(skills),
mcp: toComponents(mcpServers),
plugins: toComponents(discoverPlugins(cwd)),
};
if (existing?.name) next.name = existing.name;
if (existing?.workflows) next.workflows = existing.workflows;
if (existing?.plugins) next.plugins = existing.plugins;
if (existing?.gates) next.gates = existing.gates;
if (existing?.scope) next.scope = existing.scope;
const vaultStore = actual.vaultStore ?? existing?.vault?.store;
Expand All @@ -188,13 +189,13 @@ async function profileFreeze(jsonMode: boolean): Promise<boolean> {
}
console.log(`${c.bold}kit profile freeze${c.reset} → ${c.bold}${PROFILE_FILE}${c.reset}`);
console.log(
` ${c.green}✓${c.reset} ${next.skills?.length ?? 0} skill(s), ${next.mcp?.length ?? 0} mcp server(s)${
` ${c.green}✓${c.reset} ${next.skills?.length ?? 0} skill(s), ${next.mcp?.length ?? 0} mcp server(s), ${next.plugins?.length ?? 0} plugin(s)${
next.vault?.store ? `, vault store=${next.vault.store}` : ""
}`,
);
if (existing?.workflows || existing?.plugins || existing?.scope || existing?.gates) {
if (existing?.workflows || existing?.scope || existing?.gates) {
console.log(
` ${c.dim}preserved operator-authored sections (workflows/plugins/scope/gates) unchanged${c.reset}`,
` ${c.dim}preserved operator-authored sections (workflows/scope/gates) unchanged${c.reset}`,
);
}
console.log(` ${c.dim}${profileFingerprint(next)}${c.reset}`);
Expand Down
28 changes: 25 additions & 3 deletions src/profile/reconcile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ describe("computeProfileDrift", () => {
});

describe("discoverActualState", () => {
it("discovers skills + MCP servers + vault store; workflows/plugins remain unknown", async () => {
it("discovers skills + MCP servers + plugins + vault store; workflows remain unknown", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-reconcile-"));
try {
mkdirSync(join(dir, ".claude/skills/api-test"), { recursive: true });
Expand All @@ -137,6 +137,7 @@ describe("discoverActualState", () => {
join(dir, ".mcp.json"),
JSON.stringify({ mcpServers: { postgres: { command: "npx x" } } }),
);
writeFileSync(join(dir, "package.json"), JSON.stringify({ kitPlugins: ["@acme/kit-x"] }));
writeFileSync(join(dir, ".kit.toml"), `[secrets]\nstore = "1password"\n`);

const state = await discoverActualState(dir);
Expand All @@ -148,9 +149,12 @@ describe("discoverActualState", () => {
state.mcp.map((s) => s.name),
["postgres"],
);
assert.deepEqual(
state.plugins?.map((p) => p.name),
["@acme/kit-x"],
);
assert.equal(state.vaultStore, "1password");
assert.equal(state.workflows, null);
assert.equal(state.plugins, null);
assert.equal(state.workflows, null); // no on-disk workflow convention yet
} finally {
rmSync(dir, { recursive: true, force: true });
}
Expand Down Expand Up @@ -180,4 +184,22 @@ describe("discoverActualState", () => {
rmSync(dir, { recursive: true, force: true });
}
});

it("audits plugin drift now that plugins are discoverable (was previously unaudited)", async () => {
const dir = mkdtempSync(join(tmpdir(), "kit-reconcile-"));
try {
writeFileSync(join(dir, "package.json"), JSON.stringify({ kitPlugins: ["@acme/kit-x"] }));
const state = await discoverActualState(dir);
// declared a DIFFERENT plugin → the declared one is removed, the present one is added
const d = computeProfileDrift(profile({ plugins: [{ name: "@acme/kit-old" }] }), state);
assert.deepEqual(d.unaudited, []); // no longer unaudited
const statuses = Object.fromEntries(
d.entries.filter((e) => e.kind === "plugin").map((e) => [e.name, e.status]),
);
assert.equal(statuses["@acme/kit-old"], "removed");
assert.equal(statuses["@acme/kit-x"], "added");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
12 changes: 7 additions & 5 deletions src/profile/reconcile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
*/
import { resolve } from "node:path";
import { loadConfig } from "../config.js";
import { discoverAgentToolchain } from "../agent-sbom.js";
import { discoverAgentToolchain, discoverPlugins } from "../agent-sbom.js";
import type { KitProfile, ProfileComponent } from "./schema.js";

export type ComponentKind = "skill" | "mcp" | "workflow" | "plugin";
Expand Down Expand Up @@ -171,12 +171,14 @@ export function computeProfileDrift(declared: KitProfile, actual: DiscoveredStat

/**
* Best-effort snapshot of the ACTUAL project state, mirroring `discoverAgentToolchain`'s
* defensive posture: missing/malformed inputs degrade to "unknown", never throw. Workflows and
* plugins are `null` (their discovery lands in step 4) so drift honestly reports them unaudited
* rather than pretending they are absent.
* defensive posture: missing/malformed inputs degrade to "unknown", never throw. Plugins are
* discovered from `package.json` `kitPlugins` (so plugin drift is auditable); workflows remain
* `null` — there is no on-disk workflow convention to reconcile against yet, so drift honestly
* reports declared workflows as unaudited rather than pretending they are absent.
*/
export async function discoverActualState(cwd = process.cwd()): Promise<DiscoveredState> {
const { skills, mcpServers } = discoverAgentToolchain(cwd);
const plugins = discoverPlugins(cwd);
let vaultStore: string | undefined;
try {
const cfg = await loadConfig(resolve(cwd, ".kit.toml"));
Expand All @@ -188,7 +190,7 @@ export async function discoverActualState(cwd = process.cwd()): Promise<Discover
skills: skills.map((s) => ({ name: s.name, version: s.version })),
mcp: mcpServers.map((s) => ({ name: s.name, version: s.version })),
workflows: null,
plugins: null,
plugins: plugins.map((p) => ({ name: p.name, version: p.version })),
vaultStore,
};
}
Loading