@webpieces/pr-gate 0.4.974 → 0.4.976

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 (169) hide show
  1. package/package.json +6 -6
  2. package/src/scripts/commands/await-checks-command.d.ts +6 -3
  3. package/src/scripts/commands/await-checks-command.js +17 -12
  4. package/src/scripts/commands/await-checks-command.js.map +1 -1
  5. package/src/scripts/commands/await-reviews-command.d.ts +1 -1
  6. package/src/scripts/commands/await-reviews-command.js +3 -3
  7. package/src/scripts/commands/await-reviews-command.js.map +1 -1
  8. package/src/scripts/commands/check-pr-command.d.ts +3 -1
  9. package/src/scripts/commands/check-pr-command.js +12 -9
  10. package/src/scripts/commands/check-pr-command.js.map +1 -1
  11. package/src/scripts/commands/finish-push-dev-command.js +3 -4
  12. package/src/scripts/commands/finish-push-dev-command.js.map +1 -1
  13. package/src/scripts/commands/finish-update-command.js +1 -1
  14. package/src/scripts/commands/finish-update-command.js.map +1 -1
  15. package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -1
  16. package/src/scripts/commands/finish-upsert-pr-command.js +65 -62
  17. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  18. package/src/scripts/commands/human-post-pr-command.d.ts +8 -6
  19. package/src/scripts/commands/human-post-pr-command.js +32 -31
  20. package/src/scripts/commands/human-post-pr-command.js.map +1 -1
  21. package/src/scripts/commands/land-pr-command.d.ts +5 -1
  22. package/src/scripts/commands/land-pr-command.js +36 -22
  23. package/src/scripts/commands/land-pr-command.js.map +1 -1
  24. package/src/scripts/commands/main-checkout.d.ts +4 -1
  25. package/src/scripts/commands/main-checkout.js +22 -22
  26. package/src/scripts/commands/main-checkout.js.map +1 -1
  27. package/src/scripts/commands/push-dev-command.js +28 -29
  28. package/src/scripts/commands/push-dev-command.js.map +1 -1
  29. package/src/scripts/commands/review-upsert-pr-command.js +9 -9
  30. package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
  31. package/src/scripts/commands/start-update-command.d.ts +1 -1
  32. package/src/scripts/commands/start-update-command.js +3 -3
  33. package/src/scripts/commands/start-update-command.js.map +1 -1
  34. package/src/scripts/commands/start-upsert-pr-command.js +4 -4
  35. package/src/scripts/commands/start-upsert-pr-command.js.map +1 -1
  36. package/src/scripts/commands/sync-main-command.js +2 -2
  37. package/src/scripts/commands/sync-main-command.js.map +1 -1
  38. package/src/scripts/commands/upsert-hotfix-pr-command.d.ts +6 -4
  39. package/src/scripts/commands/upsert-hotfix-pr-command.js +46 -43
  40. package/src/scripts/commands/upsert-hotfix-pr-command.js.map +1 -1
  41. package/src/scripts/commands/working-tree-gate.d.ts +4 -1
  42. package/src/scripts/commands/working-tree-gate.js +14 -11
  43. package/src/scripts/commands/working-tree-gate.js.map +1 -1
  44. package/src/scripts/commands/write-review-command.js +4 -6
  45. package/src/scripts/commands/write-review-command.js.map +1 -1
  46. package/src/scripts/commands/write-review-fixes-command.js +3 -4
  47. package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
  48. package/src/scripts/git-finishUpsertPr.js +2 -2
  49. package/src/scripts/git-finishUpsertPr.js.map +1 -1
  50. package/src/scripts/git-gatherInfo.js +6 -7
  51. package/src/scripts/git-gatherInfo.js.map +1 -1
  52. package/src/scripts/pr-gate-container.d.ts +9 -0
  53. package/src/scripts/pr-gate-container.js +19 -0
  54. package/src/scripts/pr-gate-container.js.map +1 -0
  55. package/src/scripts/workflow/await-loop.d.ts +1 -1
  56. package/src/scripts/workflow/await-loop.js +1 -1
  57. package/src/scripts/workflow/await-loop.js.map +1 -1
  58. package/src/scripts/workflow/build-affected.js +1 -1
  59. package/src/scripts/workflow/build-affected.js.map +1 -1
  60. package/src/scripts/workflow/build-artifact-gate.d.ts +1 -1
  61. package/src/scripts/workflow/build-artifact-gate.js +3 -3
  62. package/src/scripts/workflow/build-artifact-gate.js.map +1 -1
  63. package/src/scripts/workflow/build-gate-log.d.ts +9 -6
  64. package/src/scripts/workflow/build-gate-log.js +34 -40
  65. package/src/scripts/workflow/build-gate-log.js.map +1 -1
  66. package/src/scripts/workflow/checklist-scanner.d.ts +1 -1
  67. package/src/scripts/workflow/checklist-scanner.js +8 -8
  68. package/src/scripts/workflow/checklist-scanner.js.map +1 -1
  69. package/src/scripts/workflow/checklist-scope-hasher.d.ts +1 -1
  70. package/src/scripts/workflow/checklist-scope-hasher.js +2 -2
  71. package/src/scripts/workflow/checklist-scope-hasher.js.map +1 -1
  72. package/src/scripts/workflow/dev-deploy-refs.d.ts +5 -5
  73. package/src/scripts/workflow/dev-deploy-refs.js +8 -8
  74. package/src/scripts/workflow/dev-deploy-refs.js.map +1 -1
  75. package/src/scripts/workflow/dev-resolve-runner.d.ts +3 -3
  76. package/src/scripts/workflow/dev-resolve-runner.js +30 -30
  77. package/src/scripts/workflow/dev-resolve-runner.js.map +1 -1
  78. package/src/scripts/workflow/diff-basis.d.ts +4 -2
  79. package/src/scripts/workflow/diff-basis.js +18 -15
  80. package/src/scripts/workflow/diff-basis.js.map +1 -1
  81. package/src/scripts/workflow/diff-materializer.d.ts +5 -3
  82. package/src/scripts/workflow/diff-materializer.js +18 -15
  83. package/src/scripts/workflow/diff-materializer.js.map +1 -1
  84. package/src/scripts/workflow/gated-pr-publisher.d.ts +8 -6
  85. package/src/scripts/workflow/gated-pr-publisher.js +23 -22
  86. package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
  87. package/src/scripts/workflow/generated-artifact-registry.d.ts +4 -2
  88. package/src/scripts/workflow/generated-artifact-registry.js +11 -8
  89. package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
  90. package/src/scripts/workflow/git-exec.d.ts +22 -12
  91. package/src/scripts/workflow/git-exec.js +45 -29
  92. package/src/scripts/workflow/git-exec.js.map +1 -1
  93. package/src/scripts/workflow/git-findForkPoint.d.ts +6 -2
  94. package/src/scripts/workflow/git-findForkPoint.js +31 -23
  95. package/src/scripts/workflow/git-findForkPoint.js.map +1 -1
  96. package/src/scripts/workflow/git-readAiBranchName.d.ts +4 -2
  97. package/src/scripts/workflow/git-readAiBranchName.js +8 -5
  98. package/src/scripts/workflow/git-readAiBranchName.js.map +1 -1
  99. package/src/scripts/workflow/hotfix-pr-publisher.d.ts +4 -3
  100. package/src/scripts/workflow/hotfix-pr-publisher.js +7 -6
  101. package/src/scripts/workflow/hotfix-pr-publisher.js.map +1 -1
  102. package/src/scripts/workflow/landed-tree-resolver.d.ts +4 -2
  103. package/src/scripts/workflow/landed-tree-resolver.js +11 -8
  104. package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
  105. package/src/scripts/workflow/landed-worktree-reaper.d.ts +4 -2
  106. package/src/scripts/workflow/landed-worktree-reaper.js +12 -9
  107. package/src/scripts/workflow/landed-worktree-reaper.js.map +1 -1
  108. package/src/scripts/workflow/merge-end.d.ts +2 -2
  109. package/src/scripts/workflow/merge-end.js +22 -24
  110. package/src/scripts/workflow/merge-end.js.map +1 -1
  111. package/src/scripts/workflow/merge-start.d.ts +5 -1
  112. package/src/scripts/workflow/merge-start.js +56 -49
  113. package/src/scripts/workflow/merge-start.js.map +1 -1
  114. package/src/scripts/workflow/open-pr-check.d.ts +4 -2
  115. package/src/scripts/workflow/open-pr-check.js +11 -8
  116. package/src/scripts/workflow/open-pr-check.js.map +1 -1
  117. package/src/scripts/workflow/pr-comment-upserter.d.ts +5 -3
  118. package/src/scripts/workflow/pr-comment-upserter.js +15 -14
  119. package/src/scripts/workflow/pr-comment-upserter.js.map +1 -1
  120. package/src/scripts/workflow/pr-merger.d.ts +8 -5
  121. package/src/scripts/workflow/pr-merger.js +32 -27
  122. package/src/scripts/workflow/pr-merger.js.map +1 -1
  123. package/src/scripts/workflow/provenance-enforcer.d.ts +4 -2
  124. package/src/scripts/workflow/provenance-enforcer.js +19 -17
  125. package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
  126. package/src/scripts/workflow/review-round-state.d.ts +7 -6
  127. package/src/scripts/workflow/review-round-state.js +33 -38
  128. package/src/scripts/workflow/review-round-state.js.map +1 -1
  129. package/src/scripts/workflow/run-update.js +1 -1
  130. package/src/scripts/workflow/run-update.js.map +1 -1
  131. package/src/scripts/workflow/squash-settings-enforcer.d.ts +6 -3
  132. package/src/scripts/workflow/squash-settings-enforcer.js +19 -14
  133. package/src/scripts/workflow/squash-settings-enforcer.js.map +1 -1
  134. package/src/scripts/wp-await-checks.js +2 -2
  135. package/src/scripts/wp-await-checks.js.map +1 -1
  136. package/src/scripts/wp-await-reviews.js +2 -2
  137. package/src/scripts/wp-await-reviews.js.map +1 -1
  138. package/src/scripts/wp-build.js +2 -2
  139. package/src/scripts/wp-build.js.map +1 -1
  140. package/src/scripts/wp-check-pr.js +2 -2
  141. package/src/scripts/wp-check-pr.js.map +1 -1
  142. package/src/scripts/wp-cleanup.js +2 -2
  143. package/src/scripts/wp-cleanup.js.map +1 -1
  144. package/src/scripts/wp-finish-push-dev.js +2 -2
  145. package/src/scripts/wp-finish-push-dev.js.map +1 -1
  146. package/src/scripts/wp-finish-update.js +2 -2
  147. package/src/scripts/wp-finish-update.js.map +1 -1
  148. package/src/scripts/wp-human-post-pr.js +2 -2
  149. package/src/scripts/wp-human-post-pr.js.map +1 -1
  150. package/src/scripts/wp-land-pr.js +2 -2
  151. package/src/scripts/wp-land-pr.js.map +1 -1
  152. package/src/scripts/wp-push-dev.js +2 -2
  153. package/src/scripts/wp-push-dev.js.map +1 -1
  154. package/src/scripts/wp-reap-worktree.js +2 -2
  155. package/src/scripts/wp-reap-worktree.js.map +1 -1
  156. package/src/scripts/wp-review-upsert-pr.js +2 -2
  157. package/src/scripts/wp-review-upsert-pr.js.map +1 -1
  158. package/src/scripts/wp-start-update.js +2 -2
  159. package/src/scripts/wp-start-update.js.map +1 -1
  160. package/src/scripts/wp-start-upsert-pr.js +2 -2
  161. package/src/scripts/wp-start-upsert-pr.js.map +1 -1
  162. package/src/scripts/wp-sync-main.js +2 -2
  163. package/src/scripts/wp-sync-main.js.map +1 -1
  164. package/src/scripts/wp-upsert-hotfix-pr.js +2 -2
  165. package/src/scripts/wp-upsert-hotfix-pr.js.map +1 -1
  166. package/src/scripts/wp-write-review-fixes.js +2 -2
  167. package/src/scripts/wp-write-review-fixes.js.map +1 -1
  168. package/src/scripts/wp-write-review.js +2 -2
  169. package/src/scripts/wp-write-review.js.map +1 -1
