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