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.

1,200 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 TITLE_NOTE,
12 updateContext,
13 UPDATES_REPEAT_MS,
14 howToUpdate,
15 PROMPT_LIMIT,
16 RESULT_LIMIT,
17 agentResult,
18 branchFromCommand,
19 g1tTool,
20 hook,
21 repoPath,
22 MIN_CLI,
23 oldNode,
24 older,
25 typedSkill,
26 transcriptUsage,
27 USAGE_CLI,
28 LONG_PROMPT_TOKENS,
29 isG1tRemote,
30 isGitCommit,
31 isGitPush,
32 itemFromBranch,
33 itemFromCommand,
34 mayAddRemote,
35 pairSubagent,
36 plan,
37 rememberTask,
38 takeTask,
39 redact,
40 sessionFiles,
41 subagentHarnessId,
42 summarizeTool,
43 work,
44} from "../hooks/g1t.mjs";
45
46import { CONTRACT, refusal } from "./fake-g1t.mjs";
47
48const HERE = fileURLToPath(new URL(".", import.meta.url));
49const SCRIPT = join(HERE, "..", "hooks", "g1t.mjs");
50const FAKE = join(HERE, "fake-g1t.mjs");
51
52const base = { session_id: "abc-123", cwd: "/work/repo", transcript_path: "/t.jsonl", permission_mode: "default" };
53
54/** An assistant line of a transcript, as Claude Code writes one for each part of an API response. */
55function assistant(id, model, usage, requestId = `req_${id}`) {
56 return JSON.stringify({
57 type: "assistant",
58 requestId,
59 message: { id, model, role: "assistant", content: [{ type: "text", text: "the secret plan" }], usage },
60 });
61}
62
63describe("plan", () => {
64 test("SessionStart starts the session", () => {
65 const job = plan({ ...base, hook_event_name: "SessionStart", source: "startup" }, {});
66 assert.equal(job.start, true);
67 assert.deepEqual(job.steps, []);
68 });
69
70 test("UserPromptSubmit logs the prompt, cut to the limit", () => {
71 const prompt = "x".repeat(PROMPT_LIMIT + 500);
72 const job = plan({ ...base, hook_event_name: "UserPromptSubmit", prompt }, {});
73 const args = job.steps[0].args;
74 assert.deepEqual(args.slice(0, 5), ["session", "log", "--kind", "prompt", "--"]);
75 assert.equal(args[5].length, PROMPT_LIMIT);
76 assert.ok(args[5].endsWith("…"));
77 });
78
79 test("a turn Claude Code starts itself for a background task is not a prompt", () => {
80 const notification = "<task-notification>\n<task-id>a1</task-id>\n<result>SECRET OUTPUT</result>\n</task-notification>";
81 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: notification }, {}), null);
82 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "hi" }, {}).steps[0].args.at(-1), "hi");
83 });
84
85 test("UserPromptSubmit sends no title: g1t names the session from what it records", () => {
86 for (const prompt of ["fix the login redirect", "/clear", "Build me a todo app. Use React."]) {
87 const job = plan({ ...base, hook_event_name: "UserPromptSubmit", prompt }, {});
88 assert.ok(
89 job.steps.every((s) => s.args && !s.title && !s.args.includes("attach")),
90 prompt,
91 );
92 }
93 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "fix it" }, { G1T_RECORD_PROMPTS: "0" }), null);
94 });
95
96 test("G1T_RECORD_PROMPTS=0 keeps prompts back, and G1T_RECORD=0 everything", () => {
97 assert.equal(plan({ ...base, hook_event_name: "UserPromptSubmit", prompt: "hi" }, { G1T_RECORD_PROMPTS: "0" }), null);
98 assert.ok(plan({ ...base, hook_event_name: "Stop" }, { G1T_RECORD_PROMPTS: "0" }));
99 for (const hook_event_name of ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop", "SessionEnd"]) {
100 assert.equal(plan({ ...base, hook_event_name, prompt: "hi", tool_name: "Bash" }, { G1T_RECORD: "0" }), null);
101 }
102 });
103
104 test("PostToolUse sends the tool and its input's summary, never its response", () => {
105 const event = {
106 ...base,
107 hook_event_name: "PostToolUse",
108 tool_name: "Bash",
109 tool_input: { command: "npm test", description: "Run the tests" },
110 tool_response: { stdout: "SECRET OUTPUT 1234", stderr: "", interrupted: false },
111 tool_use_id: "toolu_1",
112 };
113 const job = plan(event, {});
114 assert.deepEqual(job.steps, [{ args: ["session", "log", "--kind", "tool_call", "--", "Bash: npm test"] }]);
115 assert.ok(!JSON.stringify(job).includes("SECRET OUTPUT"));
116 });
117
118 test("PostToolUse after a git push updates the head commit", () => {
119 const job = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "git push -u origin 42-fix" } }, {});
120 assert.deepEqual(job.steps[1], { headCommit: true });
121 const other = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "git status" } }, {});
122 assert.equal(other.steps.length, 1);
123 });
124
125 test("PostToolUse remembers the work item a command claims", () => {
126 const job = plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "g1t work claim 42 --note x" } }, {});
127 assert.equal(job.item, 42);
128 });
129
130 test("Stop sends a heartbeat with the transcript's usage, and SessionEnd reports it and ends the session with its reason", () => {
131 assert.deepEqual(plan({ ...base, hook_event_name: "Stop", stop_hook_active: false }, {}).steps, [{ args: ["session", "heartbeat"], usage: "/t.jsonl" }]);
132 const { transcript_path, ...untracked } = base;
133 assert.deepEqual(plan({ ...untracked, hook_event_name: "Stop" }, {}).steps, [{ args: ["session", "heartbeat"] }]);
134 const end = plan({ ...base, hook_event_name: "SessionEnd", reason: "prompt_input_exit" }, {});
135 assert.deepEqual(end.steps, [
136 { args: ["session", "heartbeat"], usage: "/t.jsonl", only: true },
137 { args: ["session", "end", "--reason", "prompt_input_exit"] },
138 ]);
139 assert.equal(end.end, true);
140 });
141
142 test("events without a session, and other events, do nothing", () => {
143 assert.equal(plan({ hook_event_name: "Stop" }, {}), null);
144 assert.equal(plan({ ...base, hook_event_name: "PreToolUse", tool_name: "Bash" }, {}), null);
145 });
146});
147
148// Payloads as Claude Code sends them (code.claude.com/docs/en/hooks).
149const fixtures = {
150 subagentStart: {
151 session_id: "abc-123",
152 transcript_path: "/t.jsonl",
153 cwd: "/work/repo",
154 hook_event_name: "SubagentStart",
155 agent_id: "agent-def456",
156 agent_type: "Explore",
157 },
158 subagentStop: {
159 session_id: "abc-123",
160 transcript_path: "/t.jsonl",
161 cwd: "/work/repo",
162 permission_mode: "default",
163 hook_event_name: "SubagentStop",
164 stop_hook_active: false,
165 agent_id: "def456",
166 agent_type: "Explore",
167 agent_transcript_path: "/t/abc-123/subagents/agent-def456.jsonl",
168 last_assistant_message: "Analysis complete. Found 3 potential issues...",
169 background_tasks: [],
170 session_crons: [],
171 },
172 agentCompleted: {
173 ...base,
174 hook_event_name: "PostToolUse",
175 tool_name: "Agent",
176 tool_input: { description: "Find API endpoints", prompt: "Find all API endpoints", subagent_type: "Explore" },
177 tool_response: {
178 status: "completed",
179 agentId: "a4d2c8f1e0b3a297",
180 content: [{ type: "text", text: "Found 12 endpoints in src/api." }],
181 resolvedModel: "claude-sonnet-4-5",
182 totalTokens: 12450,
183 totalDurationMs: 48211,
184 totalToolUseCount: 7,
185 usage: { input_tokens: 8320, output_tokens: 410 },
186 },
187 tool_use_id: "toolu_9",
188 },
189 agentLaunched: {
190 ...base,
191 hook_event_name: "PostToolUse",
192 tool_name: "Agent",
193 tool_input: { description: "Review the diff", prompt: "Review it", subagent_type: "code-reviewer", run_in_background: true },
194 tool_response: {
195 status: "async_launched",
196 agentId: "b5",
197 description: "Review the diff",
198 prompt: "Review it",
199 outputFile: "/tmp/b5.out",
200 resolvedModel: "claude-sonnet-4-5",
201 },
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: {
213 ...base,
214 hook_event_name: "PostToolUse",
215 tool_name: "Skill",
216 tool_input: { skill: "work-on-item", args: "42" },
217 tool_response: { success: true, commandName: "work-on-item" },
218 },
219};
220
221describe("subagents", () => {
222 test("SubagentStart starts a session of its own for the subagent", () => {
223 const job = plan(fixtures.subagentStart, {});
224 assert.deepEqual(job.agent, { id: "agent-def456", type: "Explore", start: true });
225 assert.deepEqual(job.steps, []);
226 assert.equal(subagentHarnessId("abc-123", "agent-def456"), "abc-123/agent/def456");
227 assert.equal(subagentHarnessId("abc-123", "def456"), "abc-123/agent/def456", "the Agent tool's id names the same subagent");
228 });
229
230 test("SubagentStop reports its own transcript's usage and ends it with its final message, cut to the limit", () => {
231 const job = plan(fixtures.subagentStop, {});
232 assert.deepEqual(job.agent, { id: "def456", type: "Explore" });
233 assert.deepEqual(job.steps, [
234 { args: ["session", "heartbeat"], usage: "/t/abc-123/subagents/agent-def456.jsonl", only: true },
235 { args: ["session", "end", "--reason", "done", "--result=Analysis complete. Found 3 potential issues..."] },
236 ]);
237 // Without agent_transcript_path, its own beside its parent's.
238 const { agent_transcript_path, ...noPath } = fixtures.subagentStop;
239 assert.equal(plan(noPath, {}).steps[0].usage, join("/t", "subagents", "agent-def456.jsonl"));
240 const long = plan({ ...fixtures.subagentStop, last_assistant_message: "z".repeat(RESULT_LIMIT * 2) }, {});
241 assert.equal(long.steps.at(-1).args.at(-1).length, "--result=".length + RESULT_LIMIT);
242 const dash = plan({ ...fixtures.subagentStop, last_assistant_message: "- Found 3 issues" }, {});
243 assert.equal(dash.steps.at(-1).args.at(-1), "--result=- Found 3 issues", "a message that starts with a dash is still a value");
244 assert.equal(refusal(dash.steps.at(-1).args), null);
245 });
246
247 test("an Agent call gives its subagent the task, and once finished its final message, and nothing else of its answer", () => {
248 const job = plan(fixtures.agentCompleted, {});
249 assert.deepEqual(job.subagent, {
250 id: "a4d2c8f1e0b3a297",
251 type: "Explore",
252 task: "Find API endpoints",
253 prompt: "Find all API endpoints",
254 model: "claude-sonnet-4-5",
255 result: "Found 12 endpoints in src/api.",
256 });
257 assert.deepEqual(job.steps, [{ args: ["session", "log", "--kind", "tool_call", "--", "Agent: Find API endpoints"] }]);
258 assert.ok(!JSON.stringify(job).includes("12450") && !JSON.stringify(job).includes("8320"));
259 const launched = plan(fixtures.agentLaunched, {});
260 assert.equal(launched.subagent.id, "b5");
261 assert.equal(launched.subagent.result, null, "a background subagent reports at SubagentStop");
262 assert.equal(plan(fixtures.agentCompleted, { G1T_RECORD_PROMPTS: "0" }).subagent.prompt, null);
263 assert.equal(agentResult({ content: "plain" }), "plain");
264 });
265
266 test("what a subagent does is its own session's, and the files it writes are touched", () => {
267 const job = plan(fixtures.inSubagent, {});
268 assert.deepEqual(job.agent, { id: "agent-def456", type: "Explore" });
269 assert.deepEqual(job.steps, [
270 { args: ["session", "log", "--kind", "tool_call", "--", "Edit: src/api/routes.ts"] },
271 { args: ["session", "touch", "--file=src/api/routes.ts"] },
272 ]);
273 assert.ok(!JSON.stringify(job).includes("SECRET PATCH"));
274 });
275
276 test("a skill is its name only", () => {
277 assert.deepEqual(plan(fixtures.skill, {}).steps, [{ args: ["session", "log", "--kind", "skill", "--", "work-on-item"], skill: "work-on-item" }]);
278 });
279
280 test("branches made, commits, claims and g1t's MCP tools are touched", () => {
281 const bash = (command) => plan({ ...base, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command } }, {});
282 assert.deepEqual(bash("git checkout -b 42-fix").steps.at(-1), { args: ["session", "touch", "--branch", "42-fix"] });
283 assert.deepEqual(bash('git commit -m "x" --trailer "G1t-Session: $G1T_SESSION"').steps.at(-1), { touchHead: true });
284 assert.deepEqual(bash("g1t work claim 42").steps.at(-1), { args: ["session", "touch", "--item", "42"] });
285 const mcp = plan(
286 { ...base, hook_event_name: "PostToolUse", tool_name: "mcp__plugin_g1t_g1t__work_item", tool_input: { action: "claim", workspace: "a", number: 7 } },
287 {},
288 );
289 assert.equal(mcp.item, 7);
290 assert.equal(branchFromCommand("git switch -c feat/x && echo"), "feat/x");
291 assert.equal(branchFromCommand("git branch -d old"), null);
292 assert.equal(isGitCommit("git -C repo commit -am x"), true);
293 assert.equal(g1tTool("mcp__g1t__session"), "session");
294 assert.equal(g1tTool("mcp__plugin_g1t_g1t__work_item"), "work_item");
295 assert.equal(g1tTool("mcp__github__issue"), null);
296 });
297
298 test("a hand-off's work item comes with the session", () => {
299 assert.equal(plan({ ...base, hook_event_name: "SessionStart" }, { G1T_ITEM: "12" }).item, 12);
300 });
301});
302
303describe("summaries", () => {
304 test("say what a tool was called with, in one short line", () => {
305 assert.equal(summarizeTool("Edit", { file_path: "/work/repo/src/a.ts", old_string: "x", new_string: "y" }, "/work/repo"), "Edit: src/a.ts");
306 assert.equal(summarizeTool("Grep", { pattern: "TODO", path: "src" }, "/w"), "Grep: TODO in src");
307 // From the top of the working copy, wherever the shell has moved to.
308 assert.equal(repoPath("/work/repo/apps/web/app/a.ts", "/work/repo/apps/web", "/work/repo"), "apps/web/app/a.ts");
309 assert.equal(repoPath("app/a.ts", "/work/repo/apps/web", "/work/repo"), "apps/web/app/a.ts");
310 assert.equal(repoPath("/elsewhere/a.ts", "/work/repo/apps/web", "/work/repo"), null);
311 assert.equal(repoPath("/work/repo/src/a.ts", "/work/repo", null), "src/a.ts");
312 assert.equal(summarizeTool("WebFetch", { url: "https://example.com", prompt: "p" }), "WebFetch: https://example.com");
313 assert.equal(summarizeTool("Bash", { command: "echo one\necho two" }), "Bash: echo one …");
314 assert.equal(summarizeTool("mcp__g1t__work_item", { action: "get", number: 4 }), "mcp__g1t__work_item: get");
315 assert.ok(summarizeTool("Bash", { command: "y".repeat(1000) }).length <= 200);
316 });
317
318 test("hide what looks like a secret", () => {
319 const line = redact('curl -H "Authorization: Bearer g1t_abcdefghijklmnop" https://u:pw@x.com GITHUB_TOKEN=ghp_123456789012 --token abc');
320 assert.ok(!line.includes("abcdefghijklmnop"));
321 assert.ok(!line.includes("ghp_123456789012"));
322 assert.ok(!line.includes("u:pw@"));
323 assert.ok(!line.includes("--token abc"));
324 });
325
326 test("hide credentials wherever text is sent, and leave references alone", () => {
327 for (const [text, secret] of [
328 ["$env:G1T_TOKEN='abc123def456'; g1t whoami", "abc123def456"],
329 ["G1T_TOKEN=abc123def456 g1t whoami", "abc123def456"],
330 ['{"password": "hunter2!"}', "hunter2"],
331 ["curl -u admin:pa55word https://x", "pa55word"],
332 ["open https://x.com/cb?state=1&token=t0k3n", "t0k3n"],
333 ["jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N", "dozjgNryP4J3"],
334 ["-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5v\n-----END OPENSSH PRIVATE KEY-----", "b3BlbnNzaC1"], // g1t:allow-secret
335 ["here is my key: sk-ant-api03-abcDEF123456ghiJKL, use it", "abcDEF123456ghiJKL"],
336 ]) {
337 const out = redact(text);
338 assert.ok(!out.includes(secret), `${secret} in ${out}`);
339 assert.ok(out.includes("[redacted]"), out);
340 }
341 for (const kept of [
342 "A path is not a secret: the rule read it as one",
343 "password: the one you set",
344 "TOKEN=$G1T_TOKEN",
345 "token: ${{ secrets.DEPLOY }}",
346 "fn f(token: String)",
347 "npm_config_user_agent",
348 "git show 58def4040e93a1dcda5f388f55360f3cd46cd97e",
349 ]) {
350 assert.equal(redact(kept), kept);
351 }
352 });
353
354 test("find the work item in a branch name", () => {
355 assert.equal(itemFromBranch("42-fix-login"), 42);
356 assert.equal(itemFromBranch("issue-7"), 7);
357 assert.equal(itemFromBranch("item-8"), 8);
358 assert.equal(itemFromBranch("fix/123-thing"), 123);
359 assert.equal(itemFromBranch("main"), null);
360 assert.equal(itemFromBranch("release/1.2"), null);
361 assert.equal(itemFromBranch("HEAD"), null);
362 assert.equal(itemFromCommand("g1t session attach --item 9"), 9);
363 assert.equal(itemFromCommand("g1t pr create --item=12 --draft"), 12);
364 assert.equal(isGitPush("cd x && git -C repo push"), true);
365 assert.equal(isGitPush("git pushd"), false);
366 assert.equal(isG1tRemote(["remote.origin.url https://g1t.sh/a/b.git"], {}), true);
367 assert.equal(isG1tRemote(["remote.origin.url https://example.com/a/b.git"], {}), false);
368 assert.equal(isG1tRemote(["remote.origin.url https://git.acme.dev/a/b.git"], { G1T_HOST: "git.acme.dev" }), true);
369 });
370});
371
372describe("the plugin's files", () => {
373 const root = join(HERE, "..", "..", "..");
374 test("parse as JSON", () => {
375 for (const file of [
376 ".claude-plugin/marketplace.json",
377 "plugins/claude-code/.claude-plugin/plugin.json",
378 "plugins/claude-code/.mcp.json",
379 "plugins/claude-code/hooks/hooks.json",
380 ]) {
381 assert.doesNotThrow(() => JSON.parse(readFileSync(join(root, file), "utf8")), file);
382 }
383 });
384
385 test("the AGENTS.md snippet is the one in the docs", () => {
386 const snippet = readFileSync(join(root, "plugins/other-harnesses/AGENTS.snippet.md"), "utf8").replaceAll("\r\n", "\n");
387 const guide = readFileSync(join(root, "apps/docs/src/content/docs/guides/claude-code-plugin.md"), "utf8").replaceAll("\r\n", "\n");
388 const block = /```md title="AGENTS.md"\n([\s\S]*?)```/.exec(guide)?.[1];
389 assert.equal(block, snippet);
390 });
391});
392
393describe("with a working copy", () => {
394 let dir, env, log;
395
396 const git = (...args) => spawnSync("git", args, { cwd: dir, encoding: "utf8" });
397 const allCalls = () =>
398 existsSync(log)
399 ? readFileSync(log, "utf8")
400 .trim()
401 .split("\n")
402 .filter(Boolean)
403 .map((l) => JSON.parse(l))
404 : [];
405 // The calls that do something: not the version check before them.
406 const calls = () => allCalls().filter((c) => c.args[0] !== "--version");
407
408 beforeEach(() => {
409 dir = mkdtempSync(join(tmpdir(), "g1t-hook-"));
410 log = join(dir, "calls.jsonl");
411 git("init", "-q", "-b", "42-fix-login");
412 git("remote", "add", "origin", "https://g1t.sh/acme/app.git");
413 env = { PATH: process.env.PATH, G1T_BIN: FAKE, FAKE_G1T_LOG: log, CLAUDE_PLUGIN_DATA: join(dir, ".data") };
414 });
415 afterEach(() => {
416 // Every call the hooks made is one the real CLI takes (the stand-in refuses the rest).
417 const refused = allCalls().filter((c) => refusal(c.args));
418 // And none let the CLI claim every uncommitted file as this session's (the stand-in logs `touch` then).
419 const guessing = allCalls().filter((c) => c.touch !== undefined);
420 rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
421 assert.deepEqual(refused, [], "the CLI refuses these calls");
422 assert.deepEqual(guessing, [], "these calls let the CLI guess what was touched");
423 });
424
425 test("SessionStart gives Claude the branch's work item's work context", () => {
426 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }, env);
427 const context = output.hookSpecificOutput.additionalContext;
428 assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart");
429 assert.match(context, /work item #42/);
430 assert.match(context, /Definition of done: it works/);
431 assert.deepEqual(calls()[0].args, ["work", "view", "42"]);
432 assert.equal(job.start, true);
433 });
434
435 test("the background half starts the session once, then logs into it", () => {
436 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
437 const { job } = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "fix the login" }, env);
438 // No SessionStart marked this session as one in a g1t working copy.
439 assert.equal(job, null);
440 work(plan({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "fix the login" }, env), env);
441 const [start, logged] = calls().filter((call) => call.args[1] !== "get_session");
442 assert.deepEqual(start.args, ["session", "start", "--harness", "claude_code", "--harness-session-id", "abc-123", "--json"]);
443 assert.deepEqual(logged, { args: ["session", "log", "--kind", "prompt", "--", "fix the login"], session: "ses_fake01" });
444 assert.equal(readFileSync(sessionFiles(base.session_id, env).id, "utf8"), "ses_fake01");
445 });
446
447 test("a shell command's writes are this session's; what was uncommitted before it is not", () => {
448 const { job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
449 work(job, env);
450 // Another session's edit, uncommitted in the same working copy.
451 writeFileSync(join(dir, "theirs.md"), "theirs");
452 const command = { ...base, cwd: dir, tool_name: "Bash", tool_use_id: "tu_1", tool_input: { command: "sed -i s/a/b/ mine.md" } };
453 hook({ ...command, hook_event_name: "PreToolUse" }, env);
454 writeFileSync(join(dir, "mine.md"), "mine");
455 const after = hook({ ...command, hook_event_name: "PostToolUse" }, env).job;
456 const touched = after.steps.filter((step) => step.args?.[1] === "touch").flatMap((step) => step.args.filter((arg) => arg.startsWith("--file=")));
457 assert.ok(touched.includes("--file=mine.md"), String(touched));
458 assert.ok(!touched.includes("--file=theirs.md"), String(touched));
459 // Read once: a command run again under the same id finds nothing kept.
460 assert.equal(existsSync(sessionFiles(base.session_id, env).shell("tu_1")), false);
461 });
462
463 test("the CLI never guesses touched files from the whole working copy", () => {
464 const { job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
465 work(job, env);
466 work(plan({ ...base, cwd: dir, hook_event_name: "Stop" }, env), env);
467 const heartbeat = calls().find((call) => call.args[0] === "session" && call.args[1] === "heartbeat");
468 assert.ok(heartbeat, "a heartbeat was sent");
469 assert.equal(heartbeat.touch, undefined);
470 });
471
472 test("background retrieval reaches the next tool without auto-acknowledging", () => {
473 // A CLI that acknowledges: an older one is told to update instead (below).
474 env.FAKE_G1T_VERSION = "0.4.0";
475 env.FAKE_G1T_UPDATES = JSON.stringify([{ id: "upd_real", kind: "overlap.detected", data: { paths: ["src/api.ts"] } }]);
476 const event = { ...base, cwd: dir, hook_event_name: "SessionStart" };
477 const { job } = hook(event, env);
478 work(job, env);
479 const next = { ...event, hook_event_name: "PreToolUse", tool_name: "Read", tool_input: { file_path: "src/api.ts" } };
480 const first = hook(next, env).output;
481 assert.match(first.hookSpecificOutput.additionalContext, /upd_real/);
482 assert.equal(first.hookSpecificOutput.hookEventName, "PreToolUse");
483 // The next tool is not told again at once; the next prompt is.
484 assert.equal(hook(next, env).output, null);
485 const prompt = hook({ ...event, hook_event_name: "UserPromptSubmit", prompt: "go on" }, env).output;
486 assert.match(prompt.hookSpecificOutput.additionalContext, /upd_real/);
487 assert.ok(calls().some((call) => call.args[1] === "get_session" && call.args.includes("after=4294967295")));
488 assert.ok(!calls().some((call) => call.args[1] === "record_session_entries"));
489 });
490
491 test("hooks after SessionStart record; SessionEnd forgets the session", () => {
492 hook({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }, env);
493 const files = sessionFiles(base.session_id, env);
494 assert.ok(existsSync(files.marker));
495 const { job } = hook({ ...base, cwd: dir, hook_event_name: "Stop" }, env);
496 work(job, env);
497 work(plan({ ...base, cwd: dir, hook_event_name: "SessionEnd", reason: "clear" }, env), env);
498 const args = calls().map((c) => c.args.join(" "));
499 assert.ok(args.includes("session heartbeat"));
500 assert.ok(args.includes("session end --reason clear"));
501 assert.ok(!existsSync(files.marker) && !existsSync(files.id));
502 });
503
504 test("a push that reached the remote updates the head commit", () => {
505 git("-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "commit", "-q", "--allow-empty", "-m", "one");
506 git("update-ref", "refs/remotes/origin/42-fix-login", "HEAD");
507 const head = git("rev-parse", "HEAD").stdout.trim();
508 work(plan({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "git push" } }, env), env);
509 const update = calls().find((c) => c.args[0] === "api");
510 assert.deepEqual(update.args, ["api", "update_session", "-f", "id=ses_fake01", "-f", `head_commit=${head}`, "--silent"]);
511 });
512
513 test("each subagent is a session of its own under this one, whatever order its hooks arrive in", () => {
514 const at = (event) => ({ ...event, cwd: dir });
515 hook(at({ ...base, hook_event_name: "SessionStart", source: "startup" }), env);
516 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
517 // Claude calls Agent; its task waits for the subagent.
518 const pre = hook(at({ ...base, hook_event_name: "PreToolUse", tool_name: "Agent", tool_input: fixtures.agentCompleted.tool_input }), env);
519 assert.equal(pre.output, null);
520 const started = hook(at(fixtures.subagentStart), env);
521 assert.match(started.output.hookSpecificOutput.additionalContext, /session of your own/);
522 assert.match(started.output.hookSpecificOutput.additionalContext, /g1t session list --item 42 --subagents|g1t session list --subagents/);
523 assert.equal(started.job.pair, true, "paired with its Agent call in the background half");
524 work(started.job, env);
525 assert.equal(started.job.agent.task, "Find API endpoints", "no files of the subagent's: the oldest call of its type");
526 // What it does goes to its own session.
527 const edited = { ...fixtures.inSubagent.tool_input, file_path: join(dir, "src", "api", "routes.ts") };
528 work(hook(at({ ...fixtures.inSubagent, tool_input: edited }), env).job, env);
529 // Its g1t commands act as it.
530 const bash = hook(
531 at({
532 ...base,
533 hook_event_name: "PreToolUse",
534 agent_id: "agent-def456",
535 agent_type: "Explore",
536 tool_name: "Bash",
537 tool_input: { command: "g1t work claim 42" },
538 }),
539 env,
540 );
541 assert.equal(bash.output.hookSpecificOutput.updatedInput.command, "export G1T_SESSION=ses_sub_def456; g1t work claim 42");
542 const mcp = hook(
543 at({
544 ...base,
545 hook_event_name: "PreToolUse",
546 agent_id: "agent-def456",
547 tool_name: "mcp__plugin_g1t_g1t__work_item",
548 tool_input: { action: "claim", workspace: "acme", number: 42 },
549 }),
550 env,
551 );
552 assert.equal(mcp.output.hookSpecificOutput.updatedInput.session_id, "ses_sub_def456");
553 // Outside a subagent, a command is left alone.
554 assert.equal(hook(at({ ...base, hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command: "g1t work claim 42" } }), env).output, null);
555 work(hook(at(fixtures.subagentStop), env).job, env);
556 // A late SubagentStart starts it again, which g1t answers with the same, ended, session.
557 work(hook(at(fixtures.subagentStart), env).job, env);
558 const log = calls();
559 const childStarts = log.filter((c) => c.args[1] === "start" && c.args.includes("--parent"));
560 assert.ok(childStarts.length >= 2);
561 const first = childStarts[0].args;
562 assert.deepEqual(first.slice(0, 8), [
563 "session",
564 "start",
565 "--harness",
566 "claude_code",
567 "--harness-session-id",
568 "abc-123/agent/def456",
569 "--parent",
570 "ses_fake01",
571 ]);
572 assert.ok(first.includes("--no-remember"));
573 assert.ok(first.includes("--agent-type=Explore"));
574 assert.ok(first.includes("--task=Find API endpoints"));
575 const edit = log.find((c) => c.args[2] === "--kind" && c.args.at(-1) === "Edit: src/api/routes.ts");
576 assert.equal(edit.session, "ses_sub_def456");
577 const touched = log.find((c) => c.args[1] === "touch");
578 assert.deepEqual(touched, { args: ["session", "touch", "--file=src/api/routes.ts"], session: "ses_sub_def456" });
579 const ended = log.find((c) => c.args[1] === "end");
580 assert.deepEqual(ended, {
581 args: ["session", "end", "--reason", "done", "--result=Analysis complete. Found 3 potential issues..."],
582 session: "ses_sub_def456",
583 });
584 });
585
586 test("five subagents of one type started at once each get their own Agent call's task, whatever order they start in", () => {
587 // Claude Code's transcript and, beside it, each subagent's files.
588 const transcript = join(dir, "projects", "abc-123.jsonl");
589 const subagents = join(dir, "projects", "abc-123", "subagents");
590 mkdirSync(subagents, { recursive: true });
591 writeFileSync(transcript, "");
592 const at = (event) => ({ ...event, cwd: dir, transcript_path: transcript });
593 hook(at({ ...base, hook_event_name: "SessionStart" }), env);
594 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
595 const n = [1, 2, 3, 4, 5];
596 // One message, five Agent calls of the same type.
597 for (const i of n) {
598 const tool_input = { description: `Task ${i}`, prompt: `Do thing ${i}, and only thing ${i}.`, subagent_type: "general-purpose" };
599 hook(at({ ...base, hook_event_name: "PreToolUse", tool_name: "Agent", tool_input, tool_use_id: `toolu_${i}` }), env);
600 }
601 const files = (i, { meta = true, first = true } = {}) => {
602 if (meta)
603 writeFileSync(
604 join(subagents, `agent-a${i}.meta.json`),
605 JSON.stringify({ agentType: "general-purpose", description: `Task ${i}`, toolUseId: `toolu_${i}` }),
606 );
607 if (first)
608 writeFileSync(
609 join(subagents, `agent-a${i}.jsonl`),
610 `${JSON.stringify({ type: "user", agentId: `a${i}`, message: { role: "user", content: `Do thing ${i}, and only thing ${i}.` } })}\n{"type":"attachment"}\n`,
611 );
612 };
613 // They start in another order: one with its meta file, one with only its transcript (by prompt), the rest with both.
614 files(4);
615 files(2, { meta: false });
616 files(5);
617 files(1);
618 files(3, { first: false });
619 for (const i of [4, 2, 5, 1, 3])
620 work(hook(at({ ...base, hook_event_name: "SubagentStart", agent_id: `a${i}`, agent_type: "general-purpose" }), env).job, env);
621 const starts = calls().filter((c) => c.args[1] === "start" && c.args.includes("--parent"));
622 assert.equal(starts.length, 5);
623 for (const i of n) {
624 const start = starts.find((c) => c.args.includes(`abc-123/agent/a${i}`)).args;
625 assert.ok(start.includes(`--task=Task ${i}`), `subagent ${i}: ${start.join(" ")}`);
626 assert.ok(start.includes(`--prompt=Do thing ${i}, and only thing ${i}.`), `subagent ${i}'s own prompt`);
627 }
628 assert.equal(readdirSync(join(env.CLAUDE_PLUGIN_DATA, "sessions")).filter((f) => f.includes(".task.")).length, 0, "every task taken once");
629 });
630
631 test("a pending task is never handed to two subagents, and an exact subagent never takes another's", () => {
632 const files = sessionFiles(base.session_id, env);
633 const input = (i) => ({ description: `Task ${i}`, prompt: `Prompt ${i}`, subagent_type: "general-purpose" });
634 for (const i of [1, 2, 3]) rememberTask(files, input(i), `toolu_${i}`);
635 assert.equal(takeTask(files, { type: "general-purpose", toolUseId: "toolu_2" }).task, "Task 2");
636 assert.equal(takeTask(files, { type: "general-purpose", toolUseId: "toolu_2" }), null, "taken once");
637 assert.equal(takeTask(files, { type: "general-purpose", prompt: "Prompt 2" }), null, "nor by its prompt");
638 assert.equal(takeTask(files, { type: "general-purpose", toolUseId: "toolu_9" }), null, "an unknown call takes nothing rather than a guess");
639 assert.equal(takeTask(files, { type: "general-purpose", prompt: " Prompt 3\n" }).task, "Task 3", "the prompt as the transcript has it");
640 // With no files of the subagent's (an older Claude Code): the oldest of its type, as before.
641 assert.equal(takeTask(files, "general-purpose").task, "Task 1");
642 assert.equal(takeTask(files, "general-purpose"), null);
643 // An Agent call answered takes its own task back, so no later subagent guesses it.
644 rememberTask(files, input(4), "toolu_4");
645 work({ ...plan({ ...fixtures.agentLaunched, cwd: dir, tool_use_id: "toolu_4" }, env) }, env);
646 assert.equal(takeTask(files, "general-purpose"), null);
647 });
648
649 test("a subagent's files give its task even when its Agent call was not kept", () => {
650 const subagents = join(dir, "t", "subagents");
651 mkdirSync(subagents, { recursive: true });
652 writeFileSync(join(subagents, "agent-a7.meta.json"), JSON.stringify({ description: "Look around", toolUseId: "toolu_7" }));
653 writeFileSync(
654 join(subagents, "agent-a7.jsonl"),
655 `${JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text: "Look around the repo" }] } })}\n`,
656 );
657 const files = sessionFiles(base.session_id, env);
658 rememberTask(files, { description: "Someone else's", prompt: "not yours", subagent_type: "Explore" }, "toolu_8");
659 const agent = pairSubagent({ id: "agent-a7", type: "Explore" }, files, join(dir, "t.jsonl"), env);
660 assert.deepEqual(agent, { id: "agent-a7", type: "Explore", task: "Look around", prompt: "Look around the repo" });
661 assert.equal(takeTask(files, "Explore").task, "Someone else's", "left for its own subagent");
662 assert.equal(pairSubagent({ id: "a7", type: "Explore" }, files, join(dir, "t.jsonl"), { G1T_RECORD_PROMPTS: "0" }).prompt, undefined);
663 });
664
665 test("a session started with no g1t remote is recorded once a command adds one", () => {
666 git("remote", "remove", "origin");
667 const at = (event) => ({ ...base, cwd: dir, ...event });
668 assert.deepEqual(hook(at({ hook_event_name: "SessionStart", source: "startup" }), env), { output: null, job: null });
669 assert.equal(hook(at({ hook_event_name: "UserPromptSubmit", prompt: "Build me a todo app. Use React." }), env).job, null);
670 assert.equal(hook(at({ hook_event_name: "UserPromptSubmit", prompt: "and make it blue" }), env).job, null);
671 const bash = (command) => at({ hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command } });
672 assert.equal(hook(at({ hook_event_name: "PostToolUse", tool_name: "Write", tool_input: { file_path: join(dir, "a.ts") } }), env).job, null);
673 assert.equal(hook(bash("npm init -y"), env).job, null);
674 assert.equal(hook(bash("git remote -v"), env).job, null, "looked, and there is none yet");
675 assert.deepEqual(calls(), [], "nothing recorded without a g1t remote");
676 // The agent makes the repository and adds it as the remote.
677 git("remote", "add", "origin", "https://g1t.sh/acme/app.git");
678 const { output, job } = hook(bash("g1t repo create acme/app --private && git remote add origin https://g1t.sh/acme/app.git"), env);
679 assert.equal(job.start, true);
680 assert.equal(output.hookSpecificOutput.hookEventName, "PostToolUse");
681 assert.match(output.hookSpecificOutput.additionalContext, /work item #42/, "told what SessionStart would have told it");
682 work(job, env);
683 const recorded = calls().filter((c) => c.args[0] === "session");
684 assert.deepEqual(recorded[0].args, ["session", "start", "--harness", "claude_code", "--harness-session-id", "abc-123", "--json"]);
685 assert.ok(recorded.some((c) => c.args[1] === "log" && c.args.at(-1).startsWith("Bash: g1t repo create acme/app")));
686 // g1t names it, from what it records from here on: no title is sent.
687 assert.ok(!recorded.some((c) => c.args[1] === "attach"));
688 const next = hook(at({ hook_event_name: "UserPromptSubmit", prompt: "Now add tests" }), env).job;
689 assert.ok(next && !next.start);
690 assert.deepEqual(
691 next.steps.map((s) => s.args.slice(0, 4)),
692 [["session", "log", "--kind", "prompt"]],
693 );
694 });
695
696 test("a session given a g1t remote between prompts is recorded at the next one", () => {
697 git("remote", "set-url", "origin", "https://example.com/acme/app.git");
698 const at = (event) => ({ ...base, cwd: dir, ...event });
699 hook(at({ hook_event_name: "SessionStart" }), env);
700 assert.equal(hook(at({ hook_event_name: "UserPromptSubmit", prompt: "/clear" }), env).job, null);
701 git("remote", "set-url", "origin", "https://g1t.sh/acme/app.git");
702 const { job } = hook(at({ hook_event_name: "UserPromptSubmit", prompt: "fix the login" }), env);
703 assert.equal(job.start, true);
704 assert.equal(job.steps.at(-1).args.at(-1), "fix the login", "its prompt is recorded, and g1t names the session from it");
705 assert.ok(existsSync(sessionFiles(base.session_id, env).marker));
706 assert.ok(!existsSync(sessionFiles(base.session_id, env).unrecorded));
707 });
708
709 test("only commands that may add a remote look for one", () => {
710 for (const command of [
711 "git remote add origin https://g1t.sh/a/b.git",
712 "git -C app push -u origin main",
713 "git init",
714 "g1t repo create a/b",
715 "cd x && git clone https://g1t.sh/a/b",
716 ]) {
717 assert.equal(mayAddRemote(command), true, command);
718 }
719 for (const command of ["git status", "npm install", "g1t work list", "echo push", undefined]) assert.equal(mayAddRemote(command), false, String(command));
720 });
721
722 test("a subagent whose stop arrives first is started, then ended", () => {
723 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
724 work(hook({ ...fixtures.subagentStop, cwd: dir }, env).job, env);
725 const [, start, end] = calls().filter((c) => c.args[0] === "session");
726 assert.ok(start.args.includes("--parent"));
727 assert.equal(end.args[1], "end");
728 assert.equal(end.session, "ses_sub_def456");
729 });
730
731 test("an Agent call that finished ends its subagent with what it reported", () => {
732 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
733 work(hook({ ...fixtures.agentCompleted, cwd: dir }, env).job, env);
734 const log = calls().filter((c) => c.args[0] === "session");
735 assert.equal(log.find((c) => c.args[1] === "log").session, "ses_fake01", "the Agent call is the parent's");
736 const end = log.find((c) => c.args[1] === "end");
737 assert.deepEqual(end, { args: ["session", "end", "--reason", "done", "--result=Found 12 endpoints in src/api."], session: "ses_sub_a4d2c8f1e0b3a297" });
738 });
739
740 test("a hand-off names its work item at the start", () => {
741 git("checkout", "-q", "-b", "main");
742 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, { ...env, G1T_ITEM: "12" });
743 assert.match(output.hookSpecificOutput.additionalContext, /work item #12 \(from the work handed to it\)/);
744 assert.match(output.hookSpecificOutput.additionalContext, /G1t-Session/);
745 work(job, env);
746 const start = calls().find((c) => c.args[1] === "start");
747 assert.ok(start.args.includes("--item") && start.args.includes("12"));
748 });
749
750 test("a missing CLI records nothing and says so once", () => {
751 const missing = { ...env, G1T_BIN: join(dir, "no-such-g1t") };
752 const first = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, missing);
753 assert.match(first.output.systemMessage, /not installed/);
754 assert.equal(first.job, null);
755 const second = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, missing);
756 assert.equal(second.output, null);
757 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "Stop" }, missing).job, null);
758 assert.deepEqual(calls(), []);
759 });
760
761 test("a signed-out CLI is said once, at the next prompt", () => {
762 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, { ...env, CLAUDE_PLUGIN_DATA: env.CLAUDE_PLUGIN_DATA });
763 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, { ...env, FAKE_G1T_EXIT: "4" });
764 const first = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env);
765 assert.match(first.output.systemMessage, /not signed in/);
766 const second = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env);
767 assert.equal(second.output, null);
768 });
769
770 test("outside a g1t repository nothing happens", () => {
771 git("remote", "set-url", "origin", "https://example.com/acme/app.git");
772 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
773 assert.equal(output, null);
774 assert.equal(job, null);
775 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "Stop" }, env).job, null);
776 assert.deepEqual(calls(), []);
777 });
778
779 test("the script answers SessionStart on stdin quickly, as JSON", async () => {
780 const started = Date.now();
781 const out = spawnSync(process.execPath, [SCRIPT], {
782 input: JSON.stringify({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }),
783 encoding: "utf8",
784 env: { ...process.env, ...env },
785 });
786 const took = Date.now() - started;
787 assert.equal(out.status, 0);
788 assert.match(JSON.parse(out.stdout).hookSpecificOutput.additionalContext, /work item #42/);
789 assert.ok(took < 3000, `took ${took} ms`);
790 // The detached half starts the session after the hook has returned.
791 const id = sessionFiles(base.session_id, env).id;
792 for (let i = 0; i < 100 && !existsSync(id); i++) await new Promise((done) => setTimeout(done, 50));
793 assert.equal(readFileSync(id, "utf8"), "ses_fake01");
794 await new Promise((done) => setTimeout(done, 200));
795 });
796
797 test("the script prints nothing for a prompt, and never fails on bad input", () => {
798 const prompt = spawnSync(process.execPath, [SCRIPT], {
799 input: JSON.stringify({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hello" }),
800 encoding: "utf8",
801 env: { ...process.env, ...env },
802 });
803 assert.equal(prompt.status, 0);
804 assert.equal(prompt.stdout, "");
805 const bad = spawnSync(process.execPath, [SCRIPT], { input: "not json", encoding: "utf8", env: { ...process.env, ...env } });
806 assert.equal(bad.status, 0);
807 assert.equal(bad.stdout, "");
808 });
809
810 test("a CLI older than the plugin needs records nothing and says so once, with how to update it", () => {
811 const old = { ...env, FAKE_G1T_VERSION: "0.3.1" };
812 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, old);
813 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, old);
814 work(plan({ ...base, cwd: dir, hook_event_name: "Stop" }, old), old);
815 // SessionStart still asks it for the work item's context.
816 assert.deepEqual(
817 calls().map((c) => c.args.join(" ")),
818 ["work view 42"],
819 "nothing is recorded with it",
820 );
821 assert.equal(allCalls().filter((c) => c.args[0] === "--version").length, 1, "the version is asked once for each build of the CLI");
822 const first = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, old);
823 assert.match(first.output.systemMessage, /g1t CLI is 0\.3\.1, and the plugin needs 0\.4\.0 or later/);
824 assert.match(first.output.systemMessage, /curl -fsSL https:\/\/g1t\.sh\/install \| sh/);
825 assert.match(first.output.systemMessage, /irm https:\/\/g1t\.sh\/install\.ps1 \| iex/);
826 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, old).output, null);
827 assert.equal(older("0.3.1", MIN_CLI), true);
828 assert.equal(older("0.3.7", MIN_CLI), true);
829 assert.equal(older("0.4.0", MIN_CLI), false);
830 assert.equal(older("0.10.0", MIN_CLI), false);
831 assert.equal(older("1.0.0", MIN_CLI), false);
832 });
833
834 test("a CLI that refuses a command (exit 2) is said once, as one to update", () => {
835 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
836 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, { ...env, FAKE_G1T_EXIT: "2" });
837 const first = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env);
838 assert.match(first.output.systemMessage, /refused `g1t session start`/);
839 assert.match(first.output.systemMessage, /installer again/);
840 assert.equal(hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "hi" }, env).output, null);
841 });
842
843 test("the stand-in CLI refuses what the real one refuses", () => {
844 assert.equal(CONTRACT.minimum_version, MIN_CLI, "the hooks ask for the CLI the contract needs");
845 assert.match(refusal(["session", "log", "--kind", "tool-calls", "--", "x"]), /takes prompt, tool_call, skill/);
846 assert.match(refusal(["session", "log", "--kind", "note", "--", "x"]), /not note/, "the hooks never send a note");
847 assert.match(refusal(["session", "end", "--result", "- a list"]), /unexpected argument/);
848 assert.equal(refusal(["session", "end", "--result=- a list"]), null);
849 assert.match(refusal(["session", "touch"]), /needs one of/);
850 assert.match(refusal(["session", "heartbeat", "--now"]), /takes no --now/);
851 assert.match(refusal(["session", "start", "--harness", "claude-managed-agents", "--harness-session-id", "x"]), /takes claude_code/);
852 assert.match(refusal(["work", "view", "abc"]), /not abc/);
853 assert.match(refusal(["session", "pause"]), /takes 0 argument/);
854 assert.equal(refusal(["api", "update_session", "-f", "id=ses_1", "-f", "head_commit=abc", "--silent"]), null);
855 // --usage-json is newer than the oldest CLI the hooks take: only a CLI that has it is given it.
856 const usage = ["session", "heartbeat", '--usage-json=[{"model":"claude-opus-5-5","input_tokens":1}]'];
857 assert.equal(refusal(usage, CONTRACT, USAGE_CLI), null);
858 assert.match(refusal(usage, CONTRACT, MIN_CLI), /takes no --usage-json/);
859 assert.equal(CONTRACT.commands.find((c) => c.command.join(" ") === "session heartbeat").since["--usage-json"], USAGE_CLI);
860 });
861
862 test("a session's usage is reported from its own transcript, to a CLI that takes it, and only the counts", () => {
863 const transcript = join(dir, "t.jsonl");
864 writeFileSync(
865 transcript,
866 `${JSON.stringify({ type: "user", message: { role: "user", content: "the secret plan" } })}\n${assistant("msg_1", "claude-opus-5-5", { input_tokens: 10, output_tokens: 20 })}\n`,
867 );
868 const subagent = join(dir, "agent-def456.jsonl");
869 writeFileSync(subagent, `${assistant("msg_2", "claude-haiku-4-5", { input_tokens: 7 })}\n`);
870 const newer = { ...env, FAKE_G1T_VERSION: USAGE_CLI };
871 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, newer);
872 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, newer);
873 work(hook({ ...base, transcript_path: transcript, cwd: dir, hook_event_name: "Stop" }, newer).job, newer);
874 work(hook({ ...fixtures.subagentStop, transcript_path: transcript, agent_transcript_path: subagent, cwd: dir }, newer).job, newer);
875 const heartbeats = calls().filter((c) => c.args[1] === "heartbeat");
876 const usage = (call) => JSON.parse(call.args.find((a) => a.startsWith("--usage-json=")).slice("--usage-json=".length));
877 assert.equal(heartbeats[0].session, "ses_fake01");
878 assert.deepEqual(usage(heartbeats[0]), [
879 { model: "claude-opus-5-5", input_tokens: 10, output_tokens: 20, cache_write_5m_tokens: 0, cache_write_1h_tokens: 0, cache_read_tokens: 0 },
880 ]);
881 // The subagent's own, to its own session, before it ends; never its parent's.
882 assert.equal(heartbeats[1].session, "ses_sub_def456");
883 assert.deepEqual(
884 usage(heartbeats[1]).map((row) => [row.model, row.input_tokens]),
885 [["claude-haiku-4-5", 7]],
886 );
887 const order = calls()
888 .filter((c) => c.session === "ses_sub_def456")
889 .map((c) => c.args[1]);
890 assert.ok(order.indexOf("heartbeat") < order.indexOf("end"), String(order));
891 assert.ok(!allCalls().some((c) => c.args.join(" ").includes("secret plan")), "nothing of what the transcript says is sent");
892 // A CLI without --usage-json gets a plain heartbeat, and no extra one before a subagent ends.
893 rmSync(log, { force: true });
894 rmSync(join(env.CLAUDE_PLUGIN_DATA, "cli.json"), { force: true });
895 work(hook({ ...base, transcript_path: transcript, cwd: dir, hook_event_name: "Stop" }, env).job, env);
896 work(hook({ ...fixtures.subagentStop, transcript_path: transcript, agent_transcript_path: subagent, cwd: dir }, env).job, env);
897 assert.deepEqual(
898 calls()
899 .filter((c) => c.args[1] === "heartbeat")
900 .map((c) => c.args),
901 [["session", "heartbeat"]],
902 );
903 });
904
905 test("PowerShell commands are read as Bash ones are, and a subagent's act as its session", () => {
906 const ps = (command, extra = {}) => ({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "PowerShell", tool_input: { command }, ...extra });
907 assert.equal(plan(ps("g1t work claim 42"), env).item, 42);
908 assert.deepEqual(plan(ps("git checkout -b 42-fix; git status"), env).steps.at(-1), { args: ["session", "touch", "--branch", "42-fix"] });
909 assert.deepEqual(plan(ps("git commit -m x"), env).steps.at(-1), { touchHead: true });
910 assert.deepEqual(plan(ps("git push origin 42-fix"), env).steps.at(-1), { headCommit: true });
911 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
912 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
913 work(hook({ ...fixtures.subagentStart, cwd: dir }, env).job, env);
914 const pre = (tool_name, command) =>
915 hook({ ...base, cwd: dir, hook_event_name: "PreToolUse", agent_id: "agent-def456", agent_type: "Explore", tool_name, tool_input: { command } }, env)
916 .output;
917 assert.equal(pre("PowerShell", "g1t work claim 42").hookSpecificOutput.updatedInput.command, "$env:G1T_SESSION='ses_sub_def456'; g1t work claim 42");
918 assert.equal(pre("PowerShell", "g1t.exe session view").hookSpecificOutput.updatedInput.command, "$env:G1T_SESSION='ses_sub_def456'; g1t.exe session view");
919 assert.equal(pre("Bash", "echo $G1T_SESSION").hookSpecificOutput.updatedInput.command, "export G1T_SESSION=ses_sub_def456; echo $G1T_SESSION");
920 assert.equal(pre("PowerShell", "$env:G1T_SESSION='ses_other'; g1t work claim 42"), null, "a session the command sets itself is kept");
921 assert.equal(pre("PowerShell", "Get-ChildItem"), null, "other commands are left alone");
922 // The tool call is recorded as Claude wrote it.
923 const after = plan(ps("$env:G1T_SESSION='ses_sub_def456'; g1t work claim 42", { agent_id: "agent-def456" }), env);
924 assert.deepEqual(after.steps[0].args.at(-1), "PowerShell: g1t work claim 42");
925 assert.equal(summarizeTool("Bash", { command: "export G1T_SESSION=ses_1; g1t pr view" }), "Bash: g1t pr view");
926 });
927
928 test("a skill typed as /plugin:name is recorded once in its turn, however Claude Code then runs it", () => {
929 assert.equal(typedSkill("/g1t:work-on-item 42"), "g1t:work-on-item");
930 assert.equal(typedSkill("/g1t:status"), "g1t:status");
931 assert.equal(typedSkill("/clear"), null, "Claude Code's own commands are not skills");
932 assert.equal(typedSkill("look at /g1t:status"), null);
933 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
934 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
935 const typed = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "/g1t:work-on-item 42" }, env).job;
936 assert.deepEqual(
937 typed.steps.map((s) => s.args.slice(0, 4)),
938 [
939 ["session", "log", "--kind", "prompt"],
940 ["session", "log", "--kind", "skill"],
941 ],
942 );
943 work(typed, env);
944 const tool = hook(
945 { ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "g1t:work-on-item", args: "42" } },
946 env,
947 ).job;
948 work(tool, env);
949 const skills = calls().filter((c) => c.args.includes("skill"));
950 assert.equal(skills.length, 2);
951 assert.deepEqual(skills[0].args, ["session", "log", "--kind", "skill", "--key=skill:work-on-item:1", "--", "g1t:work-on-item"]);
952 assert.equal(skills[1].args[4], "--key=skill:work-on-item:1", "the same key: g1t keeps the first");
953 // Another skill in the turn has a key of its own; the next prompt is another turn.
954 const next = hook({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "g1t:coordinate" } }, env).job;
955 assert.equal(next.steps[0].key, "skill:coordinate:1");
956 hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "go on" }, { ...env, G1T_RECORD_PROMPTS: "0" });
957 const later = hook({ ...base, cwd: dir, hook_event_name: "PostToolUse", tool_name: "Skill", tool_input: { skill: "g1t:work-on-item" } }, env).job;
958 assert.equal(later.steps[0].key, "skill:work-on-item:2", "a turn whose prompt is not sent is still a turn");
959 // Prompts kept back: the typed skill's name is still recorded, the prompt is not.
960 const quiet = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: "/g1t:status" }, { ...env, G1T_RECORD_PROMPTS: "0" }).job;
961 assert.deepEqual(
962 quiet.steps.map((s) => s.args.at(-1)),
963 ["g1t:status"],
964 );
965 });
966
967 test("with no work item in sight, Claude is told the session is recorded and when to open or claim one", () => {
968 git("symbolic-ref", "HEAD", "refs/heads/fix-previews");
969 const { output } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart", source: "startup" }, env);
970 const context = output.hookSpecificOutput.additionalContext;
971 assert.match(context, /this session is recorded on g1t and shows to the team/);
972 assert.match(context, /Just work/);
973 assert.match(context, /`g1t work claim --title "…"`/);
974 assert.match(context, /Never open work items for questions, exploration or trivial fixes/);
975 // Told once that g1t names the session, and when to name it itself.
976 assert.ok(context.includes(TITLE_NOTE));
977 assert.match(context, /only if you can name the whole job/);
978 assert.doesNotMatch(context, /retitle/i);
979 assert.ok(context.length < 1100, `injected every session, so short: ${context.length}`);
980 assert.ok(!calls().some((c) => c.args[0] === "work"), "no work item's context is asked for");
981 });
982
983 test("Claude is never nudged to retitle, and no prompt sets a title", () => {
984 hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, env);
985 work({ cwd: dir, sid: base.session_id, start: true, steps: [] }, env);
986 for (const text of ["/clear", "[TEST] fix the preview builds. They time out.", "now the tests", "and the docs", "commit it", "push"]) {
987 const { output, job } = hook({ ...base, cwd: dir, hook_event_name: "UserPromptSubmit", prompt: text }, env);
988 assert.doesNotMatch(JSON.stringify(output ?? {}), /retitle|attach --title/, text);
989 if (job) work(job, env);
990 }
991 assert.ok(!calls().some((c) => c.args[1] === "attach" || (c.args[1] === "heartbeat" && c.args.includes("--json"))), "no title is set or looked for");
992 });
993
994 test("Claude's own commands get the session's id once it has started", () => {
995 const envFile = join(dir, "env.sh");
996 const { job } = hook({ ...base, cwd: dir, hook_event_name: "SessionStart" }, { ...env, CLAUDE_ENV_FILE: envFile });
997 assert.ok(!existsSync(envFile), "nothing is written before the session's id is known");
998 work(job, env);
999 // A plain assignment: Claude Code gives it to PowerShell commands too.
1000 assert.equal(readFileSync(envFile, "utf8"), "export G1T_SESSION=ses_fake01\nexport G1T_TOUCH=0\n");
1001 });
1002
1003 test("on a Node older than 18 nothing is recorded, and that is said once", () => {
1004 const at = (hook_event_name) => ({ ...base, cwd: dir, hook_event_name });
1005 assert.equal(oldNode(at("SessionStart"), env, "18.0.0"), undefined);
1006 const first = oldNode(at("SessionStart"), env, "16.20.2");
1007 assert.match(first.systemMessage, /need Node 18 or later, and `node` is v16\.20\.2/);
1008 assert.equal(oldNode(at("UserPromptSubmit"), env, "16.20.2"), null);
1009 assert.equal(oldNode(at("PostToolUse"), env, "16.20.2"), null);
1010 assert.deepEqual(calls(), []);
1011 });
1012});
1013
1014test("pending updates survive delivery and stay isolated between parent and child", () => {
1015 const dir = mkdtempSync(join(tmpdir(), "g1t-inbox-"));
1016 try {
1017 const env = { CLAUDE_PLUGIN_DATA: dir };
1018 const files = sessionFiles("harness", env);
1019 mkdirSync(files.dir, { recursive: true });
1020 writeFileSync(files.id, "ses_parent");
1021 writeFileSync(files.agent("child"), "ses_child");
1022 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "parent-update", kind: "overlap.detected", data: {} }]));
1023 writeFileSync(files.updates("ses_child"), JSON.stringify([{ id: "child-update", kind: "dependency.changed", data: {} }]));
1024 const event = { session_id: "harness" };
1025 const first = updateContext(event, env);
1026 assert.match(first, /parent-update/);
1027 assert.doesNotMatch(first, /child-update/);
1028 assert.equal(updateContext(event, env), first);
1029 // Before tools: shown once, again when it changes or after a while.
1030 const files2 = sessionFiles("harness", env);
1031 rmSync(files2.shown("ses_parent"), { force: true });
1032 assert.equal(updateContext(event, env, { throttle: true, now: 1000 }), first);
1033 assert.equal(updateContext(event, env, { throttle: true, now: 2000 }), null);
1034 assert.equal(updateContext(event, env, { throttle: true, now: 1000 + UPDATES_REPEAT_MS }), first);
1035 writeFileSync(
1036 files.updates("ses_parent"),
1037 JSON.stringify([
1038 { id: "parent-update", kind: "overlap.detected", data: {} },
1039 { id: "newer", kind: "work.claimed", data: {} },
1040 ]),
1041 );
1042 assert.match(updateContext(event, env, { throttle: true, now: 1001 + UPDATES_REPEAT_MS }), /newer/);
1043 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "parent-update", kind: "overlap.detected", data: {} }]));
1044 const child = updateContext({ ...event, agent_id: "child" }, env);
1045 assert.match(child, /child-update/);
1046 assert.doesNotMatch(child, /parent-update/);
1047 assert.equal(updateContext({ ...event, agent_id: "unknown" }, env), null);
1048 writeFileSync(files.updates("ses_parent"), JSON.stringify([{ id: "oversized", data: "x".repeat(20000) }]));
1049 const bounded = updateContext(event, env);
1050 assert.ok(bounded.length < 10000);
1051 assert.match(bounded, /read get_session first/);
1052 // A payload that was omitted is not cleared from the cache.
1053 assert.match(readFileSync(files.updates("ses_parent"), "utf8"), /oversized/);
1054 writeFileSync(files.updates("ses_parent"), "[]");
1055 assert.equal(updateContext(event, env), null);
1056 assert.equal(updateContext({ ...event, agent_id: "child" }, env), child);
1057 } finally {
1058 rmSync(dir, { recursive: true, force: true });
1059 }
1060});
1061
1062test("a CLI too old to acknowledge is told to update, once per set of updates", () => {
1063 const dir = mkdtempSync(join(tmpdir(), "g1t-stuck-"));
1064 try {
1065 const env = { CLAUDE_PLUGIN_DATA: dir };
1066 const files = sessionFiles("harness", env);
1067 mkdirSync(files.dir, { recursive: true });
1068 writeFileSync(files.id, "ses_old");
1069 writeFileSync(join(dir, "cli.json"), JSON.stringify({ stamp: "x", version: "0.3.2" }));
1070 writeFileSync(files.updates("ses_old"), JSON.stringify([{ id: "upd_1", kind: "session.ended", data: {} }]));
1071 const event = { session_id: "harness" };
1072 const first = updateContext(event, env);
1073 assert.match(first, /upd_1/);
1074 assert.match(first, /cannot acknowledge them \(0\.3\.3 can\)/);
1075 assert.match(first, /install\.ps1/, "0.3.2 has no g1t upgrade: the installer");
1076 assert.doesNotMatch(first, /g1t session acknowledge/);
1077 // Nothing can clear them, so not again on every prompt or tool.
1078 assert.equal(updateContext(event, env), null);
1079 assert.equal(updateContext(event, env, { throttle: true, now: Date.now() + 10 * UPDATES_REPEAT_MS }), null);
1080 writeFileSync(
1081 files.updates("ses_old"),
1082 JSON.stringify([
1083 { id: "upd_1", data: {} },
1084 { id: "upd_2", data: {} },
1085 ]),
1086 );
1087 assert.match(updateContext(event, env), /upd_2/);
1088 // A CLI that acknowledges is asked to.
1089 writeFileSync(join(dir, "cli.json"), JSON.stringify({ stamp: "x", version: "0.3.3" }));
1090 assert.match(updateContext(event, env), /g1t session acknowledge UPDATE_ID --session ses_old/);
1091 assert.equal(howToUpdate("0.3.4"), "`g1t upgrade`");
1092 assert.match(howToUpdate("0.3.3"), /curl -fsSL https:\/\/g1t\.sh\/install \| sh/);
1093 assert.match(howToUpdate(null), /installer/);
1094 } finally {
1095 rmSync(dir, { recursive: true, force: true });
1096 }
1097});
1098
1099test("an acknowledgement refreshes the inbox at once, from the shell or MCP", () => {
1100 const dir = mkdtempSync(join(tmpdir(), "g1t-ack-"));
1101 try {
1102 const env = { CLAUDE_PLUGIN_DATA: dir };
1103 const base = { session_id: "harness", cwd: dir, hook_event_name: "PostToolUse" };
1104 const shell = plan({ ...base, tool_name: "Bash", tool_input: { command: "g1t session acknowledge upd_1 --note 'Separate scopes'" } }, env);
1105 assert.equal(shell.refreshUpdates, true);
1106 const mcp = plan({ ...base, tool_name: "mcp__plugin_g1t_g1t__session", tool_input: { action: "record", id: "ses_a", acknowledge: ["upd_1"] } }, env);
1107 assert.equal(mcp.refreshUpdates, true);
1108 const other = plan({ ...base, tool_name: "Bash", tool_input: { command: "git status" } }, env);
1109 assert.equal(other.refreshUpdates, undefined);
1110 } finally {
1111 rmSync(dir, { recursive: true, force: true });
1112 }
1113});
1114
1115describe("a transcript's usage", () => {
1116 let dir;
1117 beforeEach(() => {
1118 dir = mkdtempSync(join(tmpdir(), "g1t-usage-"));
1119 });
1120 afterEach(() => rmSync(dir, { recursive: true, force: true }));
1121
1122 const lines = [
1123 JSON.stringify({ type: "user", message: { role: "user", content: "hi" } }),
1124 // One response written as three lines, the last with its final output count.
1125 assistant("msg_1", "claude-opus-5-5", {
1126 input_tokens: 2,
1127 output_tokens: 6,
1128 cache_read_input_tokens: 100,
1129 cache_creation_input_tokens: 50,
1130 cache_creation: { ephemeral_5m_input_tokens: 30, ephemeral_1h_input_tokens: 20 },
1131 }),
1132 assistant("msg_1", "claude-opus-5-5", {
1133 input_tokens: 2,
1134 output_tokens: 6,
1135 cache_read_input_tokens: 100,
1136 cache_creation_input_tokens: 50,
1137 cache_creation: { ephemeral_5m_input_tokens: 30, ephemeral_1h_input_tokens: 20 },
1138 }),
1139 assistant("msg_1", "claude-opus-5-5", {
1140 input_tokens: 2,
1141 output_tokens: 40,
1142 cache_read_input_tokens: 100,
1143 cache_creation_input_tokens: 50,
1144 cache_creation: { ephemeral_5m_input_tokens: 30, ephemeral_1h_input_tokens: 20 },
1145 }),
1146 // Without the split, a cache write is the 5-minute kind.
1147 assistant("msg_2", "claude-opus-5-5", { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 9 }),
1148 // The same message id from another request is another response.
1149 assistant("msg_2", "claude-opus-5-5", { input_tokens: 1, output_tokens: 1 }, "req_other"),
1150 // A claude-haiku-5-5 prompt over 100,000 tokens is its long tier; one under is not.
1151 assistant("msg_3", "claude-haiku-5-5-20260101", { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: LONG_PROMPT_TOKENS }),
1152 assistant("msg_4", "claude-haiku-5-5-20260101", { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 99_000 }),
1153 JSON.stringify({ type: "assistant", message: { id: "msg_5", model: "<synthetic>", usage: { input_tokens: 0, output_tokens: 0 } } }),
1154 "not json",
1155 ];
1156
1157 test("counts each response once, per model and tier", () => {
1158 const path = join(dir, "t.jsonl");
1159 writeFileSync(path, `${lines.join("\n")}\n`);
1160 const usage = transcriptUsage(path, null);
1161 assert.deepEqual(usage, [
1162 { model: "claude-opus-5-5", input_tokens: 4, output_tokens: 42, cache_write_5m_tokens: 39, cache_write_1h_tokens: 20, cache_read_tokens: 100 },
1163 {
1164 model: "claude-haiku-5-5-20260101",
1165 tier: "long",
1166 input_tokens: 10,
1167 output_tokens: 5,
1168 cache_write_5m_tokens: 0,
1169 cache_write_1h_tokens: 0,
1170 cache_read_tokens: LONG_PROMPT_TOKENS,
1171 },
1172 { model: "claude-haiku-5-5-20260101", input_tokens: 10, output_tokens: 5, cache_write_5m_tokens: 0, cache_write_1h_tokens: 0, cache_read_tokens: 99_000 },
1173 ]);
1174 });
1175
1176 test("reads on from where it stopped, a line written in half counted once it is whole", () => {
1177 const path = join(dir, "t.jsonl");
1178 const state = join(dir, "state.json");
1179 const whole = `${lines.join("\n")}\n`;
1180 const cut = whole.indexOf("msg_2") + 10;
1181 writeFileSync(path, whole.slice(0, cut));
1182 const first = transcriptUsage(path, state);
1183 assert.equal(first.find((row) => row.model === "claude-opus-5-5").output_tokens, 40);
1184 writeFileSync(path, whole);
1185 assert.deepEqual(transcriptUsage(path, state), transcriptUsage(path, null));
1186 // A transcript written again from the top is counted again.
1187 writeFileSync(path, `${lines[4]}\n`);
1188 assert.deepEqual(
1189 transcriptUsage(path, state).map((row) => row.input_tokens),
1190 [1],
1191 );
1192 });
1193
1194 test("a transcript that cannot be read gives nothing, and never throws", () => {
1195 assert.equal(transcriptUsage(join(dir, "missing.jsonl"), join(dir, "state.json")), null);
1196 const path = join(dir, "empty.jsonl");
1197 writeFileSync(path, "");
1198 assert.deepEqual(transcriptUsage(path, null), []);
1199 });
1200});