diff --git a/src/profile/reconcile.test.ts b/src/profile/reconcile.test.ts new file mode 100644 index 00000000..6c36ea65 --- /dev/null +++ b/src/profile/reconcile.test.ts @@ -0,0 +1,183 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { computeProfileDrift, discoverActualState, type DiscoveredState } from "./reconcile.js"; +import type { KitProfile } from "./schema.js"; + +function profile(over: Partial = {}): KitProfile { + return { version: 1, generated: "1970-01-01T00:00:00.000Z", ...over }; +} + +function actual(over: Partial = {}): DiscoveredState { + return { skills: [], mcp: [], workflows: null, plugins: null, ...over }; +} + +describe("computeProfileDrift", () => { + it("is clean when declared matches discovered exactly", () => { + const d = computeProfileDrift( + profile({ skills: [{ name: "api-test", version: "1.4.0" }] }), + actual({ skills: [{ name: "api-test", version: "1.4.0" }] }), + ); + assert.equal(d.clean, true); + assert.equal(d.driftCount, 0); + assert.equal(d.entries[0]?.status, "in-sync"); + }); + + it("flags a declared-but-absent component as removed", () => { + const d = computeProfileDrift( + profile({ skills: [{ name: "legacy", version: "1.0.0" }] }), + actual({ skills: [] }), + ); + assert.equal(d.clean, false); + assert.equal(d.driftCount, 1); + assert.deepEqual(d.entries, [ + { kind: "skill", name: "legacy", status: "removed", declared: "1.0.0" }, + ]); + }); + + it("flags a present-but-undeclared component as added", () => { + const d = computeProfileDrift(profile({ mcp: [] }), actual({ mcp: [{ name: "some-server" }] })); + assert.equal(d.driftCount, 1); + assert.deepEqual(d.entries, [ + { kind: "mcp", name: "some-server", status: "added", found: undefined }, + ]); + }); + + it("flags version-drift only when both sides pin a differing version", () => { + const d = computeProfileDrift( + profile({ skills: [{ name: "s", version: "1.0.0" }] }), + actual({ skills: [{ name: "s", version: "2.1.0" }] }), + ); + assert.equal(d.entries[0]?.status, "version-drift"); + assert.equal(d.entries[0]?.declared, "1.0.0"); + assert.equal(d.entries[0]?.found, "2.1.0"); + }); + + it("does not flag drift when the declaration is unpinned", () => { + const d = computeProfileDrift( + profile({ skills: [{ name: "s" }] }), + actual({ skills: [{ name: "s", version: "9.9.9" }] }), + ); + assert.equal(d.clean, true); + assert.equal(d.entries[0]?.status, "in-sync"); + }); + + it("does not call it drift when the found version is unknown", () => { + const d = computeProfileDrift( + profile({ skills: [{ name: "s", version: "1.0.0" }] }), + actual({ skills: [{ name: "s" }] }), + ); + assert.equal(d.clean, true); + assert.equal(d.entries[0]?.status, "in-sync"); + }); + + it("reports vault store in-sync / drift / not-declared", () => { + assert.equal( + computeProfileDrift( + profile({ vault: { store: "1password" } }), + actual({ vaultStore: "1password" }), + ).vault?.status, + "in-sync", + ); + const drift = computeProfileDrift( + profile({ vault: { store: "1password" } }), + actual({ vaultStore: "vault" }), + ); + assert.equal(drift.vault?.status, "drift"); + assert.equal(drift.driftCount, 1); + assert.equal(computeProfileDrift(profile(), actual()).vault, null); + }); + + it("reports declared-but-undiscoverable kinds as unaudited, not clean-washed", () => { + const d = computeProfileDrift( + profile({ workflows: [{ name: "release" }], plugins: [{ name: "p" }] }), + actual({ workflows: null, plugins: null }), + ); + assert.deepEqual(d.unaudited, ["workflow", "plugin"]); + // unaudited kinds must NOT emit drift entries and must NOT make the profile dirty + assert.equal(d.entries.length, 0); + assert.equal(d.driftCount, 0); + assert.equal(d.clean, true); + }); + + it("does not mark a kind unaudited when nothing is declared for it", () => { + const d = computeProfileDrift(profile(), actual({ workflows: null, plugins: null })); + assert.deepEqual(d.unaudited, []); + }); + + it("sorts entries by kind, then name, then status — deterministically", () => { + const p = profile({ + mcp: [{ name: "z-srv" }, { name: "a-srv" }], + skills: [{ name: "beta" }], + }); + const a = actual({ + skills: [{ name: "alpha" }], // added (alpha), removed (beta) + mcp: [{ name: "a-srv" }, { name: "z-srv" }], + }); + const one = computeProfileDrift(p, a); + const two = computeProfileDrift(p, a); + assert.deepEqual(one, two); + // skills come before mcp; within skills alpha(added) before beta(removed) + assert.equal(one.entries[0]?.kind, "skill"); + assert.equal(one.entries[0]?.name, "alpha"); + assert.equal(one.entries[1]?.name, "beta"); + assert.equal(one.entries[2]?.kind, "mcp"); + }); +}); + +describe("discoverActualState", () => { + it("discovers skills + MCP servers + vault store; workflows/plugins remain unknown", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-reconcile-")); + try { + mkdirSync(join(dir, ".claude/skills/api-test"), { recursive: true }); + writeFileSync(join(dir, ".claude/skills/api-test/SKILL.md"), "# api-test\n"); + writeFileSync( + join(dir, ".mcp.json"), + JSON.stringify({ mcpServers: { postgres: { command: "npx x" } } }), + ); + writeFileSync(join(dir, ".kit.toml"), `[secrets]\nstore = "1password"\n`); + + const state = await discoverActualState(dir); + assert.deepEqual( + state.skills.map((s) => s.name), + ["api-test"], + ); + assert.deepEqual( + state.mcp.map((s) => s.name), + ["postgres"], + ); + assert.equal(state.vaultStore, "1password"); + assert.equal(state.workflows, null); + assert.equal(state.plugins, null); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("degrades to unknown vault store when there is no .kit.toml (never throws)", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-reconcile-")); + try { + const state = await discoverActualState(dir); + assert.equal(state.vaultStore, undefined); + assert.deepEqual(state.skills, []); + assert.deepEqual(state.mcp, []); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("feeds computeProfileDrift end-to-end (declared profile vs a real temp project)", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-reconcile-")); + try { + mkdirSync(join(dir, ".claude/skills/api-test"), { recursive: true }); + writeFileSync(join(dir, ".claude/skills/api-test/SKILL.md"), "# api-test\n"); + const state = await discoverActualState(dir); + const d = computeProfileDrift(profile({ skills: [{ name: "api-test" }] }), state); + assert.equal(d.clean, true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/profile/reconcile.ts b/src/profile/reconcile.ts new file mode 100644 index 00000000..c8ef8bc2 --- /dev/null +++ b/src/profile/reconcile.ts @@ -0,0 +1,194 @@ +/** + * kit project profile — declared-vs-discovered drift (Pillar 4 step 2). + * + * Design: `kit-research/docs/research/pillar4-traveling-profile-5.0.md` §4.3. + * + * The profile (`schema.ts`) DECLARES the intended toolchain; this module measures how far + * the actual project has drifted from that declaration. Split in two: + * + * - `computeProfileDrift(declared, actual)` — PURE comparison, fully unit-testable against + * fixtures. Same discipline as the insight loop's pure `usage-scan` core. + * - `discoverActualState(cwd)` — the thin, best-effort filesystem wiring that gathers the + * "actual" snapshot from `discoverAgentToolchain` + `.kit.toml`. + * + * Deterministic + zero-LLM: drift is set difference and exact version comparison, never a + * heuristic that can flimra. No auto-mutation here — this only REPORTS; acting on drift is the + * operator's call (the `kit profile` command, step 3). + * + * HONESTY (no false green): a kind whose actual state cannot be discovered yet (workflows, + * plugins — their discovery lands in step 4) is reported as UNAUDITED when the profile declares + * entries for it — never silently counted as "in sync". Unknown ≠ clean. + */ +import { resolve } from "node:path"; +import { loadConfig } from "../config.js"; +import { discoverAgentToolchain } from "../agent-sbom.js"; +import type { KitProfile, ProfileComponent } from "./schema.js"; + +export type ComponentKind = "skill" | "mcp" | "workflow" | "plugin"; + +export type DriftStatus = "in-sync" | "version-drift" | "removed" | "added"; + +export interface DriftEntry { + kind: ComponentKind; + name: string; + status: DriftStatus; + /** Declared version (if the profile pinned one). */ + declared?: string; + /** Discovered version (if known). */ + found?: string; +} + +export interface VaultDrift { + status: "in-sync" | "drift"; + declared?: string; + found?: string; +} + +export interface ProfileDrift { + /** Per-component drift, sorted deterministically (kind, then name, then status). */ + entries: DriftEntry[]; + /** Vault-store drift, or null when the profile declares no store to check. */ + vault: VaultDrift | null; + /** + * Component kinds the profile DECLARES but whose actual state can't be discovered yet + * (reported honestly, never folded into "clean"). Sorted, de-duplicated. + */ + unaudited: ComponentKind[]; + /** Count of real drifts (entries not in-sync + a vault drift). Unaudited kinds do NOT count. */ + driftCount: number; + /** True when there is zero measurable drift. Unaudited kinds do not make it dirty. */ + clean: boolean; +} + +export interface DiscoveredComponent { + name: string; + version?: string; +} + +export interface DiscoveredState { + skills: DiscoveredComponent[]; + mcp: DiscoveredComponent[]; + /** null = discovery for this kind is not available yet (UNKNOWN, not empty). */ + workflows: DiscoveredComponent[] | null; + plugins: DiscoveredComponent[] | null; + /** Global vault store from `.kit.toml` `secrets.store`, or undefined if none/unreadable. */ + vaultStore?: string; +} + +/** Fixed kind order for stable output. */ +const KIND_ORDER: Record = { skill: 0, mcp: 1, workflow: 2, plugin: 3 }; + +/** Compare one component kind's declared set against its discovered set. */ +function driftForKind( + kind: ComponentKind, + declared: ProfileComponent[] | undefined, + found: DiscoveredComponent[] | null, +): DriftEntry[] { + const entries: DriftEntry[] = []; + const declaredList = declared ?? []; + // Discovery unavailable for this kind — the caller records it as unaudited; emit nothing. + if (found === null) return entries; + + const foundByName = new Map(found.map((c) => [c.name, c])); + const declaredNames = new Set(declaredList.map((c) => c.name)); + + for (const d of declaredList) { + const f = foundByName.get(d.name); + if (!f) { + entries.push({ kind, name: d.name, status: "removed", declared: d.version }); + continue; + } + // Only a real version drift when BOTH sides pin a version and they differ — an unpinned + // declaration matches any found version (the profile didn't pin it), and an unknown found + // version can't be called a drift. + if (d.version && f.version && d.version !== f.version) { + entries.push({ + kind, + name: d.name, + status: "version-drift", + declared: d.version, + found: f.version, + }); + } else { + entries.push({ + kind, + name: d.name, + status: "in-sync", + declared: d.version, + found: f.version, + }); + } + } + + for (const f of found) { + if (!declaredNames.has(f.name)) { + entries.push({ kind, name: f.name, status: "added", found: f.version }); + } + } + + return entries; +} + +/** + * Pure declared-vs-discovered drift. Same inputs → same output (no clock, no randomness), so + * it is safe to diff in CI. + */ +export function computeProfileDrift(declared: KitProfile, actual: DiscoveredState): ProfileDrift { + const entries: DriftEntry[] = [ + ...driftForKind("skill", declared.skills, actual.skills), + ...driftForKind("mcp", declared.mcp, actual.mcp), + ...driftForKind("workflow", declared.workflows, actual.workflows), + ...driftForKind("plugin", declared.plugins, actual.plugins), + ]; + + entries.sort( + (a, b) => + KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || + a.name.localeCompare(b.name) || + a.status.localeCompare(b.status), + ); + + // Unaudited: a kind the profile declares but whose actual state we can't discover. + const unaudited: ComponentKind[] = []; + if ((declared.workflows?.length ?? 0) > 0 && actual.workflows === null) + unaudited.push("workflow"); + if ((declared.plugins?.length ?? 0) > 0 && actual.plugins === null) unaudited.push("plugin"); + + let vault: VaultDrift | null = null; + const declaredStore = declared.vault?.store; + if (declaredStore !== undefined) { + vault = + declaredStore === actual.vaultStore + ? { status: "in-sync", declared: declaredStore, found: actual.vaultStore } + : { status: "drift", declared: declaredStore, found: actual.vaultStore }; + } + + const driftCount = + entries.filter((e) => e.status !== "in-sync").length + (vault?.status === "drift" ? 1 : 0); + + return { entries, vault, unaudited, driftCount, clean: driftCount === 0 }; +} + +/** + * 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. + */ +export async function discoverActualState(cwd = process.cwd()): Promise { + const { skills, mcpServers } = discoverAgentToolchain(cwd); + let vaultStore: string | undefined; + try { + const cfg = await loadConfig(resolve(cwd, ".kit.toml")); + vaultStore = cfg.secrets?.store; + } catch { + /* no / unreadable .kit.toml — vault store unknown */ + } + return { + skills: skills.map((s) => ({ name: s.name, version: s.version })), + mcp: mcpServers.map((s) => ({ name: s.name, version: s.version })), + workflows: null, + plugins: null, + vaultStore, + }; +}