From fe5c608b494e11976f6c9ac18a43e50bedc3d0e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 9 Jul 2026 22:02:14 +0000 Subject: [PATCH] feat(profile): kit profile show|freeze|check command (Pillar 4 step 3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wires the profile schema (#295) + drift core (#296) into a CLI verb via COMMAND_REGISTRY (design: pillar4-traveling-profile-5.0.md). Adds src/commands/profile.ts: - show — render the declared profile with per-line reconciliation marks (✓/DRIFT/REMOVED/ ADDED), fingerprint, and an unaudited note for kinds not yet discoverable. - freeze — snapshot the DISCOVERED toolchain (skills/mcp via discoverAgentToolchain, vault store from .kit.toml) into .kit-profile.toml, PRESERVING operator-authored name/workflows/plugins/gates/scope verbatim. Deliberate action, like baseline freeze. - check — report declared-vs-discovered drift; --gate turns any drift into a non-zero exit for CI (default is warn/exit-0). Honest skip (exit 0) when no profile is declared. --json on every subcommand. Zero-LLM, deterministic; never auto-mutates the toolchain. Registry entry (experimental) + SUBCOMMAND_HELP; contracts/public-surface.json regenerated for the new verb. 7 command tests. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DbF4MFePXWNCd4dxBQvqH2 --- contracts/public-surface.json | 5 + src/cli.ts | 11 ++ src/commands/profile.test.ts | 124 ++++++++++++++++++++ src/commands/profile.ts | 210 ++++++++++++++++++++++++++++++++++ 4 files changed, 350 insertions(+) create mode 100644 src/commands/profile.test.ts create mode 100644 src/commands/profile.ts diff --git a/contracts/public-surface.json b/contracts/public-surface.json index 0982aa61..d026c9e8 100644 --- a/contracts/public-surface.json +++ b/contracts/public-surface.json @@ -52,6 +52,7 @@ "pkg": "stable", "plugin": "stable", "policy": "experimental", + "profile": "experimental", "review": "stable", "run": "stable", "sbom": "stable", @@ -180,6 +181,10 @@ "pkg", "plugin", "policy", + "profile", + "profile check", + "profile freeze", + "profile show", "review", "run", "sbom", diff --git a/src/cli.ts b/src/cli.ts index ae7e0345..d86737b6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -28,6 +28,7 @@ import { cmdUpgrade } from "./commands/upgrade.js"; import { cmdDoctor, cmdAdd, cmdSetup, cmdInit } from "./commands/setup.js"; import { cmdReview } from "./commands/review.js"; import { cmdInsight } from "./commands/insight.js"; +import { cmdProfile } from "./commands/profile.js"; import { cmdStatus, cmdHealth, @@ -674,6 +675,11 @@ const COMMAND_REGISTRY: Record = { stability: "experimental", help: "Deterministic lifecycle insight (unused: loaded-but-never-called MCP servers, from the transcript index; --json)", }, + profile: { + handler: cmdProfile, + stability: "experimental", + help: "Versioned, traveling project profile — declare {skills, mcp, workflows, plugins, vault, gates, scope} and audit declared-vs-discovered drift (show|freeze|check; --json, --gate)", + }, pkg: { handler: cmdPkg, stability: "stable", @@ -707,6 +713,11 @@ const SUBCOMMAND_HELP: Record = { "check verify-attestation": "Verify a signed .kit-check-attestation.json receipt", "airgap verify": "Prove zero-egress: assert every scanner that would run air-gapped resolves to a local artifact (no cloud-only, no registry semgrep config)", + "profile show": "Render the declared project profile with per-line reconciliation marks", + "profile freeze": + "Snapshot the discovered toolchain into .kit-profile.toml (preserves operator-authored workflows/plugins/scope/gates)", + "profile check": + "Report declared-vs-discovered drift (--gate fails CI on any drift; honest skip when no profile declared)", "memory index": "Index ~/.claude transcripts into the SQLite memory store", "memory search": "Full-text search memory (current project; --global for all)", "memory stats": "Show what the local memory store contains", diff --git a/src/commands/profile.test.ts b/src/commands/profile.test.ts new file mode 100644 index 00000000..6172f9ba --- /dev/null +++ b/src/commands/profile.test.ts @@ -0,0 +1,124 @@ +import { describe, it, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, mkdirSync, rmSync, existsSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { cmdProfile } from "./profile.js"; +import { PROFILE_FILE } from "../profile/schema.js"; + +let dir: string; +let cwd: string; +let argv: string[]; +let logs: string[]; +let origLog: typeof console.log; +let origErr: typeof console.error; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "kit-profile-cmd-")); + cwd = process.cwd(); + process.chdir(dir); + argv = process.argv; + logs = []; + origLog = console.log; + origErr = console.error; + console.log = (...a: unknown[]) => void logs.push(a.join(" ")); + console.error = (...a: unknown[]) => void logs.push(a.join(" ")); +}); + +afterEach(() => { + process.chdir(cwd); + process.argv = argv; + console.log = origLog; + console.error = origErr; + rmSync(dir, { recursive: true, force: true }); +}); + +function setArgs(...sub: string[]): void { + process.argv = ["node", "kit", "profile", ...sub]; +} + +describe("cmdProfile", () => { + it("show skips honestly (exit 0, JSON) when no profile is declared", async () => { + setArgs("show", "--json"); + const ok = await cmdProfile(); + assert.equal(ok, true); + const out = JSON.parse(logs.join("\n")); + assert.equal(out.skipped, true); + assert.match(out.reason, /no profile/); + }); + + it("freeze snapshots the discovered toolchain into .kit-profile.toml", async () => { + 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`); + + setArgs("freeze", "--json"); + const ok = await cmdProfile(); + assert.equal(ok, true); + assert.ok(existsSync(join(dir, PROFILE_FILE))); + const written = readFileSync(join(dir, PROFILE_FILE), "utf-8"); + assert.match(written, /api-test/); + assert.match(written, /postgres/); + assert.match(written, /1password/); + }); + + it("freeze preserves operator-authored sections (scope/workflows) verbatim", async () => { + writeFileSync( + join(dir, PROFILE_FILE), + `version = 1\nname = "acme"\n[[workflows]]\nname = "release"\n[scope]\negress = ["api.acme.com"]\n`, + ); + setArgs("freeze", "--json"); + const ok = await cmdProfile(); + assert.equal(ok, true); + const out = JSON.parse(logs.join("\n")); + assert.equal(out.profile.name, "acme"); + assert.equal(out.profile.workflows[0].name, "release"); + assert.deepEqual(out.profile.scope.egress, ["api.acme.com"]); + }); + + it("check is clean after freeze (round-trip)", async () => { + mkdirSync(join(dir, ".claude/skills/s1"), { recursive: true }); + writeFileSync(join(dir, ".claude/skills/s1/SKILL.md"), "# s1\n"); + setArgs("freeze"); + await cmdProfile(); + + setArgs("check", "--json"); + logs = []; + const ok = await cmdProfile(); + assert.equal(ok, true); + const out = JSON.parse(logs.join("\n")); + assert.equal(out.clean, true); + assert.equal(out.driftCount, 0); + }); + + it("check --gate exits non-zero on drift", async () => { + // Declare a skill that isn't present → removed drift. + writeFileSync(join(dir, PROFILE_FILE), `version = 1\n[[skills]]\nname = "ghost"\n`); + setArgs("check", "--json", "--gate"); + const ok = await cmdProfile(); + assert.equal(ok, false); // gating: drift → non-zero + const out = JSON.parse(logs.join("\n")); + assert.equal(out.clean, false); + assert.equal(out.gate, true); + }); + + it("check without --gate reports drift but still exits 0 (warn)", async () => { + writeFileSync(join(dir, PROFILE_FILE), `version = 1\n[[skills]]\nname = "ghost"\n`); + setArgs("check", "--json"); + const ok = await cmdProfile(); + assert.equal(ok, true); // warn: drift but exit 0 + const out = JSON.parse(logs.join("\n")); + assert.equal(out.clean, false); + }); + + it("rejects an unknown subcommand", async () => { + setArgs("bogus"); + const ok = await cmdProfile(); + assert.equal(ok, false); + assert.match(logs.join("\n"), /usage: kit profile/); + }); +}); diff --git a/src/commands/profile.ts b/src/commands/profile.ts new file mode 100644 index 00000000..cd668531 --- /dev/null +++ b/src/commands/profile.ts @@ -0,0 +1,210 @@ +/** + * `kit profile` — the versioned, traveling project profile surface (Pillar 4 step 3). + * + * Design: `kit-research/docs/research/pillar4-traveling-profile-5.0.md`. + * + * Three subcommands over the schema (`profile/schema.ts`) + drift core + * (`profile/reconcile.ts`): + * - `show` — render the declared profile with per-line reconciliation marks. + * - `freeze` — snapshot the DISCOVERED toolchain into `.kit-profile.toml`, preserving any + * operator-authored sections (name/workflows/plugins/gates/scope). A deliberate + * operator action, like `kit baseline freeze`. + * - `check` — report declared-vs-discovered drift; `--gate` turns any drift into a non-zero + * exit for CI. Honest `skip` when no profile is declared. + * + * Zero-LLM, deterministic. NEVER auto-mutates the toolchain — freeze writes only the profile + * declaration, and nothing here removes a skill/server/plugin. `--json` on every subcommand. + */ +import { c } from "../utils/colors.js"; +import { hasFlag } from "../utils/flags.js"; +import { discoverAgentToolchain } from "../agent-sbom.js"; +import { + loadProfile, + saveProfile, + profileFingerprint, + PROFILE_FILE, + type KitProfile, + type ProfileComponent, +} from "../profile/schema.js"; +import { + computeProfileDrift, + discoverActualState, + type ProfileDrift, + type DriftEntry, +} from "../profile/reconcile.js"; + +function noProfileNotice(jsonMode: boolean): boolean { + if (jsonMode) { + console.log(JSON.stringify({ skipped: true, reason: "no profile declared" }, null, 2)); + return true; + } + console.log(`${c.bold}kit profile${c.reset}`); + console.log( + ` ${c.yellow}!${c.reset} ${c.dim}no ${c.reset}${c.bold}${PROFILE_FILE}${c.reset}${c.dim} declared — run ${c.reset}${c.bold}kit profile freeze${c.reset}${c.dim} to snapshot the current setup. Skipped.${c.reset}`, + ); + return true; +} + +function statusMark(status: DriftEntry["status"]): string { + switch (status) { + case "in-sync": + return `${c.green}✓ in sync ${c.reset}`; + case "version-drift": + return `${c.yellow}⚠ DRIFT ${c.reset}`; + case "removed": + return `${c.yellow}⚠ REMOVED ${c.reset}`; + case "added": + return `${c.yellow}⚠ ADDED ${c.reset}`; + } +} + +function detailFor(e: DriftEntry): string { + switch (e.status) { + case "version-drift": + return `${c.dim}declared ${e.declared}, found ${e.found}${c.reset}`; + case "removed": + return `${c.dim}declared, not present${c.reset}`; + case "added": + return `${c.dim}present, not declared${c.reset}`; + case "in-sync": + return e.declared ? `${c.dim}${e.declared}${c.reset}` : ""; + } +} + +/** Render a drift report (shared by show + check). */ +function renderDrift(drift: ProfileDrift): void { + const byKind = new Map(); + for (const e of drift.entries) { + const list = byKind.get(e.kind) ?? []; + list.push(e); + byKind.set(e.kind, list); + } + const labels: Record = { + skill: "skills", + mcp: "mcp servers", + workflow: "workflows", + plugin: "plugins", + }; + for (const kind of ["skill", "mcp", "workflow", "plugin"]) { + const list = byKind.get(kind); + if (!list || list.length === 0) continue; + console.log(` ${c.bold}${labels[kind]}${c.reset}`); + for (const e of list) { + console.log(` ${statusMark(e.status)} ${e.name} ${detailFor(e)}`); + } + } + if (drift.vault) { + const mark = + drift.vault.status === "in-sync" ? statusMark("in-sync") : statusMark("version-drift"); + const detail = + drift.vault.status === "in-sync" + ? `${c.dim}store=${drift.vault.declared}${c.reset}` + : `${c.dim}declared ${drift.vault.declared}, found ${drift.vault.found ?? "none"}${c.reset}`; + console.log(` ${c.bold}vault${c.reset}`); + console.log(` ${mark} store ${detail}`); + } + for (const kind of drift.unaudited) { + console.log( + ` ${c.dim}? ${labels[kind]}: declared but not auditable yet (discovery lands later) — not judged.${c.reset}`, + ); + } +} + +async function profileShow(jsonMode: boolean): Promise { + const profile = await loadProfile(); + if (!profile) return noProfileNotice(jsonMode); + const drift = computeProfileDrift(profile, await discoverActualState()); + if (jsonMode) { + console.log(JSON.stringify({ skipped: false, profile, drift }, null, 2)); + return true; + } + console.log( + `${c.bold}kit profile${c.reset}${profile.name ? ` — ${profile.name}` : ""} ${c.dim}${profileFingerprint(profile)}${c.reset}`, + ); + renderDrift(drift); + console.log( + drift.clean + ? ` ${c.green}→ in sync with declaration${c.reset}` + : ` ${c.dim}→ ${drift.driftCount} drift(s) vs declared profile (kit changes nothing automatically)${c.reset}`, + ); + return true; +} + +async function profileCheck(jsonMode: boolean, gate: boolean): Promise { + const profile = await loadProfile(); + if (!profile) return noProfileNotice(jsonMode); + const drift = computeProfileDrift(profile, await discoverActualState()); + if (jsonMode) { + console.log(JSON.stringify({ skipped: false, gate, ...drift }, null, 2)); + return gate ? drift.clean : true; + } + console.log(`${c.bold}kit profile check${c.reset}`); + renderDrift(drift); + if (drift.clean) { + console.log(` ${c.green}✓ no drift vs declared profile${c.reset}`); + return true; + } + console.log( + ` ${gate ? c.red : c.yellow}→ ${drift.driftCount} drift(s)${c.reset}${c.dim}${gate ? " (gating)" : " (warn — pass --gate to fail CI on drift)"}${c.reset}`, + ); + return !gate; +} + +/** Build a ProfileComponent list from discovered pieces (name + provenance; unpinned). */ +function toComponents(items: { name: string; source?: string }[]): ProfileComponent[] { + return items + .map((i) => (i.source ? { name: i.name, source: i.source } : { name: i.name })) + .sort((a, b) => a.name.localeCompare(b.name)); +} + +async function profileFreeze(jsonMode: boolean): Promise { + const cwd = process.cwd(); + const existing = await loadProfile(); + const { skills, mcpServers } = discoverAgentToolchain(cwd); + const actual = await discoverActualState(cwd); + + // Snapshot the discoverable dimensions; preserve operator-authored sections verbatim. + const next: KitProfile = { + version: existing?.version ?? 1, + generated: existing?.generated ?? new Date(0).toISOString(), + skills: toComponents(skills), + mcp: toComponents(mcpServers), + }; + 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; + if (vaultStore !== undefined) next.vault = { ...existing?.vault, store: vaultStore }; + else if (existing?.vault) next.vault = existing.vault; + await saveProfile(next, cwd); + + if (jsonMode) { + console.log(JSON.stringify({ frozen: true, profile: next }, null, 2)); + return true; + } + 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)${ + next.vault?.store ? `, vault store=${next.vault.store}` : "" + }`, + ); + if (existing?.workflows || existing?.plugins || existing?.scope || existing?.gates) { + console.log( + ` ${c.dim}preserved operator-authored sections (workflows/plugins/scope/gates) unchanged${c.reset}`, + ); + } + console.log(` ${c.dim}${profileFingerprint(next)}${c.reset}`); + return true; +} + +export async function cmdProfile(): Promise { + const sub = process.argv[3] ?? "show"; + const jsonMode = hasFlag(process.argv, "--json"); + if (sub === "show") return await profileShow(jsonMode); + if (sub === "freeze") return await profileFreeze(jsonMode); + if (sub === "check") return await profileCheck(jsonMode, hasFlag(process.argv, "--gate")); + console.error(`${c.red}usage: kit profile [--json] [--gate]${c.reset}`); + return false; +}