Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
781 linesCodeBlameRaw
1// Tests for the plugin's hooks: node --test plugins/claude-code/test/
2import assert from "node:assert/strict";
3import { spawnSync } from "node:child_process";
4import { existsSync, mkdtempSync, readFileSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
5import { tmpdir } from "node:os";
6import { join } from "node:path";
7import { afterEach, beforeEach, describe, test } from "node:test";
8import { fileURLToPath } from "node:url";
9
10import {
11 updateContext,
12 UPDATES_REPEAT_MS,
13 howToUpdate,
14 PROMPT_LIMIT,
15 RESULT_LIMIT,
16 agentResult,
17 branchFromCommand,
18 g1tTool,
19 hasTitle,
20 hook,
21 intentTitle,
22 MIN_CLI,
23 TITLE_LIMIT,
24 oldNode,
25 older,
26 typedSkill,
27 isG1tRemote,
28 isGitCommit,
29 isGitPush,
30 issueFromBranch,
31 issueFromCommand,
32 plan,
33 redact,
34 sessionFiles,
35 subagentHarnessId,
36 summarizeTool,
37 work,
38} from "../hooks/g1t.mjs";
39
40import { CONTRACT, refusal } from "./fake-g1t.mjs";
41
42const HERE = fileURLToPath(new URL(".", import.meta.url));
43const SCRIPT = join(HERE, "..", "hooks", "g1t.mjs");
44const FAKE = join(HERE, "fake-g1t.mjs");
45
46const base = { session_id: "abc-123", cwd: "/work/repo", transcript_path: "/t.jsonl", permission_mode: "default" };
47
48describe("plan", () => {
49 test("SessionStart starts the session", () => {
50 const job = plan({ ...base, hook_event_name: "SessionStart", source: "startup" }, {});
51 assert.equal(job.start, true);
52 assert.deepEqual(job.steps, []);
53 });
54
55 test("UserPromptSubmit logs the prompt, cut to the limit", () => {
56 const prompt = "x".repeat(PROMPT_LIMIT + 500);
57 const job = plan({ ...base, hook_event_name: "UserPromptSubmit", prompt }, {});
58 const args = job.steps[0].args;
59 assert.deepEqual(args.slice(0, 5), ["session", "log", "--kind", "prompt", "--"]);
60 assert.equal(args[5].length, PROMPT_LIMIT);
61 assert.ok(args[5].endsWith("…"));
62 });
63
64 test("a turn Claude Code starts itself for a background task is not a prompt", () => {
65 const notification = "<task-notification>\n<task-id>a1</task-id>\n<result>SECRET OUTPUT</result>\n</task-notification>";
66 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: notification }, {}), null);
67 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "hi" }, {}).steps[0].args.at(-1), "hi");
68 });
69
70 test("a prompt's intent is its first line or sentence, plain, clipped on a word", () => {
71 assert.equal(intentTitle("fix the login redirect"), "Fix the login redirect");
72 assert.equal(intentTitle("Make preview builds faster. They time out on big repositories."), "Make preview builds faster");
73 assert.equal(intentTitle("Why does `src/app.ts` fail? It worked yesterday."), "Why does src/app.ts fail?");
74 assert.equal(intentTitle("```js\nconst a = 1;\n```\n## Clean **this** up\nmore"), "Clean this up");
75 assert.equal(intentTitle("\n\n- look at [the docs](https://docs.g1t.sh) for g1t.mjs"), "Look at the docs for g1t.mjs");
76 assert.equal(intentTitle(" spread over\tspaces "), "Spread over spaces");
77 const long = intentTitle("[TEST] Tidy up the README and then look at the CI pipeline, which keeps failing on the Windows runners");
78 assert.ok(long.length <= TITLE_LIMIT, long);
79 assert.ok(long.endsWith("…") && !long.endsWith(" …"), long);
80 assert.ok(long.startsWith("[TEST] Tidy up the README"), long);
81 assert.ok("[TEST] Tidy up the README and then look at the CI pipeline, which keeps failing on the Windows runners".startsWith(long.slice(0, -1)));
82 // Not intents: slash commands, turns Claude Code starts, nothing to say.
83 for (const prompt of ["/clear", "/compact keep the plan", "/g1t:status 4", "<command-name>/clear</command-name>", "```\ncode only\n```", "?", "", null]) {
84 assert.equal(intentTitle(prompt), null, String(prompt));
85 }
86 });
87
88 test("UserPromptSubmit titles the session with its intent, unless prompts are kept back", () => {
89 const job = plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "fix the login redirect" }, {});
90 assert.deepEqual(job.steps.at(-1), { title: "Fix the login redirect" });
91 assert.ok(!plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "/clear" }, {}).steps.some((s) => s.title));
92 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "fix it" }, { G1T_RECORD_PROMPTS: "0" }), null);
93 assert.equal(hasTitle(JSON.stringify({ id: "ses_1", title: null })), false);
94 assert.equal(hasTitle(JSON.stringify({ id: "ses_1", title: " " })), false);
95 assert.equal(hasTitle(JSON.stringify({ id: "ses_1", title: "Fix it" })), true);
96 assert.equal(hasTitle("not json"), true, "unreadable: nothing is replaced");
97 });
98
99 test("G1T_RECORD_PROMPTS=0 keeps prompts back, and G1T_RECORD=0 everything", () => {
100 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "hi" }, { G1T_RECORD_PROMPTS: "0" }), null);
101 assert.ok(plan({ ...base, hook_event_name: "Stop" }, { G1T_RECORD_PROMPTS: "0" }));
102 for (const hook_event_name of ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop", "SessionEnd"]) {
103 assert.equal(plan({ ...base, hook_event_name, prompt: "hi", tool_name: "Bash" }, { G1T_RECORD: "0" }), null);
104 }
105 });
106
107 test("PostToolUse sends the tool and its input's summary, never its response", () => {
108 const event = {
109 ...base,
110 hook_event_name: "PostToolUse",
111 tool_name: "Bash",
112 tool_input: { command: "npm test", description: "Run the tests" },
113 tool_response: { stdout: "SECRET OUTPUT 1234", stderr: "", interrupted: false },
114 tool_use_id: "toolu_1",
115 };
116 const job = plan(event, {});
117 assert.deepEqual(job.steps, [{ args: ["session", "log", "--kind", "tool_call", "--", "Bash: npm test"] }]);
118 assert.ok(!JSON.stringify(job).includes("SECRET OUTPUT"));
119 });
120
121 test("PostToolUse after a git push updates the head commit", () => {
122 const job = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "git push -u origin 42-fix" } }, {});
123 assert.deepEqual(job.steps[1], { headCommit: true });
124 const other = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "git status" } }, {});
125 assert.equal(other.steps.length, 1);
126 });
127
128 test("PostToolUse remembers the issue a command claims", () => {
129 const job = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "g1t work claim 42 --note x" } }, {});
130 assert.equal(job.issue, 42);
131 });
132
133 test("Stop sends a heartbeat and SessionEnd ends the session with its reason", () => {
134 assert.deepEqual(plan({ ...base, hook_event_name: "Stop", stop_hook_active: false }, {}).steps, [{ args: ["session", "heartbeat"] }]);
135 const end = plan({ ...base, hook_event_name: "SessionEnd", reason: "prompt_input_exit" }, {});
136 assert.deepEqual(end.steps, [{ args: ["session", "end", "--reason", "prompt_input_exit"] }]);
137 assert.equal(end.end, true);
138 });
139
140 test("events without a session, and other events, do nothing", () => {
141 assert.equal(plan({ hook_event_name: "Stop" }, {}), null);
142 assert.equal(plan({ ...base, hook_event_name: "PreToolUse", tool_name: "Bash" }, {}), null);
143 });
144});
145
146// Payloads as Claude Code sends them (code.claude.com/docs/en/hooks).
147const fixtures = {
148 subagentStart: {
149 session_id: "abc-123",
150 transcript_path: "/t.jsonl",
151 cwd: "/work/repo",
152 hook_event_name: "SubagentStart",
153 agent_id: "agent-def456",
154 agent_type: "Explore",
155 },
156 subagentStop: {
157 session_id: "abc-123",
158 transcript_path: "/t.jsonl",
159 cwd: "/work/repo",
160 permission_mode: "default",
161 hook_event_name: "SubagentStop",
162 stop_hook_active: false,
163 agent_id: "def456",
164 agent_type: "Explore",
165 agent_transcript_path: "/t/abc-123/subagents/agent-def456.jsonl",
166 last_assistant_message: "Analysis complete. Found 3 potential issues...",
167 background_tasks: [],
168 session_crons: [],
169 },
170 agentCompleted: {
171 ...base,
172 hook_event_name: "PostToolUse",
173 tool_name: "Agent",
174 tool_input: { description: "Find API endpoints", prompt: "Find all API endpoints", subagent_type: "Explore" },
175 tool_response: {
176 status: "completed",
177 agentId: "a4d2c8f1e0b3a297",
178 content: [{ type: "text", text: "Found 12 endpoints in src/api." }],
179 resolvedModel: "claude-sonnet-4-5",
180 totalTokens: 12450,
181 totalDurationMs: 48211,
182 totalToolUseCount: 7,
183 usage: { input_tokens: 8320, output_tokens: 410 },
184 },
185 tool_use_id: "toolu_9",
186 },
187 agentLaunched: {
188 ...base,
189 hook_event_name: "PostToolUse",
190 tool_name: "Agent",
191 tool_input: { description: "Review the diff", prompt: "Review it", subagent_type: "code-reviewer", run_in_background: true },
192 tool_response: { status: "async_launched", agentId: "b5", description: "Review the diff", prompt: "Review it", outputFile: "/tmp/b5.out", resolvedModel: "claude-sonnet-4-5" },
193 },
194 inSubagent: {
195 ...base,
196 hook_event_name: "PostToolUse",
197 agent_id: "agent-def456",
198 agent_type: "Explore",
199 tool_name: "Edit",
200 tool_input: { file_path: "/work/repo/src/api/routes.ts", old_string: "a", new_string: "b" },
201 tool_response: { filePath: "/work/repo/src/api/routes.ts", structuredPatch: "SECRET PATCH" },
202 },
203 skill: { ...base, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "work-on-issue", args: "42" }, tool_response: { success: true, commandName: "work-on-issue" } },
204};
205
206describe("subagents", () => {
207 test("SubagentStart starts a session of its own for the subagent", () => {
208 const job = plan(fixtures.subagentStart, {});
209 assert.deepEqual(job.agent, { id: "agent-def456", type: "Explore", start: true });
210 assert.deepEqual(job.steps, []);
211 assert.equal(subagentHarnessId("abc-123", "agent-def456"), "abc-123/agent/def456");
212 assert.equal(subagentHarnessId("abc-123", "def456"), "abc-123/agent/def456", "the Agent tool's id names the same subagent");
213 });
214
215 test("SubagentStop ends it with its final message, cut to the limit", () => {
216 const job = plan(fixtures.subagentStop, {});
217 assert.deepEqual(job.agent, { id: "def456", type: "Explore" });
218 assert.deepEqual(job.steps, [{ args: ["session", "end", "--reason", "done", "--result=Analysis complete. Found 3 potential issues..."] }]);
219 const long = plan({ ...fixtures.subagentStop, last_assistant_message: "z".repeat(RESULT_LIMIT * 2) }, {});
220 assert.equal(long.steps[0].args.at(-1).length, "--result=".length + RESULT_LIMIT);
221 const dash = plan({ ...fixtures.subagentStop, last_assistant_message: "- Found 3 issues" }, {});
222 assert.equal(dash.steps[0].args.at(-1), "--result=- Found 3 issues", "a message that starts with a dash is still a value");
223 assert.equal(refusal(dash.steps[0].args), null);
224 });
225
226 test("an Agent call gives its subagent the task, and once finished its final message, and nothing else of its answer", () => {
227 const job = plan(fixtures.agentCompleted, {});
228 assert.deepEqual(job.subagent, {
229 id: "a4d2c8f1e0b3a297",
230 type: "Explore",
231 task: "Find API endpoints",
232 prompt: "Find all API endpoints",
233 model: "claude-sonnet-4-5",
234 result: "Found 12 endpoints in src/api.",
235 });
236 assert.deepEqual(job.steps, [{ args: ["session", "log", "--kind", "tool_call", "--", "Agent: Find API endpoints"] }]);
237 assert.ok(!JSON.stringify(job).includes("12450") && !JSON.stringify(job).includes("8320"));
238 const launched = plan(fixtures.agentLaunched, {});
239 assert.equal(launched.subagent.id, "b5");
240 assert.equal(launched.subagent.result, null, "a background subagent reports at SubagentStop");
241 assert.equal(plan(fixtures.agentCompleted, { G1T_RECORD_PROMPTS: "0" }).subagent.prompt, null);
242 assert.equal(agentResult({ content: "plain" }), "plain");
243 });
244
245 test("what a subagent does is its own session's, and the files it writes are touched", () => {
246 const job = plan(fixtures.inSubagent, {});
247 assert.deepEqual(job.agent, { id: "agent-def456", type: "Explore" });
248 assert.deepEqual(job.steps, [
249 { args: ["session", "log", "--kind", "tool_call", "--", "Edit: src/api/routes.ts"] },
250 { args: ["session", "touch", "--file=src/api/routes.ts"] },
251 ]);
252 assert.ok(!JSON.stringify(job).includes("SECRET PATCH"));
253 });
254
255 test("a skill is its name only", () => {
256 assert.deepEqual(plan(fixtures.skill, {}).steps, [{ args: ["session", "log", "--kind", "skill", "--", "work-on-issue"], skill: "work-on-issue" }]);
257 });
258
259 test("branches made, commits, claims and g1t's MCP tools are touched", () => {
260 const bash = (command) => plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command } }, {});
261 assert.deepEqual(bash("git checkout -b 42-fix").steps.at(-1), { args: ["session", "touch", "--branch", "42-fix"] });
262 assert.deepEqual(bash('git commit -m "x" --trailer "G1t-Session: $G1T_SESSION"').steps.at(-1), { touchHead: true });
263 assert.deepEqual(bash("g1t work claim 42").steps.at(-1), { args: ["session", "touch", "--issue", "42"] });
264 const mcp = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "mcp__plugin_g1t_g1t__issue", tool_input: { action: "claim", repo: "a/b", number: 7 } }, {});
265 assert.equal(mcp.issue, 7);
266 assert.equal(branchFromCommand("git switch -c feat/x && echo"), "feat/x");
267 assert.equal(branchFromCommand("git branch -d old"), null);
268 assert.equal(isGitCommit("git -C repo commit -am x"), true);
269 assert.equal(g1tTool("mcp__g1t__session"), "session");
270 assert.equal(g1tTool("mcp__github__issue"), null);
271 });
272
273 test("a hand-off's issue comes with the session", () => {
274 assert.equal(plan({ ...base, hook_event_name: "SessionStart" }, { G1T_ISSUE: "12" }).issue, 12);
275 });
276});
277
278describe("summaries", () => {
279 test("say what a tool was called with, in one short line", () => {
280 assert.equal(summarizeTool("Edit", { file_path: "/work/repo/src/a.ts", old_string: "x", new_string: "y" }, "/work/repo"), "Edit: src/a.ts");
281 assert.equal(summarizeTool("Grep", { pattern: "TODO", path: "src" }, "/w"), "Grep: TODO in src");
282 assert.equal(summarizeTool("WebFetch", { url: "https://example.com", prompt: "p" }), "WebFetch: https://example.com");
283 assert.equal(summarizeTool("Bash", { command: "echo one\necho two" }), "Bash: echo one …");
284 assert.equal(summarizeTool("mcp__g1t__issue", { action: "get", number: 4 }), "mcp__g1t__issue: get");
285 assert.ok(summarizeTool("Bash", { command: "y".repeat(1000) }).length <= 200);
286 });
287
288 test("hide what looks like a secret", () => {
289 const line = redact('curl -H "Authorization: Bearer g1t_abcdefghijklmnop" https://u:pw@x.com GITHUB_TOKEN=ghp_123456789012 --token abc');
290 assert.ok(!line.includes("abcdefghijklmnop"));
291 assert.ok(!line.includes("ghp_123456789012"));
292 assert.ok(!line.includes("u:pw@"));
293 assert.ok(!line.includes("--token abc"));
294 });
295
296 test("find the issue in a branch name", () => {
297 assert.equal(issueFromBranch("42-fix-login"), 42);
298 assert.equal(issueFromBranch("issue-7"), 7);
299 assert.equal(issueFromBranch("fix/123-thing"), 123);
300 assert.equal(issueFromBranch("main"), null);
301 assert.equal(issueFromBranch("release/1.2"), null);
302 assert.equal(issueFromBranch("HEAD"), null);
303 assert.equal(issueFromCommand("g1t session attach --issue 9"), 9);
304 assert.equal(issueFromCommand("g1t pr create --issue=12 --draft"), 12);
305 assert.equal(isGitPush("cd x && git -C repo push"), true);
306 assert.equal(isGitPush("git pushd"), false);
307 assert.equal(isG1tRemote(["remote.origin.url https://g1t.sh/a/b.git"], {}), true);
308 assert.equal(isG1tRemote(["remote.origin.url https://example.com/a/b.git"], {}), false);
309 assert.equal(isG1tRemote(["remote.origin.url https://git.acme.dev/a/b.git"], { G1T_HOST: "git.acme.dev" }), true);
310 });
311});
312
313describe("the plugin's files", () => {
314 const root = join(HERE, "..", "..", "..");
315 test("parse as JSON", () => {
316 for (const file of [".claude-plugin/marketplace.json", "plugins/claude-code/.claude-plugin/plugin.json", "plugins/claude-code/.mcp.json", "plugins/claude-code/hooks/hooks.json"]) {
317 assert.doesNotThrow(() => JSON.parse(readFileSync(join(root, file), "utf8")), file);
318 }
319 });
320
321 test("the AGENTS.md snippet is the one in the docs", () => {
322 const snippet = readFileSync(join(root, "plugins/other-harnesses/AGENTS.snippet.md"), "utf8").replaceAll("\r\n", "\n");
323 const guide = readFileSync(join(root, "apps/docs/src/content/docs/guides/claude-code-plugin.md"), "utf8").replaceAll("\r\n", "\n");
324 const block = /```md title="AGENTS.md"\n([\s\S]*?)```/.exec(guide)?.[1];
325 assert.equal(block, snippet);
326 });
327});
328
329describe("with a working copy", () => {
330 let dir, env, log;
331
332 const git = (...args) => spawnSync("git", args, { cwd: dir, encoding: "utf8" });
333 const allCalls = () =>
334 existsSync(log)
335 ? readFileSync(log, "utf8")
336 .trim()
337 .split("\n")
338 .filter(Boolean)
339 .map((l) => JSON.parse(l))
340 : [];
341 // The calls that do something: not the version check before them.
342 const calls = () => allCalls().filter((c) => c.args[0] !== "--version");
343
344 beforeEach(() => {
345 dir = mkdtempSync(join(tmpdir(), "g1t-hook-"));
346 log = join(dir, "calls.jsonl");
347 git("init", "-q", "-b", "42-fix-login");
348 git("remote", "add", "origin", "https://g1t.sh/acme/app.git");
349 env = { PATH: process.env.PATH, G1T_BIN: FAKE, FAKE_G1T_LOG: log, CLAUDE_PLUGIN_DATA: join(dir, ".data") };
350 });
351 afterEach(() => {
352 // Every call the hooks made is one the real CLI takes (the stand-in refuses the rest).
353 const refused = allCalls().filter((c) => refusal(c.args));
354 rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
355 assert.deepEqual(refused, [], "the CLI refuses these calls");
356 });
357
358 test("SessionStart gives Claude the branch's issue's work context", () => {
359 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }, env);
360 const context = output.hookSpecificOutput.additionalContext;
361 assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart");
362 assert.match(context, /issue #42/);
363 assert.match(context, /Definition of done: it works/);
364 assert.deepEqual(calls()[0].args, ["work", "context", "42"]);
365 assert.equal(job.start, true);
366 });
367
368 test("the background half starts the session once, then logs into it", () => {
369 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
370 const { job } = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "fix the login" }, env);
371 // No SessionStart marked this session as one in a g1t working copy.
372 assert.equal(job, null);
373 work(plan({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "fix the login" }, env), env);
374 const [start, logged] = calls().filter((call) => call.args[1] !== "get_session");
375 assert.deepEqual(start.args, ["session", "start", "--harness", "claude_code", "--harness-session-id", "abc-123", "--json"]);
376 assert.deepEqual(logged, { args: ["session", "log", "--kind", "prompt", "--", "fix the login"], session: "ses_fake01" });
377 assert.equal(readFileSync(sessionFiles(base.session_id, env).id, "utf8"), "ses_fake01");
378 });
379
380 test("background retrieval reaches the next tool without auto-acknowledging", () => {
381 // A CLI that acknowledges: an older one is told to update instead (below).
382 env.FAKE_G1T_VERSION = "0.3.3";
383 env.FAKE_G1T_UPDATES = JSON.stringify([{ id: "upd_real", kind: "overlap.detected", data: { paths: ["src/api.ts"] } }]);
384 const event = { ...base, cwd: dir, hook_event_name: "SessionStart" };
385 const { job } = hook(event, env);
386 work(job, env);
387 const next = { ...event, hook_event_name: "PreToolUse", tool_name: "Read", tool_input: { file_path: "src/api.ts" } };
388 const first = hook(next, env).output;
389 assert.match(first.hookSpecificOutput.additionalContext, /upd_real/);
390 assert.equal(first.hookSpecificOutput.hookEventName, "PreToolUse");
391 // The next tool is not told again at once; the next prompt is.
392 assert.equal(hook(next, env).output, null);
393 const prompt = hook({ ...event, hook_event_name: "UserPromptSubmit", prompt: "go on" }, env).output;
394 assert.match(prompt.hookSpecificOutput.additionalContext, /upd_real/);
395 assert.ok(calls().some((call) => call.args[1] === "get_session" && call.args.includes("after=4294967295")));
396 assert.ok(!calls().some((call) => call.args[1] === "record_session_entries"));
397 });
398
399 test("hooks after SessionStart record; SessionEnd forgets the session", () => {
400 hook({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }, env);
401 const files = sessionFiles(base.session_id, env);
402 assert.ok(existsSync(files.marker));
403 const { job } = hook({ ...base, cwd: dir, hook_event_name: "Stop" }, env);
404 work(job, env);
405 work(plan({ ...base, cwd: dir, hook_event_name: "SessionEnd", reason: "clear" }, env), env);
406 const args = calls().map((c) => c.args.join(" "));
407 assert.ok(args.includes("session heartbeat"));
408 assert.ok(args.includes("session end --reason clear"));
409 assert.ok(!existsSync(files.marker) && !existsSync(files.id));
410 });
411
412 test("a push that reached the remote updates the head commit", () => {
413 git("-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "commit", "-q", "--allow-empty", "-m", "one");
414 git("update-ref", "refs/remotes/origin/42-fix-login", "HEAD");
415 const head = git("rev-parse", "HEAD").stdout.trim();
416 work(plan({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "git push" } }, env), env);
417 const update = calls().find((c) => c.args[0] === "api");
418 assert.deepEqual(update.args, ["api", "update_session", "-f", "id=ses_fake01", "-f", `head_commit=${head}`, "--silent"]);
419 });
420
421 test("each subagent is a session of its own under this one, whatever order its hooks arrive in", () => {
422 const at = (event) => ({ ...event, cwd: dir });
423 hook(at({ ...base, hook_event_name: "SessionStart", source: "startup" }), env);
424 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
425 // Claude calls Agent; its task waits for the subagent.
426 const pre = hook(at({ ...base, hook_event_name: "PreToolUse", tool_name: "Agent", tool_input: fixtures.agentCompleted.tool_input }), env);
427 assert.equal(pre.output, null);
428 const started = hook(at(fixtures.subagentStart), env);
429 assert.match(started.output.hookSpecificOutput.additionalContext, /session of your own/);
430 assert.match(started.output.hookSpecificOutput.additionalContext, /g1t session list --issue 42 --subagents|g1t session list --subagents/);
431 assert.equal(started.job.agent.task, "Find API endpoints");
432 work(started.job, env);
433 // What it does goes to its own session.
434 const edited = { ...fixtures.inSubagent.tool_input, file_path: join(dir, "src", "api", "routes.ts") };
435 work(hook(at({ ...fixtures.inSubagent, tool_input: edited }), env).job, env);
436 // Its g1t commands act as it.
437 const bash = hook(at({ ...base, hook_event_name: "PreToolUse", agent_id: "agent-def456", agent_type: "Explore", tool_name: "Bash", tool_input: { command: "g1t work claim 42" } }), env);
438 assert.equal(bash.output.hookSpecificOutput.updatedInput.command, "export G1T_SESSION=ses_sub_def456; g1t work claim 42");
439 const mcp = hook(at({ ...base, hook_event_name: "PreToolUse", agent_id: "agent-def456", tool_name: "mcp__plugin_g1t_g1t__issue", tool_input: { action: "claim", repo: "acme/app", number: 42 } }), env);
440 assert.equal(mcp.output.hookSpecificOutput.updatedInput.session_id, "ses_sub_def456");
441 // Outside a subagent, a command is left alone.
442 assert.equal(hook(at({ ...base, hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command: "g1t work claim 42" } }), env).output, null);
443 work(hook(at(fixtures.subagentStop), env).job, env);
444 // A late SubagentStart starts it again, which g1t answers with the same, ended, session.
445 work(hook(at(fixtures.subagentStart), env).job, env);
446 const log = calls();
447 const childStarts = log.filter((c) => c.args[1] === "start" && c.args.includes("--parent"));
448 assert.ok(childStarts.length >= 2);
449 const first = childStarts[0].args;
450 assert.deepEqual(first.slice(0, 8), ["session", "start", "--harness", "claude_code", "--harness-session-id", "abc-123/agent/def456", "--parent", "ses_fake01"]);
451 assert.ok(first.includes("--no-remember"));
452 assert.ok(first.includes("--agent-type=Explore"));
453 assert.ok(first.includes("--task=Find API endpoints"));
454 const edit = log.find((c) => c.args[2] === "--kind" && c.args.at(-1) === "Edit: src/api/routes.ts");
455 assert.equal(edit.session, "ses_sub_def456");
456 const touched = log.find((c) => c.args[1] === "touch");
457 assert.deepEqual(touched, { args: ["session", "touch", "--file=src/api/routes.ts"], session: "ses_sub_def456" });
458 const ended = log.find((c) => c.args[1] === "end");
459 assert.deepEqual(ended, { args: ["session", "end", "--reason", "done", "--result=Analysis complete. Found 3 potential issues..."], session: "ses_sub_def456" });
460 });
461
462 test("a subagent whose stop arrives first is started, then ended", () => {
463 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
464 work(hook({ ...fixtures.subagentStop, cwd: dir }, env).job, env);
465 const [, start, end] = calls().filter((c) => c.args[0] === "session");
466 assert.ok(start.args.includes("--parent"));
467 assert.equal(end.args[1], "end");
468 assert.equal(end.session, "ses_sub_def456");
469 });
470
471 test("an Agent call that finished ends its subagent with what it reported", () => {
472 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
473 work(hook({ ...fixtures.agentCompleted, cwd: dir }, env).job, env);
474 const log = calls().filter((c) => c.args[0] === "session");
475 assert.equal(log.find((c) => c.args[1] === "log").session, "ses_fake01", "the Agent call is the parent's");
476 const end = log.find((c) => c.args[1] === "end");
477 assert.deepEqual(end, { args: ["session", "end", "--reason", "done", "--result=Found 12 endpoints in src/api."], session: "ses_sub_a4d2c8f1e0b3a297" });
478 });
479
480 test("a hand-off names its issue at the start", () => {
481 git("checkout", "-q", "-b", "main");
482 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, { ...env, G1T_ISSUE: "12" });
483 assert.match(output.hookSpecificOutput.additionalContext, /issue #12 \(from the work handed to it\)/);
484 assert.match(output.hookSpecificOutput.additionalContext, /G1t-Session/);
485 work(job, env);
486 const start = calls().find((c) => c.args[1] === "start");
487 assert.ok(start.args.includes("--issue") && start.args.includes("12"));
488 });
489
490 test("a missing CLI records nothing and says so once", () => {
491 const missing = { ...env, G1T_BIN: join(dir, "no-such-g1t") };
492 const first = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, missing);
493 assert.match(first.output.systemMessage, /not installed/);
494 assert.equal(first.job, null);
495 const second = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, missing);
496 assert.equal(second.output, null);
497 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "Stop" }, missing).job, null);
498 assert.deepEqual(calls(), []);
499 });
500
501 test("a signed-out CLI is said once, at the next prompt", () => {
502 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, { ...env, CLAUDE_PLUGIN_DATA: env.CLAUDE_PLUGIN_DATA });
503 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, { ...env, FAKE_G1T_EXIT: "4" });
504 const first = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env);
505 assert.match(first.output.systemMessage, /not signed in/);
506 const second = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env);
507 assert.equal(second.output, null);
508 });
509
510 test("outside a g1t repository nothing happens", () => {
511 git("remote", "set-url", "origin", "https://example.com/acme/app.git");
512 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
513 assert.equal(output, null);
514 assert.equal(job, null);
515 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "Stop" }, env).job, null);
516 assert.deepEqual(calls(), []);
517 });
518
519 test("the script answers SessionStart on stdin quickly, as JSON", async () => {
520 const started = Date.now();
521 const out = spawnSync(process.execPath, [SCRIPT], {
522 input: JSON.stringify({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }),
523 encoding: "utf8",
524 env: { ...process.env, ...env },
525 });
526 const took = Date.now() - started;
527 assert.equal(out.status, 0);
528 assert.match(JSON.parse(out.stdout).hookSpecificOutput.additionalContext, /issue #42/);
529 assert.ok(took < 3000, `took ${took} ms`);
530 // The detached half starts the session after the hook has returned.
531 const id = sessionFiles(base.session_id, env).id;
532 for (let i = 0; i < 100 && !existsSync(id); i++) await new Promise((done) => setTimeout(done, 50));
533 assert.equal(readFileSync(id, "utf8"), "ses_fake01");
534 await new Promise((done) => setTimeout(done, 200));
535 });
536
537 test("the script prints nothing for a prompt, and never fails on bad input", () => {
538 const prompt = spawnSync(process.execPath, [SCRIPT], {
539 input: JSON.stringify({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hello" }),
540 encoding: "utf8",
541 env: { ...process.env, ...env },
542 });
543 assert.equal(prompt.status, 0);
544 assert.equal(prompt.stdout, "");
545 const bad = spawnSync(process.execPath, [SCRIPT], { input: "not json", encoding: "utf8", env: { ...process.env, ...env } });
546 assert.equal(bad.status, 0);
547 assert.equal(bad.stdout, "");
548 });
549
550 test("a CLI older than the plugin needs records nothing and says so once, with how to update it", () => {
551 const old = { ...env, FAKE_G1T_VERSION: "0.3.1" };
552 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, old);
553 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, old);
554 work(plan({ ...base, cwd: dir, hook_event_name: "Stop" }, old), old);
555 // SessionStart still asks it for the issue's context, which every CLI gives.
556 assert.deepEqual(calls().map((c) => c.args.join(" ")), ["work context 42"], "nothing is recorded with it");
557 assert.equal(allCalls().filter((c) => c.args[0] === "--version").length, 1, "the version is asked once for each build of the CLI");
558 const first = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, old);
559 assert.match(first.output.systemMessage, /g1t CLI is 0\.3\.1, and the plugin needs 0\.3\.2 or later/);
560 assert.match(first.output.systemMessage, /curl -fsSL https:\/\/g1t\.sh\/install \| sh/);
561 assert.match(first.output.systemMessage, /irm https:\/\/g1t\.sh\/install\.ps1 \| iex/);
562 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, old).output, null);
563 assert.equal(older("0.3.1", MIN_CLI), true);
564 assert.equal(older("0.3.2", MIN_CLI), false);
565 assert.equal(older("0.10.0", MIN_CLI), false);
566 assert.equal(older("1.0.0", MIN_CLI), false);
567 });
568
569 test("a CLI that refuses a command (exit 2) is said once, as one to update", () => {
570 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
571 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, { ...env, FAKE_G1T_EXIT: "2" });
572 const first = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env);
573 assert.match(first.output.systemMessage, /refused `g1t session start`/);
574 assert.match(first.output.systemMessage, /installer again/);
575 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env).output, null);
576 });
577
578 test("the stand-in CLI refuses what the real one refuses", () => {
579 assert.equal(CONTRACT.minimum_version, MIN_CLI, "the hooks ask for the CLI the contract needs");
580 assert.match(refusal(["session", "log", "--kind", "tool-calls", "--", "x"]), /takes prompt, tool_call, skill/);
581 assert.match(refusal(["session", "log", "--kind", "note", "--", "x"]), /not note/, "the hooks never send a note");
582 assert.match(refusal(["session", "end", "--result", "- a list"]), /unexpected argument/);
583 assert.equal(refusal(["session", "end", "--result=- a list"]), null);
584 assert.match(refusal(["session", "touch"]), /needs one of/);
585 assert.match(refusal(["session", "heartbeat", "--now"]), /takes no --now/);
586 assert.match(refusal(["session", "start", "--harness", "claude-managed-agents", "--harness-session-id", "x"]), /takes claude_code/);
587 assert.match(refusal(["work", "context", "abc"]), /not abc/);
588 assert.match(refusal(["session", "pause"]), /takes 0 argument/);
589 assert.equal(refusal(["api", "update_session", "-f", "id=ses_1", "-f", "head_commit=abc", "--silent"]), null);
590 });
591
592 test("PowerShell commands are read as Bash ones are, and a subagent's act as its session", () => {
593 const ps = (command, extra = {}) => ({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "PowerShell", tool_input: { command }, ...extra });
594 assert.equal(plan(ps("g1t work claim 42"), env).issue, 42);
595 assert.deepEqual(plan(ps("git checkout -b 42-fix; git status"), env).steps.at(-1), { args: ["session", "touch", "--branch", "42-fix"] });
596 assert.deepEqual(plan(ps("git commit -m x"), env).steps.at(-1), { touchHead: true });
597 assert.deepEqual(plan(ps("git push origin 42-fix"), env).steps.at(-1), { headCommit: true });
598 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
599 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
600 work(hook({ ...fixtures.subagentStart, cwd: dir }, env).job, env);
601 const pre = (tool_name, command) =>
602 hook({ ...base, cwd: dir, hook_event_name: "PreToolUse", agent_id: "agent-def456", agent_type: "Explore", tool_name, tool_input: { command } }, env).output;
603 assert.equal(pre("PowerShell", "g1t work claim 42").hookSpecificOutput.updatedInput.command, "$env:G1T_SESSION='ses_sub_def456'; g1t work claim 42");
604 assert.equal(pre("PowerShell", "g1t.exe session view").hookSpecificOutput.updatedInput.command, "$env:G1T_SESSION='ses_sub_def456'; g1t.exe session view");
605 assert.equal(pre("Bash", "echo $G1T_SESSION").hookSpecificOutput.updatedInput.command, "export G1T_SESSION=ses_sub_def456; echo $G1T_SESSION");
606 assert.equal(pre("PowerShell", "$env:G1T_SESSION='ses_other'; g1t work claim 42"), null, "a session the command sets itself is kept");
607 assert.equal(pre("PowerShell", "Get-ChildItem"), null, "other commands are left alone");
608 // The tool call is recorded as Claude wrote it.
609 const after = plan(ps("$env:G1T_SESSION='ses_sub_def456'; g1t work claim 42", { agent_id: "agent-def456" }), env);
610 assert.deepEqual(after.steps[0].args.at(-1), "PowerShell: g1t work claim 42");
611 assert.equal(summarizeTool("Bash", { command: "export G1T_SESSION=ses_1; g1t pr view" }), "Bash: g1t pr view");
612 });
613
614 test("a skill typed as /plugin:name is recorded once in its turn, however Claude Code then runs it", () => {
615 assert.equal(typedSkill("/g1t:work-on-issue 42"), "g1t:work-on-issue");
616 assert.equal(typedSkill("/g1t:status"), "g1t:status");
617 assert.equal(typedSkill("/clear"), null, "Claude Code's own commands are not skills");
618 assert.equal(typedSkill("look at /g1t:status"), null);
619 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
620 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
621 const typed = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "/g1t:work-on-issue 42" }, env).job;
622 assert.deepEqual(typed.steps.map((s) => s.args.slice(0, 4)), [["session", "log", "--kind", "prompt"], ["session", "log", "--kind", "skill"]]);
623 work(typed, env);
624 const tool = hook({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "g1t:work-on-issue", args: "42" } }, env).job;
625 work(tool, env);
626 const skills = calls().filter((c) => c.args.includes("skill"));
627 assert.equal(skills.length, 2);
628 assert.deepEqual(skills[0].args, ["session", "log", "--kind", "skill", "--key=skill:work-on-issue:1", "--", "g1t:work-on-issue"]);
629 assert.equal(skills[1].args[4], "--key=skill:work-on-issue:1", "the same key: g1t keeps the first");
630 // Another skill in the turn has a key of its own; the next prompt is another turn.
631 const next = hook({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "g1t:coordinate" } }, env).job;
632 assert.equal(next.steps[0].key, "skill:coordinate:1");
633 hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "go on" }, { ...env, G1T_RECORD_PROMPTS: "0" });
634 const later = hook({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "g1t:work-on-issue" } }, env).job;
635 assert.equal(later.steps[0].key, "skill:work-on-issue:2", "a turn whose prompt is not sent is still a turn");
636 // Prompts kept back: the typed skill's name is still recorded, the prompt is not.
637 const quiet = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "/g1t:status" }, { ...env, G1T_RECORD_PROMPTS: "0" }).job;
638 assert.deepEqual(quiet.steps.map((s) => s.args.at(-1)), ["g1t:status"]);
639 });
640
641 test("with no issue in sight, Claude is told the session is recorded and when to open or claim one", () => {
642 git("symbolic-ref", "HEAD", "refs/heads/fix-previews");
643 const { output } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }, env);
644 const context = output.hookSpecificOutput.additionalContext;
645 assert.match(context, /this session is recorded on g1t and shows to the team/);
646 assert.match(context, /Just work/);
647 assert.match(context, /`g1t work claim --title "…"`/);
648 assert.match(context, /Never open issues for questions, exploration or trivial fixes/);
649 assert.ok(context.length < 900, `injected every session, so short: ${context.length}`);
650 assert.ok(!calls().some((c) => c.args[0] === "work"), "no issue's context is asked for");
651 });
652
653 test("the session's first prompt with an intent titles it, once, and never over a title it has", () => {
654 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
655 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
656 const prompt = (text, more = {}) => hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: text }, { ...env, ...more }).job;
657 // A slash command says nothing of what the session is for.
658 work(prompt("/clear"), env);
659 assert.ok(!calls().some((c) => c.args[1] === "attach" || c.args[1] === "heartbeat"));
660 work(prompt("[TEST] fix the preview builds. They time out."), env);
661 const titled = calls().filter((c) => c.args[1] === "heartbeat" || c.args[1] === "attach");
662 assert.deepEqual(titled, [
663 { args: ["session", "heartbeat", "--json"], session: "ses_fake01" },
664 { args: ["session", "attach", "--title=[TEST] fix the preview builds"], session: "ses_fake01" },
665 ]);
666 // Later prompts do not try again.
667 const next = prompt("now the tests");
668 assert.ok(!next.steps.some((s) => s.title));
669 });
670
671 test("a session titled already keeps its title", () => {
672 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
673 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
674 const job = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "fix the login" }, env).job;
675 work(job, { ...env, FAKE_G1T_TITLE: "Rewrite the auth flow" });
676 assert.ok(calls().some((c) => c.args[1] === "heartbeat"));
677 assert.ok(!calls().some((c) => c.args[1] === "attach"), "a title set before is never replaced");
678 });
679
680 test("Claude's own commands get the session's id once it has started", () => {
681 const envFile = join(dir, "env.sh");
682 const { job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, { ...env, CLAUDE_ENV_FILE: envFile });
683 assert.ok(!existsSync(envFile), "nothing is written before the session's id is known");
684 work(job, env);
685 // A plain assignment: Claude Code gives it to PowerShell commands too.
686 assert.equal(readFileSync(envFile, "utf8"), "export G1T_SESSION=ses_fake01\n");
687 });
688
689 test("on a Node older than 18 nothing is recorded, and that is said once", () => {
690 const at = (hook_event_name) => ({ ...base, cwd: dir, hook_event_name });
691 assert.equal(oldNode(at("SessionStart"), env, "18.0.0"), undefined);
692 const first = oldNode(at("SessionStart"), env, "16.20.2");
693 assert.match(first.systemMessage, /need Node 18 or later, and `node` is v16\.20\.2/);
694 assert.equal(oldNode(at("UserPromptSubmit"), env, "16.20.2"), null);
695 assert.equal(oldNode(at("PostToolUse"), env, "16.20.2"), null);
696 assert.deepEqual(calls(), []);
697 });
698});
699
700test("pending updates survive delivery and stay isolated between parent and child", () => {
701 const dir = mkdtempSync(join(tmpdir(), "g1t-inbox-"));
702 try {
703 const env = { CLAUDE_PLUGIN_DATA: dir };
704 const files = sessionFiles("harness", env);
705 mkdirSync(files.dir, { recursive: true });
706 writeFileSync(files.id, "ses_parent");
707 writeFileSync(files.agent("child"), "ses_child");
708 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "parent-update", kind: "overlap.detected", data: {} }]));
709 writeFileSync(files.updates("ses_child"), JSON.stringify([{ id: "child-update", kind: "dependency.changed", data: {} }]));
710 const event = { session_id: "harness" };
711 const first = updateContext(event, env);
712 assert.match(first, /parent-update/);
713 assert.doesNotMatch(first, /child-update/);
714 assert.equal(updateContext(event, env), first);
715 // Before tools: shown once, again when it changes or after a while.
716 const files2 = sessionFiles("harness", env);
717 rmSync(files2.shown("ses_parent"), { force: true });
718 assert.equal(updateContext(event, env, { throttle: true, now: 1000 }), first);
719 assert.equal(updateContext(event, env, { throttle: true, now: 2000 }), null);
720 assert.equal(updateContext(event, env, { throttle: true, now: 1000 + UPDATES_REPEAT_MS }), first);
721 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "parent-update", kind: "overlap.detected", data: {} }, { id: "newer", kind: "work.claimed", data: {} }]));
722 assert.match(updateContext(event, env, { throttle: true, now: 1001 + UPDATES_REPEAT_MS }), /newer/);
723 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "parent-update", kind: "overlap.detected", data: {} }]));
724 const child = updateContext({ ...event, agent_id: "child" }, env);
725 assert.match(child, /child-update/);
726 assert.doesNotMatch(child, /parent-update/);
727 assert.equal(updateContext({ ...event, agent_id: "unknown" }, env), null);
728 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "oversized", data: "x".repeat(20000) }]));
729 const bounded = updateContext(event, env);
730 assert.ok(bounded.length < 10000);
731 assert.match(bounded, /read get_session first/);
732 // A payload that was omitted is not cleared from the cache.
733 assert.match(readFileSync(files.updates("ses_parent"), "utf8"), /oversized/);
734 writeFileSync(files.updates("ses_parent"), "[]");
735 assert.equal(updateContext(event, env), null);
736 assert.equal(updateContext({ ...event, agent_id: "child" }, env), child);
737 } finally { rmSync(dir, { recursive: true, force: true }); }
738});
739
740test("a CLI too old to acknowledge is told to update, once per set of updates", () => {
741 const dir = mkdtempSync(join(tmpdir(), "g1t-stuck-"));
742 try {
743 const env = { CLAUDE_PLUGIN_DATA: dir };
744 const files = sessionFiles("harness", env);
745 mkdirSync(files.dir, { recursive: true });
746 writeFileSync(files.id, "ses_old");
747 writeFileSync(join(dir, "cli.json"), JSON.stringify({ stamp: "x", version: "0.3.2" }));
748 writeFileSync(files.updates("ses_old"), JSON.stringify([{ id: "upd_1", kind: "session.ended", data: {} }]));
749 const event = { session_id: "harness" };
750 const first = updateContext(event, env);
751 assert.match(first, /upd_1/);
752 assert.match(first, /cannot acknowledge them \(0\.3\.3 can\)/);
753 assert.match(first, /install\.ps1/, "0.3.2 has no g1t upgrade: the installer");
754 assert.doesNotMatch(first, /g1t session acknowledge/);
755 // Nothing can clear them, so not again on every prompt or tool.
756 assert.equal(updateContext(event, env), null);
757 assert.equal(updateContext(event, env, { throttle: true, now: Date.now() + 10 * UPDATES_REPEAT_MS }), null);
758 writeFileSync(files.updates("ses_old"), JSON.stringify([{ id: "upd_1", data: {} }, { id: "upd_2", data: {} }]));
759 assert.match(updateContext(event, env), /upd_2/);
760 // A CLI that acknowledges is asked to.
761 writeFileSync(join(dir, "cli.json"), JSON.stringify({ stamp: "x", version: "0.3.3" }));
762 assert.match(updateContext(event, env), /g1t session acknowledge UPDATE_ID --session ses_old/);
763 assert.equal(howToUpdate("0.3.4"), "`g1t upgrade`");
764 assert.match(howToUpdate("0.3.3"), /curl -fsSL https:\/\/g1t\.sh\/install \| sh/);
765 assert.match(howToUpdate(null), /installer/);
766 } finally { rmSync(dir, { recursive: true, force: true }); }
767});
768
769test("an acknowledgement refreshes the inbox at once, from the shell or MCP", () => {
770 const dir = mkdtempSync(join(tmpdir(), "g1t-ack-"));
771 try {
772 const env = { CLAUDE_PLUGIN_DATA: dir };
773 const base = { session_id: "harness", cwd: dir, hook_event_name: "PostToolUse" };
774 const shell = plan({ ...base, tool_name: "Bash", tool_input: { command: "g1t session acknowledge upd_1 --note 'Separate scopes'" } }, env);
775 assert.equal(shell.refreshUpdates, true);
776 const mcp = plan({ ...base, tool_name: "mcp__plugin_g1t_g1t__session", tool_input: { action: "record", id: "ses_a", acknowledge: ["upd_1"] } }, env);
777 assert.equal(mcp.refreshUpdates, true);
778 const other = plan({ ...base, tool_name: "Bash", tool_input: { command: "git status" } }, env);
779 assert.equal(other.refreshUpdates, undefined);
780 } finally { rmSync(dir, { recursive: true, force: true }); }
781});