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