Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(hooks): tell the user when the plugin and the cogit command drift apart
Eren5048975c4362
diff --git a/packages/cli/src/agents/claude/hooks.ts b/packages/cli/src/agents/claude/hooks.tsindex 1e06c6a..67f55be 100644--- a/packages/cli/src/agents/claude/hooks.ts+++ b/packages/cli/src/agents/claude/hooks.ts@@ -32,6 +32,11 @@ export function parseHookInput(stdin: string): HookInput | undefined {return parsed.success ? parsed.data : undefined;}+/** A hook answer Claude Code shows the user as a warning line; the agent does not see it. */+export function userNotice(text: string): Record<string, unknown> {+ return { systemMessage: text };+}+/** One hook answer that adds text to the agent's context, in Claude Code's shape. */export function additionalContext(event: string, text: string): Record<string, unknown> {return { hookSpecificOutput: { hookEventName: event, additionalContext: text } };diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.tsindex d9c5fc9..c1b2089 100644--- a/packages/cli/src/agents/claude/index.ts+++ b/packages/cli/src/agents/claude/index.ts@@ -1,5 +1,5 @@import { type AgentAdapter, DEFAULT_AGENT } from "../types.js";-import { additionalContext, parseHookInput } from "./hooks.js";+import { additionalContext, parseHookInput, userNotice } from "./hooks.js";import {allowSkill,CLAUDE_DEFAULT_RETENTION,@@ -56,6 +56,7 @@ export const claude: AgentAdapter = {parseHookInput,additionalContext,+ userNotice,readRetention,readPluginInstalled,diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsindex 198c1ef..f323bde 100644--- a/packages/cli/src/agents/types.ts+++ b/packages/cli/src/agents/types.ts@@ -137,6 +137,8 @@ export interface AgentAdapter {parseHookInput(stdin: string): HookInput | undefined;/** Hook output that adds context for the agent, in the agent's own protocol. */additionalContext(event: string, text: string): Record<string, unknown>;+ /** A hook answer that shows one line to the user, not to the agent. */+ userNotice(text: string): Record<string, unknown>;/** Days the agent keeps transcripts, undefined when the setting is unreadable. */readRetention(env: NodeJS.ProcessEnv): Promise<number | undefined>;/** Whether the agent lists the plugin as installed; undefined when unreadable. */diff --git a/packages/cli/src/cli-version.ts b/packages/cli/src/cli-version.tsnew file mode 100644index 0000000..ef20264--- /dev/null+++ b/packages/cli/src/cli-version.ts@@ -0,0 +1,55 @@+import { readFile, realpath, stat } from "node:fs/promises";+import { delimiter, dirname, join } from "node:path";++/**+ * The plugin and the `cogit` command on the PATH update through different channels+ * (a marketplace, npm), so one can fall behind the other. The plugin's hooks run their+ * own bundled CLI and keep recording either way; this only tells the user which one to+ * update. Nothing here touches the network: it reads the installed package's manifest.+ */++const PACKAGE = "@cogit/cli";++/** The version of the `cogit` command on `env.PATH`; undefined when there is none or it is not ours. */+export async function installedCliVersion(env: NodeJS.ProcessEnv): Promise<string | undefined> {+ for (const dir of (env.PATH ?? "").split(delimiter)) {+ if (dir === "") continue;+ const bin = join(dir, "cogit");+ try {+ if (!(await stat(bin)).isFile()) continue;+ // npm links bin/cogit to <package>/dist/cli.js.+ const pkg = JSON.parse(+ await readFile(join(dirname(dirname(await realpath(bin))), "package.json"), "utf8"),+ ) as { name?: unknown; version?: unknown };+ if (pkg.name === PACKAGE && typeof pkg.version === "string") return pkg.version;+ return undefined;+ } catch {}+ }+ return undefined;+}++/** Compares two x.y.z versions numerically; a pre-release suffix is ignored. */+export function compareVersions(a: string, b: string): number {+ const parts = (v: string) =>+ (v.split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);+ const [x, y] = [parts(a), parts(b)];+ for (let i = 0; i < Math.max(x.length, y.length); i++) {+ const d = (x[i] ?? 0) - (y[i] ?? 0);+ if (d !== 0) return Math.sign(d);+ }+ return 0;+}++/** One line for the user when the plugin (`running`) and the installed command differ. */+export function versionNotice(running: string, installed: string | undefined): string | undefined {+ if (installed === undefined) return undefined;+ const order = compareVersions(running, installed);+ if (order > 0)+ return `cogit: the cogit command is ${installed}, the plugin ${running}. Update the command with \`npm install -g ${PACKAGE}\`.`;+ if (order < 0)+ return (+ `cogit: the plugin is ${running}, the cogit command ${installed}. Update the plugin with ` ++ "`claude plugin update cogit@cogit`, or turn on auto-update in /plugin → Marketplaces → cogit."+ );+ return undefined;+}diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.tsindex 1d2bda9..87b19d4 100644--- a/packages/cli/src/hooks/sessionstart.ts+++ b/packages/cli/src/hooks/sessionstart.ts@@ -1,4 +1,6 @@+import pkg from "../../package.json" with { type: "json" };import { defaultAgent } from "../agents/index.js";+import { installedCliVersion, versionNotice } from "../cli-version.js";import { branchesOf, type LogBranch } from "../commands/log.js";import { findGitRoot } from "../git.js";import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";@@ -67,6 +69,14 @@ export function setupHint(ctx: HookContext): string {* an initialized project it gets the handoff (Story 8.11).*/export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undefined> {+ const output = await sessionStartOutput(ctx);+ // Once per new chat: the user hears when the plugin and the cogit command drifted apart.+ if (ctx.input.source !== "startup") return output;+ const notice = versionNotice(pkg.version, await installedCliVersion(ctx.env));+ return notice === undefined ? output : { ...output, ...ctx.agent.userNotice(notice) };+}++async function sessionStartOutput(ctx: HookContext): Promise<HookOutput | undefined> {if (ctx.input.source === "compact") return compactRequest(ctx);const source = ctx.input.source;if (source !== "startup" && source !== "resume" && source !== "clear") return undefined;diff --git a/packages/cli/test/cli-version.test.ts b/packages/cli/test/cli-version.test.tsnew file mode 100644index 0000000..1617a4d--- /dev/null+++ b/packages/cli/test/cli-version.test.ts@@ -0,0 +1,88 @@+import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { beforeEach, describe, expect, it } from "vitest";+import pkg from "../package.json" with { type: "json" };+import { compareVersions, installedCliVersion, versionNotice } from "../src/cli-version.js";+import { runHook } from "../src/hooks/run.js";+import { envFor, T0, tempDir } from "./helpers.js";++let dir: string;+beforeEach(async () => {+ dir = await tempDir();+});++/** A global npm install: prefix/bin/cogit -> ../lib/node_modules/<name>/dist/cli.js. */+async function npmPrefix(name: string, version: string): Promise<string> {+ const prefix = join(dir, `npm-${version}`);+ const pkgDir = join(prefix, "lib", "node_modules", ...name.split("/"));+ await mkdir(join(pkgDir, "dist"), { recursive: true });+ await writeFile(join(pkgDir, "package.json"), JSON.stringify({ name, version }));+ await writeFile(join(pkgDir, "dist", "cli.js"), "");+ await mkdir(join(prefix, "bin"));+ await symlink(join(pkgDir, "dist", "cli.js"), join(prefix, "bin", "cogit"));+ return join(prefix, "bin");+}++describe("the installed cogit command", () => {+ it("reads the version of the first cogit on the PATH", async () => {+ const older = await npmPrefix("@cogit/cli", "0.18.0");+ const newer = await npmPrefix("@cogit/cli", "0.19.1");+ const empty = join(dir, "empty");+ await mkdir(join(empty, "cogit"), { recursive: true });+ expect(await installedCliVersion({ PATH: ["", empty, older, newer].join(":") })).toBe("0.18.0");+ });++ it("says nothing for no PATH, no cogit, or a cogit that is not ours", async () => {+ expect(await installedCliVersion({})).toBeUndefined();+ expect(await installedCliVersion({ PATH: join(dir, "nowhere") })).toBeUndefined();+ const other = await npmPrefix("co-git", "9.9.9");+ expect(await installedCliVersion({ PATH: other })).toBeUndefined();+ // A plain script with no package next to it.+ const bin = join(dir, "plain");+ await mkdir(bin);+ await writeFile(join(bin, "cogit"), "#!/bin/sh\n");+ await chmod(join(bin, "cogit"), 0o755);+ expect(await installedCliVersion({ PATH: bin })).toBeUndefined();+ });++ it("compares versions by number", () => {+ expect(compareVersions("0.19.1", "0.19.0")).toBe(1);+ expect(compareVersions("0.9.0", "0.10.0")).toBe(-1);+ expect(compareVersions("1.0", "1.0.0")).toBe(0);+ expect(compareVersions("1.0.0-beta.1", "1.0.0")).toBe(0);+ expect(compareVersions("x", "0.0.0")).toBe(0);+ });++ it("names the one to update", () => {+ expect(versionNotice("0.19.1", undefined)).toBeUndefined();+ expect(versionNotice("0.19.1", "0.19.1")).toBeUndefined();+ expect(versionNotice("0.19.1", "0.19.0")).toBe(+ "cogit: the cogit command is 0.19.0, the plugin 0.19.1. Update the command with `npm install -g @cogit/cli`.",+ );+ expect(versionNotice("0.19.0", "0.19.1")).toContain(+ "the plugin is 0.19.0, the cogit command 0.19.1. Update the plugin with `claude plugin update cogit@cogit`",+ );+ });++ it("shows the notice to the user when a new chat starts, beside the agent's context", async () => {+ const root = join(dir, "proj");+ await mkdir(root);+ const env = { ...envFor(dir), PATH: await npmPrefix("@cogit/cli", "0.0.1") };+ const start = async (source: string) =>+ runHook(+ "sessionstart",+ JSON.stringify({ session_id: "s1", cwd: root, source }),+ env,+ T0,+ () => {},+ );+ const out = JSON.parse((await start("startup")) ?? "");+ expect(out.systemMessage).toBe(+ `cogit: the cogit command is 0.0.1, the plugin ${pkg.version}. Update the command with \`npm install -g @cogit/cli\`.`,+ );+ // The setup offer for this uninitialized project still reaches the agent.+ expect(out.hookSpecificOutput.additionalContext).toContain("cogit is not set up");+ // A resumed chat gets its usual context and no notice.+ expect(JSON.parse((await start("resume")) ?? "").systemMessage).toBeUndefined();+ });+});