@@ -1,3 +1,4 @@
1
+ import { NativeProcessApi } from '@webpieces/tooling-common';
1
2
  /**
2
3
  * The five terminal shapes a merge attempt can take. The CALLER branches on these — a `message` string
3
4
  * is for humans to read, never for code to pattern-match, and the banner that frames it must be able to
@@ -105,13 +106,15 @@ export declare class MergeIntent {
105
106
  * Every `gh` status is checked. Nothing here is allowed to fail silently.
106
107
  */
107
108
  export declare class PrMerger {
109
+ private readonly processes;
110
+ constructor(processes: NativeProcessApi);
108
111
  /**
109
112
  * @param subject the squash-commit subject, normally `<PR title> (#N)`
110
113
  * @param mergeBodyFile file holding the squash-commit body (risk/flags/PR link)
111
114
  * @param intent the real pr-gate.mergeMode PLUS whether this caller commands the merge
112
115
  * regardless of it (see MergeIntent).
113
116
  */
114
- merge(baseBranch: string, subject: string, mergeBodyFile: string, intent: MergeIntent): MergeOutcome;
117
+ merge(baseBranch: string, subject: string, mergeBodyFile: string, intent: MergeIntent): Promise<MergeOutcome>;
115
118
  /**
116
119
  * The auto-merge queue: the only way to still land a not-yet-mergeable PR unattended. Returns the
117
120
  * BEHIND outcome regardless of how queuing went whenever GitHub says the branch is out of date —
@@ -148,10 +151,10 @@ export declare class PrMerger {
148
151
  * purpose: a gh hiccup returns an all-'' state (never BEHIND) so a transient API blip can only cost
149
152
  * us the extra diagnosis, never turn a working run into a crash.
150
153
  */
151
- protected prMergeState(baseBranch: string): PrMergeState;
152
- protected autoMergeAllowed(): boolean;
153
- protected gh(args: string[], quiet?: boolean): number;
154
- protected ghCapture(args: string[]): GhResult;
154
+ private prMergeState;
155
+ private autoMergeAllowed;
156
+ private gh;
157
+ private ghCapture;
155
158
  }
