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
5 changes: 5 additions & 0 deletions contracts/public-surface.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"pkg": "stable",
"plugin": "stable",
"policy": "experimental",
"profile": "experimental",
"review": "stable",
"run": "stable",
"sbom": "stable",
Expand Down Expand Up @@ -180,6 +181,10 @@
"pkg",
"plugin",
"policy",
"profile",
"profile check",
"profile freeze",
"profile show",
"review",
"run",
"sbom",
Expand Down
11 changes: 11 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -674,6 +675,11 @@ const COMMAND_REGISTRY: Record<string, CommandDescriptor> = {
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",
Expand Down Expand Up @@ -707,6 +713,11 @@ const SUBCOMMAND_HELP: Record<string, string> = {
"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",
Expand Down
124 changes: 124 additions & 0 deletions src/commands/profile.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
210 changes: 210 additions & 0 deletions src/commands/profile.ts
Original file line number Diff line number Diff line change
@@ -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<string, DriftEntry[]>();
for (const e of drift.entries) {
const list = byKind.get(e.kind) ?? [];
list.push(e);
byKind.set(e.kind, list);
}
const labels: Record<string, string> = {
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<boolean> {
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<boolean> {
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<boolean> {
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<boolean> {
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 <show|freeze|check> [--json] [--gate]${c.reset}`);
return false;
}
Loading