@aviaratech/ai-delivery 0.3.35 → 0.3.36

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 (297) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -554
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +402 -515
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +329 -353
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +59 -19
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.js +73 -67
  95. package/dist/git.js.map +7 -1
  96. package/dist/gitProcess.d.ts +1 -1
  97. package/dist/gitProcess.js +58 -53
  98. package/dist/gitProcess.js.map +7 -1
  99. package/dist/github/client.d.ts +2 -2
  100. package/dist/github/client.js +484 -379
  101. package/dist/github/client.js.map +7 -1
  102. package/dist/github/commandIdentityPolicy.js +44 -52
  103. package/dist/github/commandIdentityPolicy.js.map +7 -1
  104. package/dist/github/discovery.d.ts +1 -0
  105. package/dist/github/discovery.js +197 -215
  106. package/dist/github/discovery.js.map +7 -1
  107. package/dist/github/discovery.test.js +223 -177
  108. package/dist/github/discovery.test.js.map +7 -1
  109. package/dist/github/issueHistory.d.ts +2 -2
  110. package/dist/github/issueHistory.js +117 -125
  111. package/dist/github/issueHistory.js.map +7 -1
  112. package/dist/github/machineAuth.d.ts +1 -1
  113. package/dist/github/machineAuth.js +126 -117
  114. package/dist/github/machineAuth.js.map +7 -1
  115. package/dist/github/machineAuth.test.js +755 -639
  116. package/dist/github/machineAuth.test.js.map +7 -1
  117. package/dist/github/nativeIssueMetadata.js +286 -273
  118. package/dist/github/nativeIssueMetadata.js.map +7 -1
  119. package/dist/github/projectDelivery.d.ts +18 -2
  120. package/dist/github/projectDelivery.js +615 -557
  121. package/dist/github/projectDelivery.js.map +7 -1
  122. package/dist/github/relationships.js +433 -389
  123. package/dist/github/relationships.js.map +7 -1
  124. package/dist/github/repo.d.ts +1 -0
  125. package/dist/github/repo.js +123 -96
  126. package/dist/github/repo.js.map +7 -1
  127. package/dist/index.js +3 -3
  128. package/dist/index.js.map +7 -1
  129. package/dist/issue.d.ts +40 -9
  130. package/dist/issue.js +2102 -1742
  131. package/dist/issue.js.map +7 -1
  132. package/dist/issue63History.test.js +40 -42
  133. package/dist/issue63History.test.js.map +7 -1
  134. package/dist/issue63Routes.test.js +154 -143
  135. package/dist/issue63Routes.test.js.map +7 -1
  136. package/dist/issueBatchUpdate.test.js +989 -885
  137. package/dist/issueBatchUpdate.test.js.map +7 -1
  138. package/dist/issueBlockerGuard.test.js +262 -226
  139. package/dist/issueBlockerGuard.test.js.map +7 -1
  140. package/dist/issueContract.d.ts +23 -4
  141. package/dist/issueContract.js +416 -395
  142. package/dist/issueContract.js.map +7 -1
  143. package/dist/issueContract.test.d.ts +4 -3
  144. package/dist/issueContract.test.js +358 -321
  145. package/dist/issueContract.test.js.map +7 -1
  146. package/dist/issueDates.test.js +235 -233
  147. package/dist/issueDates.test.js.map +7 -1
  148. package/dist/issueInfoReadback.test.js +304 -190
  149. package/dist/issueInfoReadback.test.js.map +7 -1
  150. package/dist/issueIntake.test.js +1945 -1732
  151. package/dist/issueIntake.test.js.map +7 -1
  152. package/dist/issueJournal.d.ts +40 -19
  153. package/dist/issueJournal.js +229 -138
  154. package/dist/issueJournal.js.map +7 -1
  155. package/dist/issueJournal.test.js +605 -422
  156. package/dist/issueJournal.test.js.map +7 -1
  157. package/dist/issueRollup.test.d.ts +1 -0
  158. package/dist/issueRollup.test.js +476 -0
  159. package/dist/issueRollup.test.js.map +7 -0
  160. package/dist/issueTracking.test.js +1059 -989
  161. package/dist/issueTracking.test.js.map +7 -1
  162. package/dist/issueWriteRecovery.test.d.ts +1 -0
  163. package/dist/issueWriteRecovery.test.js +260 -0
  164. package/dist/issueWriteRecovery.test.js.map +7 -0
  165. package/dist/lifecycle.test.js +112 -441
  166. package/dist/lifecycle.test.js.map +7 -1
  167. package/dist/logger.js +80 -74
  168. package/dist/logger.js.map +7 -1
  169. package/dist/mcp/index.js +116 -94
  170. package/dist/mcp/index.js.map +7 -1
  171. package/dist/mcp/tools.d.ts +264 -286
  172. package/dist/mcp/tools.js +267 -340
  173. package/dist/mcp/tools.js.map +7 -1
  174. package/dist/pluginAuthProbe.js +63 -52
  175. package/dist/pluginAuthProbe.js.map +7 -1
  176. package/dist/pluginAuthProbe.test.js +85 -62
  177. package/dist/pluginAuthProbe.test.js.map +7 -1
  178. package/dist/pluginCredentials.test.js +282 -259
  179. package/dist/pluginCredentials.test.js.map +7 -1
  180. package/dist/pluginDoctor.test.js +653 -588
  181. package/dist/pluginDoctor.test.js.map +7 -1
  182. package/dist/pluginInstaller.d.ts +7 -5
  183. package/dist/pluginInstaller.js +1173 -1229
  184. package/dist/pluginInstaller.js.map +7 -1
  185. package/dist/pluginInstaller.test.js +1842 -1423
  186. package/dist/pluginInstaller.test.js.map +7 -1
  187. package/dist/pluginPackaging.test.js +460 -409
  188. package/dist/pluginPackaging.test.js.map +7 -1
  189. package/dist/pr.d.ts +132 -94
  190. package/dist/pr.js +1521 -1323
  191. package/dist/pr.js.map +7 -1
  192. package/dist/pr.test.js +1678 -632
  193. package/dist/pr.test.js.map +7 -1
  194. package/dist/prAssociation.test.js +2419 -1788
  195. package/dist/prAssociation.test.js.map +7 -1
  196. package/dist/prDispatch.test.js +150 -89
  197. package/dist/prDispatch.test.js.map +7 -1
  198. package/dist/readView.d.ts +183 -0
  199. package/dist/readView.js +217 -0
  200. package/dist/readView.js.map +7 -0
  201. package/dist/readView.test.d.ts +1 -0
  202. package/dist/readView.test.js +119 -0
  203. package/dist/readView.test.js.map +7 -0
  204. package/dist/releaseReconciliation.test.js +267 -288
  205. package/dist/releaseReconciliation.test.js.map +7 -1
  206. package/dist/releaseWorkflow.test.js +2493 -422
  207. package/dist/releaseWorkflow.test.js.map +7 -1
  208. package/dist/review.d.ts +738 -2
  209. package/dist/review.js +601 -348
  210. package/dist/review.js.map +7 -1
  211. package/dist/review.test.js +1218 -812
  212. package/dist/review.test.js.map +7 -1
  213. package/dist/reviewSubmit.test.d.ts +1 -0
  214. package/dist/reviewSubmit.test.js +747 -0
  215. package/dist/reviewSubmit.test.js.map +7 -0
  216. package/dist/services/agentReadinessService.js +42 -37
  217. package/dist/services/agentReadinessService.js.map +7 -1
  218. package/dist/services/blockerGuardService.js +188 -188
  219. package/dist/services/blockerGuardService.js.map +7 -1
  220. package/dist/services/boardReconcileService.d.ts +125 -125
  221. package/dist/services/boardReconcileService.js +1295 -1421
  222. package/dist/services/boardReconcileService.js.map +7 -1
  223. package/dist/services/deliveryAdmission.js +131 -154
  224. package/dist/services/deliveryAdmission.js.map +7 -1
  225. package/dist/services/deliveryHealthService.js +197 -199
  226. package/dist/services/deliveryHealthService.js.map +7 -1
  227. package/dist/services/legacyIssueMigration.js +263 -277
  228. package/dist/services/legacyIssueMigration.js.map +7 -1
  229. package/dist/services/worktreeRegistry.d.ts +27 -119
  230. package/dist/services/worktreeRegistry.js +765 -1182
  231. package/dist/services/worktreeRegistry.js.map +7 -1
  232. package/dist/stagedChecks.test.js +396 -194
  233. package/dist/stagedChecks.test.js.map +7 -1
  234. package/dist/start.test.js +99 -95
  235. package/dist/start.test.js.map +7 -1
  236. package/dist/stdoutRegression.test.js +353 -352
  237. package/dist/stdoutRegression.test.js.map +7 -1
  238. package/dist/targetPolicyDiscovery.test.js +141 -143
  239. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  240. package/dist/targetPolicyEntrypoints.test.js +308 -269
  241. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  242. package/dist/targetPolicyLocal.test.js +580 -1051
  243. package/dist/targetPolicyLocal.test.js.map +7 -1
  244. package/dist/targetPolicyRoutes.test.js +305 -281
  245. package/dist/targetPolicyRoutes.test.js.map +7 -1
  246. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  247. package/dist/targetRepositoryExecution.test.js +463 -0
  248. package/dist/targetRepositoryExecution.test.js.map +7 -0
  249. package/dist/terminalMessages.js +41 -35
  250. package/dist/terminalMessages.js.map +7 -1
  251. package/dist/toolOutput.d.ts +2 -0
  252. package/dist/toolOutput.js +36 -0
  253. package/dist/toolOutput.js.map +7 -0
  254. package/dist/toolOutput.test.d.ts +1 -0
  255. package/dist/toolOutput.test.js +240 -0
  256. package/dist/toolOutput.test.js.map +7 -0
  257. package/dist/utils/atomicJson.js +84 -76
  258. package/dist/utils/atomicJson.js.map +7 -1
  259. package/dist/utils/filesystem.js +15 -18
  260. package/dist/utils/filesystem.js.map +7 -1
  261. package/dist/utils/lockfile.js +68 -71
  262. package/dist/utils/lockfile.js.map +7 -1
  263. package/dist/verification.d.ts +1 -19
  264. package/dist/verification.js +1020 -1939
  265. package/dist/verification.js.map +7 -1
  266. package/dist/verificationGate.test.js +127 -117
  267. package/dist/verificationGate.test.js.map +7 -1
  268. package/dist/version.js +23 -24
  269. package/dist/version.js.map +7 -1
  270. package/dist/worktree.d.ts +3 -15
  271. package/dist/worktree.js +97 -177
  272. package/dist/worktree.js.map +7 -1
  273. package/package.json +9 -8
  274. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  275. package/plugins/ai-delivery/README.md +47 -156
  276. package/plugins/ai-delivery/plugin.json +1 -1
  277. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  278. package/plugins/ai-delivery/runtime/dist/cli.js +358 -115
  279. package/plugins/ai-delivery/runtime/package.json +1 -1
  280. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  281. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  282. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  283. package/dist/investigationCompletion.test.js +0 -728
  284. package/dist/investigationCompletion.test.js.map +0 -1
  285. package/dist/setup.d.ts +0 -60
  286. package/dist/setup.js +0 -585
  287. package/dist/setup.js.map +0 -1
  288. package/dist/setup.test.js +0 -3329
  289. package/dist/setup.test.js.map +0 -1
  290. package/dist/worktreeTransition.d.ts +0 -211
  291. package/dist/worktreeTransition.js +0 -1037
  292. package/dist/worktreeTransition.js.map +0 -1
  293. package/dist/worktreeTransition.test.js +0 -1191
  294. package/dist/worktreeTransition.test.js.map +0 -1
  295. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  296. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  297. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,858 +1,1264 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync } from 'node:child_process';
3
- import { generateKeyPairSync } from 'node:crypto';
4
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5
- import { tmpdir } from 'node:os';
6
- import { join } from 'node:path';
7
- import { test } from 'vitest';
8
- import { digestValue } from './delivery/legacy.js';
9
- import { createDeliveryGitHubClients, withAuthorGitToken } from './github/client.js';
10
- import { preflightReviewRoute } from './pr.js';
11
- import { readRequiredReviewState, ReviewArtifactSchema, submitReview } from './review.js';
12
- const head = { sha: 'a'.repeat(40), tree: 'b'.repeat(40) };
13
- const publicationEvidenceId = `sha256:${'c'.repeat(64)}`;
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { generateKeyPairSync } from "node:crypto";
4
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { test } from "vitest";
8
+ import { recordedReassociation, recordedZeroApproval } from "./fixtures/recordedGitHubFlows.js";
9
+ import { digestValue } from "./delivery/legacy.js";
10
+ import { createDeliveryGitHubClients, withAuthorGitToken } from "./github/client.js";
11
+ import { preflightReviewRoute } from "./pr.js";
12
+ import {
13
+ buildReviewArtifact,
14
+ parseReviewVerdict,
15
+ readRequiredReviewState,
16
+ ReviewArtifactSchema,
17
+ submitReview
18
+ } from "./review.js";
19
+ const head = { sha: "a".repeat(40), tree: "b".repeat(40) };
20
+ const publicationEvidenceId = `sha256:${"c".repeat(64)}`;
14
21
  const marker = (id) => `<!-- ai-delivery-review-artifact: ${id} -->`;