156
159
  export declare class GhResult {
157
160
  status: number;
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GhResult = exports.PrMerger = exports.MergeIntent = exports.PrMergeState = exports.MergeOutcome = exports.MERGE_RESULT_FAILED = exports.MERGE_RESULT_BEHIND_UNKNOWN = exports.MERGE_RESULT_BEHIND_CONFLICTING = exports.MERGE_RESULT_BEHIND_CLEAN = exports.MERGE_RESULT_BEHIND = exports.MERGE_RESULT_LEFT_TO_HUMAN = exports.MERGE_RESULT_AUTO_QUEUED = exports.MERGE_RESULT_MERGED = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const child_process_1 = require("child_process");
6
5
  const rules_config_1 = require("@webpieces/rules-config");
6
+ const tooling_common_1 = require("@webpieces/tooling-common");
7
7
  const inversify_1 = require("inversify");
8
8
  /**
9
9
  * The five terminal shapes a merge attempt can take. The CALLER branches on these — a `message` string
@@ -51,7 +51,7 @@ const GH_MERGEABLE_CLEAN = 'MERGEABLE';
51
51
  const GH_MERGEABLE_CONFLICTING = 'CONFLICTING';
52
52
  // What actually happened when we tried to land the squash merge. `message` is printed VERBATIM in the
53
53
  // final wp-finish-upsert-pr summary, so a merge that did not happen can never be reported as done —
54
- // the old code ignored `spawnSync().status` entirely and printed "✅ PR finished" even when `gh pr
54
+ // the old code ignored the gh exit status entirely and printed "✅ PR finished" even when `gh pr
55
55
  // merge` had errored out, which is what hid the auto-merge-disabled failure for weeks. `result` is the
56
56
  // machine-readable half of the same honesty: the banner picks its HEADER from it, so the frame around
57
57
  // the message can no longer say "finished" while the message says "did NOT merge".
@@ -169,13 +169,17 @@ exports.MergeIntent = MergeIntent;
169
169
  * Every `gh` status is checked. Nothing here is allowed to fail silently.
170
170
  */
171
171
  let PrMerger = class PrMerger {
172
+ processes;
173
+ constructor(processes) {
174
+ this.processes = processes;
175
+ }
172
176
  /**
173
177
  * @param subject the squash-commit subject, normally `<PR title> (#N)`
174
178
  * @param mergeBodyFile file holding the squash-commit body (risk/flags/PR link)
175
179
  * @param intent the real pr-gate.mergeMode PLUS whether this caller commands the merge
176
180
  * regardless of it (see MergeIntent).
177
181
  */
178
- merge(baseBranch, subject, mergeBodyFile, intent) {
182
+ async merge(baseBranch, subject, mergeBodyFile, intent) {
179
183
  // Anything that is not an explicit AUTO leaves the PR alone. The PR itself is already
180
184
  // posted/updated by this point, which is the whole job in this mode.
181
185
  if (!intent.shouldMerge()) {
@@ -205,7 +209,7 @@ let PrMerger = class PrMerger {
205
209
  // forbids a direct merge, and gh's raw `X Pull request #N is not mergeable: …` on the terminal
206
210
  // read as a hard failure to every human and agent who saw it. We reprint the reason ourselves,
207
211
  // framed as the expected first step of a two-step dance (see announceDirectFailure).
208
- const direct = this.ghCapture(['pr', 'merge', baseBranch, '--squash', '--subject', subject, '--body-file', mergeBodyFile]);
212
+ const direct = await this.ghCapture(['pr', 'merge', baseBranch, '--squash', '--subject', subject, '--body-file', mergeBodyFile]);
209
213
  if (direct.status === 0) {
210
214
  process.stdout.write(direct.output);
211
215
  return new MergeOutcome(true, false, `squash-merged the PR as: "${subject}"`, exports.MERGE_RESULT_MERGED);
@@ -214,7 +218,7 @@ let PrMerger = class PrMerger {
214
218
  // say: checks-still-running (BLOCKED) is self-healing once auto-merge is on, while out-of-date
215
219
  // (BEHIND) can NEVER land unattended. Ask GitHub itself — one cheap, failure-tolerant call, made
216
220
  // only on the failure path, so a run whose direct merge succeeded costs no extra API call.
217
- const state = this.prMergeState(baseBranch);
221
+ const state = await this.prMergeState(baseBranch);
218
222
  this.announceDirectFailure(direct.output, state);
219
223
  return this.fallBackToAutoMerge(baseBranch, subject, mergeBodyFile, state, intent);
220
224
  }
@@ -225,8 +229,8 @@ let PrMerger = class PrMerger {
225
229
  * is NOT success either, and reporting it as such is precisely the bug this whole file guards.
226
230
  */
227
231
  // eslint-disable-next-line @typescript-eslint/max-params
228
- fallBackToAutoMerge(baseBranch, subject, mergeBodyFile, state, intent) {
229
- if (!this.autoMergeAllowed()) {
232
+ async fallBackToAutoMerge(baseBranch, subject, mergeBodyFile, state, intent) {
233
+ if (!(await this.autoMergeAllowed())) {
230
234
  if (state.isBehind())
231
235
  return this.behindOutcome(state, false);
232
236
  return new MergeOutcome(false, false, this.noQueueMessage(intent), exports.MERGE_RESULT_FAILED);
@@ -235,8 +239,8 @@ let PrMerger = class PrMerger {
235
239
  // gh records the merge subject/body only at the moment auto-merge is FIRST enabled; a second
236
240
  // `--auto` on an already-enabled PR silently keeps the OLD body. Disabling first re-stamps the
237
241
  // current subject/body on every re-run (a harmless no-op when auto-merge is not enabled).
238
- this.gh(['pr', 'merge', baseBranch, '--disable-auto'], true);
239
- const auto = this.gh(['pr', 'merge', baseBranch, '--auto', '--squash', '--subject', subject, '--body-file', mergeBodyFile]);
242
+ await this.gh(['pr', 'merge', baseBranch, '--disable-auto'], true);
243
+ const auto = await this.gh(['pr', 'merge', baseBranch, '--auto', '--squash', '--subject', subject, '--body-file', mergeBodyFile]);
240
244
  if (auto !== 0) {
241
245
  if (state.isBehind())
242
246
  return this.behindOutcome(state, false);
@@ -302,12 +306,12 @@ let PrMerger = class PrMerger {
302
306
  * purpose: a gh hiccup returns an all-'' state (never BEHIND) so a transient API blip can only cost
303
307
  * us the extra diagnosis, never turn a working run into a crash.
304
308
  */
305
- prMergeState(baseBranch) {
306
- const result = (0, child_process_1.spawnSync)('gh', ['pr', 'view', baseBranch, '--json', 'mergeable,mergeStateStatus,state',
307
- '--jq', '"\\(.mergeable)\\t\\(.mergeStateStatus)\\t\\(.state)"'], { encoding: 'utf8' });
308
- if (result.status !== 0)
309
+ async prMergeState(baseBranch) {
310
+ const result = await this.processes.run('gh', ['pr', 'view', baseBranch, '--json', 'mergeable,mergeStateStatus,state',
311
+ '--jq', '"\\(.mergeable)\\t\\(.mergeStateStatus)\\t\\(.state)"']);
312
+ if (!result.ok)
309
313
  return new PrMergeState('', '', '');
310
- const parts = (result.stdout ?? '').trim().split('\t');
314
+ const parts = result.stdout.trim().split('\t');
311
315
  return new PrMergeState(parts[0] ?? '', parts[1] ?? '', parts[2] ?? '');
312
316
  }
313
317
  // Whether `gh pr merge --auto` is even possible on this repo. Many orgs set allow_auto_merge=false
@@ -315,28 +319,29 @@ let PrMerger = class PrMerger {
315
319
  // for this repository`. One API call beats discovering that from an error string. Anything other
316
320
  // than a clean `true` counts as NOT allowed: if the setting cannot be read we must not claim the
317
321
  // queue is available.
318
- autoMergeAllowed() {
319
- const result = (0, child_process_1.spawnSync)('gh', ['api', 'repos/{owner}/{repo}', '--jq', '.allow_auto_merge'], { encoding: 'utf8' });
320
- return result.status === 0 && (result.stdout ?? '').trim() === 'true';
322
+ async autoMergeAllowed() {
323
+ const result = await this.processes.run('gh', ['api', 'repos/{owner}/{repo}', '--jq', '.allow_auto_merge']);
324
+ return result.ok && result.stdout.trim() === 'true';
321
325
  }
322
- // Runs `gh`, returning its exit status (-1 when gh could not be spawned at all, which must NOT be
323
- // mistaken for the 0 that means success).
324
- gh(args, quiet = false) {
325
- const result = (0, child_process_1.spawnSync)('gh', args, { stdio: quiet ? 'ignore' : 'inherit' });
326
- return result.status ?? -1;
326
+ // Runs `gh`, returning its exit status (non-zero when gh could not be started at all, which must NOT
327
+ // be mistaken for the 0 that means success). `quiet` discards its output instead of showing it.
328
+ async gh(args, quiet = false) {
329
+ const result = quiet ? await this.processes.run('gh', args) : await this.processes.passThrough('gh', args);
330
+ return result.code;
327
331
  }
328
332
  // Runs `gh` CAPTURING both streams instead of inheriting them, so an expected-to-fail attempt can be
329
333
  // reported in our own words rather than dumping a raw `X …` line the reader reads as fatal.
330
- ghCapture(args) {
331
- const result = (0, child_process_1.spawnSync)('gh', args, { encoding: 'utf8' });
332
- return new GhResult(result.status ?? -1, (result.stdout ?? '') + (result.stderr ?? ''));
334
+ async ghCapture(args) {
335
+ const result = await this.processes.run('gh', args);
336
+ return new GhResult(result.code, result.stdout + result.stderr);
333
337
  }
334
338
  };
335
339
  exports.PrMerger = PrMerger;
336
340
  exports.PrMerger = PrMerger = tslib_1.__decorate([
337
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
341
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
342
+ tslib_1.__metadata("design:paramtypes", [tooling_common_1.NativeProcessApi])
338
343
  ], PrMerger);
339
- // A captured `gh` invocation: its exit status (-1 when gh could not be spawned) and both streams
344
+ // A captured `gh` invocation: its exit status (non-zero when gh could not be started) and both streams
340
345
  // combined, in the order a terminal would have shown them.
341
346
  class GhResult {
342
347
  status;
@@ -1 +1 @@
1
- {"version":3,"file":"pr-merger.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/pr-merger.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAA2E;AAC3E,yCAA2D;AAE3D;;;;GAIG;AACU,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC5C,yGAAyG;AAC5F,QAAA,wBAAwB,GAAG,aAAa,CAAC;AACtD,qGAAqG;AACxF,QAAA,0BAA0B,GAAG,eAAe,CAAC;AAC1D;;;;;GAKG;AACU,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAC5C;;;;;GAKG;AACU,QAAA,yBAAyB,GAAG,cAAc,CAAC;AACxD;;;;GAIG;AACU,QAAA,+BAA+B,GAAG,oBAAoB,CAAC;AACpE;;;;GAIG;AACU,QAAA,2BAA2B,GAAG,gBAAgB,CAAC;AAC5D,kGAAkG;AACrF,QAAA,mBAAmB,GAAG,QAAQ,CAAC;AAE5C,wGAAwG;AACxG,MAAM,eAAe,GAAG,QAAQ,CAAC;AACjC,0GAA0G;AAC1G,sFAAsF;AACtF,MAAM,kBAAkB,GAAG,WAAW,CAAC;AACvC,MAAM,wBAAwB,GAAG,aAAa,CAAC;AAE/C,sGAAsG;AACtG,oGAAoG;AACpG,kGAAkG;AAClG,uGAAuG;AACvG,sGAAsG;AACtG,mFAAmF;AACnF,MAAa,YAAY;IACrB,MAAM,CAAU;IAChB,gBAAgB,CAAU;IAC1B,OAAO,CAAS;IAChB,MAAM,CAA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CAAC,MAAM,IAAI,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC;IAC5F,CAAC;CACJ,CAAA;AAxLY,4BAAQ;mBAAR,QAAQ;IADpB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,QAAQ,CAwLpB;AAED,iGAAiG;AACjG,2DAA2D;AAC3D,MAAa,QAAQ;IACjB,MAAM,CAAS;IACf,MAAM,CAAS;IAEf,YAAY,MAAc,EAAE,MAAc;QACtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,4BAQC","sourcesContent":["import { spawnSync } from 'child_process';\nimport { MERGE_MODE_AUTO, MERGE_MODE_NONE } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * The five terminal shapes a merge attempt can take. The CALLER branches on these — a `message` string\n * is for humans to read, never for code to pattern-match, and the banner that frames it must be able to\n * tell \"done\" from \"stranded\" without parsing prose.\n */\nexport const MERGE_RESULT_MERGED = 'MERGED';\n/** Not merged YET, but queued: auto-merge is enabled and lands it when the checks pass. Self-healing. */\nexport const MERGE_RESULT_AUTO_QUEUED = 'AUTO_QUEUED';\n/** This command did not attempt a merge; the caller may still owe landing under the user request. */\nexport const MERGE_RESULT_LEFT_TO_HUMAN = 'LEFT_TO_HUMAN';\n/**\n * Not merged and it NEVER will be without action: `gh pr view --json mergeStateStatus` says BEHIND, i.e.\n * the head branch is out of date with base. Unlike BLOCKED (waiting on checks — self-healing), BEHIND\n * cannot resolve itself; the branch must be re-synced from main. This is the case that used to print a\n * green \"✅ PR finished\" and get abandoned.\n */\nexport const MERGE_RESULT_BEHIND = 'BEHIND';\n/**\n * BEHIND *and* GitHub says the tree merges cleanly (`mergeable: MERGEABLE`). Nobody touched the same\n * lines — somebody simply landed on main first. One clean re-run of ①②③ converges. Split out from the\n * conflicting case because the two need completely different sentences: this one is not the author's\n * problem to solve, it is a queue collision, and telling them \"resolve the conflict\" is a lie.\n */\nexport const MERGE_RESULT_BEHIND_CLEAN = 'BEHIND_CLEAN';\n/**\n * BEHIND *and* `mergeable: CONFLICTING` — the landed work and this branch touch the same lines. Real\n * human/AI judgement is owed, and if others keep landing first it genuinely repeats. That is inherent to\n * concurrent editing, not a defect, and the banner says so rather than pretending a re-run is free.\n */\nexport const MERGE_RESULT_BEHIND_CONFLICTING = 'BEHIND_CONFLICTING';\n/**\n * BEHIND but `mergeable: UNKNOWN` (or unreadable). GitHub computes mergeability ASYNCHRONOUSLY and we ask\n * moments after a force-push, so UNKNOWN is the EXPECTED answer, not an error. Diagnosing from it would be\n * guessing, so this outcome asks for a re-check instead of prescribing a remedy.\n */\nexport const MERGE_RESULT_BEHIND_UNKNOWN = 'BEHIND_UNKNOWN';\n/** Not merged for some other reason (config mismatch, gh error, no PR at all). Read `message`. */\nexport const MERGE_RESULT_FAILED = 'FAILED';\n\n// The `mergeStateStatus` value GitHub reports for \"head branch is not up to date with the base branch\".\nconst GH_STATE_BEHIND = 'BEHIND';\n// `mergeable` values. GitHub returns UNKNOWN while it is still computing the merge — which is most of the\n// time in the seconds after a push — so UNKNOWN must never be read as \"no conflicts\".\nconst GH_MERGEABLE_CLEAN = 'MERGEABLE';\nconst GH_MERGEABLE_CONFLICTING = 'CONFLICTING';\n\n// What actually happened when we tried to land the squash merge. `message` is printed VERBATIM in the\n// final wp-finish-upsert-pr summary, so a merge that did not happen can never be reported as done —\n// the old code ignored `spawnSync().status` entirely and printed \"✅ PR finished\" even when `gh pr\n// merge` had errored out, which is what hid the auto-merge-disabled failure for weeks. `result` is the\n// machine-readable half of the same honesty: the banner picks its HEADER from it, so the frame around\n// the message can no longer say \"finished\" while the message says \"did NOT merge\".\nexport class MergeOutcome {\n merged: boolean;\n autoMergeEnabled: boolean;\n message: string;\n result: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(merged: boolean, autoMergeEnabled: boolean, message: string, result: string) {\n this.merged = merged;\n this.autoMergeEnabled = autoMergeEnabled;\n this.message = message;\n this.result = result;\n }\n\n // TRUE for every flavour of \"the branch is out of date with main\", so the banner can ask that one\n // question once instead of listing four constants at each branch point. Kept here rather than as a\n // module function because `no-function-outside-class` forbids the latter — and PrMergeState below\n // already sets the precedent that a verdict class answers questions about itself.\n isBehind(): boolean {\n return this.result === MERGE_RESULT_BEHIND\n || this.result === MERGE_RESULT_BEHIND_CLEAN\n || this.result === MERGE_RESULT_BEHIND_CONFLICTING\n || this.result === MERGE_RESULT_BEHIND_UNKNOWN;\n }\n}\n\n// GitHub's own verdict on the PR, straight from `gh pr view --json mergeable,mergeStateStatus,state`.\n// All '' when gh could not be asked — an unreadable answer must never be treated as a diagnosis.\nexport class PrMergeState {\n mergeable: string;\n mergeStateStatus: string;\n state: string;\n\n constructor(mergeable: string, mergeStateStatus: string, state: string) {\n this.mergeable = mergeable;\n this.mergeStateStatus = mergeStateStatus;\n this.state = state;\n }\n\n isBehind(): boolean {\n return this.mergeStateStatus === GH_STATE_BEHIND;\n }\n\n /**\n * WHICH kind of BEHIND this is, from the `mergeable` field we have always fetched and never read.\n *\n * This is the whole point of the split. \"Out of date\" and \"conflicting\" are different situations with\n * different costs, and collapsing them told every author the expensive story: a clean queue collision\n * — nobody touched your lines, somebody just landed first — got reported in the same alarming words as\n * a genuine textual conflict.\n *\n * UNKNOWN is its own answer, never folded into CLEAN. GitHub computes mergeability asynchronously and\n * we ask seconds after a force-push, so UNKNOWN is the ordinary reply in exactly our situation.\n * Treating it as \"no conflicts\" would promise a clean re-run we cannot see.\n */\n behindKind(): string {\n if (this.mergeable === GH_MERGEABLE_CLEAN) return MERGE_RESULT_BEHIND_CLEAN;\n if (this.mergeable === GH_MERGEABLE_CONFLICTING) return MERGE_RESULT_BEHIND_CONFLICTING;\n return MERGE_RESULT_BEHIND_UNKNOWN;\n }\n\n // One-line rendering for the failure message, or '' when GitHub could not be asked.\n describe(): string {\n if (this.mergeStateStatus === '') return '';\n return `mergeable=${this.mergeable}, mergeStateStatus=${this.mergeStateStatus}, state=${this.state}`;\n }\n}\n\n/**\n * WHY this run is allowed to merge — the config value, kept separate from the caller's intent.\n *\n * Those two used to be one `mergeMode: string` parameter, and `wp-land-pr` passed a literal\n * `MERGE_MODE_AUTO` through it to mean \"merge it\" rather than \"config says AUTO\". PrMerger could not\n * tell the two apart, so on a `mergeMode: \"NONE\"` repo it reported a CONFIG MISMATCH naming a value\n * nobody had set, and prescribed remedies that were already in place. Keeping the real `mergeMode`\n * alongside a `commanded` flag means no message ever has to assert a config value the code did not read.\n */\nexport class MergeIntent {\n /** pr-gate.mergeMode EXACTLY as read from webpieces.config.json — '' when it could not be read. */\n mergeMode: string;\n /**\n * TRUE when running the command IS the intent to merge (`wp-land-pr`), so the merge happens whatever\n * the config says. FALSE for the policy-driven caller (`wp-finish-upsert-pr`), where only an\n * explicit AUTO merges.\n */\n commanded: boolean;\n\n constructor(mergeMode: string, commanded: boolean) {\n this.mergeMode = mergeMode;\n this.commanded = commanded;\n }\n\n // The gate: a commanded run always proceeds; otherwise only an explicit AUTO does. Anything else\n // (including a repo on a published rules-config that predates the field) is treated as NONE —\n // when the policy is unreadable, do NOT touch main.\n shouldMerge(): boolean {\n return this.commanded || this.mergeMode === MERGE_MODE_AUTO;\n }\n}\n\n/**\n * Lands — or queues — the squash merge with an EXPLICIT subject/body, on BOTH kinds of repo:\n *\n * - auto-merge ALLOWED (`allow_auto_merge: true`): a PR whose checks are still running falls back to\n * the auto-merge queue, carrying the same subject/body so it lands when the checks pass.\n * - auto-merge DISALLOWED (`allow_auto_merge: false`, a deliberate policy control in many orgs): the\n * direct merge still works the moment the PR is mergeable, because `gh pr merge --squash --subject\n * --body-file` does not depend on that setting at all. When the PR is NOT yet mergeable there is no\n * queue to fall back to, so we say so loudly instead of firing a `--auto` that can only fail.\n *\n * WHICH of those a repo gets is not guessed — `pr-gate.mergeMode` is REQUIRED config. AUTO means the\n * tooling attempts landing; NONE means this automatic step only publishes the PR. No mode can force a queue the\n * repo has turned off, so AUTO on a repo with allow_auto_merge=false is a CONFIG error, reported as\n * one rather than papered over — but ONLY when the AUTO was read from config. A commanded merge\n * (`wp-land-pr`) on a NONE repo is not a mismatch at all; see MergeIntent.\n *\n * Every `gh` status is checked. Nothing here is allowed to fail silently.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PrMerger {\n /**\n * @param subject the squash-commit subject, normally `<PR title> (#N)`\n * @param mergeBodyFile file holding the squash-commit body (risk/flags/PR link)\n * @param intent the real pr-gate.mergeMode PLUS whether this caller commands the merge\n * regardless of it (see MergeIntent).\n */\n merge(baseBranch: string, subject: string, mergeBodyFile: string, intent: MergeIntent): MergeOutcome {\n // Anything that is not an explicit AUTO leaves the PR alone. The PR itself is already\n // posted/updated by this point, which is the whole job in this mode.\n if (!intent.shouldMerge()) {\n const mergeMode = intent.mergeMode;\n // What a UI merge produces, in terms of the repo's OWN two settings.\n //\n // This message said the opposite one release ago: \"a UI merge pastes the whole dashboard into\n // git log, land it with wp-land-pr instead\". That was true while the PR description held the\n // long dashboard. It is now the compact git-log body (see Dashboard.renderPrBody), so\n // `squash_merge_commit_message: PR_BODY` copies exactly the right text and a UI merge is\n // CORRECT — provided both settings are right. Naming them is the useful thing to say; telling\n // a mergeMode=NONE repo to stop using the UI is not; either landing route is valid.\n return new MergeOutcome(false, false,\n `did NOT merge — pr-gate.mergeMode is ${mergeMode === MERGE_MODE_NONE ? 'NONE' : `\"${mergeMode}\"`}, so wp-finish-upsert-pr published the PR without attempting a merge.\\n` +\n ` Clicking Merge is fine and writes the right history: this flow keeps\\n` +\n ` squash_merge_commit_title=PR_TITLE and squash_merge_commit_message=PR_BODY pinned on\\n` +\n ` the repo, so the subject becomes \"${subject}\" and the body is the gated description\\n` +\n ` verbatim. Nothing to set up.\\n` +\n ` \\`pnpm wp-land-pr\\` lands the same bytes from the CLI.\\n` +\n ` This setting does not require additional authorization. Honor existing user instructions,\\n` +\n ` including $full-cycle or /full-cycle, and continue to landing when requested.`,\n MERGE_RESULT_LEFT_TO_HUMAN);\n }\n\n // A direct `gh pr merge --squash --subject --body-file` writes exactly this subject/body to\n // main's history regardless of the repo's squash_merge_commit_title/message defaults — and\n // regardless of allow_auto_merge. It is the ONLY path that guarantees the good commit message.\n //\n // Its output is CAPTURED, not inherited: this attempt fails BY DESIGN on any repo whose policy\n // forbids a direct merge, and gh's raw `X Pull request #N is not mergeable: …` on the terminal\n // read as a hard failure to every human and agent who saw it. We reprint the reason ourselves,\n // framed as the expected first step of a two-step dance (see announceDirectFailure).\n const direct = this.ghCapture(['pr', 'merge', baseBranch, '--squash', '--subject', subject, '--body-file', mergeBodyFile]);\n if (direct.status === 0) {\n process.stdout.write(direct.output);\n return new MergeOutcome(true, false, `squash-merged the PR as: \"${subject}\"`, MERGE_RESULT_MERGED);\n }\n\n // Past here the PR is not mergeable yet. WHY matters enormously and gh's exit status does not\n // say: checks-still-running (BLOCKED) is self-healing once auto-merge is on, while out-of-date\n // (BEHIND) can NEVER land unattended. Ask GitHub itself — one cheap, failure-tolerant call, made\n // only on the failure path, so a run whose direct merge succeeded costs no extra API call.\n const state = this.prMergeState(baseBranch);\n this.announceDirectFailure(direct.output, state);\n return this.fallBackToAutoMerge(baseBranch, subject, mergeBodyFile, state, intent);\n }\n\n /**\n * The auto-merge queue: the only way to still land a not-yet-mergeable PR unattended. Returns the\n * BEHIND outcome regardless of how queuing went whenever GitHub says the branch is out of date —\n * queuing a BEHIND PR is not an error (a repo that auto-updates branches will still land it), but it\n * is NOT success either, and reporting it as such is precisely the bug this whole file guards.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private fallBackToAutoMerge(baseBranch: string, subject: string, mergeBodyFile: string, state: PrMergeState, intent: MergeIntent): MergeOutcome {\n if (!this.autoMergeAllowed()) {\n if (state.isBehind()) return this.behindOutcome(state, false);\n return new MergeOutcome(false, false, this.noQueueMessage(intent), MERGE_RESULT_FAILED);\n }\n\n process.stdout.write(' … retrying with --auto (the auto-merge queue)\\n');\n // gh records the merge subject/body only at the moment auto-merge is FIRST enabled; a second\n // `--auto` on an already-enabled PR silently keeps the OLD body. Disabling first re-stamps the\n // current subject/body on every re-run (a harmless no-op when auto-merge is not enabled).\n this.gh(['pr', 'merge', baseBranch, '--disable-auto'], true);\n const auto = this.gh(['pr', 'merge', baseBranch, '--auto', '--squash', '--subject', subject, '--body-file', mergeBodyFile]);\n if (auto !== 0) {\n if (state.isBehind()) return this.behindOutcome(state, false);\n return new MergeOutcome(false, false,\n '⚠️ did NOT merge and could NOT enable auto-merge either (see the gh error above) —\\n' +\n ' NOTHING is queued. Re-run once the PR is healthy.',\n MERGE_RESULT_FAILED);\n }\n if (state.isBehind()) return this.behindOutcome(state, true);\n return new MergeOutcome(false, true,\n `enabled auto-merge — it will squash-merge as \"${subject}\" when the checks pass`,\n MERGE_RESULT_AUTO_QUEUED);\n }\n\n /**\n * \"Not mergeable yet, and this repo has no queue to park it in\" — in the words that are TRUE for the\n * caller we actually have.\n *\n * A COMMANDED run (`wp-land-pr`) is not a misconfiguration at all: nobody set mergeMode to AUTO, the\n * user asked for a merge by hand, and the checks simply are not green yet. Telling that reader to\n * \"set mergeMode to NONE\" named a value they had already set and sent them investigating a mismatch\n * that did not exist. Nothing is owed here but a re-run.\n *\n * A POLICY-driven run (`wp-finish-upsert-pr`) only reaches here with a config that really does say\n * AUTO on a repo that forbids the queue — the genuine mismatch, where both remedies are real.\n */\n private noQueueMessage(intent: MergeIntent): string {\n if (intent.commanded) {\n return '⚠️ did NOT merge, and queued NOTHING — the PR is not mergeable yet (checks still\\n' +\n ' running, or a required review outstanding), and this repo has allow_auto_merge=false,\\n' +\n ' so there was no queue to fall back to. NOTHING is misconfigured and nothing needs\\n' +\n ' changing — re-run `pnpm wp-land-pr` once the PR is green and it will land.';\n }\n return '⚠️ did NOT merge, and queued NOTHING — CONFIG MISMATCH: pr-gate.mergeMode is AUTO, but\\n' +\n ' this repo has allow_auto_merge=false, so there is no queue to fall back to and the\\n' +\n ' PR is not mergeable yet. `gh pr merge --auto` cannot override a repo that says no.\\n' +\n ' Fix it at ONE of the two ends: turn on \"Allow auto-merge\" in the repo settings, or\\n' +\n ' set commands.pr-gate.mergeMode to \"NONE\" (and set that repo\\'s\\n' +\n ' squash_merge_commit_title to PR_TITLE so a human merge still gets a real subject).';\n }\n\n /**\n * The one outcome that looks queued but is stranded. `queued` says whether auto-merge did get enabled,\n * because \"parked forever\" and \"not queued at all\" need different sentences — but neither is done.\n *\n * The `result` now carries WHICH kind of behind, so the banner can stop describing a queue collision\n * in the vocabulary of a merge conflict. The wording here is deliberately blame-free: nothing the\n * author did caused this, and the PR itself is in perfectly good shape — pushed, bodied, gate-green.\n */\n private behindOutcome(state: PrMergeState, queued: boolean): MergeOutcome {\n const parked = queued ? 'Auto-merge is enabled but parked.' : 'Nothing is queued.';\n return new MergeOutcome(false, queued,\n `did NOT merge — someone else landed on main first, so GitHub wants this branch rebuilt on\\n` +\n ` top of theirs before it will merge (${state.describe()}).\\n` +\n ` This does NOT self-heal: auto-merge never updates your branch. ${parked}`,\n state.behindKind());\n }\n\n // Reprint the expected first-attempt failure as CONTEXT, not as a verdict. gh's own `X …` line is\n // captured (never inherited) so this framing is the only thing on screen.\n private announceDirectFailure(ghOutput: string, state: PrMergeState): void {\n const reason = ghOutput.trim().split('\\n').filter((l: string): boolean => l.trim() !== '').pop() ?? '';\n process.stdout.write(\n 'ℹ️ the direct squash-merge did not go through (expected while checks run, or when repo\\n' +\n ' policy forbids direct merges):\\n' +\n (reason === '' ? '' : ` ${reason}\\n`) +\n (state.describe() === '' ? '' : ` GitHub says: ${state.describe()}\\n`),\n );\n }\n\n /**\n * GitHub's own verdict on the PR. AUTHORITATIVE for the BEHIND check — the alternative is\n * pattern-matching gh's English error prose, which changes between releases. Failure-tolerant on\n * purpose: a gh hiccup returns an all-'' state (never BEHIND) so a transient API blip can only cost\n * us the extra diagnosis, never turn a working run into a crash.\n */\n protected prMergeState(baseBranch: string): PrMergeState {\n const result = spawnSync(\n 'gh',\n ['pr', 'view', baseBranch, '--json', 'mergeable,mergeStateStatus,state',\n '--jq', '\"\\\\(.mergeable)\\\\t\\\\(.mergeStateStatus)\\\\t\\\\(.state)\"'],\n { encoding: 'utf8' },\n );\n if (result.status !== 0) return new PrMergeState('', '', '');\n const parts = (result.stdout ?? '').trim().split('\\t');\n return new PrMergeState(parts[0] ?? '', parts[1] ?? '', parts[2] ?? '');\n }\n\n // Whether `gh pr merge --auto` is even possible on this repo. Many orgs set allow_auto_merge=false\n // as a policy control, where `--auto` can only ever fail with `GraphQL: Auto merge is not allowed\n // for this repository`. One API call beats discovering that from an error string. Anything other\n // than a clean `true` counts as NOT allowed: if the setting cannot be read we must not claim the\n // queue is available.\n protected autoMergeAllowed(): boolean {\n const result = spawnSync('gh', ['api', 'repos/{owner}/{repo}', '--jq', '.allow_auto_merge'], { encoding: 'utf8' });\n return result.status === 0 && (result.stdout ?? '').trim() === 'true';\n }\n\n // Runs `gh`, returning its exit status (-1 when gh could not be spawned at all, which must NOT be\n // mistaken for the 0 that means success).\n protected gh(args: string[], quiet: boolean = false): number {\n const result = spawnSync('gh', args, { stdio: quiet ? 'ignore' : 'inherit' });\n return result.status ?? -1;\n }\n\n // Runs `gh` CAPTURING both streams instead of inheriting them, so an expected-to-fail attempt can be\n // reported in our own words rather than dumping a raw `X …` line the reader reads as fatal.\n protected ghCapture(args: string[]): GhResult {\n const result = spawnSync('gh', args, { encoding: 'utf8' });\n return new GhResult(result.status ?? -1, (result.stdout ?? '') + (result.stderr ?? ''));\n }\n}\n\n// A captured `gh` invocation: its exit status (-1 when gh could not be spawned) and both streams\n// combined, in the order a terminal would have shown them.\nexport class GhResult {\n status: number;\n output: string;\n\n constructor(status: number, output: string) {\n this.status = status;\n this.output = output;\n }\n}\n"]}
1
+ {"version":3,"file":"pr-merger.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/pr-merger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AI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,4BAQC","sourcesContent":["import { MERGE_MODE_AUTO, MERGE_MODE_NONE } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * The five terminal shapes a merge attempt can take. The CALLER branches on these — a `message` string\n * is for humans to read, never for code to pattern-match, and the banner that frames it must be able to\n * tell \"done\" from \"stranded\" without parsing prose.\n */\nexport const MERGE_RESULT_MERGED = 'MERGED';\n/** Not merged YET, but queued: auto-merge is enabled and lands it when the checks pass. Self-healing. */\nexport const MERGE_RESULT_AUTO_QUEUED = 'AUTO_QUEUED';\n/** This command did not attempt a merge; the caller may still owe landing under the user request. */\nexport const MERGE_RESULT_LEFT_TO_HUMAN = 'LEFT_TO_HUMAN';\n/**\n * Not merged and it NEVER will be without action: `gh pr view --json mergeStateStatus` says BEHIND, i.e.\n * the head branch is out of date with base. Unlike BLOCKED (waiting on checks — self-healing), BEHIND\n * cannot resolve itself; the branch must be re-synced from main. This is the case that used to print a\n * green \"✅ PR finished\" and get abandoned.\n */\nexport const MERGE_RESULT_BEHIND = 'BEHIND';\n/**\n * BEHIND *and* GitHub says the tree merges cleanly (`mergeable: MERGEABLE`). Nobody touched the same\n * lines — somebody simply landed on main first. One clean re-run of ①②③ converges. Split out from the\n * conflicting case because the two need completely different sentences: this one is not the author's\n * problem to solve, it is a queue collision, and telling them \"resolve the conflict\" is a lie.\n */\nexport const MERGE_RESULT_BEHIND_CLEAN = 'BEHIND_CLEAN';\n/**\n * BEHIND *and* `mergeable: CONFLICTING` — the landed work and this branch touch the same lines. Real\n * human/AI judgement is owed, and if others keep landing first it genuinely repeats. That is inherent to\n * concurrent editing, not a defect, and the banner says so rather than pretending a re-run is free.\n */\nexport const MERGE_RESULT_BEHIND_CONFLICTING = 'BEHIND_CONFLICTING';\n/**\n * BEHIND but `mergeable: UNKNOWN` (or unreadable). GitHub computes mergeability ASYNCHRONOUSLY and we ask\n * moments after a force-push, so UNKNOWN is the EXPECTED answer, not an error. Diagnosing from it would be\n * guessing, so this outcome asks for a re-check instead of prescribing a remedy.\n */\nexport const MERGE_RESULT_BEHIND_UNKNOWN = 'BEHIND_UNKNOWN';\n/** Not merged for some other reason (config mismatch, gh error, no PR at all). Read `message`. */\nexport const MERGE_RESULT_FAILED = 'FAILED';\n\n// The `mergeStateStatus` value GitHub reports for \"head branch is not up to date with the base branch\".\nconst GH_STATE_BEHIND = 'BEHIND';\n// `mergeable` values. GitHub returns UNKNOWN while it is still computing the merge — which is most of the\n// time in the seconds after a push — so UNKNOWN must never be read as \"no conflicts\".\nconst GH_MERGEABLE_CLEAN = 'MERGEABLE';\nconst GH_MERGEABLE_CONFLICTING = 'CONFLICTING';\n\n// What actually happened when we tried to land the squash merge. `message` is printed VERBATIM in the\n// final wp-finish-upsert-pr summary, so a merge that did not happen can never be reported as done —\n// the old code ignored the gh exit status entirely and printed \"✅ PR finished\" even when `gh pr\n// merge` had errored out, which is what hid the auto-merge-disabled failure for weeks. `result` is the\n// machine-readable half of the same honesty: the banner picks its HEADER from it, so the frame around\n// the message can no longer say \"finished\" while the message says \"did NOT merge\".\nexport class MergeOutcome {\n merged: boolean;\n autoMergeEnabled: boolean;\n message: string;\n result: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(merged: boolean, autoMergeEnabled: boolean, message: string, result: string) {\n this.merged = merged;\n this.autoMergeEnabled = autoMergeEnabled;\n this.message = message;\n this.result = result;\n }\n\n // TRUE for every flavour of \"the branch is out of date with main\", so the banner can ask that one\n // question once instead of listing four constants at each branch point. Kept here rather than as a\n // module function because `no-function-outside-class` forbids the latter — and PrMergeState below\n // already sets the precedent that a verdict class answers questions about itself.\n isBehind(): boolean {\n return this.result === MERGE_RESULT_BEHIND\n || this.result === MERGE_RESULT_BEHIND_CLEAN\n || this.result === MERGE_RESULT_BEHIND_CONFLICTING\n || this.result === MERGE_RESULT_BEHIND_UNKNOWN;\n }\n}\n\n// GitHub's own verdict on the PR, straight from `gh pr view --json mergeable,mergeStateStatus,state`.\n// All '' when gh could not be asked — an unreadable answer must never be treated as a diagnosis.\nexport class PrMergeState {\n mergeable: string;\n mergeStateStatus: string;\n state: string;\n\n constructor(mergeable: string, mergeStateStatus: string, state: string) {\n this.mergeable = mergeable;\n this.mergeStateStatus = mergeStateStatus;\n this.state = state;\n }\n\n isBehind(): boolean {\n return this.mergeStateStatus === GH_STATE_BEHIND;\n }\n\n /**\n * WHICH kind of BEHIND this is, from the `mergeable` field we have always fetched and never read.\n *\n * This is the whole point of the split. \"Out of date\" and \"conflicting\" are different situations with\n * different costs, and collapsing them told every author the expensive story: a clean queue collision\n * — nobody touched your lines, somebody just landed first — got reported in the same alarming words as\n * a genuine textual conflict.\n *\n * UNKNOWN is its own answer, never folded into CLEAN. GitHub computes mergeability asynchronously and\n * we ask seconds after a force-push, so UNKNOWN is the ordinary reply in exactly our situation.\n * Treating it as \"no conflicts\" would promise a clean re-run we cannot see.\n */\n behindKind(): string {\n if (this.mergeable === GH_MERGEABLE_CLEAN) return MERGE_RESULT_BEHIND_CLEAN;\n if (this.mergeable === GH_MERGEABLE_CONFLICTING) return MERGE_RESULT_BEHIND_CONFLICTING;\n return MERGE_RESULT_BEHIND_UNKNOWN;\n }\n\n // One-line rendering for the failure message, or '' when GitHub could not be asked.\n describe(): string {\n if (this.mergeStateStatus === '') return '';\n return `mergeable=${this.mergeable}, mergeStateStatus=${this.mergeStateStatus}, state=${this.state}`;\n }\n}\n\n/**\n * WHY this run is allowed to merge — the config value, kept separate from the caller's intent.\n *\n * Those two used to be one `mergeMode: string` parameter, and `wp-land-pr` passed a literal\n * `MERGE_MODE_AUTO` through it to mean \"merge it\" rather than \"config says AUTO\". PrMerger could not\n * tell the two apart, so on a `mergeMode: \"NONE\"` repo it reported a CONFIG MISMATCH naming a value\n * nobody had set, and prescribed remedies that were already in place. Keeping the real `mergeMode`\n * alongside a `commanded` flag means no message ever has to assert a config value the code did not read.\n */\nexport class MergeIntent {\n /** pr-gate.mergeMode EXACTLY as read from webpieces.config.json — '' when it could not be read. */\n mergeMode: string;\n /**\n * TRUE when running the command IS the intent to merge (`wp-land-pr`), so the merge happens whatever\n * the config says. FALSE for the policy-driven caller (`wp-finish-upsert-pr`), where only an\n * explicit AUTO merges.\n */\n commanded: boolean;\n\n constructor(mergeMode: string, commanded: boolean) {\n this.mergeMode = mergeMode;\n this.commanded = commanded;\n }\n\n // The gate: a commanded run always proceeds; otherwise only an explicit AUTO does. Anything else\n // (including a repo on a published rules-config that predates the field) is treated as NONE —\n // when the policy is unreadable, do NOT touch main.\n shouldMerge(): boolean {\n return this.commanded || this.mergeMode === MERGE_MODE_AUTO;\n }\n}\n\n/**\n * Lands — or queues — the squash merge with an EXPLICIT subject/body, on BOTH kinds of repo:\n *\n * - auto-merge ALLOWED (`allow_auto_merge: true`): a PR whose checks are still running falls back to\n * the auto-merge queue, carrying the same subject/body so it lands when the checks pass.\n * - auto-merge DISALLOWED (`allow_auto_merge: false`, a deliberate policy control in many orgs): the\n * direct merge still works the moment the PR is mergeable, because `gh pr merge --squash --subject\n * --body-file` does not depend on that setting at all. When the PR is NOT yet mergeable there is no\n * queue to fall back to, so we say so loudly instead of firing a `--auto` that can only fail.\n *\n * WHICH of those a repo gets is not guessed — `pr-gate.mergeMode` is REQUIRED config. AUTO means the\n * tooling attempts landing; NONE means this automatic step only publishes the PR. No mode can force a queue the\n * repo has turned off, so AUTO on a repo with allow_auto_merge=false is a CONFIG error, reported as\n * one rather than papered over — but ONLY when the AUTO was read from config. A commanded merge\n * (`wp-land-pr`) on a NONE repo is not a mismatch at all; see MergeIntent.\n *\n * Every `gh` status is checked. Nothing here is allowed to fail silently.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PrMerger {\n constructor(private readonly processes: NativeProcessApi) {}\n\n /**\n * @param subject the squash-commit subject, normally `<PR title> (#N)`\n * @param mergeBodyFile file holding the squash-commit body (risk/flags/PR link)\n * @param intent the real pr-gate.mergeMode PLUS whether this caller commands the merge\n * regardless of it (see MergeIntent).\n */\n async merge(baseBranch: string, subject: string, mergeBodyFile: string, intent: MergeIntent): Promise<MergeOutcome> {\n // Anything that is not an explicit AUTO leaves the PR alone. The PR itself is already\n // posted/updated by this point, which is the whole job in this mode.\n if (!intent.shouldMerge()) {\n const mergeMode = intent.mergeMode;\n // What a UI merge produces, in terms of the repo's OWN two settings.\n //\n // This message said the opposite one release ago: \"a UI merge pastes the whole dashboard into\n // git log, land it with wp-land-pr instead\". That was true while the PR description held the\n // long dashboard. It is now the compact git-log body (see Dashboard.renderPrBody), so\n // `squash_merge_commit_message: PR_BODY` copies exactly the right text and a UI merge is\n // CORRECT — provided both settings are right. Naming them is the useful thing to say; telling\n // a mergeMode=NONE repo to stop using the UI is not; either landing route is valid.\n return new MergeOutcome(false, false,\n `did NOT merge — pr-gate.mergeMode is ${mergeMode === MERGE_MODE_NONE ? 'NONE' : `\"${mergeMode}\"`}, so wp-finish-upsert-pr published the PR without attempting a merge.\\n` +\n ` Clicking Merge is fine and writes the right history: this flow keeps\\n` +\n ` squash_merge_commit_title=PR_TITLE and squash_merge_commit_message=PR_BODY pinned on\\n` +\n ` the repo, so the subject becomes \"${subject}\" and the body is the gated description\\n` +\n ` verbatim. Nothing to set up.\\n` +\n ` \\`pnpm wp-land-pr\\` lands the same bytes from the CLI.\\n` +\n ` This setting does not require additional authorization. Honor existing user instructions,\\n` +\n ` including $full-cycle or /full-cycle, and continue to landing when requested.`,\n MERGE_RESULT_LEFT_TO_HUMAN);\n }\n\n // A direct `gh pr merge --squash --subject --body-file` writes exactly this subject/body to\n // main's history regardless of the repo's squash_merge_commit_title/message defaults — and\n // regardless of allow_auto_merge. It is the ONLY path that guarantees the good commit message.\n //\n // Its output is CAPTURED, not inherited: this attempt fails BY DESIGN on any repo whose policy\n // forbids a direct merge, and gh's raw `X Pull request #N is not mergeable: …` on the terminal\n // read as a hard failure to every human and agent who saw it. We reprint the reason ourselves,\n // framed as the expected first step of a two-step dance (see announceDirectFailure).\n const direct = await this.ghCapture(['pr', 'merge', baseBranch, '--squash', '--subject', subject, '--body-file', mergeBodyFile]);\n if (direct.status === 0) {\n process.stdout.write(direct.output);\n return new MergeOutcome(true, false, `squash-merged the PR as: \"${subject}\"`, MERGE_RESULT_MERGED);\n }\n\n // Past here the PR is not mergeable yet. WHY matters enormously and gh's exit status does not\n // say: checks-still-running (BLOCKED) is self-healing once auto-merge is on, while out-of-date\n // (BEHIND) can NEVER land unattended. Ask GitHub itself — one cheap, failure-tolerant call, made\n // only on the failure path, so a run whose direct merge succeeded costs no extra API call.\n const state = await this.prMergeState(baseBranch);\n this.announceDirectFailure(direct.output, state);\n return this.fallBackToAutoMerge(baseBranch, subject, mergeBodyFile, state, intent);\n }\n\n /**\n * The auto-merge queue: the only way to still land a not-yet-mergeable PR unattended. Returns the\n * BEHIND outcome regardless of how queuing went whenever GitHub says the branch is out of date —\n * queuing a BEHIND PR is not an error (a repo that auto-updates branches will still land it), but it\n * is NOT success either, and reporting it as such is precisely the bug this whole file guards.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private async fallBackToAutoMerge(baseBranch: string, subject: string, mergeBodyFile: string, state: PrMergeState, intent: MergeIntent): Promise<MergeOutcome> {\n if (!(await this.autoMergeAllowed())) {\n if (state.isBehind()) return this.behindOutcome(state, false);\n return new MergeOutcome(false, false, this.noQueueMessage(intent), MERGE_RESULT_FAILED);\n }\n\n process.stdout.write(' … retrying with --auto (the auto-merge queue)\\n');\n // gh records the merge subject/body only at the moment auto-merge is FIRST enabled; a second\n // `--auto` on an already-enabled PR silently keeps the OLD body. Disabling first re-stamps the\n // current subject/body on every re-run (a harmless no-op when auto-merge is not enabled).\n await this.gh(['pr', 'merge', baseBranch, '--disable-auto'], true);\n const auto = await this.gh(['pr', 'merge', baseBranch, '--auto', '--squash', '--subject', subject, '--body-file', mergeBodyFile]);\n if (auto !== 0) {\n if (state.isBehind()) return this.behindOutcome(state, false);\n return new MergeOutcome(false, false,\n '⚠️ did NOT merge and could NOT enable auto-merge either (see the gh error above) —\\n' +\n ' NOTHING is queued. Re-run once the PR is healthy.',\n MERGE_RESULT_FAILED);\n }\n if (state.isBehind()) return this.behindOutcome(state, true);\n return new MergeOutcome(false, true,\n `enabled auto-merge — it will squash-merge as \"${subject}\" when the checks pass`,\n MERGE_RESULT_AUTO_QUEUED);\n }\n\n /**\n * \"Not mergeable yet, and this repo has no queue to park it in\" — in the words that are TRUE for the\n * caller we actually have.\n *\n * A COMMANDED run (`wp-land-pr`) is not a misconfiguration at all: nobody set mergeMode to AUTO, the\n * user asked for a merge by hand, and the checks simply are not green yet. Telling that reader to\n * \"set mergeMode to NONE\" named a value they had already set and sent them investigating a mismatch\n * that did not exist. Nothing is owed here but a re-run.\n *\n * A POLICY-driven run (`wp-finish-upsert-pr`) only reaches here with a config that really does say\n * AUTO on a repo that forbids the queue — the genuine mismatch, where both remedies are real.\n */\n private noQueueMessage(intent: MergeIntent): string {\n if (intent.commanded) {\n return '⚠️ did NOT merge, and queued NOTHING — the PR is not mergeable yet (checks still\\n' +\n ' running, or a required review outstanding), and this repo has allow_auto_merge=false,\\n' +\n ' so there was no queue to fall back to. NOTHING is misconfigured and nothing needs\\n' +\n ' changing — re-run `pnpm wp-land-pr` once the PR is green and it will land.';\n }\n return '⚠️ did NOT merge, and queued NOTHING — CONFIG MISMATCH: pr-gate.mergeMode is AUTO, but\\n' +\n ' this repo has allow_auto_merge=false, so there is no queue to fall back to and the\\n' +\n ' PR is not mergeable yet. `gh pr merge --auto` cannot override a repo that says no.\\n' +\n ' Fix it at ONE of the two ends: turn on \"Allow auto-merge\" in the repo settings, or\\n' +\n ' set commands.pr-gate.mergeMode to \"NONE\" (and set that repo\\'s\\n' +\n ' squash_merge_commit_title to PR_TITLE so a human merge still gets a real subject).';\n }\n\n /**\n * The one outcome that looks queued but is stranded. `queued` says whether auto-merge did get enabled,\n * because \"parked forever\" and \"not queued at all\" need different sentences — but neither is done.\n *\n * The `result` now carries WHICH kind of behind, so the banner can stop describing a queue collision\n * in the vocabulary of a merge conflict. The wording here is deliberately blame-free: nothing the\n * author did caused this, and the PR itself is in perfectly good shape — pushed, bodied, gate-green.\n */\n private behindOutcome(state: PrMergeState, queued: boolean): MergeOutcome {\n const parked = queued ? 'Auto-merge is enabled but parked.' : 'Nothing is queued.';\n return new MergeOutcome(false, queued,\n `did NOT merge — someone else landed on main first, so GitHub wants this branch rebuilt on\\n` +\n ` top of theirs before it will merge (${state.describe()}).\\n` +\n ` This does NOT self-heal: auto-merge never updates your branch. ${parked}`,\n state.behindKind());\n }\n\n // Reprint the expected first-attempt failure as CONTEXT, not as a verdict. gh's own `X …` line is\n // captured (never inherited) so this framing is the only thing on screen.\n private announceDirectFailure(ghOutput: string, state: PrMergeState): void {\n const reason = ghOutput.trim().split('\\n').filter((l: string): boolean => l.trim() !== '').pop() ?? '';\n process.stdout.write(\n 'ℹ️ the direct squash-merge did not go through (expected while checks run, or when repo\\n' +\n ' policy forbids direct merges):\\n' +\n (reason === '' ? '' : ` ${reason}\\n`) +\n (state.describe() === '' ? '' : ` GitHub says: ${state.describe()}\\n`),\n );\n }\n\n /**\n * GitHub's own verdict on the PR. AUTHORITATIVE for the BEHIND check — the alternative is\n * pattern-matching gh's English error prose, which changes between releases. Failure-tolerant on\n * purpose: a gh hiccup returns an all-'' state (never BEHIND) so a transient API blip can only cost\n * us the extra diagnosis, never turn a working run into a crash.\n */\n private async prMergeState(baseBranch: string): Promise<PrMergeState> {\n const result = await this.processes.run(\n 'gh',\n ['pr', 'view', baseBranch, '--json', 'mergeable,mergeStateStatus,state',\n '--jq', '\"\\\\(.mergeable)\\\\t\\\\(.mergeStateStatus)\\\\t\\\\(.state)\"'],\n );\n if (!result.ok) return new PrMergeState('', '', '');\n const parts = result.stdout.trim().split('\\t');\n return new PrMergeState(parts[0] ?? '', parts[1] ?? '', parts[2] ?? '');\n }\n\n // Whether `gh pr merge --auto` is even possible on this repo. Many orgs set allow_auto_merge=false\n // as a policy control, where `--auto` can only ever fail with `GraphQL: Auto merge is not allowed\n // for this repository`. One API call beats discovering that from an error string. Anything other\n // than a clean `true` counts as NOT allowed: if the setting cannot be read we must not claim the\n // queue is available.\n private async autoMergeAllowed(): Promise<boolean> {\n const result = await this.processes.run('gh', ['api', 'repos/{owner}/{repo}', '--jq', '.allow_auto_merge']);\n return result.ok && result.stdout.trim() === 'true';\n }\n\n // Runs `gh`, returning its exit status (non-zero when gh could not be started at all, which must NOT\n // be mistaken for the 0 that means success). `quiet` discards its output instead of showing it.\n private async gh(args: string[], quiet: boolean = false): Promise<number> {\n const result = quiet ? await this.processes.run('gh', args) : await this.processes.passThrough('gh', args);\n return result.code;\n }\n\n // Runs `gh` CAPTURING both streams instead of inheriting them, so an expected-to-fail attempt can be\n // reported in our own words rather than dumping a raw `X …` line the reader reads as fatal.\n private async ghCapture(args: string[]): Promise<GhResult> {\n const result = await this.processes.run('gh', args);\n return new GhResult(result.code, result.stdout + result.stderr);\n }\n}\n\n// A captured `gh` invocation: its exit status (non-zero when gh could not be started) and both streams\n// combined, in the order a terminal would have shown them.\nexport class GhResult {\n status: number;\n output: string;\n\n constructor(status: number, output: string) {\n this.status = status;\n this.output = output;\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { RequiredChecklist, PrGateConfig, ReviewJsonService, SubagentProvenanceService, ReviewerEvidence, ReviewProvenanceService, ReviewerInstructionsService } from '@webpieces/rules-config';
2
+ import { GitProcessApi } from '@webpieces/tooling-common';
2
3
  import { AiBranchName } from './git-readAiBranchName';
3
4
  import { VerdictProvenanceService } from './verdict-provenance';
4
5
  /**
@@ -28,7 +29,8 @@ export declare class ProvenanceEnforcer {
28
29
  private readonly reviewerInstructions;
29
30
  private readonly reviewJsonService;
30
31
  private readonly verdictProvenance;
31
- constructor(aiBranchName: AiBranchName, provenance: SubagentProvenanceService, provenanceRecord: ReviewProvenanceService, reviewerInstructions: ReviewerInstructionsService, reviewJsonService: ReviewJsonService, verdictProvenance: VerdictProvenanceService);
32
+ private readonly git;
33
+ constructor(aiBranchName: AiBranchName, provenance: SubagentProvenanceService, provenanceRecord: ReviewProvenanceService, reviewerInstructions: ReviewerInstructionsService, reviewJsonService: ReviewJsonService, verdictProvenance: VerdictProvenanceService, git: GitProcessApi);
32
34
  /**
33
35
  * Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps
34
36
  * the transcript links belonging to the round that produced it — a record overwritten by the NEXT
@@ -39,7 +41,7 @@ export declare class ProvenanceEnforcer {
39
41
  */
40
42
  archiveRecord(prDir: string): void;
41
43
  private gitOut;
42
- enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport;
44
+ enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): Promise<ProvenanceReport>;
43
45
  /**
44
46
  * Evidence from `review-round<N>-<id>.provenance.json` when there are no Claude transcripts to read: the harness,
45
47
  * session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ProvenanceEnforcer = exports.ProvenanceReport = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const child_process_1 = require("child_process");
6
5
  const fs = tslib_1.__importStar(require("fs"));
7
6
  const path = tslib_1.__importStar(require("path"));
8
7
  const rules_config_1 = require("@webpieces/rules-config");
@@ -41,14 +40,16 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
41
40
  reviewerInstructions;
42
41
  reviewJsonService;
43
42
  verdictProvenance;
43
+ git;
44
44
  // eslint-disable-next-line @typescript-eslint/max-params
45
- constructor(aiBranchName, provenance, provenanceRecord, reviewerInstructions, reviewJsonService, verdictProvenance) {
45
+ constructor(aiBranchName, provenance, provenanceRecord, reviewerInstructions, reviewJsonService, verdictProvenance, git) {
46
46
  this.aiBranchName = aiBranchName;
47
47
  this.provenance = provenance;
48
48
  this.provenanceRecord = provenanceRecord;
49
49
  this.reviewerInstructions = reviewerInstructions;
50
50
  this.reviewJsonService = reviewJsonService;
51
51
  this.verdictProvenance = verdictProvenance;
52
+ this.git = git;
52
53
  }
53
54
  /**
54
55
  * Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps
@@ -63,9 +64,9 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
63
64
  }
64
65
  // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades
65
66
  // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.
66
- gitOut(args) {
67
- const result = (0, child_process_1.spawnSync)('git', args, { encoding: 'utf8' });
68
- return result.status === 0 ? (result.stdout ?? '').trim() : '';
67
+ async gitOut(args) {
68
+ const result = await this.git.run(args);
69
+ return result.ok ? result.stdout.trim() : '';
69
70
  }
70
71
  // Enforce that EACH matched checklist was reviewed by a real reviewer SUBAGENT — the coding agent may
71
72
  // not self-certify. Not by one of a particular NAME: see SubagentProvenanceService.isReviewerRun. One run may cover several checklists, because `reviewerAgents` is a
@@ -77,7 +78,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
77
78
  // not write for a reviewer subagent. What is skipped is only the transcript evidence, and the audit
78
79
  // record is filled from the bin's provenance instead — so a Codex reviewer's identity is recorded too.
79
80
  // eslint-disable-next-line @typescript-eslint/max-params
80
- enforce(required, branch, repoRoot, config) {
81
+ async enforce(required, branch, repoRoot, config) {
81
82
  const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified
82
83
  // Defense in depth: the scanner normally hands finish an empty set under this project policy, but
83
84
  // provenance must never resurrect a reviewer requirement if a caller still passes matched checklists.
@@ -85,7 +86,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
85
86
  const expected = enforced
86
87
  .filter((r) => r.reviewer.agentName.trim() !== '')
87
88
  .map((r) => new rules_config_1.ExpectedReviewer(r.id, r.reviewer.agentName.trim()));
88
- const context = this.contextFor(repoRoot, enforced, branch);
89
+ const context = await this.contextFor(repoRoot, enforced, branch);
89
90
  // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no
90
91
  // checklists still gets a provenance record naming the session and the main agent's own transcript.
91
92
  const result = this.provenance.verifyReviewers(expected, context);
@@ -94,13 +95,13 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
94
95
  process.stderr.write(`⚠️ ${result.detail}\n`);
95
96
  const skipped = result.status === rules_config_1.PROVENANCE_SKIPPED;
96
97
  report.evidence = skipped
97
- ? this.binEvidence(repoRoot, expected)
98
+ ? await this.binEvidence(repoRoot, expected)
98
99
  : this.provenance.evidenceFor(context, expected, result.agentIds);
99
100
  // Bin evidence says WHO submitted, not what they read, so it cannot be judged blind.
100
101
  const blind = skipped ? [] : this.blindReviewers(report.evidence, config);
101
102
  // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record
102
103
  // that only ever appeared on success could not answer what the reviewers did the time it was refused.
103
- this.writeProvenanceRecord(repoRoot, enforced, result, report.evidence);
104
+ await this.writeProvenanceRecord(repoRoot, enforced, result, report.evidence);
104
105
  this.refuse(result, blind, context);
105
106
  return report;
106
107
  }
@@ -108,8 +109,8 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
108
109
  * Evidence from `review-round<N>-<id>.provenance.json` when there are no Claude transcripts to read: the harness,
109
110
  * session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.
110
111
  */
111
- binEvidence(repoRoot, expected) {
112
- const summaryPath = (0, rules_config_1.summaryJsonPath)(repoRoot, this.aiBranchName.getFeatureName());
112
+ async binEvidence(repoRoot, expected) {
113
+ const summaryPath = (0, rules_config_1.summaryJsonPath)(repoRoot, await this.aiBranchName.getFeatureName());
113
114
  const out = [];
114
115
  for (const want of expected) {
115
116
  const record = this.verdictProvenance.read(summaryPath, want.checklistId, this.reviewJsonService.latestVerdictRound(summaryPath, want.checklistId));
@@ -224,8 +225,8 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
224
225
  * One object for crediting and for evidence: they ask different questions of the same files, and
225
226
  * building the paths twice is how the two could drift apart.
226
227
  */
227
- contextFor(repoRoot, required, branch) {
228
- const featureName = this.aiBranchName.getFeatureName();
228
+ async contextFor(repoRoot, required, branch) {
229
+ const featureName = await this.aiBranchName.getFeatureName();
229
230
  const summaryPath = (0, rules_config_1.summaryJsonPath)(repoRoot, featureName);
230
231
  const docPaths = {};
231
232
  const verdictPaths = {};
@@ -259,10 +260,10 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
259
260
  * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.
260
261
  */
261
262
  // eslint-disable-next-line @typescript-eslint/max-params
262
- writeProvenanceRecord(repoRoot, required, result, evidence) {
263
- const featureName = this.aiBranchName.getFeatureName();
263
+ async writeProvenanceRecord(repoRoot, required, result, evidence) {
264
+ const featureName = await this.aiBranchName.getFeatureName();
264
265
  const prDir = (0, rules_config_1.prDirFor)(repoRoot, featureName);
265
- const request = new rules_config_1.ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);
266
+ const request = new rules_config_1.ProvenanceWriteRequest(prDir, featureName, await this.gitOut(['rev-parse', 'HEAD']), result.status);
266
267
  request.offered = new rules_config_1.OfferedContext(path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));
267
268
  request.reviewers = evidence.map((e) => new rules_config_1.ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));
268
269
  const written = this.provenanceRecord.write(request);
@@ -308,6 +309,7 @@ exports.ProvenanceEnforcer = ProvenanceEnforcer = tslib_1.__decorate([
308
309
  rules_config_1.ReviewProvenanceService,
309
310
  rules_config_1.ReviewerInstructionsService,
310
311
  rules_config_1.ReviewJsonService,
311
- verdict_provenance_1.VerdictProvenanceService])
312
+ verdict_provenance_1.VerdictProvenanceService,
313
+ tooling_common_1.GitProcessApi])
312
314
  ], ProvenanceEnforcer);
313
315
  //# sourceMappingURL=provenance-enforcer.js.map