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.

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