15
- function fixture(input = {}) {
16
- const root = mkdtempSync(join(tmpdir(), 'ai-delivery-review-'));
17
- execFileSync('git', ['init', '-q', root]);
18
- const artifactContent = {
19
- authorIdentity: input.personalAuthor ? 'host-author' : 'synthetic-author',
20
- checks: ['build'],
21
- diffScopeHash: digestValue(['change.ts']),
22
- elapsedMs: 1,
23
- findings: [],
24
- head,
25
- issueNumber: 17,
26
- prNumber: 19,
27
- readOnly: true,
28
- requestedEffort: 'xhigh',
29
- requestedModel: 'gpt-6-astra',
30
- effectiveEffort: 'xhigh',
31
- effectiveModel: 'gpt-6-astra',
32
- reviewerIdentity: 'synthetic-reviewer',
33
- schemaVersion: 'ai-delivery.review-artifact@1',
34
- summary: 'Reviewed exact changes.',
35
- verdict: 'approve',
36
- };
37
- const artifact = ReviewArtifactSchema.parse({ ...artifactContent, artifactId: digestValue(artifactContent) });
38
- const review = {
39
- id: 41,
40
- state: 'APPROVED',
41
- commit_id: head.sha,
42
- user: { login: input.reviewLogin ?? 'synthetic-reviewer[bot]' },
43
- html_url: 'https://github.com/example/repo/pull/19#pullrequestreview-41',
44
- body: `${artifact.summary}\n\n${marker(artifact.artifactId)}\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(artifact)).toString('base64url')} -->`,
45
- };
46
- const reviews = input.existingReview ? [review] : [];
47
- let created = 0;
48
- let actorLookups = 0;
49
- let currentPrHead = head.sha;
50
- const context = {
51
- root,
52
- repo: { owner: 'example', repo: 'repo' },
53
- config: {
54
- repository: 'example/repo',
55
- roles: {
56
- author: input.personalAuthor
57
- ? { authSource: 'personal', identity: 'host-author' }
58
- : { identity: 'synthetic-author' },
59
- reviewer: { identity: 'synthetic-reviewer' },
60
- },
61
- },
22
+ const verdictInput = () => ({
23
+ schemaVersion: "ai-delivery.review-verdict@1",
24
+ verdict: "approve",
25
+ summary: "Reviewed changes.",
26
+ issueNumber: 17,
27
+ scope: { headSha: head.sha, headTree: head.tree, changedPaths: ["change.ts"] },
28
+ verificationReproduced: ["Required checks passed."],
29
+ requestedModel: "gpt-6-astra",
30
+ effectiveModel: "gpt-6-astra",
31
+ elapsedMs: 1,
32
+ findings: [],
33
+ readOnly: true
34
+ });
35
+ test("a verdict without an effort override truthfully records inherited effort", () => {
36
+ const verdict = parseReviewVerdict(verdictInput());
37
+ assert.equal(verdict.requestedEffort, "inherited");
38
+ assert.equal(verdict.effectiveEffort, "inherited");
39
+ assert.equal(parseReviewVerdict({ ...verdictInput(), effectiveEffort: "xhigh" }).effectiveEffort, "xhigh");
40
+ });
41
+ test("formal review normalizes unsorted duplicate and canonical rename-old paths", async () => {
42
+ const state = fixture();
43
+ try {
44
+ state.context.clients.rest.pulls.listFiles = (async () => ({
45
+ data: [{ filename: "change.ts", previous_filename: "old.ts", status: "renamed" }]
46
+ }));
47
+ const make = (changedPaths) => buildReviewArtifact({
48
+ verdict: parseReviewVerdict({
49
+ ...verdictInput(),
50
+ requestedEffort: "high",
51
+ effectiveEffort: "high",
52
+ scope: { ...verdictInput().scope, changedPaths }
53
+ }),
54
+ verdictFileSha256: `sha256:${"d".repeat(64)}`,
55
+ identity: "synthetic-reviewer",
56
+ provider: "openai",
57
+ expectedHead: head.sha,
58
+ prNumber: 19,
59
+ authorIdentity: "synthetic-author"
60
+ });
61
+ await submitReview({
62
+ context: state.context,
63
+ artifact: make(["old.ts", "change.ts", "change.ts"]),
64
+ issueNumber: 17,
65
+ prNumber: 19,
66
+ dryRun: true
67
+ });
68
+ for (const paths of [["old.ts"], ["change.ts", "unknown.ts"]])
69
+ await assert.rejects(
70
+ submitReview({ context: state.context, artifact: make(paths), issueNumber: 17, prNumber: 19, dryRun: true }),
71
+ /scope/u
72
+ );
73
+ assert.equal(state.created, 0);
74
+ } finally {
75
+ rmSync(state.root, { recursive: true, force: true });
76
+ }
77
+ });
78
+ for (const scenario of [
79
+ "clean",
80
+ "base-touch",
81
+ "reverted-touch",
82
+ "late-base-touch",
83
+ "changed-hunk",
84
+ "failed-verify",
85
+ "focused-verify",
86
+ "unfinalized-verify",
87
+ "legacy",
88
+ "dismissed-original",
89
+ "foreign-commit"
90
+ ]) {
91
+ test(`clean-rebase submission eligibility: ${scenario}`, async () => {
92
+ const state = fixture();
93
+ const proof = mkdtempSync(join(tmpdir(), "review-reuse-proof-"));
94
+ try {
95
+ const g = (...args) => execFileSync(
96
+ "git",
97
+ [
98
+ "-c",
99
+ "user.name=Fixture",
100
+ "-c",
101
+ "user.email=fixture@example.invalid",
102
+ "-c",
103
+ "commit.gpgsign=false",
104
+ "-c",
105
+ "core.hooksPath=/dev/null",
106
+ ...args
107
+ ],
108
+ { cwd: state.root, encoding: "utf8" }
109
+ ).trim();
110
+ const lines = Array.from({ length: 100 }, (_, i) => `line ${i}`);
111
+ writeFileSync(join(state.root, "change.ts"), lines.join("\n") + "\n");
112
+ g("add", ".");
113
+ g("commit", "-qm", "Original base");
114
+ const oldBase = g("rev-parse", "HEAD");
115
+ lines[50] = "reviewed change";
116
+ writeFileSync(join(state.root, "change.ts"), lines.join("\n") + "\n");
117
+ g("commit", "-qam", "Reviewed patch");
118
+ const oldHead = g("rev-parse", "HEAD");
119
+ const oldTree = g("rev-parse", "HEAD^{tree}");
120
+ g("checkout", "-qb", "advanced", oldBase);
121
+ writeFileSync(join(state.root, "other.ts"), "Unrelated base change\n");
122
+ if (scenario === "base-touch" || scenario === "reverted-touch") {
123
+ const baseLines = [...lines];
124
+ baseLines[50] = "line 50";
125
+ baseLines[5] = "base touched";
126
+ writeFileSync(join(state.root, "change.ts"), baseLines.join("\n") + "\n");
127
+ }
128
+ g("add", ".");
129
+ g("commit", "-qm", "Advance base");
130
+ if (scenario === "reverted-touch") {
131
+ const restored = [...lines];
132
+ restored[50] = "line 50";
133
+ writeFileSync(join(state.root, "change.ts"), restored.join("\n") + "\n");
134
+ g("commit", "-qam", "Revert base touch");
135
+ }
136
+ const newBase = g("rev-parse", "HEAD");
137
+ g("cherry-pick", oldHead);
138
+ if (scenario === "changed-hunk") {
139
+ lines[50] = "different patch";
140
+ writeFileSync(join(state.root, "change.ts"), lines.join("\n") + "\n");
141
+ g("commit", "-qam", "Change reviewed hunk");
142
+ }
143
+ const newHead = { sha: g("rev-parse", "HEAD"), tree: g("rev-parse", "HEAD^{tree}") };
144
+ let currentBase = newBase;
145
+ if (scenario === "late-base-touch") {
146
+ g("checkout", "-qb", "later-base", newBase);
147
+ const later = [...lines];
148
+ later[50] = "line 50";
149
+ later[5] = "late base touch";
150
+ writeFileSync(join(state.root, "change.ts"), later.join("\n") + "\n");
151
+ g("commit", "-qam", "Touch reviewed path after rebase");
152
+ later[5] = "line 5";
153
+ writeFileSync(join(state.root, "change.ts"), later.join("\n") + "\n");
154
+ g("commit", "-qam", "Revert late base touch");
155
+ currentBase = g("rev-parse", "HEAD");
156
+ g("checkout", "-q", newHead.sha);
157
+ }
158
+ const seal = (content) => ({ ...content, artifactId: digestValue(content) });
159
+ const { artifactId: _id, ...original } = state.artifact;
160
+ const oldArtifact = seal({
161
+ ...original,
162
+ head: { sha: oldHead, tree: oldTree },
163
+ ...scenario === "legacy" ? {} : { reviewBase: { baseSha: oldBase, mergeBaseSha: oldBase } }
164
+ });
165
+ const oldBody = `${marker(oldArtifact.artifactId)}
166
+ <!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(oldArtifact)).toString("base64url")} -->`;
167
+ const reviews = [
168
+ {
169
+ id: 41,
170
+ state: scenario === "dismissed-original" ? "DISMISSED" : "APPROVED",
171
+ // An approval belongs to the head it reviewed; a foreign commit must not carry it.
172
+ commit_id: scenario === "foreign-commit" ? newBase : oldHead,
173
+ user: { login: "synthetic-reviewer[bot]" },
174
+ html_url: "https://github.com/example/repo/pull/19#pullrequestreview-41",
175
+ body: oldBody
176
+ }
177
+ ];
178
+ const resultPath = join(proof, scenario === "unfinalized-verify" ? "result.json.tmp" : "result.json");
179
+ writeFileSync(
180
+ resultPath,
181
+ JSON.stringify({
182
+ schemaVersion: "contributor-checks@1",
183
+ scope: scenario === "focused-verify" ? "focused" : "full",
184
+ status: scenario === "failed-verify" ? "failed" : "passed",
185
+ exitCode: scenario === "failed-verify" ? 1 : 0,
186
+ fullSuccess: true,
187
+ omitted: [],
188
+ gates: ["format", "lint", "types", "build", "tests", "inventory"],
189
+ verifiedHead: newHead,
190
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
191
+ commands: ["format", "lint", "types", "build", "tests", "inventory"].map((stage) => ({
192
+ stage,
193
+ status: "passed",
194
+ exitCode: 0,
195
+ cleanupConfirmed: true
196
+ }))
197
+ }),
198
+ { mode: 384 }
199
+ );
200
+ const artifact = seal({
201
+ ...original,
202
+ head: newHead,
203
+ reviewBase: { baseSha: currentBase, mergeBaseSha: newBase },
204
+ reuse: { fromReviewId: 41, verificationResultPath: resultPath }
205
+ });
206
+ const rest = state.context.clients.rest;
207
+ const context = {
208
+ ...state.context,
62
209
  clients: {
63
- authSource: 'app',
64
- role: 'reviewer',
65
- appActorLogin: async () => {
66
- actorLookups += 1;
67
- return 'synthetic-reviewer[bot]';
68
- },
69
- rest: {
70
- users: {
71
- getAuthenticated: () => {
72
- throw new Error('installation token cannot call GET /user');
73
- },
74
- },
75
- git: { getCommit: async () => ({ data: { sha: head.sha, tree: { sha: head.tree } } }) },
76
- pulls: {
77
- get: async () => ({
78
- data: {
79
- number: 19,
80
- changed_files: 1,
81
- base: { sha: 'c'.repeat(40), repo: { full_name: 'example/repo' } },
82
- head: { sha: currentPrHead, repo: { full_name: 'example/repo' } },
83
- state: 'open',
84
- user: { login: input.authorLogin === undefined ? 'synthetic-author[bot]' : input.authorLogin },
85
- },
86
- }),
87
- listFiles: async () => ({ data: [{ filename: 'change.ts' }] }),
88
- getReview: async () => ({ data: review }),
89
- listReviews: async () => ({ data: reviews }),
90
- createReview: async (input) => {
91
- review.body = input.body;
92
- created += 1;
93
- reviews.push(review);
94
- return { data: review };
95
- },
96
- },
210
+ ...state.context.clients,
211
+ rest: Object.assign({}, rest, {
212
+ git: {
213
+ ...rest.git,
214
+ getCommit: async ({ commit_sha }) => ({
215
+ data: { sha: commit_sha, tree: { sha: g("rev-parse", `${commit_sha}^{tree}`) } }
216
+ })
97
217
  },
98
- },
99
- };
100
- const classification = { head, changedPaths: ['change.ts'] };
101
- const submit = () => submitReview({ artifact, classification, context, issueNumber: 17, prNumber: 19, publicationEvidenceId });
102
- return {
103
- root,
104
- artifact,
105
- reviews,
106
- submit,
107
- setPrHead(sha) {
108
- currentPrHead = sha;
109
- },
110
- get created() {
111
- return created;
112
- },
113
- get actorLookups() {
114
- return actorLookups;
115
- },
116
- };
218
+ repos: { compareCommitsWithBasehead: async () => ({ data: { merge_base_commit: { sha: newBase } } }) },
219
+ pulls: {
220
+ ...rest.pulls,
221
+ get: async () => ({
222
+ data: {
223
+ number: 19,
224
+ state: "open",
225
+ changed_files: 1,
226
+ base: { sha: currentBase, repo: { full_name: "example/repo" } },
227
+ head: { sha: newHead.sha, repo: { full_name: "example/repo" } },
228
+ user: { login: "author" }
229
+ }
230
+ }),
231
+ listReviews: async () => ({ data: reviews }),
232
+ getReview: async ({ review_id }) => ({
233
+ data: reviews.find((x) => x.id === review_id)
234
+ }),
235
+ createReview: async ({ body, commit_id }) => {
236
+ assert.equal(commit_id, newHead.sha);
237
+ const created = {
238
+ ...reviews[0],
239
+ id: 42,
240
+ body,
241
+ commit_id,
242
+ html_url: "https://github.com/example/repo/pull/19#pullrequestreview-42"
243
+ };
244
+ reviews.push(created);
245
+ return { data: created };
246
+ }
247
+ }
248
+ })
249
+ }
250
+ };
251
+ const action = () => submitReview({ context, artifact, issueNumber: 17, prNumber: 19 });
252
+ if (scenario === "clean") {
253
+ const result = await action();
254
+ assert.equal(result.githubReviewId, 42);
255
+ assert.equal(result.artifact.head.sha, newHead.sha);
256
+ const reused = result.artifact.reusedFrom;
257
+ assert.equal(reused?.oldHead, oldHead);
258
+ assert.equal(reused?.newHead, newHead.sha);
259
+ assert.equal(reused?.reviewId, 41);
260
+ assert.ok(!reviews[1].body.includes(resultPath));
261
+ } else await assert.rejects(action(), /fresh review/u);
262
+ assert.equal(reviews.length, scenario === "clean" ? 2 : 1);
263
+ assert.equal(reviews[0].body, oldBody);
264
+ } finally {
265
+ rmSync(state.root, { recursive: true, force: true });
266
+ rmSync(proof, { recursive: true, force: true });
267
+ }
268
+ });
117
269
  }
118
- test('reviewer App bot submits and reuses an exact-head approval without GET /user', async () => {
119
- const state = fixture();
120
- try {
121
- const first = await state.submit();
122
- assert.equal(first.login, 'synthetic-reviewer[bot]');
123
- assert.equal(state.created, 1);
124
- const encoded = state.reviews[0].body.match(/<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->/u)?.[1];
125
- assert.ok(encoded, 'App review must retain its independently hash-verifiable artifact binding');
126
- assert.deepEqual(JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')), state.artifact);
127
- const second = await state.submit();
128
- assert.equal(second.receiptId, first.receiptId);
129
- assert.equal(state.created, 1);
130
- assert.equal(state.actorLookups, 2);
131
- state.setPrHead('d'.repeat(40));
132
- await assert.rejects(state.submit(), /head changed/u);
270
+ function fixture(input = {}) {
271
+ const fixtureHead = input.head ?? head;
272
+ const root = mkdtempSync(join(tmpdir(), "ai-delivery-review-"));
273
+ execFileSync("git", ["init", "-q", root]);
274
+ const artifactContent = {
275
+ authorIdentity: input.personalAuthor ? "host-author" : "synthetic-author",
276
+ checks: ["build"],
277
+ diffScopeHash: digestValue(["change.ts"]),
278
+ elapsedMs: 1,
279
+ findings: [],
280
+ head: fixtureHead,
281
+ issueNumber: 17,
282
+ prNumber: 19,
283
+ readOnly: true,
284
+ requestedEffort: "xhigh",
285
+ requestedModel: "gpt-6-astra",
286
+ effectiveEffort: "xhigh",
287
+ effectiveModel: "gpt-6-astra",
288
+ reviewerIdentity: "synthetic-reviewer",
289
+ schemaVersion: "ai-delivery.review-artifact@1",
290
+ summary: "Reviewed exact changes.",
291
+ verdict: input.verdict ?? "approve"
292
+ };
293
+ const artifact = ReviewArtifactSchema.parse({ ...artifactContent, artifactId: digestValue(artifactContent) });
294
+ const review = {
295
+ id: 41,
296
+ state: input.verdict === "request-changes" ? "CHANGES_REQUESTED" : "APPROVED",
297
+ commit_id: fixtureHead.sha,
298
+ user: { login: input.reviewLogin ?? "synthetic-reviewer[bot]" },
299
+ html_url: "https://github.com/example/repo/pull/19#pullrequestreview-41",
300
+ body: `${artifact.summary}
301
+
302
+ ${marker(artifact.artifactId)}
303
+ <!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(artifact)).toString("base64url")} -->`
304
+ };
305
+ const reviews = input.existingReview ? [review] : [];
306
+ let created = 0;
307
+ let actorLookups = 0;
308
+ let currentPrHead = fixtureHead.sha;
309
+ const events = [];
310
+ const context = {
311
+ root,
312
+ repo: { owner: "example", repo: "repo" },
313
+ config: {
314
+ repository: "example/repo",
315
+ roles: {
316
+ author: input.personalAuthor ? { authSource: "personal", identity: "host-author" } : { identity: "synthetic-author" },
317
+ reviewer: { identity: "synthetic-reviewer" }
318
+ }
319
+ },
320
+ clients: {
321
+ authSource: "app",
322
+ role: "reviewer",
323
+ appActorLogin: async () => {
324
+ actorLookups += 1;
325
+ return "synthetic-reviewer[bot]";
326
+ },
327
+ rest: {
328
+ users: {
329
+ getAuthenticated: () => {
330
+ throw new Error("installation token cannot call GET /user");
331
+ }
332
+ },
333
+ git: { getCommit: async () => ({ data: { sha: fixtureHead.sha, tree: { sha: fixtureHead.tree } } }) },
334
+ pulls: {
335
+ get: async () => ({
336
+ data: {
337
+ number: 19,
338
+ changed_files: 1,
339
+ base: { sha: "c".repeat(40), repo: { full_name: "example/repo" } },
340
+ head: { sha: currentPrHead, repo: { full_name: "example/repo" } },
341
+ state: "open",
342
+ user: { login: input.authorLogin === void 0 ? "synthetic-author[bot]" : input.authorLogin }
343
+ }
344
+ }),
345
+ listFiles: async () => ({ data: [{ filename: "change.ts" }] }),
346
+ getReview: async () => ({ data: review }),
347
+ listReviews: async () => ({ data: reviews }),
348
+ createReview: async (input2) => {
349
+ events.push(input2.event ?? "missing");
350
+ review.body = input2.body;
351
+ created += 1;
352
+ reviews.push(review);
353
+ return { data: review };
354
+ }
355
+ }
356
+ }
133
357
  }
134
- finally {
135
- rmSync(state.root, { recursive: true, force: true });
358
+ };
359
+ const classification = { head: fixtureHead, changedPaths: ["change.ts"] };
360
+ const submit = () => submitReview({ artifact, classification, context, issueNumber: 17, prNumber: 19, publicationEvidenceId });
361
+ return {
362
+ root,
363
+ context,
364
+ artifact,
365
+ reviews,
366
+ events,
367
+ submit,
368
+ setPrHead(sha) {
369
+ currentPrHead = sha;
370
+ },
371
+ get created() {
372
+ return created;
373
+ },
374
+ get actorLookups() {
375
+ return actorLookups;
136
376
  }
377
+ };
378
+ }
379
+ test("request-changes posts its own event and reuses only its exact rejection receipt", async () => {
380
+ const state = fixture({ verdict: "request-changes" });
381
+ try {
382
+ const result = await state.submit();
383
+ assert.equal(result.state, "CHANGES_REQUESTED");
384
+ assert.deepEqual(state.events, ["REQUEST_CHANGES"]);
385
+ assert.equal((await state.submit()).receiptId, result.receiptId);
386
+ assert.equal(state.created, 1);
387
+ state.setPrHead("f".repeat(40));
388
+ await assert.rejects(state.submit(), /head changed/u);
389
+ assert.equal(state.created, 1);
390
+ } finally {
391
+ rmSync(state.root, { recursive: true, force: true });
392
+ }
137
393
  });
138
- test('configured App reviewer approves a host-authored PR once at the exact head', async () => {
139
- const state = fixture({ authorLogin: 'host-user', personalAuthor: true });
140
- try {
141
- const first = await state.submit();
142
- assert.equal(first.login, 'synthetic-reviewer[bot]');
143
- assert.equal(state.created, 1);
144
- assert.equal((await state.submit()).receiptId, first.receiptId);
145
- assert.equal(state.created, 1);
146
- }
147
- finally {
148
- rmSync(state.root, { recursive: true, force: true });
149
- }
394
+ test("reviewer App bot submits and reuses an exact-head approval without GET /user", async () => {
395
+ const state = fixture();
396
+ try {
397
+ const first = await state.submit();
398
+ assert.equal(first.login, "synthetic-reviewer[bot]");
399
+ assert.equal(state.created, 1);
400
+ const encoded = state.reviews[0].body.match(/<!-- ai-delivery-review-artifact-data: ([A-Za-z0-9_-]+) -->/u)?.[1];
401
+ assert.ok(encoded, "App review must retain its independently hash-verifiable artifact binding");
402
+ assert.deepEqual(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")), state.artifact);
403
+ const second = await state.submit();
404
+ assert.equal(second.receiptId, first.receiptId);
405
+ assert.equal(state.created, 1);
406
+ assert.equal(state.actorLookups, 2);
407
+ state.setPrHead("d".repeat(40));
408
+ await assert.rejects(state.submit(), /head changed/u);
409
+ } finally {
410
+ rmSync(state.root, { recursive: true, force: true });
411
+ }
150
412
  });
151
- test('reviewer App bot recovers a matching remote marker without another review', async () => {
152
- const state = fixture({ existingReview: true });
153
- try {
154
- const receipt = await state.submit();
155
- assert.equal(receipt.githubReviewId, 41);
156
- assert.equal(state.created, 0);
157
- }
158
- finally {
159
- rmSync(state.root, { recursive: true, force: true });
160
- }
413
+ test("configured App reviewer approves a host-authored PR once at the exact head", async () => {
414
+ const state = fixture({ authorLogin: "host-user", personalAuthor: true });
415
+ try {
416
+ const first = await state.submit();
417
+ assert.equal(first.login, "synthetic-reviewer[bot]");
418
+ assert.equal(state.created, 1);
419
+ assert.equal((await state.submit()).receiptId, first.receiptId);
420
+ assert.equal(state.created, 1);
421
+ } finally {
422
+ rmSync(state.root, { recursive: true, force: true });
423
+ }
161
424
  });
162
- test('reviewer submits a fresh exact-head artifact despite a historical remapped approval', async () => {
163
- const state = fixture({ existingReview: true });
164
- try {
165
- const { artifactId: _artifactId, ...original } = state.artifact;
166
- const oldContent = { ...original, head: { sha: 'e'.repeat(40), tree: 'f'.repeat(40) } };
167
- const oldArtifact = ReviewArtifactSchema.parse({ ...oldContent, artifactId: digestValue(oldContent) });
168
- state.reviews[0].body = `${marker(oldArtifact.artifactId)}\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(oldArtifact)).toString('base64url')} -->`;
169
- assert.equal(state.reviews[0].commit_id, state.artifact.head.sha);
170
- await state.submit();
171
- assert.equal(state.created, 1);
172
- }
173
- finally {
174
- rmSync(state.root, { recursive: true, force: true });
175
- }
425
+ test("reviewer App bot recovers a matching remote marker without another review", async () => {
426
+ const state = fixture({ existingReview: true });
427
+ try {
428
+ const receipt = await state.submit();
429
+ assert.equal(receipt.githubReviewId, 41);
430
+ assert.equal(state.created, 0);
431
+ } finally {
432
+ rmSync(state.root, { recursive: true, force: true });
433
+ }
176
434
  });
177
- test('reviewer App rejects self review and a foreign marker actor', async () => {
178
- const self = fixture({ authorLogin: 'synthetic-reviewer[bot]' });
179
- const unknownAuthor = fixture({ authorLogin: null });
180
- const foreign = fixture({ existingReview: true, reviewLogin: 'another-app[bot]' });
181
- try {
182
- await assert.rejects(self.submit(), /must differ from PR author/u);
183
- await assert.rejects(unknownAuthor.submit(), /must differ from PR author/u);
184
- await assert.rejects(foreign.submit(), /conflicts with exact-head approval/u);
185
- assert.equal(self.created, 0);
186
- assert.equal(unknownAuthor.created, 0);
187
- assert.equal(foreign.created, 0);
188
- }
189
- finally {
190
- rmSync(self.root, { recursive: true, force: true });
191
- rmSync(unknownAuthor.root, { recursive: true, force: true });
192
- rmSync(foreign.root, { recursive: true, force: true });
193
- }
435
+ test("reviewer submits a fresh exact-head artifact despite a historical remapped approval", async () => {
436
+ const state = fixture({ existingReview: true });
437
+ try {
438
+ const { artifactId: _artifactId, ...original } = state.artifact;
439
+ const oldContent = { ...original, head: { sha: "e".repeat(40), tree: "f".repeat(40) } };
440
+ const oldArtifact = ReviewArtifactSchema.parse({ ...oldContent, artifactId: digestValue(oldContent) });
441
+ state.reviews[0].body = `${marker(oldArtifact.artifactId)}
442
+ <!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(oldArtifact)).toString("base64url")} -->`;
443
+ assert.equal(state.reviews[0].commit_id, state.artifact.head.sha);
444
+ await state.submit();
445
+ assert.equal(state.created, 1);
446
+ } finally {
447
+ rmSync(state.root, { recursive: true, force: true });
448
+ }
194
449
  });
195
- for (const reviewDecision of [undefined, 'UNKNOWN', false, 0, {}]) {
196
- test(`missing or malformed review decision ${JSON.stringify(reviewDecision)} cannot carry qualifying review evidence`, async () => {
197
- let accessReads = 0;
198
- const context = {
199
- repo: { owner: 'example', repo: 'repo' },
200
- clients: {
201
- graphql: async (query) => {
202
- if (query.includes('DeliveryReviewAccess')) {
203
- accessReads++;
204
- return {
205
- repository: {
206
- pullRequest: {
207
- reviews: {
208
- nodes: [
209
- {
210
- fullDatabaseId: 41,
211
- author: { login: 'reviewer' },
212
- commit: { oid: head.sha },
213
- state: 'APPROVED',
214
- authorCanPushToRepository: true,
215
- },
216
- ],
217
- },
218
- },
219
- },
220
- };
221
- }
222
- return { repository: { pullRequest: { headRefOid: head.sha, reviewDecision } } };
223
- },
224
- },
225
- };
226
- const result = await readRequiredReviewState(context, 19, head.sha, { id: 41, login: 'reviewer[bot]' });
227
- assert.equal(result.reviewDecision, null);
228
- assert.equal(result.status, 'unknown');
229
- assert.equal(result.submittedReviewAuthorCanPushToRepository, null);
230
- assert.equal(accessReads, 0);
231
- });
232
- }
233
- test('live GitHub review decision distinguishes a submitted review from a satisfied requirement', async () => {
234
- const state = fixture();
235
- try {
236
- const context = {
237
- root: state.root,
238
- repo: { owner: 'example', repo: 'repo' },
239
- clients: {
240
- graphql: async () => ({
241
- repository: { pullRequest: { headRefOid: head.sha, reviewDecision: 'REVIEW_REQUIRED' } },
242
- }),
243
- },
244
- };
245
- const pending = await readRequiredReviewState(context, 19, head.sha);
246
- assert.equal(pending.status, 'still-required');
247
- assert.equal(pending.reviewDecision, 'REVIEW_REQUIRED');
248
- assert.match(pending.nextAction, /eligible independent reviewer/u);
249
- assert.doesNotMatch(pending.nextAction, /submitted APPROVED review/u);
250
- context.clients.graphql = (async () => ({
251
- repository: { pullRequest: { headRefOid: head.sha, reviewDecision: 'APPROVED' } },
252
- }));
253
- const satisfied = await readRequiredReviewState(context, 19, head.sha);
254
- assert.equal(satisfied.status, 'satisfied');
255
- context.clients.graphql = (async () => {
256
- throw new Error('Repository rules unreadable');
257
- });
258
- const unknown = await readRequiredReviewState(context, 19, head.sha);
259
- assert.equal(unknown.status, 'unknown');
260
- assert.match(unknown.nextAction, /inspect the PR review requirement/iu);
261
- context.clients.graphql = (async () => ({ repository: null }));
262
- assert.equal((await readRequiredReviewState(context, 19, head.sha)).status, 'unknown');
263
- }
264
- finally {
265
- rmSync(state.root, { recursive: true, force: true });
266
- }
450
+ test("reviewer App rejects self review and a foreign marker actor", async () => {
451
+ const self = fixture({ authorLogin: "synthetic-reviewer[bot]" });
452
+ const unknownAuthor = fixture({ authorLogin: null });
453
+ const foreign = fixture({ existingReview: true, reviewLogin: "another-app[bot]" });
454
+ try {
455
+ await assert.rejects(self.submit(), /must differ from PR author/u);
456
+ await assert.rejects(unknownAuthor.submit(), /must differ from PR author/u);
457
+ await assert.rejects(foreign.submit(), /conflicts with exact-head approval/u);
458
+ assert.equal(self.created, 0);
459
+ assert.equal(unknownAuthor.created, 0);
460
+ assert.equal(foreign.created, 0);
461
+ } finally {
462
+ rmSync(self.root, { recursive: true, force: true });
463
+ rmSync(unknownAuthor.root, { recursive: true, force: true });
464
+ rmSync(foreign.root, { recursive: true, force: true });
465
+ }
267
466
  });
268
- test('post-review readback reports exact App review push access without overriding GitHub decision', async () => {
269
- let reviewDecision = 'REVIEW_REQUIRED';
270
- let reviewId = '41';
271
- let reviewAuthor = 'reviewer-app';
272
- let reviewCommit = head.sha;
273
- let authorCanPushToRepository = false;
467
+ for (const reviewDecision of [void 0, "UNKNOWN", false, 0, {}]) {
468
+ test(`missing or malformed review decision ${JSON.stringify(reviewDecision)} cannot carry qualifying review evidence`, async () => {
469
+ let accessReads = 0;
274
470
  const context = {
275
- repo: { owner: 'example', repo: 'repo' },
276
- clients: {
277
- graphql: async (query) => query.includes('DeliveryReviewAccess')
278
- ? {
279
- repository: {
280
- pullRequest: {
281
- reviews: {
282
- nodes: [
283
- {
284
- fullDatabaseId: reviewId,
285
- author: { login: reviewAuthor },
286
- commit: { oid: reviewCommit },
287
- state: 'APPROVED',
288
- authorCanPushToRepository,
289
- },
290
- ],
291
- },
292
- },
293
- },
471
+ repo: { owner: "example", repo: "repo" },
472
+ clients: {
473
+ graphql: async (query) => {
474
+ if (query.includes("DeliveryReviewAccess")) {
475
+ accessReads++;
476
+ return {
477
+ repository: {
478
+ pullRequest: {
479
+ reviews: {
480
+ nodes: [
481
+ {
482
+ fullDatabaseId: 41,
483
+ author: { login: "reviewer" },
484
+ commit: { oid: head.sha },
485
+ state: "APPROVED",
486
+ authorCanPushToRepository: true
487
+ }
488
+ ]
489
+ }
294
490
  }
295
- : { repository: { pullRequest: { headRefOid: head.sha, reviewDecision } } },
296
- },
297
- };
298
- const submittedReview = { id: 41, login: 'reviewer-app[bot]' };
299
- const insufficient = await readRequiredReviewState(context, 19, head.sha, submittedReview);
300
- assert.equal(insufficient.status, 'still-required');
301
- assert.equal(insufficient.submittedReviewAuthorCanPushToRepository, false);
302
- assert.match(insufficient.nextAction, /reviewer App.*write access/iu);
303
- authorCanPushToRepository = true;
304
- const writeCapable = await readRequiredReviewState(context, 19, head.sha, submittedReview);
305
- assert.equal(writeCapable.status, 'still-required');
306
- assert.equal(writeCapable.submittedReviewAuthorCanPushToRepository, true);
307
- reviewAuthor = 'unrelated-reviewer[bot]';
308
- assert.equal((await readRequiredReviewState(context, 19, head.sha, submittedReview)).submittedReviewAuthorCanPushToRepository, null);
309
- reviewAuthor = 'reviewer-app';
310
- reviewId = '42';
311
- assert.equal((await readRequiredReviewState(context, 19, head.sha, submittedReview)).submittedReviewAuthorCanPushToRepository, null);
312
- reviewId = '41';
313
- reviewCommit = 'd'.repeat(40);
314
- assert.equal((await readRequiredReviewState(context, 19, head.sha, submittedReview)).submittedReviewAuthorCanPushToRepository, null);
315
- reviewCommit = head.sha;
316
- authorCanPushToRepository = false;
317
- reviewDecision = 'APPROVED';
318
- const satisfied = await readRequiredReviewState(context, 19, head.sha, submittedReview);
319
- assert.equal(satisfied.status, 'satisfied');
320
- assert.equal(satisfied.submittedReviewAuthorCanPushToRepository, false);
321
- });
322
- function unprotectedRouteFixture() {
323
- const state = {
324
- deniedRoute: '',
325
- protectionError: { status: 404, response: { status: 404, data: { message: 'Branch not protected' } } },
326
- rules: { status: 200, headers: {}, data: [] },
327
- rulesets: { status: 200, headers: {}, data: [] },
328
- branch: { status: 200, data: { name: 'main', protected: false, protection: { enabled: false } } },
329
- repository: {
330
- status: 200,
331
- data: { full_name: 'example/repo', permissions: { push: true, admin: true } },
332
- },
333
- };
334
- const reviewer = {
335
- authSource: 'app',
336
- role: 'reviewer',
337
- effectiveContentsPermission: 'read',
338
- appActorLogin: async () => 'reviewer-app[bot]',
339
- rest: { repos: { get: async () => ({ data: { full_name: 'example/repo' } }) } },
491
+ }
492
+ };
493
+ }
494
+ return { repository: { pullRequest: { headRefOid: head.sha, reviewDecision } } };
495
+ }
496
+ }
340
497
  };
498
+ const result = await readRequiredReviewState(context, 19, head.sha, { id: 41, login: "reviewer[bot]" });
499
+ assert.equal(result.reviewDecision, null);
500
+ assert.equal(result.status, "unknown");
501
+ assert.equal(result.submittedReviewAuthorCanPushToRepository, null);
502
+ assert.equal(accessReads, 0);
503
+ });
504
+ }
505
+ test("live GitHub review decision distinguishes a submitted review from a satisfied requirement", async () => {
506
+ const state = fixture();
507
+ try {
341
508
  const context = {
342
- repo: { owner: 'example', repo: 'repo' },
343
- config: { roles: { author: { authSource: 'personal', identity: 'author' }, reviewer: { identity: 'reviewer' } } },
344
- clients: {
345
- authSource: 'personal',
346
- role: 'author',
347
- authenticatedAuthor: async () => ({ actorLogin: 'host-user', credentialIdentity: 'user:37' }),
348
- rest: {
349
- request: async (route, input) => {
350
- assert.equal(input.owner, 'example');
351
- assert.equal(input.repo, 'repo');
352
- if (route === state.deniedRoute)
353
- throw Object.assign(new Error('Denied'), { status: 403 });
354
- if (route.endsWith('/rules/branches/{branch}'))
355
- return state.rules;
356
- if (route.endsWith('/branches/{branch}/protection'))
357
- throw state.protectionError;
358
- if (route.endsWith('/branches/{branch}')) {
359
- assert.equal(input.branch, 'main');
360
- return state.branch;
361
- }
362
- if (route.endsWith('/rulesets')) {
363
- assert.equal(input.includes_parents, true);
364
- assert.equal(input.page, 1);
365
- assert.equal(input.per_page, 100);
366
- return state.rulesets;
367
- }
368
- if (route === 'GET /repos/{owner}/{repo}')
369
- return state.repository;
370
- throw new Error(`Unexpected fictional route ${route}`);
371
- },
372
- },
373
- },
509
+ root: state.root,
510
+ repo: { owner: "example", repo: "repo" },
511
+ clients: {
512
+ graphql: async () => ({
513
+ repository: { pullRequest: { headRefOid: head.sha, reviewDecision: "REVIEW_REQUIRED" } }
514
+ })
515
+ }
374
516
  };
375
- return { state, read: () => preflightReviewRoute(context, 'main', reviewer) };
517
+ const pending = await readRequiredReviewState(context, 19, head.sha);
518
+ assert.equal(pending.status, "still-required");
519
+ assert.equal(pending.reviewDecision, "REVIEW_REQUIRED");
520
+ assert.match(pending.nextAction, /eligible independent reviewer/u);
521
+ assert.doesNotMatch(pending.nextAction, /submitted APPROVED review/u);
522
+ context.clients.graphql = (async () => ({
523
+ repository: { pullRequest: { headRefOid: head.sha, reviewDecision: "APPROVED" } }
524
+ }));
525
+ const satisfied = await readRequiredReviewState(context, 19, head.sha);
526
+ assert.equal(satisfied.status, "satisfied");
527
+ context.clients.graphql = (async () => {
528
+ throw new Error("Repository rules unreadable");
529
+ });
530
+ const unknown = await readRequiredReviewState(context, 19, head.sha);
531
+ assert.equal(unknown.status, "unknown");
532
+ assert.match(unknown.nextAction, /inspect the PR review requirement/iu);
533
+ context.clients.graphql = (async () => ({ repository: null }));
534
+ assert.equal((await readRequiredReviewState(context, 19, head.sha)).status, "unknown");
535
+ } finally {
536
+ rmSync(state.root, { recursive: true, force: true });
537
+ }
538
+ });
539
+ test("post-review readback reports exact App review push access without overriding GitHub decision", async () => {
540
+ let reviewDecision = "REVIEW_REQUIRED";
541
+ let reviewId = "41";
542
+ let reviewAuthor = "reviewer-app";
543
+ let reviewCommit = head.sha;
544
+ let authorCanPushToRepository = false;
545
+ const context = {
546
+ repo: { owner: "example", repo: "repo" },
547
+ clients: {
548
+ graphql: async (query) => query.includes("DeliveryReviewAccess") ? {
549
+ repository: {
550
+ pullRequest: {
551
+ reviews: {
552
+ nodes: [
553
+ {
554
+ fullDatabaseId: reviewId,
555
+ author: { login: reviewAuthor },
556
+ commit: { oid: reviewCommit },
557
+ state: "APPROVED",
558
+ authorCanPushToRepository
559
+ }
560
+ ]
561
+ }
562
+ }
563
+ }
564
+ } : { repository: { pullRequest: { headRefOid: head.sha, reviewDecision } } }
565
+ }
566
+ };
567
+ const submittedReview = { id: 41, login: "reviewer-app[bot]" };
568
+ const insufficient = await readRequiredReviewState(context, 19, head.sha, submittedReview);
569
+ assert.equal(insufficient.status, "still-required");
570
+ assert.equal(insufficient.submittedReviewAuthorCanPushToRepository, false);
571
+ assert.match(insufficient.nextAction, /reviewer App.*write access/iu);
572
+ authorCanPushToRepository = true;
573
+ const writeCapable = await readRequiredReviewState(context, 19, head.sha, submittedReview);
574
+ assert.equal(writeCapable.status, "still-required");
575
+ assert.equal(writeCapable.submittedReviewAuthorCanPushToRepository, true);
576
+ reviewAuthor = "unrelated-reviewer[bot]";
577
+ assert.equal(
578
+ (await readRequiredReviewState(context, 19, head.sha, submittedReview)).submittedReviewAuthorCanPushToRepository,
579
+ null
580
+ );
581
+ reviewAuthor = "reviewer-app";
582
+ reviewId = "42";
583
+ assert.equal(
584
+ (await readRequiredReviewState(context, 19, head.sha, submittedReview)).submittedReviewAuthorCanPushToRepository,
585
+ null
586
+ );
587
+ reviewId = "41";
588
+ reviewCommit = "d".repeat(40);
589
+ assert.equal(
590
+ (await readRequiredReviewState(context, 19, head.sha, submittedReview)).submittedReviewAuthorCanPushToRepository,
591
+ null
592
+ );
593
+ reviewCommit = head.sha;
594
+ authorCanPushToRepository = false;
595
+ reviewDecision = "APPROVED";
596
+ const satisfied = await readRequiredReviewState(context, 19, head.sha, submittedReview);
597
+ assert.equal(satisfied.status, "satisfied");
598
+ assert.equal(satisfied.submittedReviewAuthorCanPushToRepository, false);
599
+ });
600
+ function unprotectedRouteFixture() {
601
+ const state = {
602
+ deniedRoute: "",
603
+ protectionError: { status: 404, response: { status: 404, data: { message: "Branch not protected" } } },
604
+ rules: { status: 200, headers: {}, data: [] },
605
+ rulesets: { status: 200, headers: {}, data: [] },
606
+ branch: { status: 200, data: { name: "main", protected: false, protection: { enabled: false } } },
607
+ repository: {
608
+ status: 200,
609
+ data: { full_name: "example/repo", permissions: { push: true, admin: true } }
610
+ }
611
+ };
612
+ const reviewer = {
613
+ authSource: "app",
614
+ role: "reviewer",
615
+ effectiveContentsPermission: "read",
616
+ appActorLogin: async () => "reviewer-app[bot]",
617
+ rest: { repos: { get: async () => ({ data: { full_name: "example/repo" } }) } }
618
+ };
619
+ const context = {
620
+ repo: { owner: "example", repo: "repo" },
621
+ config: { roles: { author: { authSource: "personal", identity: "author" }, reviewer: { identity: "reviewer" } } },
622
+ clients: {
623
+ authSource: "personal",
624
+ role: "author",
625
+ authenticatedAuthor: async () => ({ actorLogin: "host-user", credentialIdentity: "user:37" }),
626
+ rest: {
627
+ request: async (route, input) => {
628
+ assert.equal(input.owner, "example");
629
+ assert.equal(input.repo, "repo");
630
+ if (route === state.deniedRoute) throw Object.assign(new Error("Denied"), { status: 403 });
631
+ if (route.endsWith("/rules/branches/{branch}")) return state.rules;
632
+ if (route.endsWith("/branches/{branch}/protection")) throw state.protectionError;
633
+ if (route.endsWith("/branches/{branch}")) {
634
+ assert.equal(input.branch, "main");
635
+ return state.branch;
636
+ }
637
+ if (route.endsWith("/rulesets")) {
638
+ assert.equal(input.includes_parents, true);
639
+ assert.equal(input.page, 1);
640
+ assert.equal(input.per_page, 100);
641
+ return state.rulesets;
642
+ }
643
+ if (route === "GET /repos/{owner}/{repo}") return state.repository;
644
+ throw new Error(`Unexpected fictional route ${route}`);
645
+ }
646
+ }
647
+ }
648
+ };
649
+ return { state, read: () => preflightReviewRoute(context, "main", reviewer) };
376
650
  }
377
- test('confirmed unprotected branch has complete visibility without asserting reviewer eligibility', async () => {
378
- const { read } = unprotectedRouteFixture();
379
- const route = await read();
380
- assert.deepEqual(route.rules, { visibility: 'complete', observedRequiredApprovals: 0 });
381
- assert.equal(route.approvalEligibility, 'unknown');
382
- assert.equal(route.reviewer.actorLogin, 'reviewer-app[bot]');
651
+ test("confirmed unprotected branch has complete visibility without asserting reviewer eligibility", async () => {
652
+ const { read } = unprotectedRouteFixture();
653
+ const route = await read();
654
+ assert.deepEqual(route.rules, { visibility: "complete", observedRequiredApprovals: 0 });
655
+ assert.equal(route.approvalEligibility, "unknown");
656
+ assert.equal(route.reviewer.actorLogin, "reviewer-app[bot]");
383
657
  });
384
658
  for (const [name, change] of [
385
- ['generic 404', { protectionError: { status: 404, response: { status: 404, data: { message: 'Not Found' } } } }],
386
- [
387
- 'permission denial',
388
- { protectionError: { status: 403, response: { status: 403, data: { message: 'Branch not protected' } } } },
389
- ],
390
- ['unstructured error', { protectionError: Object.assign(new Error('Branch not protected'), { status: 404 }) }],
391
- [
392
- 'conflicting error status',
393
- { protectionError: { status: 404, response: { status: 403, data: { message: 'Branch not protected' } } } },
394
- ],
395
- [
396
- 'incomplete applicable rules',
397
- { rules: { status: 200, data: [], headers: { link: '<https://api.github.com/next>; rel="next"' } } },
398
- ],
399
- [
400
- 'incomplete rulesets',
401
- { rulesets: { status: 200, data: [], headers: { link: '<https://api.github.com/next>; rel="next"' } } },
402
- ],
403
- [
404
- 'inherited ruleset',
405
- { rulesets: { status: 200, headers: {}, data: [{ source_type: 'Organization', enforcement: 'active' }] } },
406
- ],
407
- [
408
- 'inherited active rule',
409
- {
410
- rules: {
411
- status: 200,
412
- headers: {},
413
- data: [{ type: 'pull_request', parameters: { required_approving_review_count: 1 } }],
414
- },
415
- },
416
- ],
417
- ['malformed rules', { rules: { status: 200, headers: {}, data: {} } }],
418
- ['malformed rulesets', { rulesets: { status: 200, headers: {}, data: null } }],
419
- ['missing pagination headers', { rulesets: { status: 200, data: [] } }],
420
- ['null pagination headers', { rulesets: { status: 200, headers: null, data: [] } }],
421
- [
422
- 'malformed repository identity',
423
- { repository: { status: 200, data: { full_name: 37, permissions: { push: true } } } },
424
- ],
425
- ['denied branch read', { deniedRoute: 'GET /repos/{owner}/{repo}/branches/{branch}' }],
426
- ['denied repository read', { deniedRoute: 'GET /repos/{owner}/{repo}' }],
427
- ['denied ruleset read', { deniedRoute: 'GET /repos/{owner}/{repo}/rulesets' }],
428
- [
429
- 'no write permission',
430
- { repository: { status: 200, data: { full_name: 'example/repo', permissions: { push: false, admin: false } } } },
431
- ],
432
- [
433
- 'foreign repository',
434
- { repository: { status: 200, data: { full_name: 'other/repo', permissions: { admin: true } } } },
435
- ],
436
- [
437
- 'protected branch',
438
- { branch: { status: 200, data: { name: 'main', protected: true, protection: { enabled: false } } } },
439
- ],
440
- [
441
- 'enabled protection',
442
- { branch: { status: 200, data: { name: 'main', protected: false, protection: { enabled: true } } } },
443
- ],
444
- [
445
- 'foreign branch',
446
- { branch: { status: 200, data: { name: 'other', protected: false, protection: { enabled: false } } } },
447
- ],
659
+ ["generic 404", { protectionError: { status: 404, response: { status: 404, data: { message: "Not Found" } } } }],
660
+ [
661
+ "permission denial",
662
+ { protectionError: { status: 403, response: { status: 403, data: { message: "Branch not protected" } } } }
663
+ ],
664
+ ["unstructured error", { protectionError: Object.assign(new Error("Branch not protected"), { status: 404 }) }],
665
+ [
666
+ "conflicting error status",
667
+ { protectionError: { status: 404, response: { status: 403, data: { message: "Branch not protected" } } } }
668
+ ],
669
+ [
670
+ "incomplete applicable rules",
671
+ { rules: { status: 200, data: [], headers: { link: '<https://api.github.com/next>; rel="next"' } } }
672
+ ],
673
+ [
674
+ "incomplete rulesets",
675
+ { rulesets: { status: 200, data: [], headers: { link: '<https://api.github.com/next>; rel="next"' } } }
676
+ ],
677
+ [
678
+ "inherited ruleset",
679
+ { rulesets: { status: 200, headers: {}, data: [{ source_type: "Organization", enforcement: "active" }] } }
680
+ ],
681
+ [
682
+ "inherited active rule",
683
+ {
684
+ rules: {
685
+ status: 200,
686
+ headers: {},
687
+ data: [{ type: "pull_request", parameters: { required_approving_review_count: 1 } }]
688
+ }
689
+ }
690
+ ],
691
+ ["malformed rules", { rules: { status: 200, headers: {}, data: {} } }],
692
+ ["malformed rulesets", { rulesets: { status: 200, headers: {}, data: null } }],
693
+ ["missing pagination headers", { rulesets: { status: 200, data: [] } }],
694
+ ["null pagination headers", { rulesets: { status: 200, headers: null, data: [] } }],
695
+ [
696
+ "malformed repository identity",
697
+ { repository: { status: 200, data: { full_name: 37, permissions: { push: true } } } }
698
+ ],
699
+ ["denied branch read", { deniedRoute: "GET /repos/{owner}/{repo}/branches/{branch}" }],
700
+ ["denied repository read", { deniedRoute: "GET /repos/{owner}/{repo}" }],
701
+ ["denied ruleset read", { deniedRoute: "GET /repos/{owner}/{repo}/rulesets" }],
702
+ [
703
+ "no write permission",
704
+ { repository: { status: 200, data: { full_name: "example/repo", permissions: { push: false, admin: false } } } }
705
+ ],
706
+ [
707
+ "foreign repository",
708
+ { repository: { status: 200, data: { full_name: "other/repo", permissions: { admin: true } } } }
709
+ ],
710
+ [
711
+ "protected branch",
712
+ { branch: { status: 200, data: { name: "main", protected: true, protection: { enabled: false } } } }
713
+ ],
714
+ [
715
+ "enabled protection",
716
+ { branch: { status: 200, data: { name: "main", protected: false, protection: { enabled: true } } } }
717
+ ],
718
+ [
719
+ "foreign branch",
720
+ { branch: { status: 200, data: { name: "other", protected: false, protection: { enabled: false } } } }
721
+ ]
448
722
  ]) {
449
- test(`unprotected classification refuses ${name}`, async () => {
450
- const { state, read } = unprotectedRouteFixture();
451
- Object.assign(state, change);
452
- assert.notEqual((await read()).rules.visibility, 'complete');
453
- });
723
+ test(`unprotected classification refuses ${name}`, async () => {
724
+ const { state, read } = unprotectedRouteFixture();
725
+ Object.assign(state, change);
726
+ assert.notEqual((await read()).rules.visibility, "complete");
727
+ });
454
728
  }
455
- test('prepublication review route reports selected actors and unknown approval eligibility', async () => {
456
- const author = {
457
- authSource: 'personal',
458
- credentialSource: 'env:AUTHOR_TOKEN',
459
- role: 'author',
460
- authenticatedAuthor: async () => ({ actorLogin: 'host-user', credentialIdentity: 'user:37' }),
729
+ test("prepublication review route reports selected actors and unknown approval eligibility", async () => {
730
+ const author = {
731
+ authSource: "personal",
732
+ credentialSource: "env:AUTHOR_TOKEN",
733
+ role: "author",
734
+ authenticatedAuthor: async () => ({ actorLogin: "host-user", credentialIdentity: "user:37" }),
735
+ rest: {
736
+ request: async (route2) => {
737
+ if (route2 === "GET /repos/{owner}/{repo}/rules/branches/{branch}")
738
+ return { data: [{ type: "pull_request", parameters: { required_approving_review_count: 1 } }] };
739
+ if (route2 === "GET /repos/{owner}/{repo}/branches/{branch}/protection")
740
+ throw Object.assign(new Error("not visible"), { status: 403 });
741
+ throw new Error(`Unexpected route ${route2}`);
742
+ }
743
+ }
744
+ };
745
+ const reviewer = {
746
+ authSource: "app",
747
+ credentialSource: "app:102:installation:202",
748
+ effectiveContentsPermission: "read",
749
+ role: "reviewer",
750
+ appActorLogin: async () => "reviewer-app[bot]",
751
+ rest: { repos: { get: async () => ({ data: { full_name: "example/repo" } }) } }
752
+ };
753
+ const context = {
754
+ repo: { owner: "example", repo: "repo" },
755
+ config: {
756
+ roles: { author: { authSource: "personal", identity: "host-author" }, reviewer: { identity: "reviewer-app" } }
757
+ },
758
+ clients: author
759
+ };
760
+ const route = await preflightReviewRoute(context, "main", reviewer);
761
+ assert.equal(route.author.actorLogin, "host-user");
762
+ assert.equal(route.author.credentialSource, "env:AUTHOR_TOKEN");
763
+ assert.equal(route.reviewer.actorLogin, "reviewer-app[bot]");
764
+ assert.equal(route.reviewer.repositoryAccess, "readable");
765
+ assert.equal(route.rules.visibility, "partial");
766
+ assert.equal(route.rules.observedRequiredApprovals, 1);
767
+ assert.equal(route.approvalEligibility, "insufficient-permission");
768
+ assert.match(route.nextAction, /Contents: write/u);
769
+ const writeCapable = await preflightReviewRoute(context, "main", {
770
+ ...reviewer,
771
+ effectiveContentsPermission: "write"
772
+ });
773
+ assert.equal(writeCapable.approvalEligibility, "unknown");
774
+ assert.match(writeCapable.nextAction, /confirm whether the reviewer approval counts/u);
775
+ const missingGrant = await preflightReviewRoute(context, "main", {
776
+ ...reviewer,
777
+ effectiveContentsPermission: void 0
778
+ });
779
+ assert.equal(missingGrant.approvalEligibility, "unknown");
780
+ const unreadable = await preflightReviewRoute(
781
+ {
782
+ ...context,
783
+ clients: {
784
+ ...author,
785
+ rest: { request: async () => Promise.reject(new Error("Rules unavailable")) }
786
+ }
787
+ },
788
+ "main",
789
+ reviewer
790
+ );
791
+ assert.equal(unreadable.rules.visibility, "unknown");
792
+ assert.equal(unreadable.rules.observedRequiredApprovals, null);
793
+ assert.equal(unreadable.approvalEligibility, "unknown");
794
+ const noRequiredReview = await preflightReviewRoute(
795
+ {
796
+ ...context,
797
+ clients: {
798
+ ...author,
461
799
  rest: {
462
- request: async (route) => {
463
- if (route === 'GET /repos/{owner}/{repo}/rules/branches/{branch}')
464
- return { data: [{ type: 'pull_request', parameters: { required_approving_review_count: 1 } }] };
465
- if (route === 'GET /repos/{owner}/{repo}/branches/{branch}/protection')
466
- throw Object.assign(new Error('not visible'), { status: 403 });
467
- throw new Error(`Unexpected route ${route}`);
468
- },
469
- },
470
- };
471
- const reviewer = {
472
- authSource: 'app',
473
- credentialSource: 'app:102:installation:202',
474
- effectiveContentsPermission: 'read',
475
- role: 'reviewer',
476
- appActorLogin: async () => 'reviewer-app[bot]',
477
- rest: { repos: { get: async () => ({ data: { full_name: 'example/repo' } }) } },
478
- };
479
- const context = {
480
- repo: { owner: 'example', repo: 'repo' },
481
- config: {
482
- roles: { author: { authSource: 'personal', identity: 'host-author' }, reviewer: { identity: 'reviewer-app' } },
483
- },
484
- clients: author,
485
- };
486
- const route = await preflightReviewRoute(context, 'main', reviewer);
487
- assert.equal(route.author.actorLogin, 'host-user');
488
- assert.equal(route.author.credentialSource, 'env:AUTHOR_TOKEN');
489
- assert.equal(route.reviewer.actorLogin, 'reviewer-app[bot]');
490
- assert.equal(route.reviewer.repositoryAccess, 'readable');
491
- assert.equal(route.rules.visibility, 'partial');
492
- assert.equal(route.rules.observedRequiredApprovals, 1);
493
- assert.equal(route.approvalEligibility, 'insufficient-permission');
494
- assert.match(route.nextAction, /Contents: write/u);
495
- const writeCapable = await preflightReviewRoute(context, 'main', {
496
- ...reviewer,
497
- effectiveContentsPermission: 'write',
498
- });
499
- assert.equal(writeCapable.approvalEligibility, 'unknown');
500
- assert.match(writeCapable.nextAction, /confirm whether the reviewer approval counts/u);
501
- const missingGrant = await preflightReviewRoute(context, 'main', {
502
- ...reviewer,
503
- effectiveContentsPermission: undefined,
504
- });
505
- assert.equal(missingGrant.approvalEligibility, 'unknown');
506
- const unreadable = await preflightReviewRoute({
507
- ...context,
508
- clients: {
509
- ...author,
510
- rest: { request: async () => Promise.reject(new Error('Rules unavailable')) },
511
- },
512
- }, 'main', reviewer);
513
- assert.equal(unreadable.rules.visibility, 'unknown');
514
- assert.equal(unreadable.rules.observedRequiredApprovals, null);
515
- assert.equal(unreadable.approvalEligibility, 'unknown');
516
- const noRequiredReview = await preflightReviewRoute({
517
- ...context,
518
- clients: {
519
- ...author,
520
- rest: {
521
- request: async (route) => route === 'GET /repos/{owner}/{repo}/rules/branches/{branch}'
522
- ? { data: [] }
523
- : { data: { required_pull_request_reviews: null } },
524
- },
525
- },
526
- }, 'main', reviewer);
527
- assert.equal(noRequiredReview.rules.visibility, 'complete');
528
- assert.equal(noRequiredReview.rules.observedRequiredApprovals, null);
529
- assert.equal(noRequiredReview.approvalEligibility, 'unknown');
530
- assert.match(noRequiredReview.nextAction, /No required approving review was observed/u);
531
- assert.doesNotMatch(noRequiredReview.nextAction, /Contents: write/u);
532
- const appRoute = await preflightReviewRoute({
533
- ...context,
534
- config: { roles: { author: { identity: 'author-app' }, reviewer: { identity: 'reviewer-app' } } },
535
- clients: {
536
- ...author,
537
- authSource: 'app',
538
- credentialSource: 'app:101:installation:201',
539
- authenticatedAuthor: async () => ({
540
- actorLogin: 'author-app[bot]',
541
- credentialIdentity: 'app:101:installation:201',
542
- }),
543
- },
544
- }, 'main', reviewer);
545
- assert.equal(appRoute.author.actorLogin, 'author-app[bot]');
546
- assert.equal(appRoute.author.authSource, 'app');
547
- await assert.rejects(preflightReviewRoute(context, 'main', { ...reviewer, appActorLogin: async () => 'host-user' }), /same GitHub actor/u);
548
- await assert.rejects(preflightReviewRoute({
800
+ request: async (route2) => route2 === "GET /repos/{owner}/{repo}/rules/branches/{branch}" ? { data: [] } : { data: { required_pull_request_reviews: null } }
801
+ }
802
+ }
803
+ },
804
+ "main",
805
+ reviewer
806
+ );
807
+ assert.equal(noRequiredReview.rules.visibility, "complete");
808
+ assert.equal(noRequiredReview.rules.observedRequiredApprovals, null);
809
+ assert.equal(noRequiredReview.approvalEligibility, "unknown");
810
+ assert.match(noRequiredReview.nextAction, /No required approving review was observed/u);
811
+ assert.doesNotMatch(noRequiredReview.nextAction, /Contents: write/u);
812
+ const appRoute = await preflightReviewRoute(
813
+ {
814
+ ...context,
815
+ config: { roles: { author: { identity: "author-app" }, reviewer: { identity: "reviewer-app" } } },
816
+ clients: {
817
+ ...author,
818
+ authSource: "app",
819
+ credentialSource: "app:101:installation:201",
820
+ authenticatedAuthor: async () => ({
821
+ actorLogin: "author-app[bot]",
822
+ credentialIdentity: "app:101:installation:201"
823
+ })
824
+ }
825
+ },
826
+ "main",
827
+ reviewer
828
+ );
829
+ assert.equal(appRoute.author.actorLogin, "author-app[bot]");
830
+ assert.equal(appRoute.author.authSource, "app");
831
+ await assert.rejects(
832
+ preflightReviewRoute(context, "main", { ...reviewer, appActorLogin: async () => "host-user" }),
833
+ /same GitHub actor/u
834
+ );
835
+ await assert.rejects(
836
+ preflightReviewRoute(
837
+ {
549
838
  ...context,
550
- config: { roles: { author: { identity: 'app-author' }, reviewer: { identity: 'reviewer-app' } } },
551
- }, 'main', reviewer), /configure the personal author role/u);
839
+ config: { roles: { author: { identity: "app-author" }, reviewer: { identity: "reviewer-app" } } }
840
+ },
841
+ "main",
842
+ reviewer
843
+ ),
844
+ /configure the personal author role/u
845
+ );
552
846
  });
553
847
  test.each([
554
- 'available',
555
- 'missing-reviewer',
556
- 'reviewer-permission',
557
- 'author-readback',
558
- 'same-actor',
559
- 'wrong-repository',
560
- ])('development personal override uses the real reviewer factory with unused author App credentials absent: %s', async (scenario) => {
561
- const root = mkdtempSync(join(tmpdir(), 'ai-delivery-personal-preflight-'));
848
+ "available",
849
+ "missing-reviewer",
850
+ "reviewer-permission",
851
+ "author-readback",
852
+ "same-actor",
853
+ "wrong-repository"
854
+ ])(
855
+ "development personal override uses the real reviewer factory with unused author App credentials absent: %s",
856
+ async (scenario) => {
857
+ const root = mkdtempSync(join(tmpdir(), "ai-delivery-personal-preflight-"));
562
858
  const originalFetch = globalThis.fetch;
563
- const keyPath = join(root, 'reviewer.pem');
859
+ const keyPath = join(root, "reviewer.pem");
564
860
  const config = {
565
- roles: {
566
- author: {
567
- identity: 'unused-author-app',
568
- credentialEnv: {
569
- appId: 'PREFLIGHT_UNUSED_AUTHOR_APP_ID',
570
- installationId: 'PREFLIGHT_UNUSED_AUTHOR_INSTALLATION_ID',
571
- privateKeyPath: 'PREFLIGHT_UNUSED_AUTHOR_KEY_PATH',
572
- },
573
- },
574
- reviewer: {
575
- identity: 'reviewer-app',
576
- credentialEnv: {
577
- appId: 'PREFLIGHT_REVIEWER_APP_ID',
578
- installationId: 'PREFLIGHT_REVIEWER_INSTALLATION_ID',
579
- privateKeyPath: 'PREFLIGHT_REVIEWER_KEY_PATH',
580
- },
581
- },
861
+ roles: {
862
+ author: {
863
+ identity: "unused-author-app",
864
+ credentialEnv: {
865
+ appId: "PREFLIGHT_UNUSED_AUTHOR_APP_ID",
866
+ installationId: "PREFLIGHT_UNUSED_AUTHOR_INSTALLATION_ID",
867
+ privateKeyPath: "PREFLIGHT_UNUSED_AUTHOR_KEY_PATH"
868
+ }
582
869
  },
870
+ reviewer: {
871
+ identity: "reviewer-app",
872
+ credentialEnv: {
873
+ appId: "PREFLIGHT_REVIEWER_APP_ID",
874
+ installationId: "PREFLIGHT_REVIEWER_INSTALLATION_ID",
875
+ privateKeyPath: "PREFLIGHT_REVIEWER_KEY_PATH"
876
+ }
877
+ }
878
+ }
583
879
  };
584
880
  const reviewerEnv = {
585
- PREFLIGHT_REVIEWER_APP_ID: '102',
586
- PREFLIGHT_REVIEWER_INSTALLATION_ID: '202',
587
- PREFLIGHT_REVIEWER_KEY_PATH: keyPath,
881
+ PREFLIGHT_REVIEWER_APP_ID: "102",
882
+ PREFLIGHT_REVIEWER_INSTALLATION_ID: "202",
883
+ PREFLIGHT_REVIEWER_KEY_PATH: keyPath
588
884
  };
885
+ assert.ok("credentialEnv" in config.roles.author);
589
886
  const envNames = [...Object.values(config.roles.author.credentialEnv), ...Object.keys(reviewerEnv)];
590
887
  const savedEnv = new Map(envNames.map((name) => [name, process.env[name]]));
591
888
  const requests = [];
592
889
  try {
593
- writeFileSync(keyPath, generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ format: 'pem', type: 'pkcs8' }));
594
- for (const name of envNames)
595
- delete process.env[name];
596
- if (scenario !== 'missing-reviewer')
597
- Object.assign(process.env, reviewerEnv);
598
- globalThis.fetch = async (url, init) => {
599
- const pathname = new URL(url instanceof Request ? url.url : String(url)).pathname;
600
- const authorization = new Headers(init?.headers).get('authorization') ?? '';
601
- requests.push(`${init?.method ?? 'GET'} ${pathname}`);
602
- const response = (data, status = 200) => new Response(JSON.stringify(data), {
603
- status,
604
- headers: { 'content-type': 'application/json' },
605
- });
606
- if (pathname === '/user') {
607
- assert.equal(authorization, 'token synthetic-development-author');
608
- return response({
609
- id: 37,
610
- login: scenario === 'author-readback' ? '' : scenario === 'same-actor' ? 'reviewer-app[bot]' : 'host-user',
611
- });
612
- }
613
- if (pathname === '/app' || pathname === '/app/installations/202/access_tokens') {
614
- assert.match(authorization, /^bearer [^.]+\.[^.]+\.[^.]+$/u);
615
- const jwt = JSON.parse(Buffer.from(authorization.split('.')[1], 'base64url').toString());
616
- assert.equal(String(jwt.iss), '102');
617
- if (pathname === '/app')
618
- return response({ id: 102, slug: 'reviewer-app' });
619
- return response({
620
- token: 'ghs_synthetic_reviewer',
621
- expires_at: new Date(Date.now() + 3600000).toISOString(),
622
- permissions: {
623
- contents: 'read',
624
- ...(scenario === 'reviewer-permission' ? {} : { pull_requests: 'write' }),
625
- },
626
- repository_selection: 'all',
627
- }, 201);
628
- }
629
- if (pathname === '/repos/example/repo') {
630
- assert.equal(authorization, 'token ghs_synthetic_reviewer');
631
- return response({ full_name: scenario === 'wrong-repository' ? 'example/other' : 'example/repo' });
632
- }
633
- assert.ok(['/repos/example/repo/rules/branches/main', '/repos/example/repo/branches/main/protection'].includes(pathname));
634
- assert.equal(authorization, 'token synthetic-development-author');
635
- return response({ message: 'Rules unavailable' }, 403);
636
- };
637
- const author = await createDeliveryGitHubClients({
638
- config,
639
- env: {},
640
- identity: 'personal',
641
- personalAuth: { enabled: true, token: 'synthetic-development-author' },
642
- role: 'author',
890
+ writeFileSync(
891
+ keyPath,
892
+ generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ format: "pem", type: "pkcs8" })
893
+ );
894
+ for (const name of envNames) delete process.env[name];
895
+ if (scenario !== "missing-reviewer") Object.assign(process.env, reviewerEnv);
896
+ globalThis.fetch = async (url, init) => {
897
+ const pathname = new URL(url instanceof Request ? url.url : String(url)).pathname;
898
+ const authorization = new Headers(init?.headers).get("authorization") ?? "";
899
+ requests.push(`${init?.method ?? "GET"} ${pathname}`);
900
+ const response = (data, status = 200) => new Response(JSON.stringify(data), {
901
+ status,
902
+ headers: { "content-type": "application/json" }
643
903
  });
644
- const context = { root, repo: { owner: 'example', repo: 'repo' }, config, clients: author };
645
- if (scenario === 'available') {
646
- const route = await preflightReviewRoute(context, 'main', undefined, 'development');
647
- assert.equal(route.author.actorLogin, 'host-user');
648
- assert.equal(route.author.identity, 'personal');
649
- assert.equal(route.reviewer.actorLogin, 'reviewer-app[bot]');
650
- assert.equal(route.reviewer.repositoryAccess, 'readable');
651
- assert.equal(route.reviewer.effectiveContentsPermission, 'read');
652
- assert.equal(route.rules.visibility, 'unknown');
653
- assert.equal(route.approvalEligibility, 'unknown');
654
- assert.deepEqual(requests, [
655
- 'GET /user',
656
- 'POST /app/installations/202/access_tokens',
657
- 'GET /app',
658
- 'GET /repos/example/repo',
659
- 'GET /repos/example/repo/rules/branches/main',
660
- 'GET /repos/example/repo/branches/main/protection',
661
- ]);
662
- await assert.rejects(preflightReviewRoute(context, 'main'), /requires the configured author credential/u);
663
- // Ordinary configured App/App factory calls still require the author App and distinct credentials.
664
- await assert.rejects(createDeliveryGitHubClients({ config, env: reviewerEnv, identity: 'reviewer-app', role: 'reviewer' }), /Missing GitHub App credentials for author role/u);
665
- await assert.rejects(createDeliveryGitHubClients({
666
- config,
667
- env: {
668
- ...reviewerEnv,
669
- PREFLIGHT_UNUSED_AUTHOR_APP_ID: '102',
670
- PREFLIGHT_UNUSED_AUTHOR_INSTALLATION_ID: '201',
671
- PREFLIGHT_UNUSED_AUTHOR_KEY_PATH: join(root, 'unused-author.pem'),
672
- },
673
- identity: 'reviewer-app',
674
- role: 'reviewer',
675
- }), /distinct GitHub App credentials/u);
904
+ if (pathname === "/user") {
905
+ assert.equal(authorization, "token synthetic-development-author");
906
+ return response({
907
+ id: 37,
908
+ login: scenario === "author-readback" ? "" : scenario === "same-actor" ? "reviewer-app[bot]" : "host-user"
909
+ });
676
910
  }
677
- else {
678
- await assert.rejects(preflightReviewRoute(context, 'main', undefined, 'development'), {
679
- 'missing-reviewer': /Missing GitHub App credentials for reviewer role/u,
680
- 'reviewer-permission': /reviewer role lacks required pull_requests:write/u,
681
- 'author-readback': /Personal author identity readback is incomplete/u,
682
- 'same-actor': /same GitHub actor/u,
683
- 'wrong-repository': /repository readback disagrees/u,
684
- }[scenario]);
685
- }
686
- }
687
- finally {
688
- globalThis.fetch = originalFetch;
689
- for (const [name, value] of savedEnv) {
690
- if (value === undefined)
691
- delete process.env[name];
692
- else
693
- process.env[name] = value;
694
- }
695
- rmSync(root, { recursive: true, force: true });
696
- }
697
- });
698
- test('App client resolves its bot from JWT GET /app and keeps author token scoped', async () => {
699
- const root = mkdtempSync(join(tmpdir(), 'ai-delivery-app-auth-'));
700
- const originalFetch = globalThis.fetch;
701
- const originalPath = process.env.PATH;
702
- const originalSsh = process.env.GIT_SSH_COMMAND;
703
- const originalGitConfig = process.env.GIT_CONFIG;
704
- const originalGitTrace = process.env.GIT_TRACE;
705
- const originalGhToken = process.env.GH_TOKEN;
706
- const realGit = (originalPath ?? '')
707
- .split(':')
708
- .map((directory) => join(directory, 'git'))
709
- .find(existsSync);
710
- if (!realGit)
711
- throw new Error('Git executable is unavailable for transport test.');
712
- execFileSync(realGit, ['init', '-q', root]);
713
- const privateKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({
714
- format: 'pem',
715
- type: 'pkcs8',
716
- });
717
- const authorKeyPath = join(root, 'author.pem');
718
- const reviewerKeyPath = join(root, 'reviewer.pem');
719
- writeFileSync(authorKeyPath, privateKey);
720
- writeFileSync(reviewerKeyPath, privateKey);
721
- const env = {
722
- AUTHOR_APP_ID: '101',
723
- AUTHOR_INSTALLATION_ID: '201',
724
- AUTHOR_KEY_PATH: authorKeyPath,
725
- REVIEWER_APP_ID: '102',
726
- REVIEWER_INSTALLATION_ID: '202',
727
- REVIEWER_KEY_PATH: reviewerKeyPath,
728
- };
729
- const config = {
730
- roles: {
731
- author: {
732
- identity: 'synthetic-author',
733
- credentialEnv: {
734
- appId: 'AUTHOR_APP_ID',
735
- installationId: 'AUTHOR_INSTALLATION_ID',
736
- privateKeyPath: 'AUTHOR_KEY_PATH',
737
- },
738
- },
739
- reviewer: {
740
- identity: 'synthetic-reviewer',
741
- credentialEnv: {
742
- appId: 'REVIEWER_APP_ID',
743
- installationId: 'REVIEWER_INSTALLATION_ID',
744
- privateKeyPath: 'REVIEWER_KEY_PATH',
745
- },
911
+ if (pathname === "/app" || pathname === "/app/installations/202/access_tokens") {
912
+ assert.match(authorization, /^bearer [^.]+\.[^.]+\.[^.]+$/u);
913
+ const jwt = JSON.parse(Buffer.from(authorization.split(".")[1], "base64url").toString());
914
+ assert.equal(String(jwt.iss), "102");
915
+ if (pathname === "/app") return response({ id: 102, slug: "reviewer-app" });
916
+ return response(
917
+ {
918
+ token: "ghs_synthetic_reviewer",
919
+ expires_at: new Date(Date.now() + 36e5).toISOString(),
920
+ permissions: {
921
+ contents: "read",
922
+ ...scenario === "reviewer-permission" ? {} : { pull_requests: "write" }
923
+ },
924
+ repository_selection: "all"
746
925
  },
747
- },
748
- };
749
- const requests = [];
750
- let appReadbackOverride = null;
751
- let reviewerContentsPermission = 'read';
752
- globalThis.fetch = async (url, init) => {
753
- const requestUrl = new URL(url instanceof Request ? url.url : String(url));
754
- const authorization = new Headers(init?.headers).get('authorization') ?? '';
755
- requests.push(`${init?.method ?? 'GET'} ${requestUrl.pathname}`);
756
- assert.match(authorization, /^bearer [^.]+\.[^.]+\.[^.]+$/u);
757
- if (requestUrl.pathname === '/app') {
758
- const payload = JSON.parse(Buffer.from(authorization.split('.')[1], 'base64url').toString());
759
- const id = appReadbackOverride ?? Number(payload.iss);
760
- return new Response(JSON.stringify({ id, slug: id === 101 ? 'synthetic-author' : 'synthetic-reviewer' }), {
761
- status: 200,
762
- headers: { 'content-type': 'application/json' },
763
- });
926
+ 201
927
+ );
764
928
  }
765
- assert.ok(['/app/installations/201/access_tokens', '/app/installations/202/access_tokens'].includes(requestUrl.pathname));
766
- const isAuthor = requestUrl.pathname.includes('/201/');
767
- return new Response(JSON.stringify({
768
- token: isAuthor ? 'ghs_synthetic_author' : 'ghs_synthetic_reviewer',
769
- expires_at: new Date(Date.now() + 3600000).toISOString(),
770
- permissions: isAuthor
771
- ? { contents: 'write', issues: 'write', organization_projects: 'write', pull_requests: 'write' }
772
- : { contents: reviewerContentsPermission, pull_requests: 'write' },
773
- repository_selection: 'all',
774
- }), {
775
- status: 201,
776
- headers: { 'content-type': 'application/json' },
777
- });
778
- };
779
- try {
780
- const clients = await createDeliveryGitHubClients({
781
- config,
782
- env,
783
- identity: 'synthetic-reviewer',
784
- role: 'reviewer',
785
- });
786
- assert.equal(await clients.appActorLogin?.(), 'synthetic-reviewer[bot]');
787
- assert.equal(clients.effectiveContentsPermission, 'read');
788
- assert.deepEqual(requests, ['POST /app/installations/202/access_tokens', 'GET /app']);
789
- await assert.rejects(withAuthorGitToken(clients, () => undefined), /selected author credential token/u);
790
- const author = await createDeliveryGitHubClients({ config, env, identity: 'synthetic-author', role: 'author' });
791
- assert.equal(await withAuthorGitToken(author, (token) => token), 'ghs_synthetic_author');
792
- await assert.rejects(createDeliveryGitHubClients({
793
- config,
794
- env: {
795
- REVIEWER_APP_ID: env.REVIEWER_APP_ID,
796
- REVIEWER_INSTALLATION_ID: env.REVIEWER_INSTALLATION_ID,
797
- REVIEWER_KEY_PATH: env.REVIEWER_KEY_PATH,
798
- },
799
- identity: 'synthetic-reviewer',
800
- role: 'reviewer',
801
- selectedAuthor: author,
802
- }), /Missing GitHub App credentials for author role/u);
803
- await assert.rejects(createDeliveryGitHubClients({
804
- config,
805
- env: { ...env, REVIEWER_APP_ID: env.AUTHOR_APP_ID },
806
- identity: 'synthetic-reviewer',
807
- role: 'reviewer',
808
- selectedAuthor: author,
809
- }), /distinct GitHub App credentials/u);
929
+ if (pathname === "/repos/example/repo") {
930
+ assert.equal(authorization, "token ghs_synthetic_reviewer");
931
+ return response({ full_name: scenario === "wrong-repository" ? "example/other" : "example/repo" });
932
+ }
933
+ assert.ok(
934
+ ["/repos/example/repo/rules/branches/main", "/repos/example/repo/branches/main/protection"].includes(
935
+ pathname
936
+ )
937
+ );
938
+ assert.equal(authorization, "token synthetic-development-author");
939
+ return response({ message: "Rules unavailable" }, 403);
940
+ };
941
+ const author = await createDeliveryGitHubClients({
942
+ config,
943
+ env: {},
944
+ identity: "personal",
945
+ personalAuth: { enabled: true, token: "synthetic-development-author" },
946
+ role: "author"
947
+ });
948
+ const context = { root, repo: { owner: "example", repo: "repo" }, config, clients: author };
949
+ if (scenario === "available") {
950
+ const route = await preflightReviewRoute(context, "main", void 0, "development");
951
+ assert.equal(route.author.actorLogin, "host-user");
952
+ assert.equal(route.author.identity, "personal");
953
+ assert.equal(route.reviewer.actorLogin, "reviewer-app[bot]");
954
+ assert.equal(route.reviewer.repositoryAccess, "readable");
955
+ assert.equal(route.reviewer.effectiveContentsPermission, "read");
956
+ assert.equal(route.rules.visibility, "unknown");
957
+ assert.equal(route.approvalEligibility, "unknown");
810
958
  assert.deepEqual(requests, [
811
- 'POST /app/installations/202/access_tokens',
812
- 'GET /app',
813
- 'POST /app/installations/201/access_tokens',
959
+ "GET /user",
960
+ "POST /app/installations/202/access_tokens",
961
+ "GET /app",
962
+ "GET /repos/example/repo",
963
+ "GET /repos/example/repo/rules/branches/main",
964
+ "GET /repos/example/repo/branches/main/protection"
814
965
  ]);
815
- assert.deepEqual(await author.authenticatedAuthor?.(), {
816
- actorLogin: 'synthetic-author[bot]',
817
- credentialIdentity: 'app:101:installation:201',
818
- });
819
- if (!author.authenticatedAuthor)
820
- throw new Error('Author identity readback is unavailable.');
821
- appReadbackOverride = 102;
822
- await assert.rejects(author.authenticatedAuthor(), /Author GitHub App identity did not match/u);
823
- appReadbackOverride = null;
824
- reviewerContentsPermission = 'write';
825
- const writeCapableReviewer = await createDeliveryGitHubClients({
966
+ await assert.rejects(preflightReviewRoute(context, "main"), /requires the configured author credential/u);
967
+ await assert.rejects(
968
+ createDeliveryGitHubClients({ config, env: reviewerEnv, identity: "reviewer-app", role: "reviewer" }),
969
+ /Missing GitHub App credentials for author role/u
970
+ );
971
+ await assert.rejects(
972
+ createDeliveryGitHubClients({
826
973
  config,
827
- env,
828
- identity: 'synthetic-reviewer',
829
- role: 'reviewer',
830
- });
831
- assert.equal(writeCapableReviewer.effectiveContentsPermission, 'write');
974
+ env: {
975
+ ...reviewerEnv,
976
+ PREFLIGHT_UNUSED_AUTHOR_APP_ID: "102",
977
+ PREFLIGHT_UNUSED_AUTHOR_INSTALLATION_ID: "201",
978
+ PREFLIGHT_UNUSED_AUTHOR_KEY_PATH: join(root, "unused-author.pem")
979
+ },
980
+ identity: "reviewer-app",
981
+ role: "reviewer"
982
+ }),
983
+ /distinct GitHub App credentials/u
984
+ );
985
+ } else {
986
+ await assert.rejects(
987
+ preflightReviewRoute(context, "main", void 0, "development"),
988
+ {
989
+ "missing-reviewer": /Missing GitHub App credentials for reviewer role/u,
990
+ "reviewer-permission": /reviewer role lacks required pull_requests:write/u,
991
+ "author-readback": /Personal author identity readback is incomplete/u,
992
+ "same-actor": /same GitHub actor/u,
993
+ "wrong-repository": /repository readback disagrees/u
994
+ }[scenario]
995
+ );
996
+ }
997
+ } finally {
998
+ globalThis.fetch = originalFetch;
999
+ for (const [name, value] of savedEnv) {
1000
+ if (value === void 0) delete process.env[name];
1001
+ else process.env[name] = value;
1002
+ }
1003
+ rmSync(root, { recursive: true, force: true });
1004
+ }
1005
+ }
1006
+ );
1007
+ test("App client resolves its bot from JWT GET /app and keeps author token scoped", async () => {
1008
+ const root = mkdtempSync(join(tmpdir(), "ai-delivery-app-auth-"));
1009
+ const originalFetch = globalThis.fetch;
1010
+ const originalPath = process.env.PATH;
1011
+ const originalSsh = process.env.GIT_SSH_COMMAND;
1012
+ const originalGitConfig = process.env.GIT_CONFIG;
1013
+ const originalGitTrace = process.env.GIT_TRACE;
1014
+ const originalGhToken = process.env.GH_TOKEN;
1015
+ const realGit = (originalPath ?? "").split(":").map((directory) => join(directory, "git")).find(existsSync);
1016
+ if (!realGit) throw new Error("Git executable is unavailable for transport test.");
1017
+ execFileSync(realGit, ["init", "-q", root]);
1018
+ const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({
1019
+ format: "pem",
1020
+ type: "pkcs8"
1021
+ });
1022
+ const authorKeyPath = join(root, "author.pem");
1023
+ const reviewerKeyPath = join(root, "reviewer.pem");
1024
+ writeFileSync(authorKeyPath, privateKey);
1025
+ writeFileSync(reviewerKeyPath, privateKey);
1026
+ const env = {
1027
+ AUTHOR_APP_ID: "101",
1028
+ AUTHOR_INSTALLATION_ID: "201",
1029
+ AUTHOR_KEY_PATH: authorKeyPath,
1030
+ REVIEWER_APP_ID: "102",
1031
+ REVIEWER_INSTALLATION_ID: "202",
1032
+ REVIEWER_KEY_PATH: reviewerKeyPath
1033
+ };
1034
+ const config = {
1035
+ roles: {
1036
+ author: {
1037
+ identity: "synthetic-author",
1038
+ credentialEnv: {
1039
+ appId: "AUTHOR_APP_ID",
1040
+ installationId: "AUTHOR_INSTALLATION_ID",
1041
+ privateKeyPath: "AUTHOR_KEY_PATH"
1042
+ }
1043
+ },
1044
+ reviewer: {
1045
+ identity: "synthetic-reviewer",
1046
+ credentialEnv: {
1047
+ appId: "REVIEWER_APP_ID",
1048
+ installationId: "REVIEWER_INSTALLATION_ID",
1049
+ privateKeyPath: "REVIEWER_KEY_PATH"
1050
+ }
1051
+ }
832
1052
  }
833
- finally {
834
- globalThis.fetch = originalFetch;
835
- if (originalPath === undefined)
836
- delete process.env.PATH;
837
- else
838
- process.env.PATH = originalPath;
839
- if (originalSsh === undefined)
840
- delete process.env.GIT_SSH_COMMAND;
841
- else
842
- process.env.GIT_SSH_COMMAND = originalSsh;
843
- if (originalGitConfig === undefined)
844
- delete process.env.GIT_CONFIG;
845
- else
846
- process.env.GIT_CONFIG = originalGitConfig;
847
- if (originalGitTrace === undefined)
848
- delete process.env.GIT_TRACE;
849
- else
850
- process.env.GIT_TRACE = originalGitTrace;
851
- if (originalGhToken === undefined)
852
- delete process.env.GH_TOKEN;
853
- else
854
- process.env.GH_TOKEN = originalGhToken;
855
- rmSync(root, { recursive: true, force: true });
1053
+ };
1054
+ const requests = [];
1055
+ let appReadbackOverride = null;
1056
+ let reviewerContentsPermission = "read";
1057
+ globalThis.fetch = async (url, init) => {
1058
+ const requestUrl = new URL(url instanceof Request ? url.url : String(url));
1059
+ const authorization = new Headers(init?.headers).get("authorization") ?? "";
1060
+ requests.push(`${init?.method ?? "GET"} ${requestUrl.pathname}`);
1061
+ assert.match(authorization, /^bearer [^.]+\.[^.]+\.[^.]+$/u);
1062
+ if (requestUrl.pathname === "/app") {
1063
+ const payload = JSON.parse(Buffer.from(authorization.split(".")[1], "base64url").toString());
1064
+ const id = appReadbackOverride ?? Number(payload.iss);
1065
+ return new Response(JSON.stringify({ id, slug: id === 101 ? "synthetic-author" : "synthetic-reviewer" }), {
1066
+ status: 200,
1067
+ headers: { "content-type": "application/json" }
1068
+ });
856
1069
  }
1070
+ assert.ok(
1071
+ ["/app/installations/201/access_tokens", "/app/installations/202/access_tokens"].includes(requestUrl.pathname)
1072
+ );
1073
+ const isAuthor = requestUrl.pathname.includes("/201/");
1074
+ return new Response(
1075
+ JSON.stringify({
1076
+ token: isAuthor ? "ghs_synthetic_author" : "ghs_synthetic_reviewer",
1077
+ expires_at: new Date(Date.now() + 36e5).toISOString(),
1078
+ permissions: isAuthor ? { contents: "write", issues: "write", organization_projects: "write", pull_requests: "write" } : { contents: reviewerContentsPermission, pull_requests: "write" },
1079
+ repository_selection: "all"
1080
+ }),
1081
+ {
1082
+ status: 201,
1083
+ headers: { "content-type": "application/json" }
1084
+ }
1085
+ );
1086
+ };
1087
+ try {
1088
+ const clients = await createDeliveryGitHubClients({
1089
+ config,
1090
+ env,
1091
+ identity: "synthetic-reviewer",
1092
+ role: "reviewer"
1093
+ });
1094
+ assert.equal(await clients.appActorLogin?.(), "synthetic-reviewer[bot]");
1095
+ assert.equal(clients.effectiveContentsPermission, "read");
1096
+ assert.deepEqual(requests, ["POST /app/installations/202/access_tokens", "GET /app"]);
1097
+ await assert.rejects(
1098
+ withAuthorGitToken(clients, () => void 0),
1099
+ /selected author credential token/u
1100
+ );
1101
+ const author = await createDeliveryGitHubClients({ config, env, identity: "synthetic-author", role: "author" });
1102
+ assert.equal(await withAuthorGitToken(author, (token) => token), "ghs_synthetic_author");
1103
+ await assert.rejects(
1104
+ createDeliveryGitHubClients({
1105
+ config,
1106
+ env: {
1107
+ REVIEWER_APP_ID: env.REVIEWER_APP_ID,
1108
+ REVIEWER_INSTALLATION_ID: env.REVIEWER_INSTALLATION_ID,
1109
+ REVIEWER_KEY_PATH: env.REVIEWER_KEY_PATH
1110
+ },
1111
+ identity: "synthetic-reviewer",
1112
+ role: "reviewer",
1113
+ selectedAuthor: author
1114
+ }),
1115
+ /Missing GitHub App credentials for author role/u
1116
+ );
1117
+ await assert.rejects(
1118
+ createDeliveryGitHubClients({
1119
+ config,
1120
+ env: { ...env, REVIEWER_APP_ID: env.AUTHOR_APP_ID },
1121
+ identity: "synthetic-reviewer",
1122
+ role: "reviewer",
1123
+ selectedAuthor: author
1124
+ }),
1125
+ /distinct GitHub App credentials/u
1126
+ );
1127
+ assert.deepEqual(requests, [
1128
+ "POST /app/installations/202/access_tokens",
1129
+ "GET /app",
1130
+ "POST /app/installations/201/access_tokens"
1131
+ ]);
1132
+ assert.deepEqual(await author.authenticatedAuthor?.(), {
1133
+ actorLogin: "synthetic-author[bot]",
1134
+ credentialIdentity: "app:101:installation:201"
1135
+ });
1136
+ if (!author.authenticatedAuthor) throw new Error("Author identity readback is unavailable.");
1137
+ appReadbackOverride = 102;
1138
+ await assert.rejects(author.authenticatedAuthor(), /Author GitHub App identity did not match/u);
1139
+ appReadbackOverride = null;
1140
+ reviewerContentsPermission = "write";
1141
+ const writeCapableReviewer = await createDeliveryGitHubClients({
1142
+ config,
1143
+ env,
1144
+ identity: "synthetic-reviewer",
1145
+ role: "reviewer"
1146
+ });
1147
+ assert.equal(writeCapableReviewer.effectiveContentsPermission, "write");
1148
+ } finally {
1149
+ globalThis.fetch = originalFetch;
1150
+ if (originalPath === void 0) delete process.env.PATH;
1151
+ else process.env.PATH = originalPath;
1152
+ if (originalSsh === void 0) delete process.env.GIT_SSH_COMMAND;
1153
+ else process.env.GIT_SSH_COMMAND = originalSsh;
1154
+ if (originalGitConfig === void 0) delete process.env.GIT_CONFIG;
1155
+ else process.env.GIT_CONFIG = originalGitConfig;
1156
+ if (originalGitTrace === void 0) delete process.env.GIT_TRACE;
1157
+ else process.env.GIT_TRACE = originalGitTrace;
1158
+ if (originalGhToken === void 0) delete process.env.GH_TOKEN;
1159
+ else process.env.GH_TOKEN = originalGhToken;
1160
+ rmSync(root, { recursive: true, force: true });
1161
+ }
1162
+ });
1163
+ test("recorded public draft null remains observed while synthetic missing decision is unknown", async () => {
1164
+ const state = fixture();
1165
+ try {
1166
+ const response = structuredClone(recordedZeroApproval);
1167
+ state.context.clients.graphql = (async () => response);
1168
+ const observed = await readRequiredReviewState(state.context, 55, "4b54bd4b663a32957e4571e2af112f828fbc0a58");
1169
+ assert.equal(observed.observed, true);
1170
+ assert.equal(observed.reviewDecision, null);
1171
+ const { reviewDecision: _decision, ...missing } = response.repository.pullRequest;
1172
+ state.context.clients.graphql = (async () => ({ repository: { pullRequest: missing } }));
1173
+ const unavailable = await readRequiredReviewState(state.context, 55, "4b54bd4b663a32957e4571e2af112f828fbc0a58");
1174
+ assert.equal(unavailable.observed, false);
1175
+ assert.equal(unavailable.status, "unknown");
1176
+ } finally {
1177
+ rmSync(state.root, { recursive: true, force: true });
1178
+ }
1179
+ });
1180
+ test("recorded reassociation submits a fresh artifact and retry reuses only that artifact", async () => {
1181
+ const state = fixture({ head: recordedReassociation.currentArtifact.head });
1182
+ const events = [];
1183
+ const oldContent = { ...state.artifact, head: recordedReassociation.historicalArtifact.head };
1184
+ const { artifactId: _oldId, ...oldFields } = oldContent;
1185
+ const oldArtifact = { ...oldFields, artifactId: digestValue(oldFields) };
1186
+ const encode = (artifact) => `${marker(artifact.artifactId)}
1187
+ <!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(artifact)).toString("base64url")} -->`;
1188
+ const oldReview = {
1189
+ ...recordedReassociation.historicalReview,
1190
+ user: { login: "synthetic-reviewer[bot]" },
1191
+ body: encode(oldArtifact)
1192
+ };
1193
+ const freshReview = {
1194
+ ...recordedReassociation.currentReview,
1195
+ user: { login: "synthetic-reviewer[bot]" },
1196
+ body: encode(state.artifact)
1197
+ };
1198
+ const history = [oldReview];
1199
+ const rest = state.context.clients.rest;
1200
+ const get = rest.pulls.get;
1201
+ rest.pulls.get = (async (...args) => {
1202
+ assert.deepEqual(args[0], { owner: "example", repo: "repo", pull_number: 19 });
1203
+ events.push("pr");
1204
+ return get(...args);
1205
+ });
1206
+ const getCommit = rest.git.getCommit;
1207
+ rest.git.getCommit = (async (...args) => {
1208
+ events.push("commit");
1209
+ assert.equal(args[0]?.commit_sha, "aec1b0caa0d6acb44c025cdb4247d43b401e2166");
1210
+ return getCommit(...args);
1211
+ });
1212
+ rest.pulls.listFiles = (async (input) => {
1213
+ events.push("files");
1214
+ assert.equal(input.pull_number, 19);
1215
+ assert.equal(input.page, 1);
1216
+ assert.equal(input.per_page, 100);
1217
+ return { data: [{ filename: "change.ts" }] };
1218
+ });
1219
+ rest.pulls.listReviews = (async (input) => {
1220
+ events.push("reviews");
1221
+ assert.equal(input.pull_number, 19);
1222
+ assert.equal(input.page, 1);
1223
+ assert.equal(input.per_page, 100);
1224
+ return { data: history };
1225
+ });
1226
+ rest.pulls.createReview = (async (input) => {
1227
+ events.push("create");
1228
+ assert.equal(input.pull_number, 19);
1229
+ assert.equal(input.commit_id, "aec1b0caa0d6acb44c025cdb4247d43b401e2166");
1230
+ assert.equal(input.event, "APPROVE");
1231
+ assert.ok(input.body.includes(marker(state.artifact.artifactId)));
1232
+ assert.ok(!input.body.includes(marker(oldArtifact.artifactId)));
1233
+ freshReview.body = input.body;
1234
+ history.push(freshReview);
1235
+ return { data: freshReview };
1236
+ });
1237
+ rest.pulls.getReview = (async (input) => {
1238
+ events.push("readback");
1239
+ assert.equal(input.pull_number, 19);
1240
+ assert.equal(input.review_id, 5607508810);
1241
+ return { data: freshReview };
1242
+ });
1243
+ try {
1244
+ const receipt = await state.submit();
1245
+ assert.equal(receipt.githubReviewId, 5607508810);
1246
+ assert.equal(receipt.headSha, "aec1b0caa0d6acb44c025cdb4247d43b401e2166");
1247
+ assert.deepEqual(receipt.artifact.head, {
1248
+ sha: "aec1b0caa0d6acb44c025cdb4247d43b401e2166",
1249
+ tree: "2cd3b7f0fcfdf853e4f04ece00367c24df786570"
1250
+ });
1251
+ assert.equal(oldReview.commit_id, "aec1b0caa0d6acb44c025cdb4247d43b401e2166");
1252
+ assert.equal(oldArtifact.head.sha, "6534bdad0e431f966b541092df5c0881f3bbd3f9");
1253
+ assert.deepEqual(events, ["pr", "commit", "files", "reviews", "pr", "create", "readback", "pr"]);
1254
+ events.length = 0;
1255
+ const retry = await state.submit();
1256
+ assert.equal(retry.githubReviewId, 5607508810);
1257
+ assert.equal(history.length, 2);
1258
+ assert.deepEqual(events, ["pr", "commit", "files", "reviews", "pr", "readback", "pr"]);
1259
+ assert.equal(oldReview.body, encode(oldArtifact));
1260
+ } finally {
1261
+ rmSync(state.root, { recursive: true, force: true });
1262
+ }
857
1263
  });
858
- //# sourceMappingURL=review.test.js.map
1264
+ //# sourceMappingURL=review.test.js.map