diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 9ff73ff..95800e9 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agent-kit", "displayName": "Mission Kit", - "version": "6.26.2", + "version": "6.27.0", "description": "Plan, build, ship, and keep shipping. Agent Kit for Claude Code: plans, handoff, durable memory and staging-to-prod gates for long-term projects, followed from Mission Control in your browser.", "author": { "name": "agent-kit-startup" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 018d030..9e746f5 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-kit", - "version": "6.26.2", + "version": "6.27.0", "description": "Plan, build, ship, and keep shipping. Agent Kit skills for long-term projects with your own coding agents: plans, handoff, durable memory and staging-to-prod gates.", "author": { "name": "agent-kit-startup" diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 6fa450a..30b18f6 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -7,7 +7,7 @@ "description": "Plan, build, ship, and keep shipping. Agent Kit slash commands, rules and skills for long-term projects with your own coding agents: plans, handoff, durable memory and staging-to-prod gates. Follow the work in Mission Control.", "keywords": ["agents", "hitl", "handoff", "git-staging", "context", "multi-ide", "anti-slop"], "license": "Apache-2.0", - "version": "6.26.2", + "version": "6.27.0", "homepage": "https://github.com/agent-kit-startup/agent-kit", "websiteURL": "https://agent.missionkit.io/", "privacyPolicyURL": "https://github.com/agent-kit-startup/agent-kit/blob/main/PRIVACY.md", diff --git a/.cursor/agent-kit.json b/.cursor/agent-kit.json index cd69595..91144ea 100644 --- a/.cursor/agent-kit.json +++ b/.cursor/agent-kit.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "version": "6.26.2", + "version": "6.27.0", "protected": [ ".claude/commands/agent-kit.md", ".cursor/HANDOFF.md", diff --git a/CHANGELOG.md b/CHANGELOG.md index 5acd3ea..8fc61a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and ## [Unreleased] +## [6.27.0] - 2026-11-30 + +### Added + +- Contributors: `pnpm build` in `packages/cli` writes `dist/build-stamp.json` with the source commit it was built from. When the repo's hooks run that `packages/cli/dist`, session start adds one line if `packages/cli/src` has commits the build does not include (or the dist has no stamp), with the fix (`pnpm build` in packages/cli), and `agent-kit doctor` reports the same. Projects that install the CLI from npm see no change. + ## [6.26.2] - 2026-11-30 ### Fixed diff --git a/claude-directory/.claude-plugin/plugin.json b/claude-directory/.claude-plugin/plugin.json index d038f00..4cccfc2 100644 --- a/claude-directory/.claude-plugin/plugin.json +++ b/claude-directory/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agent-kit", "displayName": "Mission Kit", - "version": "6.26.2", + "version": "6.27.0", "description": "Plan, build, review, ship, keep: a working routine for long-term projects with Claude Code. Plans with to-dos you approve, review agents, staging-to-production gates that wait for your yes, and a handoff and memory that survive new chats.", "author": { "name": "agent-kit-startup" diff --git a/claude-directory/README.md b/claude-directory/README.md index 56abb69..43a20d7 100644 --- a/claude-directory/README.md +++ b/claude-directory/README.md @@ -46,7 +46,7 @@ State, memory and a live view that survive new chats and new agents. ## Install -This folder is the plugin as listed in the Claude plugin directory (version 6.26.2): the commands, agents and skills above, and no hooks or scripts. The commands work on a repository prepared by the agent-kit CLI (`agent-kit install`); see [install.md](https://github.com/agent-kit-startup/agent-kit/blob/main/install.md). Mission Control comes with the CLI. +This folder is the plugin as listed in the Claude plugin directory (version 6.27.0): the commands, agents and skills above, and no hooks or scripts. The commands work on a repository prepared by the agent-kit CLI (`agent-kit install`); see [install.md](https://github.com/agent-kit-startup/agent-kit/blob/main/install.md). Mission Control comes with the CLI. The full kit (every command, the session-start context and the shell guard hooks) installs from the repository marketplace: diff --git a/gemini-extension.json b/gemini-extension.json index 0a3a5dd..ea1a429 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,5 +1,5 @@ { "name": "agent-kit", - "version": "6.26.2", + "version": "6.27.0", "description": "Mission Kit core skills: HITL gates, plan backlog and onboarding, QA, external plan review. The full kit (slash commands, plans, HANDOFF, staging-then-prod git flow) installs with npx @dadado/agent-kit-cli@latest install." } diff --git a/package.json b/package.json index bdffd68..3180126 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "agent-kit", - "version": "6.26.2", + "version": "6.27.0", "description": "HITL framework for AI-assisted IDEs: plan, handoff, staging-to-prod, memory loop; Cursor-first with partial generators for VS Code and Windsurf.", "private": true, "license": "Apache-2.0", diff --git a/packages/cli/package.json b/packages/cli/package.json index 2d60451..e6c3675 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@dadado/agent-kit-cli", - "version": "6.26.2", + "version": "6.27.0", "description": "Agent Kit CLI: HITL framework install and tooling for AI-assisted IDEs (rules, skills, plan/handoff, context).", "keywords": [ "pi-package" @@ -37,7 +37,7 @@ "sync-dashboard": "node ../../scripts/sync-cli-dashboard.mjs", "prepack": "node ../../scripts/sync-cli-dashboard.mjs", "prepublishOnly": "node ../../scripts/verify-cli-dashboard-pack.mjs", - "build": "node ../../scripts/sync-cli-dashboard.mjs && tsup src/index.ts --format esm --dts --clean", + "build": "node ../../scripts/sync-cli-dashboard.mjs && tsup src/index.ts --format esm --dts --clean && (tsx src/lifecycle/write-cli-build-stamp.ts || echo build-stamp: skipped)", "dev": "tsx src/index.ts", "start": "tsx src/index.ts", "lint": "biome check src pi", diff --git a/packages/cli/src/hooks/session-start-factory-dist.test.ts b/packages/cli/src/hooks/session-start-factory-dist.test.ts new file mode 100644 index 0000000..8adebfe --- /dev/null +++ b/packages/cli/src/hooks/session-start-factory-dist.test.ts @@ -0,0 +1,142 @@ +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + CLI_BUILD_STAMP_FILE, + type GitRunner, + writeCliBuildStamp, +} from "../lifecycle/cli-dist-stamp.js"; +import { buildSessionStartAdditionalContext, factoryCliDistSection } from "./session-start.js"; + +const SHA = "b".repeat(40); +const noRoster = async (): Promise => { + throw new Error("no roster in tests"); +}; +const gitAnswering = + (revList: string | null): GitRunner => + async () => + revList; + +let root: string; +let cliDir: string; +let script: string; +beforeEach(async () => { + root = await mkdtemp(path.join(tmpdir(), "ak-ss-dist-")); + cliDir = path.join(root, "packages", "cli"); + await mkdir(path.join(cliDir, "dist"), { recursive: true }); + await mkdir(path.join(cliDir, "src"), { recursive: true }); + script = path.join(cliDir, "dist", "index.js"); + await writeFile(script, "// built\n"); + await writeFile( + path.join(cliDir, "package.json"), + JSON.stringify({ name: "@dadado/agent-kit-cli" }), + ); +}); +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +async function stamp(sourceCommit: string | null): Promise { + await writeFile( + path.join(cliDir, "dist", CLI_BUILD_STAMP_FILE), + JSON.stringify({ schemaVersion: 1, sourceCommit, sourceDirty: false, builtAt: "x" }), + ); +} + +describe("factoryCliDistSection", () => { + it("fresh dist: no line", async () => { + await stamp(SHA); + expect(await factoryCliDistSection(script, { git: gitAnswering("0\n") })).toBeNull(); + }); + + it("stale dist: one line with the short sha, the gap and the fix", async () => { + await stamp(SHA); + expect(await factoryCliDistSection(script, { git: gitAnswering("2\n") })).toBe( + "Factory hooks: packages/cli/dist was built from bbbbbbbb and packages/cli/src is 2 commits ahead; run `pnpm build` in packages/cli.", + ); + }); + + it("missing stamp: own wording, same fix", async () => { + const line = await factoryCliDistSection(script, { git: gitAnswering(null) }); + expect(line).toMatch(/^Factory hooks: packages\/cli\/dist has no build stamp/); + expect(line).toMatch(/run `pnpm build` in packages\/cli\.$/); + }); + + it("no git: no line (fail-open)", async () => { + await stamp(SHA); + expect(await factoryCliDistSection(script, { git: gitAnswering(null) })).toBeNull(); + }); + + it("not the project dist (global CLI, consumer, tsx): no line and no git call", async () => { + let called = false; + const git: GitRunner = async () => { + called = true; + return "5"; + }; + expect(await factoryCliDistSection("/usr/local/bin/agent-kit", { git })).toBeNull(); + expect(await factoryCliDistSection(undefined, { git })).toBeNull(); + expect(called).toBe(false); + }); + + it("consumer layout (dist without packages/cli/src): no line", async () => { + await rm(path.join(cliDir, "src"), { recursive: true }); + expect(await factoryCliDistSection(script, { git: gitAnswering("5") })).toBeNull(); + }); +}); + +describe("buildSessionStartAdditionalContext factory dist line", () => { + it("adds the line when the running script is a stale project dist", async () => { + await stamp(SHA); + const { additional_context } = await buildSessionStartAdditionalContext( + root, + {}, + { cliScript: script, git: gitAnswering("3"), liveRoster: noRoster }, + ); + expect(additional_context).toContain("packages/cli/src is 3 commits ahead"); + }); + + it("says nothing when cliScript is null", async () => { + const { additional_context } = await buildSessionStartAdditionalContext( + root, + {}, + { cliScript: null, liveRoster: noRoster }, + ); + expect(additional_context).not.toContain("Factory hooks:"); + }); +}); + +describe("real git: stale after a src commit, gone after rebuild", () => { + function git(...args: string[]): string { + return execFileSync( + "git", + [ + "-c", + "user.name=t", + "-c", + "user.email=t@example.invalid", + "-c", + "commit.gpgsign=false", + ...args, + ], + { cwd: root, encoding: "utf8" }, + ); + } + + it("fresh -> stale -> fresh", async () => { + git("init", "-q"); + await writeFile(path.join(cliDir, "src", "a.ts"), "export {};\n"); + git("add", "packages/cli/src"); + git("commit", "-q", "-m", "one"); + await writeCliBuildStamp(cliDir); + expect(await factoryCliDistSection(script)).toBeNull(); + + await writeFile(path.join(cliDir, "src", "a.ts"), "export const x = 1;\n"); + git("commit", "-q", "-am", "two"); + expect(await factoryCliDistSection(script)).toMatch(/src is 1 commit ahead/); + + await writeCliBuildStamp(cliDir); + expect(await factoryCliDistSection(script)).toBeNull(); + }); +}); diff --git a/packages/cli/src/hooks/session-start.ts b/packages/cli/src/hooks/session-start.ts index 8ed4391..e949f87 100644 --- a/packages/cli/src/hooks/session-start.ts +++ b/packages/cli/src/hooks/session-start.ts @@ -3,6 +3,13 @@ import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { validateHandoffText } from "../invariants/handoff-schema.js"; import { stampLastCheckedAt } from "../lifecycle/check-updates.js"; +import { + assessCliDistFreshness, + CLI_DIST_STALE_FIX, + describeCliDistFreshness, + factoryRootFromScript, + type GitRunner, +} from "../lifecycle/cli-dist-stamp.js"; import { loadContextConfig } from "../lifecycle/context-config.js"; import { CHANGELOG_FETCH_TIMEOUT_MS, @@ -908,6 +915,26 @@ export async function liveAgentsSection( } } +/** + * Factory only: when this process is `/packages/cli/dist/index.js` (the hook + * resolver picked the project dist), one line naming a dist built from older source. + * One git call per session, never in the guard path; consumers (no packages/cli) + * and any error say nothing. + */ +export async function factoryCliDistSection( + scriptPath: string | null | undefined, + deps: { git?: GitRunner } = {}, +): Promise { + try { + const root = factoryRootFromScript(scriptPath ?? undefined); + if (!root) return null; + const gap = describeCliDistFreshness(await assessCliDistFreshness(root, deps)); + return gap ? `Factory hooks: ${gap}; ${CLI_DIST_STALE_FIX}.` : null; + } catch { + return null; + } +} + export async function buildSessionStartAdditionalContext( rootDir: string, _payload: SessionStartPayload = {}, @@ -919,11 +946,19 @@ export async function buildSessionStartAdditionalContext( updateNotice?: UpdateNoticeOptions; /** Consumer host; `pi` adds the numbered-list HITL section after the hard rules. */ host?: SessionStartHookFormat; + /** Running CLI script (default `process.argv[1]`); null skips the factory dist check. */ + cliScript?: string | null; + /** Git seam for the factory dist check. */ + git?: GitRunner; } = {}, ): Promise<{ additional_context: string }> { const root = path.resolve(rootDir); // Started first so the roster's ps / git shell-outs overlap the other sections. const liveAgentsPending = liveAgentsSection(root, { collect: deps.liveRoster }); + const factoryDistPending = factoryCliDistSection( + deps.cliScript === undefined ? process.argv[1] : deps.cliScript, + { git: deps.git }, + ); const handoffPath = path.join(root, HANDOFF_REL); const handoffFull = await readFull(handoffPath); const handoff = capHandoffExcerpt(handoffFull); @@ -941,6 +976,9 @@ export async function buildSessionStartAdditionalContext( const colonyHost = colonyHostSection(); if (colonyHost) parts.push(colonyHost); + const factoryDist = await factoryDistPending.catch(() => null); + if (factoryDist) parts.push(factoryDist); + // The three spawn-backed nudges run concurrently, each capped by a deadline that // kills its children, so one hung check cannot stall sessionStart. parts[] order // is unchanged. Children run without --stamp: the parent is the single writer of diff --git a/packages/cli/src/invariants/hooks-health.test.ts b/packages/cli/src/invariants/hooks-health.test.ts index 4c76d47..a2725ac 100644 --- a/packages/cli/src/invariants/hooks-health.test.ts +++ b/packages/cli/src/invariants/hooks-health.test.ts @@ -7,6 +7,7 @@ import { assessClaudeCommandAdapters, assessClaudeGuardProbe, assessClaudeMergeAllowGuard, + assessFactoryCliDist, assessGitHooksInstallDrift, assessHooksHealth, assessSignatureGateHook, @@ -196,6 +197,70 @@ describe("assessGitHooksInstallDrift", () => { }); }); +describe("assessFactoryCliDist", () => { + const SHA = "c".repeat(40); + const git = (answer: string | null) => async () => answer; + + beforeEach(() => { + vi.stubEnv("AGENT_KIT_HOOK_BIN", ""); + vi.stubEnv("PATH", "/usr/bin:/bin"); + }); + afterEach(() => vi.unstubAllEnvs()); + + async function factory(stamp: string | null | undefined): Promise { + const root = await mkdtemp(path.join(tmpdir(), "ak-factory-dist-")); + const cli = path.join(root, "packages", "cli"); + await mkdir(path.join(cli, "dist"), { recursive: true }); + await mkdir(path.join(cli, "src"), { recursive: true }); + await writeFile(path.join(cli, "dist", "index.js"), "// built\n", "utf8"); + await writeFile( + path.join(cli, "package.json"), + JSON.stringify({ name: "@dadado/agent-kit-cli" }), + "utf8", + ); + if (stamp !== undefined) { + await writeFile( + path.join(cli, "dist", "build-stamp.json"), + JSON.stringify({ schemaVersion: 1, sourceCommit: stamp, sourceDirty: false, builtAt: "x" }), + "utf8", + ); + } + return root; + } + + it("flags a stale dist for session-start and the guard with the fix", async () => { + const tips = await assessFactoryCliDist(await factory(SHA), { git: git("4\n") }); + expect(tips).toEqual([ + "Factory hooks (session-start and the PreToolUse guard) run a stale CLI: packages/cli/dist was built from cccccccc and packages/cli/src is 4 commits ahead; run `pnpm build` in packages/cli.", + ]); + }); + + it("flags an unstamped dist", async () => { + const tips = await assessFactoryCliDist(await factory(undefined), { git: git(null) }); + expect(tips).toHaveLength(1); + expect(tips[0]).toMatch(/has no build stamp.*run `pnpm build` in packages\/cli\.$/); + }); + + it("is silent on a fresh dist and when git fails", async () => { + expect(await assessFactoryCliDist(await factory(SHA), { git: git("0") })).toEqual([]); + expect(await assessFactoryCliDist(await factory(SHA), { git: git(null) })).toEqual([]); + }); + + it("is silent when the resolver picks node_modules/.bin/agent-kit first", async () => { + const root = await factory(undefined); + const bin = path.join(root, "node_modules", ".bin"); + await mkdir(bin, { recursive: true }); + await writeFile(path.join(bin, "agent-kit"), "#!/bin/sh\n", "utf8"); + await chmod(path.join(bin, "agent-kit"), 0o755); + expect(await assessFactoryCliDist(root, { git: git("4") })).toEqual([]); + }); + + it("is silent in a consumer (no packages/cli)", async () => { + const root = await mkdtemp(path.join(tmpdir(), "ak-consumer-")); + expect(await assessFactoryCliDist(root, { git: git("4") })).toEqual([]); + }); +}); + describe("assessClaudeGuardProbe", () => { const DENY = JSON.stringify({ hookSpecificOutput: { diff --git a/packages/cli/src/invariants/hooks-health.ts b/packages/cli/src/invariants/hooks-health.ts index 3501d7d..370d47e 100644 --- a/packages/cli/src/invariants/hooks-health.ts +++ b/packages/cli/src/invariants/hooks-health.ts @@ -13,7 +13,12 @@ import { RESOLVE_AGENT_KIT_REL, SESSION_START_HOOK_MARKER, } from "../generator/claude-session-start-hook.js"; - +import { + assessCliDistFreshness, + CLI_DIST_STALE_FIX, + describeCliDistFreshness, + type GitRunner, +} from "../lifecycle/cli-dist-stamp.js"; import { findOnPath } from "../utils/find-on-path.js"; const CLAUDE_SETTINGS_LOCAL_REL = ".claude/settings.local.json"; @@ -241,6 +246,32 @@ async function resolveGuardProbeArgv(root: string): Promise { return hit ? [hit] : null; } +/** + * Factory only: when the hook resolver would run `/packages/cli/dist/index.js` + * (no `AGENT_KIT_HOOK_BIN`, no `node_modules/.bin/agent-kit`), compare its build stamp + * with `packages/cli/src`. One advisory covers session-start and the guard alike, since + * both resolve the same CLI. Silent in consumers, on a fresh dist and on any error. + */ +export async function assessFactoryCliDist( + rootDir: string, + deps: { git?: GitRunner } = {}, +): Promise { + try { + const root = path.resolve(rootDir); + const argv = await resolveGuardProbeArgv(root); + const dist = path.join(root, "packages", "cli", "dist", "index.js"); + if (!argv || argv[argv.length - 1] !== dist) return []; + const gap = describeCliDistFreshness(await assessCliDistFreshness(root, deps)); + return gap + ? [ + `Factory hooks (session-start and the PreToolUse guard) run a stale CLI: ${gap}; ${CLI_DIST_STALE_FIX}.`, + ] + : []; + } catch { + return []; + } +} + /** * Capability probe for the Claude PreToolUse(Bash) guard. Silent when * `.claude/settings.json` is absent or unreadable. With the guard marker present, runs @@ -312,6 +343,7 @@ export async function assessHooksHealth(rootDir: string): Promise new Date("2026-11-30T12:00:00.000Z"); + +function fakeGit(answers: Record): GitRunner & { calls: string[][] } { + const calls: string[][] = []; + const fn = (async (_cwd: string, args: string[]) => { + calls.push(args); + const key = args[0] ?? ""; + return key in answers ? (answers[key] ?? null) : null; + }) as GitRunner & { calls: string[][] }; + fn.calls = calls; + return fn; +} + +let root: string; +let cliDir: string; +beforeEach(async () => { + root = await mkdtemp(path.join(tmpdir(), "ak-dist-stamp-")); + cliDir = path.join(root, "packages", "cli"); + await mkdir(path.join(cliDir, "dist"), { recursive: true }); + await mkdir(path.join(cliDir, "src"), { recursive: true }); + await writeFile(path.join(cliDir, "dist", "index.js"), "// built\n"); + await writeFile( + path.join(cliDir, "package.json"), + JSON.stringify({ name: "@dadado/agent-kit-cli" }), + ); +}); +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +describe("computeCliBuildStamp", () => { + it("records the newest src commit and a clean tree", async () => { + const git = fakeGit({ log: `${SHA}\n`, status: "" }); + const stamp = await computeCliBuildStamp(cliDir, { git, now: NOW }); + expect(stamp).toEqual({ + schemaVersion: 1, + sourceCommit: SHA, + sourceDirty: false, + builtAt: "2026-11-30T12:00:00.000Z", + }); + expect(git.calls[0]).toEqual(["log", "-1", "--format=%H", "--", "src"]); + }); + + it("flags uncommitted src changes", async () => { + const git = fakeGit({ log: SHA, status: " M src/index.ts\n" }); + expect((await computeCliBuildStamp(cliDir, { git, now: NOW })).sourceDirty).toBe(true); + }); + + it("without git the source is unknown and nothing throws", async () => { + const git = fakeGit({}); + const stamp = await computeCliBuildStamp(cliDir, { git, now: NOW }); + expect(stamp.sourceCommit).toBeNull(); + expect(stamp.sourceDirty).toBeNull(); + }); +}); + +describe("writeCliBuildStamp / readCliBuildStamp", () => { + it("round-trips through dist/build-stamp.json", async () => { + await writeCliBuildStamp(cliDir, { git: fakeGit({ log: SHA, status: "" }), now: NOW }); + const raw = JSON.parse(await readFile(path.join(cliDir, "dist", CLI_BUILD_STAMP_FILE), "utf8")); + expect(raw.sourceCommit).toBe(SHA); + expect(await readCliBuildStamp(path.join(cliDir, "dist"))).toEqual(raw); + }); + + it("returns null instead of throwing when dist is missing", async () => { + await rm(path.join(cliDir, "dist"), { recursive: true }); + expect(await writeCliBuildStamp(cliDir, { git: fakeGit({}), now: NOW })).toBeNull(); + }); + + it("reads a garbage stamp as null", async () => { + await writeFile(path.join(cliDir, "dist", CLI_BUILD_STAMP_FILE), "not json"); + expect(await readCliBuildStamp(path.join(cliDir, "dist"))).toBeNull(); + }); +}); + +describe("assessCliDistFreshness", () => { + async function stamp(sourceCommit: string | null): Promise { + await writeFile( + path.join(cliDir, "dist", CLI_BUILD_STAMP_FILE), + JSON.stringify({ schemaVersion: 1, sourceCommit, sourceDirty: false, builtAt: "x" }), + ); + } + + it("fresh when src has no commits after the stamp", async () => { + await stamp(SHA); + const git = fakeGit({ "rev-list": "0\n" }); + expect(await assessCliDistFreshness(root, { git })).toEqual({ state: "fresh" }); + expect(git.calls).toEqual([["rev-list", "--count", `${SHA}..HEAD`, "--", "src"]]); + expect(describeCliDistFreshness({ state: "fresh" })).toBeNull(); + }); + + it("stale names the short sha and the commit count", async () => { + await stamp(SHA); + const f = await assessCliDistFreshness(root, { git: fakeGit({ "rev-list": "3\n" }) }); + expect(f).toEqual({ state: "stale", sourceCommit: SHA, ahead: 3 }); + expect(describeCliDistFreshness(f)).toBe( + "packages/cli/dist was built from aaaaaaaa and packages/cli/src is 3 commits ahead", + ); + }); + + it("a missing stamp counts as stale with its own wording and no git call", async () => { + const git = fakeGit({}); + const f = await assessCliDistFreshness(root, { git }); + expect(f).toEqual({ state: "missing" }); + expect(git.calls).toEqual([]); + expect(describeCliDistFreshness(f)).toMatch(/has no build stamp/); + }); + + it("a stamp without a source commit is reported as unknown source", async () => { + await stamp(null); + const f = await assessCliDistFreshness(root, { git: fakeGit({}) }); + expect(f).toEqual({ state: "unknown-source" }); + expect(describeCliDistFreshness(f)).toMatch(/without git history/); + }); + + it("git failure says nothing (fail-open)", async () => { + await stamp(SHA); + expect(await assessCliDistFreshness(root, { git: fakeGit({}) })).toBeNull(); + }); + + it("a consumer root (no packages/cli/src) says nothing", async () => { + await rm(path.join(cliDir, "src"), { recursive: true }); + expect(await assessCliDistFreshness(root, { git: fakeGit({}) })).toBeNull(); + }); + + it("a consumer monorepo's own packages/cli says nothing", async () => { + await writeFile(path.join(cliDir, "package.json"), JSON.stringify({ name: "acme-cli" })); + expect(await assessCliDistFreshness(root, { git: fakeGit({ "rev-list": "4" }) })).toBeNull(); + }); + + it("no dist says nothing", async () => { + await rm(path.join(cliDir, "dist"), { recursive: true }); + expect(await assessCliDistFreshness(root, { git: fakeGit({}) })).toBeNull(); + }); +}); + +describe("factoryRootFromScript", () => { + it("returns the root for /packages/cli/dist/index.js", () => { + expect(factoryRootFromScript(path.join(root, "packages", "cli", "dist", "index.js"))).toBe( + root, + ); + }); + it("ignores a global or node_modules CLI and tsx from src", () => { + expect( + factoryRootFromScript("/usr/lib/node_modules/@dadado/agent-kit-cli/dist/index.js"), + ).toBeNull(); + expect(factoryRootFromScript(path.join(root, "packages", "cli", "src", "index.ts"))).toBeNull(); + expect(factoryRootFromScript(undefined)).toBeNull(); + }); +}); diff --git a/packages/cli/src/lifecycle/cli-dist-stamp.ts b/packages/cli/src/lifecycle/cli-dist-stamp.ts new file mode 100644 index 0000000..63884eb --- /dev/null +++ b/packages/cli/src/lifecycle/cli-dist-stamp.ts @@ -0,0 +1,208 @@ +/** + * Build stamp for the factory `packages/cli/dist`. + * + * The factory hooks resolve `/packages/cli/dist/index.js` before the global + * CLI (`.cursor/hooks/agent/resolve-agent-kit.sh`, same order as doctor), so a dist + * built from older source runs old hook behavior and reads as a product bug. + * `pnpm build` in `packages/cli` writes `dist/build-stamp.json` after tsup with the + * newest commit under `packages/cli/src`; session-start and doctor compare it with + * the checkout and name the gap in one line. + * + * Fail-open everywhere: no git (a tarball, a CI checkout without history) writes a + * stamp with an unknown source and never fails the build; any read or git error + * makes the check say nothing. + */ +import { execFile } from "node:child_process"; +import { readFile, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const CLI_BUILD_STAMP_FILE = "build-stamp.json"; +export const CLI_DIST_ENTRY_REL = path.join("packages", "cli", "dist", "index.js"); +export const CLI_BUILD_STAMP_SCHEMA = 1; +/** Only the kit's own CLI package counts: a consumer monorepo's `packages/cli` stays silent. */ +export const KIT_CLI_PACKAGE_NAME = "@dadado/agent-kit-cli"; +/** Fix line shared by session-start and doctor. */ +export const CLI_DIST_STALE_FIX = "run `pnpm build` in packages/cli"; +const GIT_TIMEOUT_MS = 2_000; + +export interface CliBuildStamp { + schemaVersion: number; + /** Newest commit touching `packages/cli/src` at build time; null when git was unavailable. */ + sourceCommit: string | null; + /** True when `packages/cli/src` had uncommitted changes; null when unknown. */ + sourceDirty: boolean | null; + builtAt: string; +} + +/** Runs git in `cwd`; resolves stdout, or null on any failure. */ +export type GitRunner = (cwd: string, args: string[]) => Promise; + +export const defaultGitRunner: GitRunner = (cwd, args) => + new Promise((resolve) => { + try { + execFile( + "git", + args, + { cwd, encoding: "utf8", timeout: GIT_TIMEOUT_MS, windowsHide: true }, + (err, stdout) => resolve(err ? null : String(stdout)), + ); + } catch { + resolve(null); + } + }); + +const SHA_RE = /^[0-9a-f]{40,64}$/; + +/** Stamp for the package at `cliDir` (`packages/cli`): two git calls at build time only. */ +export async function computeCliBuildStamp( + cliDir: string, + deps: { git?: GitRunner; now?: () => Date } = {}, +): Promise { + const git = deps.git ?? defaultGitRunner; + const now = deps.now ?? (() => new Date()); + const head = (await git(cliDir, ["log", "-1", "--format=%H", "--", "src"]))?.trim() ?? ""; + const sourceCommit = SHA_RE.test(head) ? head : null; + let sourceDirty: boolean | null = null; + if (sourceCommit) { + const status = await git(cliDir, ["status", "--porcelain", "--", "src"]); + sourceDirty = status === null ? null : status.trim().length > 0; + } + return { + schemaVersion: CLI_BUILD_STAMP_SCHEMA, + sourceCommit, + sourceDirty, + builtAt: now().toISOString(), + }; +} + +/** Writes `/dist/build-stamp.json`. Never throws: a stamp failure is not a build failure. */ +export async function writeCliBuildStamp( + cliDir: string, + deps: { git?: GitRunner; now?: () => Date } = {}, +): Promise { + try { + const stamp = await computeCliBuildStamp(cliDir, deps); + await writeFile( + path.join(cliDir, "dist", CLI_BUILD_STAMP_FILE), + `${JSON.stringify(stamp, null, 2)}\n`, + ); + return stamp; + } catch { + return null; + } +} + +/** Parsed stamp, or null when absent or not a stamp. */ +export async function readCliBuildStamp(distDir: string): Promise { + try { + const raw = JSON.parse( + await readFile(path.join(distDir, CLI_BUILD_STAMP_FILE), "utf8"), + ) as Partial | null; + if (!raw || typeof raw !== "object") return null; + const sourceCommit = + typeof raw.sourceCommit === "string" && SHA_RE.test(raw.sourceCommit) + ? raw.sourceCommit + : null; + return { + schemaVersion: typeof raw.schemaVersion === "number" ? raw.schemaVersion : 0, + sourceCommit, + sourceDirty: typeof raw.sourceDirty === "boolean" ? raw.sourceDirty : null, + builtAt: typeof raw.builtAt === "string" ? raw.builtAt : "", + }; + } catch { + return null; + } +} + +export type CliDistFreshness = + | { state: "fresh" } + | { state: "stale"; sourceCommit: string; ahead: number } + | { state: "missing" } + | { state: "unknown-source" }; + +/** + * Compares `/packages/cli/dist/build-stamp.json` with the checkout: one git + * call (`rev-list --count ..HEAD -- src`). Null when `root` is not a factory + * checkout (no `packages/cli/src` next to the dist) or on any error. + */ +export async function assessCliDistFreshness( + root: string, + deps: { git?: GitRunner } = {}, +): Promise { + try { + const cliDir = path.join(path.resolve(root), "packages", "cli"); + const distDir = path.join(cliDir, "dist"); + if (!(await isFile(path.join(distDir, "index.js")))) return null; + if (!(await isDir(path.join(cliDir, "src")))) return null; + if (!(await isKitCliPackage(cliDir))) return null; + const stamp = await readCliBuildStamp(distDir); + if (!stamp) return { state: "missing" }; + if (!stamp.sourceCommit) return { state: "unknown-source" }; + const git = deps.git ?? defaultGitRunner; + const out = await git(cliDir, [ + "rev-list", + "--count", + `${stamp.sourceCommit}..HEAD`, + "--", + "src", + ]); + const ahead = out === null ? Number.NaN : Number.parseInt(out.trim(), 10); + if (!Number.isFinite(ahead) || ahead < 0) return null; + return ahead === 0 + ? { state: "fresh" } + : { state: "stale", sourceCommit: stamp.sourceCommit, ahead }; + } catch { + return null; + } +} + +/** One-line description of a stale or unstamped dist, or null when fresh/unknown. */ +export function describeCliDistFreshness(f: CliDistFreshness | null): string | null { + if (!f || f.state === "fresh") return null; + if (f.state === "stale") { + const commits = f.ahead === 1 ? "1 commit" : `${f.ahead} commits`; + return `packages/cli/dist was built from ${f.sourceCommit.slice(0, 8)} and packages/cli/src is ${commits} ahead`; + } + if (f.state === "missing") { + return "packages/cli/dist has no build stamp (built before stamps existed or outside `pnpm build`), so its source age is unknown"; + } + return "packages/cli/dist build stamp has no source commit (built without git history), so its source age is unknown"; +} + +/** + * Root of the factory checkout whose `packages/cli/dist/index.js` is this running + * script, or null (global CLI, node_modules bin, tsx from src). + */ +export function factoryRootFromScript(scriptPath: string | undefined): string | null { + if (!scriptPath) return null; + const abs = path.resolve(scriptPath); + const suffix = path.sep + CLI_DIST_ENTRY_REL; + return abs.endsWith(suffix) ? abs.slice(0, -suffix.length) || path.sep : null; +} + +async function isKitCliPackage(cliDir: string): Promise { + try { + const pkg = JSON.parse(await readFile(path.join(cliDir, "package.json"), "utf8")) as { + name?: unknown; + }; + return pkg.name === KIT_CLI_PACKAGE_NAME; + } catch { + return false; + } +} + +async function isFile(p: string): Promise { + try { + return (await stat(p)).isFile(); + } catch { + return false; + } +} + +async function isDir(p: string): Promise { + try { + return (await stat(p)).isDirectory(); + } catch { + return false; + } +} diff --git a/packages/cli/src/lifecycle/write-cli-build-stamp.ts b/packages/cli/src/lifecycle/write-cli-build-stamp.ts new file mode 100644 index 0000000..f3738c4 --- /dev/null +++ b/packages/cli/src/lifecycle/write-cli-build-stamp.ts @@ -0,0 +1,18 @@ +/** + * Build step: `pnpm build` in packages/cli runs this after tsup to write + * `dist/build-stamp.json` (see cli-dist-stamp.ts). Always exits 0. + */ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeCliBuildStamp } from "./cli-dist-stamp.js"; + +const cliDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const stamp = await writeCliBuildStamp(cliDir); +if (stamp) { + const source = stamp.sourceCommit + ? `${stamp.sourceCommit.slice(0, 8)}${stamp.sourceDirty ? " (dirty)" : ""}` + : "unknown"; + console.error(`build-stamp: dist/build-stamp.json source ${source}`); +} else { + console.error("build-stamp: could not write dist/build-stamp.json (ignored)"); +} diff --git a/plugin.json b/plugin.json index 4e2babf..55d375b 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "agent-kit", - "version": "6.26.2", + "version": "6.27.0", "description": "Mission Kit core skills: HITL gates, plan backlog and onboarding, QA, external plan review. The full kit (slash commands, plans, HANDOFF, staging-then-prod git flow) installs with npx @dadado/agent-kit-cli@latest install.", "author": { "name": "agent-kit-startup"