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