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