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.

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