@asterxsk/kiln 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,565 +1,565 @@
1
- import assert from "node:assert/strict";
2
- import { spawnSync } from "node:child_process";
3
- import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { delimiter, join } from "node:path";
6
- import { test } from "node:test";
7
-
8
- const moduleUrl = new URL("../github-issue-pr.ts", import.meta.url).href;
9
- const extractUrl = new URL("../extract.ts", import.meta.url).href;
10
- const publicLookup = async () => [{ address: "140.82.112.6", family: 4 }];
11
-
12
- // Fake shebang `gh` executables cannot run on Windows: extensionless scripts are
13
- // not resolvable/spawnable via CreateProcess, and `.cmd` shims are refused by
14
- // child_process without `shell: true` (post CVE-2024-27980 hardening). Tests
15
- // below that depend on the fake gh's canned JSON skip there; they still run on
16
- // POSIX CI. Tests that only need gh to fail (fallback/abort paths) keep
17
- // running, since a spawn error exercises the same fallback.
18
-
19
- async function writeFakeExecutable(binDir, name, source) {
20
- const executable = join(binDir, name);
21
- await writeFile(executable, `#!/usr/bin/env node\n${source}\n`, { mode: 0o755 });
22
- if (process.platform === "win32") {
23
- // Windows CreateProcess resolves executables via PATHEXT, so the
24
- // extensionless shebang script above is invisible to spawn/execFile.
25
- await writeFile(join(binDir, `${name}.cmd`), `@echo off\r\nnode "%~dp0${name}" %*\r\n`);
26
- }
27
- return executable;
28
- }
29
-
30
- const SKIP_FAKE_GH = process.platform === "win32"
31
- ? "requires a runnable fake gh executable (unavailable on Windows)"
32
- : false;
33
-
34
- test("parseGitHubIssuePrUrl accepts PR and issue variants without changing repo parsing", async () => {
35
- const { parseGitHubIssuePrUrl } = await import(moduleUrl);
36
- assert.deepEqual(parseGitHubIssuePrUrl("https://github.com/owner/repo/pull/123/files#discussion_r42"), {
37
- owner: "owner", repo: "repo", kind: "pull", number: 123, anchor: "discussion_r42",
38
- });
39
- assert.deepEqual(parseGitHubIssuePrUrl("https://www.github.com/owner/repo/issues/5#issuecomment-99"), {
40
- owner: "owner", repo: "repo", kind: "issue", number: 5, anchor: "issuecomment-99",
41
- });
42
- assert.deepEqual(parseGitHubIssuePrUrl("https://www.github.com/owner/repo/issues/5#discussion_r99"), {
43
- owner: "owner", repo: "repo", kind: "issue", number: 5,
44
- });
45
- assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/pulls"), null);
46
- assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/issues/new"), null);
47
- assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/pull/123/unknown"), null);
48
- assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/issues/5/edit"), null);
49
- assert.equal(parseGitHubIssuePrUrl("https://github.com/owner%2Frepo/repo/issues/1"), null);
50
- });
51
-
52
- test("renderer orders sections, marks truncation, and forces anchored comments inline", async () => {
53
- const { renderGitHubPrIssue } = await import(moduleUrl);
54
- const comments = Array.from({ length: 20 }, (_, index) => ({
55
- id: index + 1,
56
- user: { login: `user${index + 1}` },
57
- created_at: "2026-01-01T00:00:00Z",
58
- body: index === 18 ? "anchored comment body" : `comment ${index + 1}`,
59
- }));
60
- const result = renderGitHubPrIssue({
61
- url: "https://github.com/owner/repo/pull/7#issuecomment-19",
62
- owner: "owner",
63
- repo: "repo",
64
- kind: "pull",
65
- number: 7,
66
- anchor: "issuecomment-19",
67
- reviewThreads: [],
68
- fallbackNotes: [],
69
- view: {
70
- number: 7,
71
- title: "Improve fetch",
72
- state: "OPEN",
73
- isDraft: false,
74
- author: { login: "alice" },
75
- baseRefName: "main",
76
- headRefName: "feature",
77
- headRepositoryOwner: { login: "fork" },
78
- createdAt: "2026-01-01T00:00:00Z",
79
- labels: [{ name: "bug" }],
80
- additions: 5,
81
- deletions: 1,
82
- changedFiles: 1,
83
- body: "x".repeat(4100),
84
- files: [{ path: "a.ts", additions: 5, deletions: 1 }],
85
- commits: [{ oid: "abcdef123456", messageHeadline: "commit subject" }],
86
- comments,
87
- statusCheckRollup: [{ name: "test", conclusion: "SUCCESS" }],
88
- },
89
- });
90
-
91
- assert.equal(result.error, null);
92
- assert.match(result.content, /#7 Improve fetch/);
93
- assert.ok(result.content.indexOf("## Body") < result.content.indexOf("## Checks"));
94
- assert.match(result.content, /\[body truncated; use get_search_content/);
95
- assert.match(result.content, /user19.*\[anchored\]/s);
96
- assert.match(result.content, /15 of 20 comments shown|16 of 20 comments shown/);
97
- assert.match(result.content, /gh pr diff 7 --repo owner\/repo/);
98
- });
99
-
100
- test("renderer marks truncated review verdicts", async () => {
101
- const { renderGitHubPrIssue } = await import(moduleUrl);
102
- const reviews = Array.from({ length: 11 }, (_, index) => ({
103
- author: { login: `reviewer${index}` },
104
- state: "COMMENTED",
105
- body: `review ${index}`,
106
- }));
107
- const result = renderGitHubPrIssue({
108
- url: "https://github.com/owner/repo/pull/7",
109
- owner: "owner",
110
- repo: "repo",
111
- kind: "pull",
112
- number: 7,
113
- reviewThreads: [],
114
- fallbackNotes: [],
115
- view: { number: 7, title: "Reviews", state: "OPEN", author: { login: "alice" }, body: "body", reviews },
116
- });
117
-
118
- assert.match(result.content, /10 of 11 review verdicts shown/);
119
- });
120
-
121
- test("extractGitHubIssuePr retries gh view with core fields on unknown --json field", { skip: SKIP_FAKE_GH }, async () => {
122
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-pr-"));
123
- const binDir = join(root, "bin");
124
- const agentDir = join(root, "agent");
125
- await mkdir(binDir, { recursive: true });
126
- await mkdir(agentDir, { recursive: true });
127
- await writeFakeExecutable(binDir, "gh", `
128
- const args = process.argv.slice(2);
129
- if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
130
- if (args[0] === "pr" && args[1] === "view") {
131
- const fields = args[args.indexOf("--json") + 1] || "";
132
- if (fields.includes("statusCheckRollup")) { console.error("Unknown JSON field: statusCheckRollup"); process.exit(1); }
133
- console.log(JSON.stringify({ number: 12, title: "Fallback fields", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
134
- process.exit(0);
135
- }
136
- if (args[0] === "api") { console.log("[]"); process.exit(0); }
137
- process.exit(1);
138
- `);
139
-
140
- const child = spawnSync(process.execPath, ["--input-type=module"], {
141
- input: `
142
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
143
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/12");
144
- console.log(JSON.stringify(result));
145
- `,
146
- encoding: "utf8",
147
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
148
- });
149
-
150
- assert.equal(child.status, 0, child.stderr);
151
- const result = JSON.parse(child.stdout);
152
- assert.match(result.content, /Fallback fields/);
153
- assert.match(result.content, /retried with the core field set/);
154
- assert.match(result.content, /Linked references\nUnavailable in this GitHub fetch path/);
155
- });
156
-
157
- test("gh path fetches an anchored review comment beyond fetched pages", { skip: SKIP_FAKE_GH }, async () => {
158
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-deep-review-anchor-"));
159
- const binDir = join(root, "bin");
160
- const agentDir = join(root, "agent");
161
- await mkdir(binDir, { recursive: true });
162
- await mkdir(agentDir, { recursive: true });
163
- await writeFakeExecutable(binDir, "gh", `
164
- const args = process.argv.slice(2);
165
- if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
166
- if (args[0] === "pr" && args[1] === "view") {
167
- console.log(JSON.stringify({ number: 7, title: "Deep anchor", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
168
- process.exit(0);
169
- }
170
- if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) {
171
- const comments = Array.from({ length: 100 }, (_, index) => ({ id: index + 1, user: { login: "page" }, path: "a.ts", line: 1, body: "paged" }));
172
- console.log(JSON.stringify(comments));
173
- process.exit(0);
174
- }
175
- if (args[0] === "api" && args[1].endsWith("/pulls/comments/999")) {
176
- console.log(JSON.stringify({ id: 999, pull_request_url: "https://api.github.com/repos/owner/repo/pulls/7", user: { login: "reviewer" }, path: "deep.ts", line: 44, body: "deep anchor" }));
177
- process.exit(0);
178
- }
179
- process.exit(1);
180
- `);
181
-
182
- const child = spawnSync(process.execPath, ["--input-type=module"], {
183
- input: `
184
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
185
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7#discussion_r999");
186
- console.log(JSON.stringify(result));
187
- `,
188
- encoding: "utf8",
189
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
190
- });
191
-
192
- assert.equal(child.status, 0, child.stderr);
193
- const result = JSON.parse(child.stdout);
194
- assert.match(result.content, /reviewer.*\[anchored\]/s);
195
- assert.match(result.content, /deep anchor/);
196
- assert.match(result.content, /review threads: at least 301/);
197
- assert.match(result.content, /review thread comments shown from at least 301/);
198
- });
199
-
200
- test("gh path rejects anchored review comments from another pull request", { skip: SKIP_FAKE_GH }, async () => {
201
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-cross-review-anchor-"));
202
- const binDir = join(root, "bin");
203
- const agentDir = join(root, "agent");
204
- await mkdir(binDir, { recursive: true });
205
- await mkdir(agentDir, { recursive: true });
206
- await writeFakeExecutable(binDir, "gh", `
207
- const args = process.argv.slice(2);
208
- if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
209
- if (args[0] === "pr" && args[1] === "view") {
210
- console.log(JSON.stringify({ number: 7, title: "Cross anchor", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
211
- process.exit(0);
212
- }
213
- if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) { console.log(JSON.stringify([])); process.exit(0); }
214
- if (args[0] === "api" && args[1].endsWith("/pulls/comments/999")) {
215
- console.log(JSON.stringify({ id: 999, pull_request_url: "https://api.github.com/repos/other/repo/pulls/7", user: { login: "wrong" }, path: "wrong.ts", line: 1, body: "wrong pull" }));
216
- process.exit(0);
217
- }
218
- process.exit(1);
219
- `);
220
-
221
- const child = spawnSync(process.execPath, ["--input-type=module"], {
222
- input: `
223
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
224
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7#discussion_r999");
225
- console.log(JSON.stringify(result));
226
- `,
227
- encoding: "utf8",
228
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
229
- });
230
-
231
- assert.equal(child.status, 0, child.stderr);
232
- const result = JSON.parse(child.stdout);
233
- assert.doesNotMatch(result.content, /wrong pull/);
234
- assert.match(result.content, /anchored review thread comment unavailable for this pull request/);
235
- });
236
-
237
- test("gh path still attempts an anchored review comment after page failure", { skip: SKIP_FAKE_GH }, async () => {
238
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-page-fail-anchor-"));
239
- const binDir = join(root, "bin");
240
- const agentDir = join(root, "agent");
241
- await mkdir(binDir, { recursive: true });
242
- await mkdir(agentDir, { recursive: true });
243
- await writeFakeExecutable(binDir, "gh", `
244
- const args = process.argv.slice(2);
245
- if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
246
- if (args[0] === "pr" && args[1] === "view") {
247
- console.log(JSON.stringify({ number: 7, title: "Page fail anchor", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
248
- process.exit(0);
249
- }
250
- if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) { process.exit(1); }
251
- if (args[0] === "api" && args[1].endsWith("/pulls/comments/999")) {
252
- console.log(JSON.stringify({ id: 999, pull_request_url: "https://api.github.com/repos/owner/repo/pulls/7", user: { login: "reviewer" }, path: "deep.ts", line: 44, body: "deep after page failure" }));
253
- process.exit(0);
254
- }
255
- process.exit(1);
256
- `);
257
-
258
- const child = spawnSync(process.execPath, ["--input-type=module"], {
259
- input: `
260
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
261
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7#discussion_r999");
262
- console.log(JSON.stringify(result));
263
- `,
264
- encoding: "utf8",
265
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
266
- });
267
-
268
- assert.equal(child.status, 0, child.stderr);
269
- const result = JSON.parse(child.stdout);
270
- assert.match(result.content, /reviewer.*\[anchored\]/s);
271
- assert.match(result.content, /deep after page failure/);
272
- });
273
-
274
- test("gh review thread page failure renders unavailable instead of none", { skip: SKIP_FAKE_GH }, async () => {
275
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-review-unavailable-"));
276
- const binDir = join(root, "bin");
277
- const agentDir = join(root, "agent");
278
- await mkdir(binDir, { recursive: true });
279
- await mkdir(agentDir, { recursive: true });
280
- await writeFakeExecutable(binDir, "gh", `
281
- const args = process.argv.slice(2);
282
- if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
283
- if (args[0] === "pr" && args[1] === "view") {
284
- console.log(JSON.stringify({ number: 7, title: "Unavailable reviews", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
285
- process.exit(0);
286
- }
287
- if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) { process.exit(1); }
288
- process.exit(1);
289
- `);
290
-
291
- const child = spawnSync(process.execPath, ["--input-type=module"], {
292
- input: `
293
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
294
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7");
295
- console.log(JSON.stringify(result));
296
- `,
297
- encoding: "utf8",
298
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
299
- });
300
-
301
- assert.equal(child.status, 0, child.stderr);
302
- const result = JSON.parse(child.stdout);
303
- assert.match(result.content, /review threads: unavailable/);
304
- assert.match(result.content, /Review thread comments\nUnavailable in this GitHub fetch path/);
305
- });
306
-
307
- test("extractGitHubIssuePr aborts active gh work with the caller signal", async () => {
308
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-abort-"));
309
- const binDir = join(root, "bin");
310
- const agentDir = join(root, "agent");
311
- await mkdir(binDir, { recursive: true });
312
- await mkdir(agentDir, { recursive: true });
313
- await writeFakeExecutable(binDir, "gh", `
314
- const args = process.argv.slice(2);
315
- if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
316
- setTimeout(() => {}, 30000);
317
- `);
318
-
319
- const child = spawnSync(process.execPath, ["--input-type=module"], {
320
- input: `
321
- globalThis.fetch = async (_input, init = {}) => {
322
- if (!init.signal?.aborted) throw new Error("fallback fetch did not receive aborted signal");
323
- throw new Error("aborted fallback fetch");
324
- };
325
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
326
- const controller = new AbortController();
327
- setTimeout(() => controller.abort(), 50);
328
- const started = Date.now();
329
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7", controller.signal, { lookup: async () => [{ address: "140.82.112.6", family: 4 }] });
330
- console.log(JSON.stringify({ elapsed: Date.now() - started, result }));
331
- `,
332
- encoding: "utf8",
333
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
334
- });
335
-
336
- assert.equal(child.status, 0, child.stderr);
337
- const output = JSON.parse(child.stdout);
338
- assert.equal(output.result.error, "Aborted");
339
- assert.ok(output.elapsed < 1000, `expected abort before gh timeout, got ${output.elapsed}ms`);
340
- });
341
-
342
- test("extractGitHubIssuePr aborts a hung gh availability probe", async () => {
343
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-probe-abort-"));
344
- const binDir = join(root, "bin");
345
- const agentDir = join(root, "agent");
346
- await mkdir(binDir, { recursive: true });
347
- await mkdir(agentDir, { recursive: true });
348
- await writeFakeExecutable(binDir, "gh", `setTimeout(() => {}, 30000);`);
349
-
350
- const child = spawnSync(process.execPath, ["--input-type=module"], {
351
- input: `
352
- const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
353
- const controller = new AbortController();
354
- setTimeout(() => controller.abort(), 50);
355
- const started = Date.now();
356
- const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7", controller.signal);
357
- console.log(JSON.stringify({ elapsed: Date.now() - started, result }));
358
- `,
359
- encoding: "utf8",
360
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
361
- });
362
-
363
- assert.equal(child.status, 0, child.stderr);
364
- const output = JSON.parse(child.stdout);
365
- assert.equal(output.result.error, "Aborted");
366
- assert.ok(output.elapsed < 1000, `expected abort before gh probe timeout, got ${output.elapsed}ms`);
367
- });
368
-
369
- test("REST fallback preserves caller cancellation", async () => {
370
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-rest-abort-"));
371
- const binDir = join(root, "bin");
372
- const agentDir = join(root, "agent");
373
- await mkdir(binDir, { recursive: true });
374
- await mkdir(agentDir, { recursive: true });
375
- await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
376
-
377
- const child = spawnSync(process.execPath, ["--input-type=module"], {
378
- input: `
379
- const controller = new AbortController();
380
- globalThis.fetch = async (_input, init = {}) => {
381
- setTimeout(() => controller.abort(), 10);
382
- await new Promise((resolve, reject) => init.signal.addEventListener("abort", () => reject(new Error("Aborted REST fetch")), { once: true }));
383
- };
384
- const { extractContent } = await import(${JSON.stringify(extractUrl)});
385
- const lookup = ${publicLookup.toString()};
386
- const started = Date.now();
387
- const result = await extractContent("https://github.com/owner/repo/issues/12", controller.signal, { lookup });
388
- console.log(JSON.stringify({ elapsed: Date.now() - started, result }));
389
- `,
390
- encoding: "utf8",
391
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
392
- });
393
-
394
- assert.equal(child.status, 0, child.stderr);
395
- const output = JSON.parse(child.stdout.split("\n").at(-2));
396
- assert.equal(output.result.error, "Aborted");
397
- assert.ok(output.elapsed < 1000, `expected REST abort before generic fallback, got ${output.elapsed}ms`);
398
- });
399
-
400
- test("extractContent returns an actionable GitHub rate-limit result instead of HTML fall-through", async () => {
401
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-rate-"));
402
- const binDir = join(root, "bin");
403
- const agentDir = join(root, "agent");
404
- await mkdir(binDir, { recursive: true });
405
- await mkdir(agentDir, { recursive: true });
406
- await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
407
-
408
- const child = spawnSync(process.execPath, ["--input-type=module"], {
409
- input: `
410
- globalThis.fetch = async () => new Response("rate limited", { status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "1800000000" } });
411
- const { extractContent } = await import(${JSON.stringify(extractUrl)});
412
- const lookup = ${publicLookup.toString()};
413
- const result = await extractContent("https://github.com/owner/repo/issues/12", undefined, { lookup });
414
- console.log(JSON.stringify(result));
415
- `,
416
- encoding: "utf8",
417
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
418
- });
419
-
420
- assert.equal(child.status, 0, child.stderr);
421
- const result = JSON.parse(child.stdout.split("\n").at(-2));
422
- assert.equal(result.status, 403);
423
- assert.match(result.error, /rate limit/i);
424
- assert.match(result.content, /gh auth login/);
425
- });
426
-
427
- test("REST fallback fetches an anchored issue comment outside the first page", async () => {
428
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-issue-anchor-"));
429
- const binDir = join(root, "bin");
430
- const agentDir = join(root, "agent");
431
- await mkdir(binDir, { recursive: true });
432
- await mkdir(agentDir, { recursive: true });
433
- await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
434
-
435
- const child = spawnSync(process.execPath, ["--input-type=module"], {
436
- input: `
437
- globalThis.fetch = async (input) => {
438
- const url = String(input);
439
- if (url.endsWith("/issues/12")) return new Response(JSON.stringify({ number: 12, title: "Issue", state: "open", user: { login: "owner" }, body: "body", comments: 75 }), { status: 200 });
440
- if (url.endsWith("/issues/12/comments?per_page=50")) return new Response(JSON.stringify([{ id: 1, user: { login: "first" }, created_at: "2026-01-01T00:00:00Z", body: "first page" }]), { status: 200 });
441
- if (url.endsWith("/issues/comments/99")) return new Response(JSON.stringify({ id: 99, issue_url: "https://api.github.com/repos/owner/repo/issues/12", user: { login: "anchored" }, created_at: "2026-01-02T00:00:00Z", body: "outside first page" }), { status: 200 });
442
- throw new Error("unexpected URL " + url);
443
- };
444
- const { extractContent } = await import(${JSON.stringify(extractUrl)});
445
- const lookup = ${publicLookup.toString()};
446
- const result = await extractContent("https://github.com/owner/repo/issues/12#issuecomment-99", undefined, { lookup });
447
- console.log(JSON.stringify(result));
448
- `,
449
- encoding: "utf8",
450
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
451
- });
452
-
453
- assert.equal(child.status, 0, child.stderr);
454
- const result = JSON.parse(child.stdout.split("\n").at(-2));
455
- assert.match(result.content, /anchored.*\[anchored\]/s);
456
- assert.match(result.content, /outside first page/);
457
- assert.match(result.content, /comments: at least 75/);
458
- assert.match(result.content, /comments shown from at least 75/);
459
- });
460
-
461
- test("REST fallback rejects anchored issue comments from another work item", async () => {
462
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-cross-issue-anchor-"));
463
- const binDir = join(root, "bin");
464
- const agentDir = join(root, "agent");
465
- await mkdir(binDir, { recursive: true });
466
- await mkdir(agentDir, { recursive: true });
467
- await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
468
-
469
- const child = spawnSync(process.execPath, ["--input-type=module"], {
470
- input: `
471
- globalThis.fetch = async (input) => {
472
- const url = String(input);
473
- if (url.endsWith("/issues/12")) return new Response(JSON.stringify({ number: 12, title: "Issue", state: "open", user: { login: "owner" }, body: "body", comments: 1 }), { status: 200 });
474
- if (url.endsWith("/issues/12/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
475
- if (url.endsWith("/issues/comments/99")) return new Response(JSON.stringify({ id: 98, issue_url: "https://api.github.com/repos/other/repo/issues/12", user: { login: "wrong" }, created_at: "2026-01-02T00:00:00Z", body: "wrong issue" }), { status: 200 });
476
- throw new Error("unexpected URL " + url);
477
- };
478
- const { extractContent } = await import(${JSON.stringify(extractUrl)});
479
- const lookup = ${publicLookup.toString()};
480
- const result = await extractContent("https://github.com/owner/repo/issues/12#issuecomment-99", undefined, { lookup });
481
- console.log(JSON.stringify(result));
482
- `,
483
- encoding: "utf8",
484
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
485
- });
486
-
487
- assert.equal(child.status, 0, child.stderr);
488
- const result = JSON.parse(child.stdout.split("\n").at(-2));
489
- assert.doesNotMatch(result.content, /wrong issue/);
490
- assert.match(result.content, /anchored comment unavailable for this issue or pull request/);
491
- });
492
-
493
- test("REST fallback fetches an anchored PR review comment outside the first page", async () => {
494
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-review-anchor-"));
495
- const binDir = join(root, "bin");
496
- const agentDir = join(root, "agent");
497
- await mkdir(binDir, { recursive: true });
498
- await mkdir(agentDir, { recursive: true });
499
- await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
500
-
501
- const child = spawnSync(process.execPath, ["--input-type=module"], {
502
- input: `
503
- globalThis.fetch = async (input) => {
504
- const url = String(input);
505
- if (url.endsWith("/pulls/7")) return new Response(JSON.stringify({ number: 7, title: "PR", state: "open", user: { login: "owner" }, body: "body", draft: false, base: { ref: "main" }, head: { ref: "feature", repo: { owner: { login: "owner" } } }, additions: 1, deletions: 0, changed_files: 75, review_comments: 12 }), { status: 200 });
506
- if (url.endsWith("/issues/7/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
507
- if (url.endsWith("/pulls/7/files?per_page=50")) return new Response(JSON.stringify(Array.from({ length: 50 }, (_, index) => ({ filename: "file" + index + ".ts", additions: 1, deletions: 0 }))), { status: 200 });
508
- if (url.endsWith("/pulls/7/comments?per_page=50")) return new Response(JSON.stringify([{ id: 1, user: { login: "first" }, path: "a.ts", line: 1, body: "first review" }]), { status: 200 });
509
- if (url.endsWith("/pulls/comments/42")) return new Response(JSON.stringify({ id: 42, pull_request_url: "https://api.github.com/repos/owner/repo/pulls/7", user: { login: "reviewer" }, path: "b.ts", line: 9, body: "outside review page" }), { status: 200 });
510
- throw new Error("unexpected URL " + url);
511
- };
512
- const { extractContent } = await import(${JSON.stringify(extractUrl)});
513
- const lookup = ${publicLookup.toString()};
514
- const result = await extractContent("https://github.com/owner/repo/pull/7#discussion_r42", undefined, { lookup });
515
- console.log(JSON.stringify(result));
516
- `,
517
- encoding: "utf8",
518
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
519
- });
520
-
521
- assert.equal(child.status, 0, child.stderr);
522
- const result = JSON.parse(child.stdout.split("\n").at(-2));
523
- assert.match(result.content, /reviewer.*\[anchored\]/s);
524
- assert.match(result.content, /outside review page/);
525
- assert.match(result.content, /commits unavailable/);
526
- assert.match(result.content, /Review verdicts\nUnavailable in this GitHub fetch path/);
527
- assert.match(result.content, /50 files shown from at least 75/);
528
- assert.match(result.content, /Commits\nUnavailable in this GitHub fetch path/);
529
- assert.match(result.content, /review threads: at least 12/);
530
- assert.match(result.content, /review thread comments shown from at least 12/);
531
- assert.match(result.content, /Linked references\nUnavailable in this GitHub fetch path/);
532
- });
533
-
534
- test("REST fallback does not render positive changedFiles as none when files are missing", async () => {
535
- const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-files-unavailable-"));
536
- const binDir = join(root, "bin");
537
- const agentDir = join(root, "agent");
538
- await mkdir(binDir, { recursive: true });
539
- await mkdir(agentDir, { recursive: true });
540
- await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
541
-
542
- const child = spawnSync(process.execPath, ["--input-type=module"], {
543
- input: `
544
- globalThis.fetch = async (input) => {
545
- const url = String(input);
546
- if (url.endsWith("/pulls/7")) return new Response(JSON.stringify({ number: 7, title: "PR", state: "open", user: { login: "owner" }, body: "body", draft: false, base: { ref: "main" }, head: { ref: "feature", repo: { owner: { login: "owner" } } }, additions: 1, deletions: 0, changed_files: 3 }), { status: 200 });
547
- if (url.endsWith("/issues/7/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
548
- if (url.endsWith("/pulls/7/files?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
549
- if (url.endsWith("/pulls/7/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
550
- throw new Error("unexpected URL " + url);
551
- };
552
- const { extractContent } = await import(${JSON.stringify(extractUrl)});
553
- const lookup = ${publicLookup.toString()};
554
- const result = await extractContent("https://github.com/owner/repo/pull/7", undefined, { lookup });
555
- console.log(JSON.stringify(result));
556
- `,
557
- encoding: "utf8",
558
- env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
559
- });
560
-
561
- assert.equal(child.status, 0, child.stderr);
562
- const result = JSON.parse(child.stdout.split("\n").at(-2));
563
- assert.match(result.content, /0 files shown from at least 3/);
564
- assert.doesNotMatch(result.content, /Files\nnone/);
565
- });
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { delimiter, join } from "node:path";
6
+ import { test } from "node:test";
7
+
8
+ const moduleUrl = new URL("../github-issue-pr.ts", import.meta.url).href;
9
+ const extractUrl = new URL("../extract.ts", import.meta.url).href;
10
+ const publicLookup = async () => [{ address: "140.82.112.6", family: 4 }];
11
+
12
+ // Fake shebang `gh` executables cannot run on Windows: extensionless scripts are
13
+ // not resolvable/spawnable via CreateProcess, and `.cmd` shims are refused by
14
+ // child_process without `shell: true` (post CVE-2024-27980 hardening). Tests
15
+ // below that depend on the fake gh's canned JSON skip there; they still run on
16
+ // POSIX CI. Tests that only need gh to fail (fallback/abort paths) keep
17
+ // running, since a spawn error exercises the same fallback.
18
+
19
+ async function writeFakeExecutable(binDir, name, source) {
20
+ const executable = join(binDir, name);
21
+ await writeFile(executable, `#!/usr/bin/env node\n${source}\n`, { mode: 0o755 });
22
+ if (process.platform === "win32") {
23
+ // Windows CreateProcess resolves executables via PATHEXT, so the
24
+ // extensionless shebang script above is invisible to spawn/execFile.
25
+ await writeFile(join(binDir, `${name}.cmd`), `@echo off\r\nnode "%~dp0${name}" %*\r\n`);
26
+ }
27
+ return executable;
28
+ }
29
+
30
+ const SKIP_FAKE_GH = process.platform === "win32"
31
+ ? "requires a runnable fake gh executable (unavailable on Windows)"
32
+ : false;
33
+
34
+ test("parseGitHubIssuePrUrl accepts PR and issue variants without changing repo parsing", async () => {
35
+ const { parseGitHubIssuePrUrl } = await import(moduleUrl);
36
+ assert.deepEqual(parseGitHubIssuePrUrl("https://github.com/owner/repo/pull/123/files#discussion_r42"), {
37
+ owner: "owner", repo: "repo", kind: "pull", number: 123, anchor: "discussion_r42",
38
+ });
39
+ assert.deepEqual(parseGitHubIssuePrUrl("https://www.github.com/owner/repo/issues/5#issuecomment-99"), {
40
+ owner: "owner", repo: "repo", kind: "issue", number: 5, anchor: "issuecomment-99",
41
+ });
42
+ assert.deepEqual(parseGitHubIssuePrUrl("https://www.github.com/owner/repo/issues/5#discussion_r99"), {
43
+ owner: "owner", repo: "repo", kind: "issue", number: 5,
44
+ });
45
+ assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/pulls"), null);
46
+ assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/issues/new"), null);
47
+ assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/pull/123/unknown"), null);
48
+ assert.equal(parseGitHubIssuePrUrl("https://github.com/owner/repo/issues/5/edit"), null);
49
+ assert.equal(parseGitHubIssuePrUrl("https://github.com/owner%2Frepo/repo/issues/1"), null);
50
+ });
51
+
52
+ test("renderer orders sections, marks truncation, and forces anchored comments inline", async () => {
53
+ const { renderGitHubPrIssue } = await import(moduleUrl);
54
+ const comments = Array.from({ length: 20 }, (_, index) => ({
55
+ id: index + 1,
56
+ user: { login: `user${index + 1}` },
57
+ created_at: "2026-01-01T00:00:00Z",
58
+ body: index === 18 ? "anchored comment body" : `comment ${index + 1}`,
59
+ }));
60
+ const result = renderGitHubPrIssue({
61
+ url: "https://github.com/owner/repo/pull/7#issuecomment-19",
62
+ owner: "owner",
63
+ repo: "repo",
64
+ kind: "pull",
65
+ number: 7,
66
+ anchor: "issuecomment-19",
67
+ reviewThreads: [],
68
+ fallbackNotes: [],
69
+ view: {
70
+ number: 7,
71
+ title: "Improve fetch",
72
+ state: "OPEN",
73
+ isDraft: false,
74
+ author: { login: "alice" },
75
+ baseRefName: "main",
76
+ headRefName: "feature",
77
+ headRepositoryOwner: { login: "fork" },
78
+ createdAt: "2026-01-01T00:00:00Z",
79
+ labels: [{ name: "bug" }],
80
+ additions: 5,
81
+ deletions: 1,
82
+ changedFiles: 1,
83
+ body: "x".repeat(4100),
84
+ files: [{ path: "a.ts", additions: 5, deletions: 1 }],
85
+ commits: [{ oid: "abcdef123456", messageHeadline: "commit subject" }],
86
+ comments,
87
+ statusCheckRollup: [{ name: "test", conclusion: "SUCCESS" }],
88
+ },
89
+ });
90
+
91
+ assert.equal(result.error, null);
92
+ assert.match(result.content, /#7 Improve fetch/);
93
+ assert.ok(result.content.indexOf("## Body") < result.content.indexOf("## Checks"));
94
+ assert.match(result.content, /\[body truncated; use get_search_content/);
95
+ assert.match(result.content, /user19.*\[anchored\]/s);
96
+ assert.match(result.content, /15 of 20 comments shown|16 of 20 comments shown/);
97
+ assert.match(result.content, /gh pr diff 7 --repo owner\/repo/);
98
+ });
99
+
100
+ test("renderer marks truncated review verdicts", async () => {
101
+ const { renderGitHubPrIssue } = await import(moduleUrl);
102
+ const reviews = Array.from({ length: 11 }, (_, index) => ({
103
+ author: { login: `reviewer${index}` },
104
+ state: "COMMENTED",
105
+ body: `review ${index}`,
106
+ }));
107
+ const result = renderGitHubPrIssue({
108
+ url: "https://github.com/owner/repo/pull/7",
109
+ owner: "owner",
110
+ repo: "repo",
111
+ kind: "pull",
112
+ number: 7,
113
+ reviewThreads: [],
114
+ fallbackNotes: [],
115
+ view: { number: 7, title: "Reviews", state: "OPEN", author: { login: "alice" }, body: "body", reviews },
116
+ });
117
+
118
+ assert.match(result.content, /10 of 11 review verdicts shown/);
119
+ });
120
+
121
+ test("extractGitHubIssuePr retries gh view with core fields on unknown --json field", { skip: SKIP_FAKE_GH }, async () => {
122
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-pr-"));
123
+ const binDir = join(root, "bin");
124
+ const agentDir = join(root, "agent");
125
+ await mkdir(binDir, { recursive: true });
126
+ await mkdir(agentDir, { recursive: true });
127
+ await writeFakeExecutable(binDir, "gh", `
128
+ const args = process.argv.slice(2);
129
+ if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
130
+ if (args[0] === "pr" && args[1] === "view") {
131
+ const fields = args[args.indexOf("--json") + 1] || "";
132
+ if (fields.includes("statusCheckRollup")) { console.error("Unknown JSON field: statusCheckRollup"); process.exit(1); }
133
+ console.log(JSON.stringify({ number: 12, title: "Fallback fields", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
134
+ process.exit(0);
135
+ }
136
+ if (args[0] === "api") { console.log("[]"); process.exit(0); }
137
+ process.exit(1);
138
+ `);
139
+
140
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
141
+ input: `
142
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
143
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/12");
144
+ console.log(JSON.stringify(result));
145
+ `,
146
+ encoding: "utf8",
147
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
148
+ });
149
+
150
+ assert.equal(child.status, 0, child.stderr);
151
+ const result = JSON.parse(child.stdout);
152
+ assert.match(result.content, /Fallback fields/);
153
+ assert.match(result.content, /retried with the core field set/);
154
+ assert.match(result.content, /Linked references\nUnavailable in this GitHub fetch path/);
155
+ });
156
+
157
+ test("gh path fetches an anchored review comment beyond fetched pages", { skip: SKIP_FAKE_GH }, async () => {
158
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-deep-review-anchor-"));
159
+ const binDir = join(root, "bin");
160
+ const agentDir = join(root, "agent");
161
+ await mkdir(binDir, { recursive: true });
162
+ await mkdir(agentDir, { recursive: true });
163
+ await writeFakeExecutable(binDir, "gh", `
164
+ const args = process.argv.slice(2);
165
+ if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
166
+ if (args[0] === "pr" && args[1] === "view") {
167
+ console.log(JSON.stringify({ number: 7, title: "Deep anchor", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
168
+ process.exit(0);
169
+ }
170
+ if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) {
171
+ const comments = Array.from({ length: 100 }, (_, index) => ({ id: index + 1, user: { login: "page" }, path: "a.ts", line: 1, body: "paged" }));
172
+ console.log(JSON.stringify(comments));
173
+ process.exit(0);
174
+ }
175
+ if (args[0] === "api" && args[1].endsWith("/pulls/comments/999")) {
176
+ console.log(JSON.stringify({ id: 999, pull_request_url: "https://api.github.com/repos/owner/repo/pulls/7", user: { login: "reviewer" }, path: "deep.ts", line: 44, body: "deep anchor" }));
177
+ process.exit(0);
178
+ }
179
+ process.exit(1);
180
+ `);
181
+
182
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
183
+ input: `
184
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
185
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7#discussion_r999");
186
+ console.log(JSON.stringify(result));
187
+ `,
188
+ encoding: "utf8",
189
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
190
+ });
191
+
192
+ assert.equal(child.status, 0, child.stderr);
193
+ const result = JSON.parse(child.stdout);
194
+ assert.match(result.content, /reviewer.*\[anchored\]/s);
195
+ assert.match(result.content, /deep anchor/);
196
+ assert.match(result.content, /review threads: at least 301/);
197
+ assert.match(result.content, /review thread comments shown from at least 301/);
198
+ });
199
+
200
+ test("gh path rejects anchored review comments from another pull request", { skip: SKIP_FAKE_GH }, async () => {
201
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-cross-review-anchor-"));
202
+ const binDir = join(root, "bin");
203
+ const agentDir = join(root, "agent");
204
+ await mkdir(binDir, { recursive: true });
205
+ await mkdir(agentDir, { recursive: true });
206
+ await writeFakeExecutable(binDir, "gh", `
207
+ const args = process.argv.slice(2);
208
+ if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
209
+ if (args[0] === "pr" && args[1] === "view") {
210
+ console.log(JSON.stringify({ number: 7, title: "Cross anchor", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
211
+ process.exit(0);
212
+ }
213
+ if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) { console.log(JSON.stringify([])); process.exit(0); }
214
+ if (args[0] === "api" && args[1].endsWith("/pulls/comments/999")) {
215
+ console.log(JSON.stringify({ id: 999, pull_request_url: "https://api.github.com/repos/other/repo/pulls/7", user: { login: "wrong" }, path: "wrong.ts", line: 1, body: "wrong pull" }));
216
+ process.exit(0);
217
+ }
218
+ process.exit(1);
219
+ `);
220
+
221
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
222
+ input: `
223
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
224
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7#discussion_r999");
225
+ console.log(JSON.stringify(result));
226
+ `,
227
+ encoding: "utf8",
228
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
229
+ });
230
+
231
+ assert.equal(child.status, 0, child.stderr);
232
+ const result = JSON.parse(child.stdout);
233
+ assert.doesNotMatch(result.content, /wrong pull/);
234
+ assert.match(result.content, /anchored review thread comment unavailable for this pull request/);
235
+ });
236
+
237
+ test("gh path still attempts an anchored review comment after page failure", { skip: SKIP_FAKE_GH }, async () => {
238
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-page-fail-anchor-"));
239
+ const binDir = join(root, "bin");
240
+ const agentDir = join(root, "agent");
241
+ await mkdir(binDir, { recursive: true });
242
+ await mkdir(agentDir, { recursive: true });
243
+ await writeFakeExecutable(binDir, "gh", `
244
+ const args = process.argv.slice(2);
245
+ if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
246
+ if (args[0] === "pr" && args[1] === "view") {
247
+ console.log(JSON.stringify({ number: 7, title: "Page fail anchor", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
248
+ process.exit(0);
249
+ }
250
+ if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) { process.exit(1); }
251
+ if (args[0] === "api" && args[1].endsWith("/pulls/comments/999")) {
252
+ console.log(JSON.stringify({ id: 999, pull_request_url: "https://api.github.com/repos/owner/repo/pulls/7", user: { login: "reviewer" }, path: "deep.ts", line: 44, body: "deep after page failure" }));
253
+ process.exit(0);
254
+ }
255
+ process.exit(1);
256
+ `);
257
+
258
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
259
+ input: `
260
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
261
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7#discussion_r999");
262
+ console.log(JSON.stringify(result));
263
+ `,
264
+ encoding: "utf8",
265
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
266
+ });
267
+
268
+ assert.equal(child.status, 0, child.stderr);
269
+ const result = JSON.parse(child.stdout);
270
+ assert.match(result.content, /reviewer.*\[anchored\]/s);
271
+ assert.match(result.content, /deep after page failure/);
272
+ });
273
+
274
+ test("gh review thread page failure renders unavailable instead of none", { skip: SKIP_FAKE_GH }, async () => {
275
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-review-unavailable-"));
276
+ const binDir = join(root, "bin");
277
+ const agentDir = join(root, "agent");
278
+ await mkdir(binDir, { recursive: true });
279
+ await mkdir(agentDir, { recursive: true });
280
+ await writeFakeExecutable(binDir, "gh", `
281
+ const args = process.argv.slice(2);
282
+ if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
283
+ if (args[0] === "pr" && args[1] === "view") {
284
+ console.log(JSON.stringify({ number: 7, title: "Unavailable reviews", state: "OPEN", author: { login: "alice" }, body: "body", comments: [] }));
285
+ process.exit(0);
286
+ }
287
+ if (args[0] === "api" && args[1].includes("/pulls/7/comments?")) { process.exit(1); }
288
+ process.exit(1);
289
+ `);
290
+
291
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
292
+ input: `
293
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
294
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7");
295
+ console.log(JSON.stringify(result));
296
+ `,
297
+ encoding: "utf8",
298
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
299
+ });
300
+
301
+ assert.equal(child.status, 0, child.stderr);
302
+ const result = JSON.parse(child.stdout);
303
+ assert.match(result.content, /review threads: unavailable/);
304
+ assert.match(result.content, /Review thread comments\nUnavailable in this GitHub fetch path/);
305
+ });
306
+
307
+ test("extractGitHubIssuePr aborts active gh work with the caller signal", async () => {
308
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-abort-"));
309
+ const binDir = join(root, "bin");
310
+ const agentDir = join(root, "agent");
311
+ await mkdir(binDir, { recursive: true });
312
+ await mkdir(agentDir, { recursive: true });
313
+ await writeFakeExecutable(binDir, "gh", `
314
+ const args = process.argv.slice(2);
315
+ if (args[0] === "--version") { console.log("gh version 2.0.0"); process.exit(0); }
316
+ setTimeout(() => {}, 30000);
317
+ `);
318
+
319
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
320
+ input: `
321
+ globalThis.fetch = async (_input, init = {}) => {
322
+ if (!init.signal?.aborted) throw new Error("fallback fetch did not receive aborted signal");
323
+ throw new Error("aborted fallback fetch");
324
+ };
325
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
326
+ const controller = new AbortController();
327
+ setTimeout(() => controller.abort(), 50);
328
+ const started = Date.now();
329
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7", controller.signal, { lookup: async () => [{ address: "140.82.112.6", family: 4 }] });
330
+ console.log(JSON.stringify({ elapsed: Date.now() - started, result }));
331
+ `,
332
+ encoding: "utf8",
333
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
334
+ });
335
+
336
+ assert.equal(child.status, 0, child.stderr);
337
+ const output = JSON.parse(child.stdout);
338
+ assert.equal(output.result.error, "Aborted");
339
+ assert.ok(output.elapsed < 1000, `expected abort before gh timeout, got ${output.elapsed}ms`);
340
+ });
341
+
342
+ test("extractGitHubIssuePr aborts a hung gh availability probe", async () => {
343
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-probe-abort-"));
344
+ const binDir = join(root, "bin");
345
+ const agentDir = join(root, "agent");
346
+ await mkdir(binDir, { recursive: true });
347
+ await mkdir(agentDir, { recursive: true });
348
+ await writeFakeExecutable(binDir, "gh", `setTimeout(() => {}, 30000);`);
349
+
350
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
351
+ input: `
352
+ const { extractGitHubIssuePr } = await import(${JSON.stringify(moduleUrl)});
353
+ const controller = new AbortController();
354
+ setTimeout(() => controller.abort(), 50);
355
+ const started = Date.now();
356
+ const result = await extractGitHubIssuePr("https://github.com/owner/repo/pull/7", controller.signal);
357
+ console.log(JSON.stringify({ elapsed: Date.now() - started, result }));
358
+ `,
359
+ encoding: "utf8",
360
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
361
+ });
362
+
363
+ assert.equal(child.status, 0, child.stderr);
364
+ const output = JSON.parse(child.stdout);
365
+ assert.equal(output.result.error, "Aborted");
366
+ assert.ok(output.elapsed < 1000, `expected abort before gh probe timeout, got ${output.elapsed}ms`);
367
+ });
368
+
369
+ test("REST fallback preserves caller cancellation", async () => {
370
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-rest-abort-"));
371
+ const binDir = join(root, "bin");
372
+ const agentDir = join(root, "agent");
373
+ await mkdir(binDir, { recursive: true });
374
+ await mkdir(agentDir, { recursive: true });
375
+ await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
376
+
377
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
378
+ input: `
379
+ const controller = new AbortController();
380
+ globalThis.fetch = async (_input, init = {}) => {
381
+ setTimeout(() => controller.abort(), 10);
382
+ await new Promise((resolve, reject) => init.signal.addEventListener("abort", () => reject(new Error("Aborted REST fetch")), { once: true }));
383
+ };
384
+ const { extractContent } = await import(${JSON.stringify(extractUrl)});
385
+ const lookup = ${publicLookup.toString()};
386
+ const started = Date.now();
387
+ const result = await extractContent("https://github.com/owner/repo/issues/12", controller.signal, { lookup });
388
+ console.log(JSON.stringify({ elapsed: Date.now() - started, result }));
389
+ `,
390
+ encoding: "utf8",
391
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
392
+ });
393
+
394
+ assert.equal(child.status, 0, child.stderr);
395
+ const output = JSON.parse(child.stdout.split("\n").at(-2));
396
+ assert.equal(output.result.error, "Aborted");
397
+ assert.ok(output.elapsed < 1000, `expected REST abort before generic fallback, got ${output.elapsed}ms`);
398
+ });
399
+
400
+ test("extractContent returns an actionable GitHub rate-limit result instead of HTML fall-through", async () => {
401
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-rate-"));
402
+ const binDir = join(root, "bin");
403
+ const agentDir = join(root, "agent");
404
+ await mkdir(binDir, { recursive: true });
405
+ await mkdir(agentDir, { recursive: true });
406
+ await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
407
+
408
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
409
+ input: `
410
+ globalThis.fetch = async () => new Response("rate limited", { status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "1800000000" } });
411
+ const { extractContent } = await import(${JSON.stringify(extractUrl)});
412
+ const lookup = ${publicLookup.toString()};
413
+ const result = await extractContent("https://github.com/owner/repo/issues/12", undefined, { lookup });
414
+ console.log(JSON.stringify(result));
415
+ `,
416
+ encoding: "utf8",
417
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
418
+ });
419
+
420
+ assert.equal(child.status, 0, child.stderr);
421
+ const result = JSON.parse(child.stdout.split("\n").at(-2));
422
+ assert.equal(result.status, 403);
423
+ assert.match(result.error, /rate limit/i);
424
+ assert.match(result.content, /gh auth login/);
425
+ });
426
+
427
+ test("REST fallback fetches an anchored issue comment outside the first page", async () => {
428
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-issue-anchor-"));
429
+ const binDir = join(root, "bin");
430
+ const agentDir = join(root, "agent");
431
+ await mkdir(binDir, { recursive: true });
432
+ await mkdir(agentDir, { recursive: true });
433
+ await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
434
+
435
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
436
+ input: `
437
+ globalThis.fetch = async (input) => {
438
+ const url = String(input);
439
+ if (url.endsWith("/issues/12")) return new Response(JSON.stringify({ number: 12, title: "Issue", state: "open", user: { login: "owner" }, body: "body", comments: 75 }), { status: 200 });
440
+ if (url.endsWith("/issues/12/comments?per_page=50")) return new Response(JSON.stringify([{ id: 1, user: { login: "first" }, created_at: "2026-01-01T00:00:00Z", body: "first page" }]), { status: 200 });
441
+ if (url.endsWith("/issues/comments/99")) return new Response(JSON.stringify({ id: 99, issue_url: "https://api.github.com/repos/owner/repo/issues/12", user: { login: "anchored" }, created_at: "2026-01-02T00:00:00Z", body: "outside first page" }), { status: 200 });
442
+ throw new Error("unexpected URL " + url);
443
+ };
444
+ const { extractContent } = await import(${JSON.stringify(extractUrl)});
445
+ const lookup = ${publicLookup.toString()};
446
+ const result = await extractContent("https://github.com/owner/repo/issues/12#issuecomment-99", undefined, { lookup });
447
+ console.log(JSON.stringify(result));
448
+ `,
449
+ encoding: "utf8",
450
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
451
+ });
452
+
453
+ assert.equal(child.status, 0, child.stderr);
454
+ const result = JSON.parse(child.stdout.split("\n").at(-2));
455
+ assert.match(result.content, /anchored.*\[anchored\]/s);
456
+ assert.match(result.content, /outside first page/);
457
+ assert.match(result.content, /comments: at least 75/);
458
+ assert.match(result.content, /comments shown from at least 75/);
459
+ });
460
+
461
+ test("REST fallback rejects anchored issue comments from another work item", async () => {
462
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-cross-issue-anchor-"));
463
+ const binDir = join(root, "bin");
464
+ const agentDir = join(root, "agent");
465
+ await mkdir(binDir, { recursive: true });
466
+ await mkdir(agentDir, { recursive: true });
467
+ await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
468
+
469
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
470
+ input: `
471
+ globalThis.fetch = async (input) => {
472
+ const url = String(input);
473
+ if (url.endsWith("/issues/12")) return new Response(JSON.stringify({ number: 12, title: "Issue", state: "open", user: { login: "owner" }, body: "body", comments: 1 }), { status: 200 });
474
+ if (url.endsWith("/issues/12/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
475
+ if (url.endsWith("/issues/comments/99")) return new Response(JSON.stringify({ id: 98, issue_url: "https://api.github.com/repos/other/repo/issues/12", user: { login: "wrong" }, created_at: "2026-01-02T00:00:00Z", body: "wrong issue" }), { status: 200 });
476
+ throw new Error("unexpected URL " + url);
477
+ };
478
+ const { extractContent } = await import(${JSON.stringify(extractUrl)});
479
+ const lookup = ${publicLookup.toString()};
480
+ const result = await extractContent("https://github.com/owner/repo/issues/12#issuecomment-99", undefined, { lookup });
481
+ console.log(JSON.stringify(result));
482
+ `,
483
+ encoding: "utf8",
484
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
485
+ });
486
+
487
+ assert.equal(child.status, 0, child.stderr);
488
+ const result = JSON.parse(child.stdout.split("\n").at(-2));
489
+ assert.doesNotMatch(result.content, /wrong issue/);
490
+ assert.match(result.content, /anchored comment unavailable for this issue or pull request/);
491
+ });
492
+
493
+ test("REST fallback fetches an anchored PR review comment outside the first page", async () => {
494
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-review-anchor-"));
495
+ const binDir = join(root, "bin");
496
+ const agentDir = join(root, "agent");
497
+ await mkdir(binDir, { recursive: true });
498
+ await mkdir(agentDir, { recursive: true });
499
+ await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
500
+
501
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
502
+ input: `
503
+ globalThis.fetch = async (input) => {
504
+ const url = String(input);
505
+ if (url.endsWith("/pulls/7")) return new Response(JSON.stringify({ number: 7, title: "PR", state: "open", user: { login: "owner" }, body: "body", draft: false, base: { ref: "main" }, head: { ref: "feature", repo: { owner: { login: "owner" } } }, additions: 1, deletions: 0, changed_files: 75, review_comments: 12 }), { status: 200 });
506
+ if (url.endsWith("/issues/7/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
507
+ if (url.endsWith("/pulls/7/files?per_page=50")) return new Response(JSON.stringify(Array.from({ length: 50 }, (_, index) => ({ filename: "file" + index + ".ts", additions: 1, deletions: 0 }))), { status: 200 });
508
+ if (url.endsWith("/pulls/7/comments?per_page=50")) return new Response(JSON.stringify([{ id: 1, user: { login: "first" }, path: "a.ts", line: 1, body: "first review" }]), { status: 200 });
509
+ if (url.endsWith("/pulls/comments/42")) return new Response(JSON.stringify({ id: 42, pull_request_url: "https://api.github.com/repos/owner/repo/pulls/7", user: { login: "reviewer" }, path: "b.ts", line: 9, body: "outside review page" }), { status: 200 });
510
+ throw new Error("unexpected URL " + url);
511
+ };
512
+ const { extractContent } = await import(${JSON.stringify(extractUrl)});
513
+ const lookup = ${publicLookup.toString()};
514
+ const result = await extractContent("https://github.com/owner/repo/pull/7#discussion_r42", undefined, { lookup });
515
+ console.log(JSON.stringify(result));
516
+ `,
517
+ encoding: "utf8",
518
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
519
+ });
520
+
521
+ assert.equal(child.status, 0, child.stderr);
522
+ const result = JSON.parse(child.stdout.split("\n").at(-2));
523
+ assert.match(result.content, /reviewer.*\[anchored\]/s);
524
+ assert.match(result.content, /outside review page/);
525
+ assert.match(result.content, /commits unavailable/);
526
+ assert.match(result.content, /Review verdicts\nUnavailable in this GitHub fetch path/);
527
+ assert.match(result.content, /50 files shown from at least 75/);
528
+ assert.match(result.content, /Commits\nUnavailable in this GitHub fetch path/);
529
+ assert.match(result.content, /review threads: at least 12/);
530
+ assert.match(result.content, /review thread comments shown from at least 12/);
531
+ assert.match(result.content, /Linked references\nUnavailable in this GitHub fetch path/);
532
+ });
533
+
534
+ test("REST fallback does not render positive changedFiles as none when files are missing", async () => {
535
+ const root = await mkdtemp(join(tmpdir(), "pi-web-access-gh-files-unavailable-"));
536
+ const binDir = join(root, "bin");
537
+ const agentDir = join(root, "agent");
538
+ await mkdir(binDir, { recursive: true });
539
+ await mkdir(agentDir, { recursive: true });
540
+ await writeFakeExecutable(binDir, "gh", `process.exit(1);`);
541
+
542
+ const child = spawnSync(process.execPath, ["--input-type=module"], {
543
+ input: `
544
+ globalThis.fetch = async (input) => {
545
+ const url = String(input);
546
+ if (url.endsWith("/pulls/7")) return new Response(JSON.stringify({ number: 7, title: "PR", state: "open", user: { login: "owner" }, body: "body", draft: false, base: { ref: "main" }, head: { ref: "feature", repo: { owner: { login: "owner" } } }, additions: 1, deletions: 0, changed_files: 3 }), { status: 200 });
547
+ if (url.endsWith("/issues/7/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
548
+ if (url.endsWith("/pulls/7/files?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
549
+ if (url.endsWith("/pulls/7/comments?per_page=50")) return new Response(JSON.stringify([]), { status: 200 });
550
+ throw new Error("unexpected URL " + url);
551
+ };
552
+ const { extractContent } = await import(${JSON.stringify(extractUrl)});
553
+ const lookup = ${publicLookup.toString()};
554
+ const result = await extractContent("https://github.com/owner/repo/pull/7", undefined, { lookup });
555
+ console.log(JSON.stringify(result));
556
+ `,
557
+ encoding: "utf8",
558
+ env: { ...process.env, PATH: `${binDir}${delimiter}${process.env.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir },
559
+ });
560
+
561
+ assert.equal(child.status, 0, child.stderr);
562
+ const result = JSON.parse(child.stdout.split("\n").at(-2));
563
+ assert.match(result.content, /0 files shown from at least 3/);
564
+ assert.doesNotMatch(result.content, /Files\nnone/);
565
+ });