@webpieces/pr-gate 0.4.975 → 0.4.977

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 (182) 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/cleanup-command.js +12 -12
  12. package/src/scripts/commands/cleanup-command.js.map +1 -1
  13. package/src/scripts/commands/finish-push-dev-command.js +3 -4
  14. package/src/scripts/commands/finish-push-dev-command.js.map +1 -1
  15. package/src/scripts/commands/finish-update-command.js +1 -1
  16. package/src/scripts/commands/finish-update-command.js.map +1 -1
  17. package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -1
  18. package/src/scripts/commands/finish-upsert-pr-command.js +65 -62
  19. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  20. package/src/scripts/commands/human-post-pr-command.d.ts +8 -6
  21. package/src/scripts/commands/human-post-pr-command.js +33 -32
  22. package/src/scripts/commands/human-post-pr-command.js.map +1 -1
  23. package/src/scripts/commands/land-pr-command.d.ts +5 -1
  24. package/src/scripts/commands/land-pr-command.js +37 -23
  25. package/src/scripts/commands/land-pr-command.js.map +1 -1
  26. package/src/scripts/commands/main-checkout.d.ts +4 -1
  27. package/src/scripts/commands/main-checkout.js +22 -22
  28. package/src/scripts/commands/main-checkout.js.map +1 -1
  29. package/src/scripts/commands/push-dev-command.js +28 -29
  30. package/src/scripts/commands/push-dev-command.js.map +1 -1
  31. package/src/scripts/commands/reap-worktree-command.js +4 -5
  32. package/src/scripts/commands/reap-worktree-command.js.map +1 -1
  33. package/src/scripts/commands/review-upsert-pr-command.js +10 -10
  34. package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
  35. package/src/scripts/commands/start-update-command.d.ts +1 -1
  36. package/src/scripts/commands/start-update-command.js +3 -3
  37. package/src/scripts/commands/start-update-command.js.map +1 -1
  38. package/src/scripts/commands/start-upsert-pr-command.js +4 -4
  39. package/src/scripts/commands/start-upsert-pr-command.js.map +1 -1
  40. package/src/scripts/commands/sync-main-command.js +6 -6
  41. package/src/scripts/commands/sync-main-command.js.map +1 -1
  42. package/src/scripts/commands/upsert-hotfix-pr-command.d.ts +6 -4
  43. package/src/scripts/commands/upsert-hotfix-pr-command.js +46 -43
  44. package/src/scripts/commands/upsert-hotfix-pr-command.js.map +1 -1
  45. package/src/scripts/commands/working-tree-gate.d.ts +4 -1
  46. package/src/scripts/commands/working-tree-gate.js +14 -11
  47. package/src/scripts/commands/working-tree-gate.js.map +1 -1
  48. package/src/scripts/commands/worktree-cleanup.d.ts +4 -4
  49. package/src/scripts/commands/worktree-cleanup.js +4 -4
  50. package/src/scripts/commands/worktree-cleanup.js.map +1 -1
  51. package/src/scripts/commands/write-review-command.js +4 -6
  52. package/src/scripts/commands/write-review-command.js.map +1 -1
  53. package/src/scripts/commands/write-review-fixes-command.js +3 -4
  54. package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
  55. package/src/scripts/git-finishUpsertPr.js +2 -2
  56. package/src/scripts/git-finishUpsertPr.js.map +1 -1
  57. package/src/scripts/git-gatherInfo.js +6 -7
  58. package/src/scripts/git-gatherInfo.js.map +1 -1
  59. package/src/scripts/pr-gate-container.d.ts +9 -0
  60. package/src/scripts/pr-gate-container.js +19 -0
  61. package/src/scripts/pr-gate-container.js.map +1 -0
  62. package/src/scripts/workflow/await-loop.d.ts +1 -1
  63. package/src/scripts/workflow/await-loop.js +1 -1
  64. package/src/scripts/workflow/await-loop.js.map +1 -1
  65. package/src/scripts/workflow/build-affected.js +1 -1
  66. package/src/scripts/workflow/build-affected.js.map +1 -1
  67. package/src/scripts/workflow/build-artifact-gate.d.ts +1 -1
  68. package/src/scripts/workflow/build-artifact-gate.js +3 -3
  69. package/src/scripts/workflow/build-artifact-gate.js.map +1 -1
  70. package/src/scripts/workflow/build-gate-log.d.ts +9 -6
  71. package/src/scripts/workflow/build-gate-log.js +34 -40
  72. package/src/scripts/workflow/build-gate-log.js.map +1 -1
  73. package/src/scripts/workflow/checklist-detector.d.ts +2 -2
  74. package/src/scripts/workflow/checklist-detector.js +4 -4
  75. package/src/scripts/workflow/checklist-detector.js.map +1 -1
  76. package/src/scripts/workflow/checklist-scanner.d.ts +1 -1
  77. package/src/scripts/workflow/checklist-scanner.js +11 -11
  78. package/src/scripts/workflow/checklist-scanner.js.map +1 -1
  79. package/src/scripts/workflow/checklist-scope-hasher.d.ts +1 -1
  80. package/src/scripts/workflow/checklist-scope-hasher.js +2 -2
  81. package/src/scripts/workflow/checklist-scope-hasher.js.map +1 -1
  82. package/src/scripts/workflow/dev-deploy-refs.d.ts +5 -5
  83. package/src/scripts/workflow/dev-deploy-refs.js +8 -8
  84. package/src/scripts/workflow/dev-deploy-refs.js.map +1 -1
  85. package/src/scripts/workflow/dev-resolve-runner.d.ts +3 -3
  86. package/src/scripts/workflow/dev-resolve-runner.js +30 -30
  87. package/src/scripts/workflow/dev-resolve-runner.js.map +1 -1
  88. package/src/scripts/workflow/diff-basis.d.ts +4 -2
  89. package/src/scripts/workflow/diff-basis.js +18 -15
  90. package/src/scripts/workflow/diff-basis.js.map +1 -1
  91. package/src/scripts/workflow/diff-materializer.d.ts +5 -3
  92. package/src/scripts/workflow/diff-materializer.js +18 -15
  93. package/src/scripts/workflow/diff-materializer.js.map +1 -1
  94. package/src/scripts/workflow/gated-pr-publisher.d.ts +8 -6
  95. package/src/scripts/workflow/gated-pr-publisher.js +23 -22
  96. package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
  97. package/src/scripts/workflow/generated-artifact-registry.d.ts +4 -2
  98. package/src/scripts/workflow/generated-artifact-registry.js +11 -8
  99. package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
  100. package/src/scripts/workflow/git-exec.d.ts +22 -12
  101. package/src/scripts/workflow/git-exec.js +45 -29
  102. package/src/scripts/workflow/git-exec.js.map +1 -1
  103. package/src/scripts/workflow/git-findForkPoint.d.ts +6 -2
  104. package/src/scripts/workflow/git-findForkPoint.js +31 -23
  105. package/src/scripts/workflow/git-findForkPoint.js.map +1 -1
  106. package/src/scripts/workflow/git-readAiBranchName.d.ts +4 -2
  107. package/src/scripts/workflow/git-readAiBranchName.js +8 -5
  108. package/src/scripts/workflow/git-readAiBranchName.js.map +1 -1
  109. package/src/scripts/workflow/hotfix-pr-publisher.d.ts +4 -3
  110. package/src/scripts/workflow/hotfix-pr-publisher.js +7 -6
  111. package/src/scripts/workflow/hotfix-pr-publisher.js.map +1 -1
  112. package/src/scripts/workflow/landed-tree-resolver.d.ts +4 -2
  113. package/src/scripts/workflow/landed-tree-resolver.js +11 -8
  114. package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
  115. package/src/scripts/workflow/landed-worktree-reaper.d.ts +4 -2
  116. package/src/scripts/workflow/landed-worktree-reaper.js +12 -9
  117. package/src/scripts/workflow/landed-worktree-reaper.js.map +1 -1
  118. package/src/scripts/workflow/merge-end.d.ts +5 -4
  119. package/src/scripts/workflow/merge-end.js +28 -27
  120. package/src/scripts/workflow/merge-end.js.map +1 -1
  121. package/src/scripts/workflow/merge-start.d.ts +5 -1
  122. package/src/scripts/workflow/merge-start.js +56 -49
  123. package/src/scripts/workflow/merge-start.js.map +1 -1
  124. package/src/scripts/workflow/open-pr-check.d.ts +4 -2
  125. package/src/scripts/workflow/open-pr-check.js +11 -8
  126. package/src/scripts/workflow/open-pr-check.js.map +1 -1
  127. package/src/scripts/workflow/pr-comment-upserter.d.ts +5 -3
  128. package/src/scripts/workflow/pr-comment-upserter.js +15 -14
  129. package/src/scripts/workflow/pr-comment-upserter.js.map +1 -1
  130. package/src/scripts/workflow/pr-context-writer.d.ts +1 -1
  131. package/src/scripts/workflow/pr-context-writer.js +3 -3
  132. package/src/scripts/workflow/pr-context-writer.js.map +1 -1
  133. package/src/scripts/workflow/pr-merger.d.ts +8 -5
  134. package/src/scripts/workflow/pr-merger.js +32 -27
  135. package/src/scripts/workflow/pr-merger.js.map +1 -1
  136. package/src/scripts/workflow/provenance-enforcer.d.ts +4 -2
  137. package/src/scripts/workflow/provenance-enforcer.js +19 -17
  138. package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
  139. package/src/scripts/workflow/review-round-state.d.ts +7 -6
  140. package/src/scripts/workflow/review-round-state.js +33 -38
  141. package/src/scripts/workflow/review-round-state.js.map +1 -1
  142. package/src/scripts/workflow/run-update.js +1 -1
  143. package/src/scripts/workflow/run-update.js.map +1 -1
  144. package/src/scripts/workflow/squash-settings-enforcer.d.ts +6 -3
  145. package/src/scripts/workflow/squash-settings-enforcer.js +19 -14
  146. package/src/scripts/workflow/squash-settings-enforcer.js.map +1 -1
  147. package/src/scripts/wp-await-checks.js +2 -2
  148. package/src/scripts/wp-await-checks.js.map +1 -1
  149. package/src/scripts/wp-await-reviews.js +2 -2
  150. package/src/scripts/wp-await-reviews.js.map +1 -1
  151. package/src/scripts/wp-build.js +2 -2
  152. package/src/scripts/wp-build.js.map +1 -1
  153. package/src/scripts/wp-check-pr.js +2 -2
  154. package/src/scripts/wp-check-pr.js.map +1 -1
  155. package/src/scripts/wp-cleanup.js +2 -2
  156. package/src/scripts/wp-cleanup.js.map +1 -1
  157. package/src/scripts/wp-finish-push-dev.js +2 -2
  158. package/src/scripts/wp-finish-push-dev.js.map +1 -1
  159. package/src/scripts/wp-finish-update.js +2 -2
  160. package/src/scripts/wp-finish-update.js.map +1 -1
  161. package/src/scripts/wp-human-post-pr.js +2 -2
  162. package/src/scripts/wp-human-post-pr.js.map +1 -1
  163. package/src/scripts/wp-land-pr.js +2 -2
  164. package/src/scripts/wp-land-pr.js.map +1 -1
  165. package/src/scripts/wp-push-dev.js +2 -2
  166. package/src/scripts/wp-push-dev.js.map +1 -1
  167. package/src/scripts/wp-reap-worktree.js +2 -2
  168. package/src/scripts/wp-reap-worktree.js.map +1 -1
  169. package/src/scripts/wp-review-upsert-pr.js +2 -2
  170. package/src/scripts/wp-review-upsert-pr.js.map +1 -1
  171. package/src/scripts/wp-start-update.js +2 -2
  172. package/src/scripts/wp-start-update.js.map +1 -1
  173. package/src/scripts/wp-start-upsert-pr.js +2 -2
  174. package/src/scripts/wp-start-upsert-pr.js.map +1 -1
  175. package/src/scripts/wp-sync-main.js +2 -2
  176. package/src/scripts/wp-sync-main.js.map +1 -1
  177. package/src/scripts/wp-upsert-hotfix-pr.js +2 -2
  178. package/src/scripts/wp-upsert-hotfix-pr.js.map +1 -1
  179. package/src/scripts/wp-write-review-fixes.js +2 -2
  180. package/src/scripts/wp-write-review-fixes.js.map +1 -1
  181. package/src/scripts/wp-write-review.js +2 -2
  182. package/src/scripts/wp-write-review.js.map +1 -1
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GatedPrPublisher = exports.PublishedPr = 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
  const git_exec_1 = require("./git-exec");
9
9
  // Which PR the gated body landed on. Data-only.
@@ -45,20 +45,22 @@ exports.PublishedPr = PublishedPr;
45
45
  */
46
46
  let GatedPrPublisher = class GatedPrPublisher {
47
47
  gitExec;
48
- constructor(gitExec) {
48
+ processes;
49
+ constructor(gitExec, processes) {
49
50
  this.gitExec = gitExec;
51
+ this.processes = processes;
50
52
  }
51
53
  /**
52
54
  * Land `bodyFile` on the PR for `baseBranch` and push, in the gate-safe order.
53
55
  *
54
56
  * @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha
55
57
  */
56
- publish(baseBranch, title, bodyFile, retryCommand = 'pnpm wp-finish-upsert-pr') {
57
- const existing = this.findOpenPr(baseBranch);
58
+ async publish(baseBranch, title, bodyFile, retryCommand = 'pnpm wp-finish-upsert-pr') {
59
+ const existing = await this.findOpenPr(baseBranch);
58
60
  // 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.
59
61
  if (existing !== '') {
60
62
  process.stdout.write(`Updating PR #${existing} (body before push, so CI cannot read a stale token)...\n`);
61
- this.editPrOrAbort(existing, title, bodyFile, retryCommand);
63
+ await this.editPrOrAbort(existing, title, bodyFile, retryCommand);
62
64
  // Say the consequence BEFORE the push can fail: from here the PR advertises a token for the
63
65
  // local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes
64
66
  // RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.
@@ -67,37 +69,35 @@ let GatedPrPublisher = class GatedPrPublisher {
67
69
  ` until you fix the push and re-run ${retryCommand}.\n`);
68
70
  }
69
71
  // 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.
70
- this.push(baseBranch);
72
+ await this.push(baseBranch);
71
73
  // 3. Only a brand-new PR is created, and only after the push — `gh pr create` needs the remote ref.
72
74
  if (existing !== '')
73
75
  return new PublishedPr(existing, false);
74
76
  process.stdout.write('Creating PR...\n');
75
- return new PublishedPr('', !this.createPr(baseBranch, title, bodyFile));
77
+ return new PublishedPr('', !(await this.createPr(baseBranch, title, bodyFile)));
76
78
  }
77
79
  // Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would
78
80
  // push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose
79
81
  // token is still valid for the sha the remote still has. Nothing is half-done either way.
80
- editPrOrAbort(prNumber, title, bodyFile, retryCommand) {
81
- if (this.editPr(prNumber, title, bodyFile))
82
+ async editPrOrAbort(prNumber, title, bodyFile, retryCommand) {
83
+ if (await this.editPr(prNumber, title, bodyFile))
82
84
  return;
83
85
  throw new rules_config_1.CliExitError(1, `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\n` +
84
86
  ` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\n` +
85
87
  ` ${retryCommand}. The new body is in:\n ${bodyFile}`);
86
88
  }
87
- // The `gh`/push seams, protected so the spec can drive the ordering with no gh, no network, no repo.
88
89
  // The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,
89
90
  // so the create path then fails loudly rather than silently editing the wrong PR).
90
- findOpenPr(baseBranch) {
91
- const result = (0, child_process_1.spawnSync)('gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'], { encoding: 'utf8' });
92
- return result.status === 0 ? (result.stdout ?? '').trim() : '';
91
+ async findOpenPr(baseBranch) {
92
+ const result = await this.processes.run('gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number']);
93
+ return result.ok ? result.stdout.trim() : '';
93
94
  }
94
- editPr(prNumber, title, bodyFile) {
95
- return ((0, child_process_1.spawnSync)('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], {
96
- stdio: 'inherit',
97
- }).status === 0);
95
+ async editPr(prNumber, title, bodyFile) {
96
+ const result = await this.processes.passThrough('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile]);
97
+ return result.ok;
98
98
  }
99
- createPr(baseBranch, title, bodyFile) {
100
- return ((0, child_process_1.spawnSync)('gh', [
99
+ async createPr(baseBranch, title, bodyFile) {
100
+ return (await this.processes.passThrough('gh', [
101
101
  'pr',
102
102
  'create',
103
103
  '--head',
@@ -108,17 +108,18 @@ let GatedPrPublisher = class GatedPrPublisher {
108
108
  title,
109
109
  '--body-file',
110
110
  bodyFile,
111
- ], { stdio: 'inherit' }).status === 0);
111
+ ])).ok;
112
112
  }
113
113
  // Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the
114
114
  // consequence is already printed above, and swallowing it would report a PR that was never updated.
115
115
  push(baseBranch) {
116
- this.gitExec.ensurePushed(baseBranch);
116
+ return this.gitExec.ensurePushed(baseBranch);
117
117
  }
118
118
  };
119
119
  exports.GatedPrPublisher = GatedPrPublisher;
120
120
  exports.GatedPrPublisher = GatedPrPublisher = tslib_1.__decorate([
121
121
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
122
- tslib_1.__metadata("design:paramtypes", [git_exec_1.GitExec])
122
+ tslib_1.__metadata("design:paramtypes", [git_exec_1.GitExec,
123
+ tooling_common_1.NativeProcessApi])
123
124
  ], GatedPrPublisher);
124
125
  //# sourceMappingURL=gated-pr-publisher.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gated-pr-publisher.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gated-pr-publisher.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAC3D,yCAAqC;AAErC,gDAAgD;AAChD,MAAa,WAAW;IACpB,kFAAkF;IAClF,MAAM,CAAS;IACf,6FAA6F;IAC7F,YAAY,CAAU;IAEtB,YAAY,MAAc,EAAE,YAAqB;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,kCAUC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACI;IAA7B,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IAEjD;;;;OAIG;IACH,OAAO,CACH,UAAkB,EAClB,KAAa,EACb,QAAgB,EAChB,YAAY,GAAG,0BAA0B;QAEzC,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAE7C,oGAAoG;QACpG,IAAI,QAAQ,KAAK,EAAE,EAAE,CAAC;YAClB,OAAO,CA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AAE,aAAa,CAAC,EAC/E,EAAE,QAAQ,EAAE,MAAM,EAAE,CACvB,CAAC;QACF,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,CAAC;IAES,MAAM,CAAC,QAAgB,EAAE,KAAa,EAAE,QAAgB;QAC9D,OAAO,CACH,IAAA,yBAAS,EAAC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE;YACjF,KAAK,EAAE,SAAS;SACnB,CAAC,CAAC,MAAM,KAAK,CAAC,CAClB,CAAC;IACN,CAAC;IAES,QAAQ,CAAC,UAAkB,EAAE,KAAa,EAAE,QAAgB;QAClE,OAAO,CACH,IAAA,yBAAS,EACL,IAAI,EACJ;YACI,IAAI;YACJ,QAAQ;YACR,QAAQ;YACR,UAAU;YACV,QAAQ;YACR,MAAM;YACN,SAAS;YACT,KAAK;YACL,aAAa;YACb,QAAQ;SACX,EACD,EAAE,KAAK,EAAE,SAAS,EAAE,CACvB,CAAC,MAAM,KAAK,CAAC,CACjB,CAAC;IACN,CAAC;IAED,mGAAmG;IACnG,oGAAoG;IAC1F,IAAI,CAAC,UAAkB;QAC7B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;CACJ,CAAA;AA1GY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,gBAAgB,CA0G5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitExec } from './git-exec';\n\n// Which PR the gated body landed on. Data-only.\nexport class PublishedPr {\n // The PR that already existed and was edited; '' when this run had to create one.\n number: string;\n // True only on the create path, when `gh pr create` itself failed — there is no PR to merge.\n createFailed: boolean;\n\n constructor(number: string, createFailed: boolean) {\n this.number = number;\n this.createFailed = createFailed;\n }\n}\n\n/**\n * Owns the ONE ordering constraint that lets the webpieces gate be a single required check: the PR body\n * — which carries `HMAC(gateSalt, HEAD_sha)` — is written BEFORE the push.\n *\n * WHY the order matters. Pushing first fires `pull_request:synchronize`, and CI (`wp-check-pr`) reads the\n * PR body it finds at that instant. If the body edit has not landed yet, that read sees the PREVIOUS\n * run's token, which is bound to the parent sha, and the check goes red on a timing coin-flip. #485\n * papered over this by also posting a `webpieces/pr-gate` commit status, whose newest post supersedes an\n * older one — recovery rather than prevention, and it left consumers with two entries on every PR and no\n * way to tell which one to mark required.\n *\n * The sha is already known locally: nothing about minting `HMAC(gateSalt, git rev-parse HEAD)` needs the\n * remote to have the commit. So write the body first and the `synchronize` read can only ever see the\n * right token. A brand-new PR is unaffected either way — `gh pr create` composes the body after the push,\n * so the `opened` event already sees the final body.\n *\n * THIS IS THE ONLY PUSH IN THE PR FLOW. `wp-start-upsert-pr` used to push twice (its own `ensurePushed`,\n * and the force-push inside the 3-point merge finalize), which put code on the remote before summary.json\n * and the checklists had even run, and fired `synchronize` against a PR body still carrying the previous\n * run's token. Both are gone — the merge finalize now takes `MergeEndOptions.pushRemote=false` in the PR\n * flow. So the single `synchronize` of a cycle arrives strictly after the body edit below, and can only\n * ever read the correct token.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GatedPrPublisher {\n constructor(private readonly gitExec: GitExec) {}\n\n /**\n * Land `bodyFile` on the PR for `baseBranch` and push, in the gate-safe order.\n *\n * @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha\n */\n publish(\n baseBranch: string,\n title: string,\n bodyFile: string,\n retryCommand = 'pnpm wp-finish-upsert-pr',\n ): PublishedPr {\n const existing = this.findOpenPr(baseBranch);\n\n // 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.\n if (existing !== '') {\n process.stdout.write(\n `Updating PR #${existing} (body before push, so CI cannot read a stale token)...\\n`,\n );\n this.editPrOrAbort(existing, title, bodyFile, retryCommand);\n // Say the consequence BEFORE the push can fail: from here the PR advertises a token for the\n // local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes\n // RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.\n process.stdout.write(\n ' body updated. Pushing now — if this push FAILS, the PR advertises a token for a commit\\n' +\n ' the remote does not have, so the webpieces gate check goes RED (never falsely green)\\n' +\n ` until you fix the push and re-run ${retryCommand}.\\n`,\n );\n }\n\n // 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.\n this.push(baseBranch);\n\n // 3. Only a brand-new PR is created, and only after the push — `gh pr create` needs the remote ref.\n if (existing !== '') return new PublishedPr(existing, false);\n process.stdout.write('Creating PR...\\n');\n return new PublishedPr('', !this.createPr(baseBranch, title, bodyFile));\n }\n\n // Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would\n // push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose\n // token is still valid for the sha the remote still has. Nothing is half-done either way.\n private editPrOrAbort(\n prNumber: string,\n title: string,\n bodyFile: string,\n retryCommand: string,\n ): void {\n if (this.editPr(prNumber, title, bodyFile)) return;\n throw new CliExitError(\n 1,\n `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\\n` +\n ` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\\n` +\n ` ${retryCommand}. The new body is in:\\n ${bodyFile}`,\n );\n }\n\n // The `gh`/push seams, protected so the spec can drive the ordering with no gh, no network, no repo.\n\n // The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,\n // so the create path then fails loudly rather than silently editing the wrong PR).\n protected findOpenPr(baseBranch: string): string {\n const result = spawnSync(\n 'gh',\n ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n protected editPr(prNumber: string, title: string, bodyFile: string): boolean {\n return (\n spawnSync('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], {\n stdio: 'inherit',\n }).status === 0\n );\n }\n\n protected createPr(baseBranch: string, title: string, bodyFile: string): boolean {\n return (\n spawnSync(\n 'gh',\n [\n 'pr',\n 'create',\n '--head',\n baseBranch,\n '--base',\n 'main',\n '--title',\n title,\n '--body-file',\n bodyFile,\n ],\n { stdio: 'inherit' },\n ).status === 0\n );\n }\n\n // Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the\n // consequence is already printed above, and swallowing it would report a PR that was never updated.\n protected push(baseBranch: string): void {\n this.gitExec.ensurePushed(baseBranch);\n }\n}\n"]}
1
+ {"version":3,"file":"gated-pr-publisher.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gated-pr-publisher.ts"],"names":[],"mappings":";;;;AAAA,0DAAuD;AACvD,8DAA6D;AAC7D,yCAA2D;AAC3D,yCAAqC;AAErC,gDAAgD;AAChD,MAAa,WAAW;IACpB,kFAAkF;IAClF,MAAM,CAAS;IACf,6FAA6F;IAC7F,YAAY,CAAU;IAEtB,YAAY,MAAc,EAAE,YAAqB;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,kCAUC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAEJ;IACA;IAFrB,YACqB,OAAgB,EAChB,SAA2B;QAD3B,YAAO,GAAP,OAAO,CAAS;QAChB,cAAS,GAAT,SAAS,CAAkB;IAC7C,CAAC;IAEJ;;;;OAIG;IACH,KAAK,CAAC,OAAO,CAC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,CAAC,SAAS,CAAC;6CAGP,kBAAO;QACL,iCAAgB;GAHvC,gBAAgB,CAwG5B","sourcesContent":["import { CliExitError } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitExec } from './git-exec';\n\n// Which PR the gated body landed on. Data-only.\nexport class PublishedPr {\n // The PR that already existed and was edited; '' when this run had to create one.\n number: string;\n // True only on the create path, when `gh pr create` itself failed — there is no PR to merge.\n createFailed: boolean;\n\n constructor(number: string, createFailed: boolean) {\n this.number = number;\n this.createFailed = createFailed;\n }\n}\n\n/**\n * Owns the ONE ordering constraint that lets the webpieces gate be a single required check: the PR body\n * — which carries `HMAC(gateSalt, HEAD_sha)` — is written BEFORE the push.\n *\n * WHY the order matters. Pushing first fires `pull_request:synchronize`, and CI (`wp-check-pr`) reads the\n * PR body it finds at that instant. If the body edit has not landed yet, that read sees the PREVIOUS\n * run's token, which is bound to the parent sha, and the check goes red on a timing coin-flip. #485\n * papered over this by also posting a `webpieces/pr-gate` commit status, whose newest post supersedes an\n * older one — recovery rather than prevention, and it left consumers with two entries on every PR and no\n * way to tell which one to mark required.\n *\n * The sha is already known locally: nothing about minting `HMAC(gateSalt, git rev-parse HEAD)` needs the\n * remote to have the commit. So write the body first and the `synchronize` read can only ever see the\n * right token. A brand-new PR is unaffected either way — `gh pr create` composes the body after the push,\n * so the `opened` event already sees the final body.\n *\n * THIS IS THE ONLY PUSH IN THE PR FLOW. `wp-start-upsert-pr` used to push twice (its own `ensurePushed`,\n * and the force-push inside the 3-point merge finalize), which put code on the remote before summary.json\n * and the checklists had even run, and fired `synchronize` against a PR body still carrying the previous\n * run's token. Both are gone — the merge finalize now takes `MergeEndOptions.pushRemote=false` in the PR\n * flow. So the single `synchronize` of a cycle arrives strictly after the body edit below, and can only\n * ever read the correct token.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GatedPrPublisher {\n constructor(\n private readonly gitExec: GitExec,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /**\n * Land `bodyFile` on the PR for `baseBranch` and push, in the gate-safe order.\n *\n * @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha\n */\n async publish(\n baseBranch: string,\n title: string,\n bodyFile: string,\n retryCommand = 'pnpm wp-finish-upsert-pr',\n ): Promise<PublishedPr> {\n const existing = await this.findOpenPr(baseBranch);\n\n // 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.\n if (existing !== '') {\n process.stdout.write(\n `Updating PR #${existing} (body before push, so CI cannot read a stale token)...\\n`,\n );\n await this.editPrOrAbort(existing, title, bodyFile, retryCommand);\n // Say the consequence BEFORE the push can fail: from here the PR advertises a token for the\n // local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes\n // RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.\n process.stdout.write(\n ' body updated. Pushing now — if this push FAILS, the PR advertises a token for a commit\\n' +\n ' the remote does not have, so the webpieces gate check goes RED (never falsely green)\\n' +\n ` until you fix the push and re-run ${retryCommand}.\\n`,\n );\n }\n\n // 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.\n await this.push(baseBranch);\n\n // 3. Only a brand-new PR is created, and only after the push — `gh pr create` needs the remote ref.\n if (existing !== '') return new PublishedPr(existing, false);\n process.stdout.write('Creating PR...\\n');\n return new PublishedPr('', !(await this.createPr(baseBranch, title, bodyFile)));\n }\n\n // Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would\n // push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose\n // token is still valid for the sha the remote still has. Nothing is half-done either way.\n private async editPrOrAbort(\n prNumber: string,\n title: string,\n bodyFile: string,\n retryCommand: string,\n ): Promise<void> {\n if (await this.editPr(prNumber, title, bodyFile)) return;\n throw new CliExitError(\n 1,\n `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\\n` +\n ` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\\n` +\n ` ${retryCommand}. The new body is in:\\n ${bodyFile}`,\n );\n }\n\n // The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,\n // so the create path then fails loudly rather than silently editing the wrong PR).\n private async findOpenPr(baseBranch: string): Promise<string> {\n const result = await this.processes.run(\n 'gh',\n ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n );\n return result.ok ? result.stdout.trim() : '';\n }\n\n private async editPr(prNumber: string, title: string, bodyFile: string): Promise<boolean> {\n const result = await this.processes.passThrough(\n 'gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile],\n );\n return result.ok;\n }\n\n private async createPr(baseBranch: string, title: string, bodyFile: string): Promise<boolean> {\n return (\n await this.processes.passThrough(\n 'gh',\n [\n 'pr',\n 'create',\n '--head',\n baseBranch,\n '--base',\n 'main',\n '--title',\n title,\n '--body-file',\n bodyFile,\n ],\n )\n ).ok;\n }\n\n // Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the\n // consequence is already printed above, and swallowing it would report a PR that was never updated.\n protected push(baseBranch: string): Promise<void> {\n return this.gitExec.ensurePushed(baseBranch);\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { RepoScratchDirs } from '@webpieces/rules-config';
2
+ import { NativeProcessApi } from '@webpieces/tooling-common';
2
3
  /**
3
4
  * Where the "known generated" answer came from, so a failure message can say whether it is speaking
4
5
  * from the workspace's own declarations or from the built-in fallback.
@@ -41,10 +42,11 @@ export declare class GeneratedArtifacts {
41
42
  */
42
43
  export declare class GeneratedArtifactRegistry {
43
44
  private readonly scratchDirs;
45
+ private readonly processes;
44
46
  private cached;
45
- constructor(scratchDirs: RepoScratchDirs);
47
+ constructor(scratchDirs: RepoScratchDirs, processes: NativeProcessApi);
46
48
  /** The declared build outputs for this repo, from nx when readable and the fallback table otherwise. */
47
- resolve(repoRoot: string): GeneratedArtifacts;
49
+ resolve(repoRoot: string): Promise<GeneratedArtifacts>;
48
50
  /** Test seam: pre-seed the resolved set so specs never shell out to nx. */
49
51
  seed(artifacts: GeneratedArtifacts): void;
50
52
  /**
@@ -2,10 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GeneratedArtifactRegistry = exports.GeneratedArtifacts = exports.FALLBACK_GENERATED_PATHS = exports.ARTIFACT_SOURCE_FALLBACK = exports.ARTIFACT_SOURCE_NX = 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");
8
+ const tooling_common_1 = require("@webpieces/tooling-common");
9
9
  const to_error_1 = require("@webpieces/tooling-common/to-error");
10
10
  const inversify_1 = require("inversify");
11
11
  /**
@@ -62,16 +62,18 @@ exports.GeneratedArtifacts = GeneratedArtifacts;
62
62
  */
63
63
  let GeneratedArtifactRegistry = class GeneratedArtifactRegistry {
64
64
  scratchDirs;
65
+ processes;
65
66
  // Resolved once per process: the graph does not change while one PR-gate command runs.
66
67
  cached = null;
67
- constructor(scratchDirs) {
68
+ constructor(scratchDirs, processes) {
68
69
  this.scratchDirs = scratchDirs;
70
+ this.processes = processes;
69
71
  }
70
72
  /** The declared build outputs for this repo, from nx when readable and the fallback table otherwise. */
71
- resolve(repoRoot) {
73
+ async resolve(repoRoot) {
72
74
  if (this.cached !== null)
73
75
  return this.cached;
74
- const fromNx = this.readNxOutputs(repoRoot);
76
+ const fromNx = await this.readNxOutputs(repoRoot);
75
77
  this.cached = fromNx !== null
76
78
  ? new GeneratedArtifacts(fromNx, exports.ARTIFACT_SOURCE_NX)
77
79
  : new GeneratedArtifacts(exports.FALLBACK_GENERATED_PATHS.slice(), exports.ARTIFACT_SOURCE_FALLBACK);
@@ -86,13 +88,13 @@ let GeneratedArtifactRegistry = class GeneratedArtifactRegistry {
86
88
  * an empty list) when nx is unavailable or unreadable, so the caller can tell "no nx" apart from
87
89
  * "nx says this workspace declares nothing".
88
90
  */
89
- readNxOutputs(repoRoot) {
91
+ async readNxOutputs(repoRoot) {
90
92
  const nxBin = path.join(repoRoot, 'node_modules', '.bin', 'nx');
91
93
  if (!fs.existsSync(nxBin))
92
94
  return null;
93
95
  const outFile = path.join(this.scratchDirs.make(repoRoot, 'wp-nxgraph-'), 'graph.json');
94
- const run = (0, child_process_1.spawnSync)(nxBin, ['graph', '--file', outFile], { cwd: repoRoot, encoding: 'utf8', stdio: 'pipe' });
95
- if (run.status !== 0 || !fs.existsSync(outFile))
96
+ const run = await this.processes.run(nxBin, ['graph', '--file', outFile], repoRoot);
97
+ if (!run.ok || !fs.existsSync(outFile))
96
98
  return null;
97
99
  return this.parseGraph(outFile);
98
100
  }
@@ -148,6 +150,7 @@ let GeneratedArtifactRegistry = class GeneratedArtifactRegistry {
148
150
  exports.GeneratedArtifactRegistry = GeneratedArtifactRegistry;
149
151
  exports.GeneratedArtifactRegistry = GeneratedArtifactRegistry = tslib_1.__decorate([
150
152
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
151
- tslib_1.__metadata("design:paramtypes", [rules_config_1.RepoScratchDirs])
153
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.RepoScratchDirs,
154
+ tooling_common_1.NativeProcessApi])
152
155
  ], GeneratedArtifactRegistry);
153
156
  //# sourceMappingURL=generated-artifact-registry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generated-artifact-registry.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/generated-artifact-registry.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA0D;AAC1D,iEAA6D;AAC7D,yCAA2D;AAE3D;;;GAGG;AACU,QAAA,kBAAkB,GAAG,qCAAqC,CAAC;AAC3D,QAAA,wBAAwB,GAAG,kDAAkD,C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AAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;IACvE,CAAC;CACJ,CAAA;AAhFY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAKK,8BAAe;GAJhD,yBAAyB,CAgFrC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { RepoScratchDirs } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Where the \"known generated\" answer came from, so a failure message can say whether it is speaking\n * from the workspace's own declarations or from the built-in fallback.\n */\nexport const ARTIFACT_SOURCE_NX = 'nx project graph (target `outputs`)';\nexport const ARTIFACT_SOURCE_FALLBACK = 'built-in fallback (nx project graph unavailable)';\n\n/**\n * The fallback \"known generated\" set, used ONLY when the nx project graph cannot be read (nx not\n * installed, `nx graph` failed, unparseable output). It deliberately mirrors what the webpieces nx\n * plugin declares as `outputs` today — `di-graph-generate` writes design.{json,md,html} per project\n * and the architecture targets write architecture/*.\n *\n * It is a fallback and not the primary source precisely because a hand-maintained list drifts: the\n * moment a repo adds a target that writes a new committed artifact, only the nx `outputs` declaration\n * knows about it. Data (a module-level table), not a list buried inside a function.\n */\nexport const FALLBACK_GENERATED_PATHS: readonly string[] = [\n '**/design.json',\n '**/design.md',\n '**/design.html',\n 'architecture/dependencies.json',\n 'architecture/dependencies.html',\n 'architecture/apis',\n 'architecture/runtime-dependencies.json',\n];\n\n/**\n * The set of repo-relative paths/globs that a build is EXPECTED to rewrite, plus where the set came\n * from. Data-only (per CLAUDE.md) — the resolution logic lives in GeneratedArtifactRegistry.\n */\nexport class GeneratedArtifacts {\n paths: string[];\n source: string;\n\n constructor(paths: string[], source: string) {\n this.paths = paths;\n this.source = source;\n }\n}\n\n/**\n * Answers \"is this path something the build is SUPPOSED to rewrite?\" from the workspace's own nx\n * target `outputs` declarations rather than from a parallel list maintained by hand.\n *\n * Why nx `outputs`: every target that writes a checked-in artifact already has to declare it there or\n * nx caching corrupts the workspace, so the declaration is load-bearing and therefore maintained. A\n * second list in the PR gate would be maintained by nobody and would drift the first time a repo adds\n * a generator. One `nx graph --file=<tmp>` dumps the whole workspace (every project, every target,\n * every `outputs` entry) in one ~2s call, so this costs one subprocess per PR-gate run.\n *\n * Tokens: `{projectRoot}` and `{workspaceRoot}` are expanded; anything still holding a `{...}` token\n * (`{options.outputPath}`, `{options.outputFile}`) is DROPPED — it is only resolvable per-invocation,\n * and such targets write into `dist/`, which is gitignored and therefore invisible to this gate anyway.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GeneratedArtifactRegistry {\n // Resolved once per process: the graph does not change while one PR-gate command runs.\n private cached: GeneratedArtifacts | null = null;\n\n constructor(private readonly scratchDirs: RepoScratchDirs) {}\n\n /** The declared build outputs for this repo, from nx when readable and the fallback table otherwise. */\n resolve(repoRoot: string): GeneratedArtifacts {\n if (this.cached !== null) return this.cached;\n const fromNx = this.readNxOutputs(repoRoot);\n this.cached = fromNx !== null\n ? new GeneratedArtifacts(fromNx, ARTIFACT_SOURCE_NX)\n : new GeneratedArtifacts(FALLBACK_GENERATED_PATHS.slice(), ARTIFACT_SOURCE_FALLBACK);\n return this.cached;\n }\n\n /** Test seam: pre-seed the resolved set so specs never shell out to nx. */\n seed(artifacts: GeneratedArtifacts): void {\n this.cached = artifacts;\n }\n\n /**\n * Dump the nx project graph to a temp file and collect every target's `outputs`. Returns null (not\n * an empty list) when nx is unavailable or unreadable, so the caller can tell \"no nx\" apart from\n * \"nx says this workspace declares nothing\".\n */\n private readNxOutputs(repoRoot: string): string[] | null {\n const nxBin = path.join(repoRoot, 'node_modules', '.bin', 'nx');\n if (!fs.existsSync(nxBin)) return null;\n const outFile = path.join(this.scratchDirs.make(repoRoot, 'wp-nxgraph-'), 'graph.json');\n const run = spawnSync(nxBin, ['graph', '--file', outFile], { cwd: repoRoot, encoding: 'utf8', stdio: 'pipe' });\n if (run.status !== 0 || !fs.existsSync(outFile)) return null;\n return this.parseGraph(outFile);\n }\n\n /** Read + narrow the dumped graph. Null on anything unreadable, so the caller falls back. */\n private parseGraph(outFile: string): string[] | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable/corrupt graph dump must\n // fall back to the built-in table, never fail a PR flow over a cache artifact we only consult\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque nx JSON, narrowed field by field below\n const parsed = JSON.parse(fs.readFileSync(outFile, 'utf8')) as NxGraphFile;\n const nodes = parsed.graph?.nodes;\n if (nodes === undefined) return null;\n return this.collectOutputs(nodes);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable graph => fall back to the built-in table\n return null;\n }\n }\n\n /** Walk every project → every target → every `outputs` entry, expanding the nx path tokens. */\n private collectOutputs(nodes: Record<string, NxGraphNode>): string[] {\n const found = new Set<string>();\n for (const projectName of Object.keys(nodes)) {\n const data = nodes[projectName].data;\n const targets = data.targets;\n if (targets === undefined) continue;\n for (const targetName of Object.keys(targets)) {\n for (const raw of targets[targetName].outputs ?? []) {\n const expanded = this.expand(raw, data.root ?? '.');\n if (expanded !== null) found.add(expanded);\n }\n }\n }\n return Array.from(found).sort();\n }\n\n /** Expand `{projectRoot}` / `{workspaceRoot}`; drop anything still carrying an unresolved token. */\n private expand(raw: string, projectRoot: string): string | null {\n const replaced = raw\n .replace(/\\{projectRoot\\}/g, projectRoot)\n .replace(/\\{workspaceRoot\\}\\//g, '')\n .replace(/\\{workspaceRoot\\}/g, '.');\n if (replaced.includes('{')) return null;\n const normalized = replaced.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n return normalized === '' || normalized === '.' ? null : normalized;\n }\n}\n\n// Structural views of the `nx graph --file=<json>` payload. Interfaces (not classes) on purpose: these\n// describe a foreign JSON shape we narrow, never something this codebase constructs.\ninterface NxGraphFile {\n graph?: NxGraphBody;\n}\n\ninterface NxGraphBody {\n nodes?: Record<string, NxGraphNode>;\n}\n\ninterface NxGraphNode {\n data: NxProjectData;\n}\n\ninterface NxProjectData {\n root?: string;\n targets?: Record<string, NxTarget>;\n}\n\ninterface NxTarget {\n outputs?: string[];\n}\n"]}
1
+ {"version":3,"file":"generated-artifact-registry.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/generated-artifact-registry.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA0D;AAC1D,8DAA6D;AAC7D,iEAA6D;AAC7D,yCAA2D;AAE3D;;;GAGG;AACU,QAAA,kBAAkB,GAAG,qCAAqC,CAAC;AAC3D,QAAA,wBAAwB,GAAG,kDAAkD,CAAC;AAE3F;;;;;;;;;GASG;AACU,QAAA,wBAAwB,GAAsB;IACvD,gBAAgB;IAChB,cAAc;IACd,gBAAgB;IAChB,gCAAgC;IAChC,gCAAgC;IAChC,mBAAmB;IACnB,wCAAwC;CAC3C,CAAC;AAEF;;;GAGG;AACH,MAAa,kBAAkB;IAC3B,KAAK,CAAW;IAChB,MAAM,CAAS;IAEf,YAAY,KAAe,EAAE,MAAc;QACvC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,gDAQC;AAED;;;;;;;;;;;;;GAaG;AAEI,IAAM,yBAAyB,GAA/B,MAAM,yBAAyB;IAKb;IACA;IALrB,uFAAuF;IAC/E,MAAM,GAA8B,IAAI,CAAC;IAEjD,YACqB,WAA4B,EAC5B,SAA2B;QAD3B,gBAAW,GAAX,WAAW,CAAiB;QAC5B,cAAS,GAAT,SAAS,CAAkB;IAC7C,CAAC;IAEJ,wGAAwG;IACxG,KAAK,CAAC,OAAO,CAAC,QAAgB;QAC1B,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC,MAAM,CAAC;QAC7C,MAAM,MA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,CAAC;IACpC,CAAC;IAED,oGAAoG;IAC5F,MAAM,CAAC,GAAW,EAAE,WAAmB;QAC3C,MAAM,QAAQ,GAAG,GAAG;aACf,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC;aACxC,OAAO,CAAC,sBAAsB,EAAE,EAAE,CAAC;aACnC,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,CAAC;QACxC,IAAI,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QACxC,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACrE,OAAO,UAAU,KAAK,EAAE,IAAI,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;IACvE,CAAC;CACJ,CAAA;AAnFY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMH,8BAAe;QACjB,iCAAgB;GANvC,yBAAyB,CAmFrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RepoScratchDirs } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Where the \"known generated\" answer came from, so a failure message can say whether it is speaking\n * from the workspace's own declarations or from the built-in fallback.\n */\nexport const ARTIFACT_SOURCE_NX = 'nx project graph (target `outputs`)';\nexport const ARTIFACT_SOURCE_FALLBACK = 'built-in fallback (nx project graph unavailable)';\n\n/**\n * The fallback \"known generated\" set, used ONLY when the nx project graph cannot be read (nx not\n * installed, `nx graph` failed, unparseable output). It deliberately mirrors what the webpieces nx\n * plugin declares as `outputs` today — `di-graph-generate` writes design.{json,md,html} per project\n * and the architecture targets write architecture/*.\n *\n * It is a fallback and not the primary source precisely because a hand-maintained list drifts: the\n * moment a repo adds a target that writes a new committed artifact, only the nx `outputs` declaration\n * knows about it. Data (a module-level table), not a list buried inside a function.\n */\nexport const FALLBACK_GENERATED_PATHS: readonly string[] = [\n '**/design.json',\n '**/design.md',\n '**/design.html',\n 'architecture/dependencies.json',\n 'architecture/dependencies.html',\n 'architecture/apis',\n 'architecture/runtime-dependencies.json',\n];\n\n/**\n * The set of repo-relative paths/globs that a build is EXPECTED to rewrite, plus where the set came\n * from. Data-only (per CLAUDE.md) — the resolution logic lives in GeneratedArtifactRegistry.\n */\nexport class GeneratedArtifacts {\n paths: string[];\n source: string;\n\n constructor(paths: string[], source: string) {\n this.paths = paths;\n this.source = source;\n }\n}\n\n/**\n * Answers \"is this path something the build is SUPPOSED to rewrite?\" from the workspace's own nx\n * target `outputs` declarations rather than from a parallel list maintained by hand.\n *\n * Why nx `outputs`: every target that writes a checked-in artifact already has to declare it there or\n * nx caching corrupts the workspace, so the declaration is load-bearing and therefore maintained. A\n * second list in the PR gate would be maintained by nobody and would drift the first time a repo adds\n * a generator. One `nx graph --file=<tmp>` dumps the whole workspace (every project, every target,\n * every `outputs` entry) in one ~2s call, so this costs one subprocess per PR-gate run.\n *\n * Tokens: `{projectRoot}` and `{workspaceRoot}` are expanded; anything still holding a `{...}` token\n * (`{options.outputPath}`, `{options.outputFile}`) is DROPPED — it is only resolvable per-invocation,\n * and such targets write into `dist/`, which is gitignored and therefore invisible to this gate anyway.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GeneratedArtifactRegistry {\n // Resolved once per process: the graph does not change while one PR-gate command runs.\n private cached: GeneratedArtifacts | null = null;\n\n constructor(\n private readonly scratchDirs: RepoScratchDirs,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /** The declared build outputs for this repo, from nx when readable and the fallback table otherwise. */\n async resolve(repoRoot: string): Promise<GeneratedArtifacts> {\n if (this.cached !== null) return this.cached;\n const fromNx = await this.readNxOutputs(repoRoot);\n this.cached = fromNx !== null\n ? new GeneratedArtifacts(fromNx, ARTIFACT_SOURCE_NX)\n : new GeneratedArtifacts(FALLBACK_GENERATED_PATHS.slice(), ARTIFACT_SOURCE_FALLBACK);\n return this.cached;\n }\n\n /** Test seam: pre-seed the resolved set so specs never shell out to nx. */\n seed(artifacts: GeneratedArtifacts): void {\n this.cached = artifacts;\n }\n\n /**\n * Dump the nx project graph to a temp file and collect every target's `outputs`. Returns null (not\n * an empty list) when nx is unavailable or unreadable, so the caller can tell \"no nx\" apart from\n * \"nx says this workspace declares nothing\".\n */\n private async readNxOutputs(repoRoot: string): Promise<string[] | null> {\n const nxBin = path.join(repoRoot, 'node_modules', '.bin', 'nx');\n if (!fs.existsSync(nxBin)) return null;\n const outFile = path.join(this.scratchDirs.make(repoRoot, 'wp-nxgraph-'), 'graph.json');\n const run = await this.processes.run(nxBin, ['graph', '--file', outFile], repoRoot);\n if (!run.ok || !fs.existsSync(outFile)) return null;\n return this.parseGraph(outFile);\n }\n\n /** Read + narrow the dumped graph. Null on anything unreadable, so the caller falls back. */\n private parseGraph(outFile: string): string[] | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable/corrupt graph dump must\n // fall back to the built-in table, never fail a PR flow over a cache artifact we only consult\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque nx JSON, narrowed field by field below\n const parsed = JSON.parse(fs.readFileSync(outFile, 'utf8')) as NxGraphFile;\n const nodes = parsed.graph?.nodes;\n if (nodes === undefined) return null;\n return this.collectOutputs(nodes);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable graph => fall back to the built-in table\n return null;\n }\n }\n\n /** Walk every project → every target → every `outputs` entry, expanding the nx path tokens. */\n private collectOutputs(nodes: Record<string, NxGraphNode>): string[] {\n const found = new Set<string>();\n for (const projectName of Object.keys(nodes)) {\n const data = nodes[projectName].data;\n const targets = data.targets;\n if (targets === undefined) continue;\n for (const targetName of Object.keys(targets)) {\n for (const raw of targets[targetName].outputs ?? []) {\n const expanded = this.expand(raw, data.root ?? '.');\n if (expanded !== null) found.add(expanded);\n }\n }\n }\n return Array.from(found).sort();\n }\n\n /** Expand `{projectRoot}` / `{workspaceRoot}`; drop anything still carrying an unresolved token. */\n private expand(raw: string, projectRoot: string): string | null {\n const replaced = raw\n .replace(/\\{projectRoot\\}/g, projectRoot)\n .replace(/\\{workspaceRoot\\}\\//g, '')\n .replace(/\\{workspaceRoot\\}/g, '.');\n if (replaced.includes('{')) return null;\n const normalized = replaced.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n return normalized === '' || normalized === '.' ? null : normalized;\n }\n}\n\n// Structural views of the `nx graph --file=<json>` payload. Interfaces (not classes) on purpose: these\n// describe a foreign JSON shape we narrow, never something this codebase constructs.\ninterface NxGraphFile {\n graph?: NxGraphBody;\n}\n\ninterface NxGraphBody {\n nodes?: Record<string, NxGraphNode>;\n}\n\ninterface NxGraphNode {\n data: NxProjectData;\n}\n\ninterface NxProjectData {\n root?: string;\n targets?: Record<string, NxTarget>;\n}\n\ninterface NxTarget {\n outputs?: string[];\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { RepoRootFinder } from '@webpieces/rules-config';
2
+ import { GitProcessApi } from '@webpieces/tooling-common';
2
3
  import { GitStatusEntry, GitStatusParser } from './git-status';
3
4
  /**
4
5
  * The result of a git command that was allowed to fail. Data-only (per CLAUDE.md) so a caller asks
@@ -11,11 +12,16 @@ export declare class GitOutcome {
11
12
  constructor(status: number, stdout: string, stderr: string);
12
13
  get ok(): boolean;
13
14
  }
14
- /** Shared git precondition checks + push logic for the PR/merge workflow. */
15
+ /**
16
+ * Shared git precondition checks + push logic for the PR/merge workflow. Every git it runs goes through
17
+ * the injected {@link GitProcessApi} edge (#1381), so a feature test scripts git's answers instead of
18
+ * building a repository.
19
+ */
15
20
  export declare class GitExec {
16
21
  private readonly repoRootFinder;
17
22
  private readonly statusParser;
18
- constructor(repoRootFinder: RepoRootFinder, statusParser: GitStatusParser);
23
+ private readonly git;
24
+ constructor(repoRootFinder: RepoRootFinder, statusParser: GitStatusParser, git: GitProcessApi);
19
25
  /**
20
26
  * Raw `git status --porcelain` with ONLY the trailing newline(s) stripped — never `.trim()`.
21
27
  *
@@ -29,44 +35,48 @@ export declare class GitExec {
29
35
  * Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so
30
36
  * `.webpieces/` tooling artifacts never count. Empty string = fully committed.
31
37
  */
32
- porcelainStatus(cwd: string): string;
38
+ porcelainStatus(cwd: string): Promise<string>;
33
39
  /**
34
40
  * The same status, PARSED: two status columns, an unquoted path, and explicit
35
41
  * `isStaged()`/`isUnstaged()`/`isUntracked()` answers. Use this for every semantic question.
36
42
  */
37
- statusEntries(cwd: string): GitStatusEntry[];
38
- untrackedFiles(cwd: string): string;
43
+ statusEntries(cwd: string): Promise<GitStatusEntry[]>;
44
+ untrackedFiles(cwd: string): Promise<string>;
39
45
  /**
40
46
  * Precondition for every PR/merge entry point: the working tree must be fully committed. The
41
47
  * webpieces tooling deliberately does NOT `git add`/`commit` the developer's work for them. Aborts
42
48
  * with instructions if anything is uncommitted (tracked or untracked, excluding gitignored).
43
49
  */
44
- assertCleanTree(cwd: string): void;
50
+ assertCleanTree(cwd: string): Promise<void>;
45
51
  /**
46
52
  * Narrower guard for the merge-resolve commit point, where tracked resolutions are legitimately in
47
53
  * the tree but untracked files must NOT be swept into the squash commit. Lists any untracked files
48
54
  * and aborts so the AI commits or deletes them explicitly.
49
55
  */
50
- assertNoUntracked(cwd: string): void;
56
+ assertNoUntracked(cwd: string): Promise<void>;
51
57
  /**
52
58
  * Run a git command that is expected to succeed; abort the process with a clear message if it
53
59
  * fails. Used for fetch/pull/checkout/commit where silently continuing on failure would operate on
54
- * stale or wrong state.
60
+ * stale or wrong state. Its output goes straight to the terminal.
55
61
  */
56
- runGitChecked(args: string[], errMsg: string): void;
62
+ runGitChecked(args: string[], errMsg: string): Promise<void>;
63
+ /** Run git with its output on the terminal and return its exit code — for a caller that decides itself. */
64
+ passThrough(args: string[], cwd?: string): Promise<number>;
57
65
  /**
58
66
  * Push HEAD to origin/<currentBranch>. Uses --force-with-lease for an existing remote branch (the
59
67
  * 3-point squash rewrites history) and -u for a brand-new branch.
60
68
  */
61
- ensurePushed(currentBranch: string): void;
69
+ ensurePushed(currentBranch: string): Promise<void>;
62
70
  /**
63
71
  * Run a git command that MAY legitimately fail and report the outcome instead of aborting — for the
64
72
  * questions whose "no" is an answer rather than an error (does this remote ref exist? did this merge
65
73
  * conflict?). Distinct from {@link runGitChecked}, which exists for the commands where continuing on
66
74
  * failure would operate on wrong state.
67
75
  */
68
- tryGit(args: string[], cwd: string): GitOutcome;
76
+ tryGit(args: string[], cwd: string): Promise<GitOutcome>;
77
+ /** `git branch --show-current` in `cwd` — '' on a detached HEAD. Must succeed. */
78
+ currentBranch(cwd: string): Promise<string>;
69
79
  /** Read-only git query that MUST succeed, trimmed. Public sibling of the private raw form. */
70
- gitQuery(args: string[], cwd: string, failMsg: string): string;
80
+ gitQuery(args: string[], cwd: string, failMsg: string): Promise<string>;
71
81
  private rawGitQuery;
72
82
  }
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GitExec = exports.GitOutcome = 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
  const git_status_1 = require("./git-status");
9
9
  const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
@@ -28,13 +28,19 @@ class GitOutcome {
28
28
  }
29
29
  }
30
30
  exports.GitOutcome = GitOutcome;
31
- /** Shared git precondition checks + push logic for the PR/merge workflow. */
31
+ /**
32
+ * Shared git precondition checks + push logic for the PR/merge workflow. Every git it runs goes through
33
+ * the injected {@link GitProcessApi} edge (#1381), so a feature test scripts git's answers instead of
34
+ * building a repository.
35
+ */
32
36
  let GitExec = class GitExec {
33
37
  repoRootFinder;
34
38
  statusParser;
35
- constructor(repoRootFinder, statusParser) {
39
+ git;
40
+ constructor(repoRootFinder, statusParser, git) {
36
41
  this.repoRootFinder = repoRootFinder;
37
42
  this.statusParser = statusParser;
43
+ this.git = git;
38
44
  }
39
45
  /**
40
46
  * Raw `git status --porcelain` with ONLY the trailing newline(s) stripped — never `.trim()`.
@@ -49,15 +55,16 @@ let GitExec = class GitExec {
49
55
  * Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so
50
56
  * `.webpieces/` tooling artifacts never count. Empty string = fully committed.
51
57
  */
52
- porcelainStatus(cwd) {
53
- return this.rawGitQuery(['status', '--porcelain'], cwd, 'Failed to run `git status --porcelain` to check the working tree.').replace(/\n+$/, '');
58
+ async porcelainStatus(cwd) {
59
+ const raw = await this.rawGitQuery(['status', '--porcelain'], cwd, 'Failed to run `git status --porcelain` to check the working tree.');
60
+ return raw.replace(/\n+$/, '');
54
61
  }
55
62
  /**
56
63
  * The same status, PARSED: two status columns, an unquoted path, and explicit
57
64
  * `isStaged()`/`isUnstaged()`/`isUntracked()` answers. Use this for every semantic question.
58
65
  */
59
- statusEntries(cwd) {
60
- return this.statusParser.parse(this.porcelainStatus(cwd));
66
+ async statusEntries(cwd) {
67
+ return this.statusParser.parse(await this.porcelainStatus(cwd));
61
68
  }
62
69
  // Untracked files only (respects .gitignore). Empty string = none.
63
70
  untrackedFiles(cwd) {
@@ -68,8 +75,8 @@ let GitExec = class GitExec {
68
75
  * webpieces tooling deliberately does NOT `git add`/`commit` the developer's work for them. Aborts
69
76
  * with instructions if anything is uncommitted (tracked or untracked, excluding gitignored).
70
77
  */
71
- assertCleanTree(cwd) {
72
- const dirty = this.porcelainStatus(cwd);
78
+ async assertCleanTree(cwd) {
79
+ const dirty = await this.porcelainStatus(cwd);
73
80
  if (dirty === '')
74
81
  return;
75
82
  throw new rules_config_1.CliExitError(1, '\n' + SEP +
@@ -87,8 +94,8 @@ let GitExec = class GitExec {
87
94
  * the tree but untracked files must NOT be swept into the squash commit. Lists any untracked files
88
95
  * and aborts so the AI commits or deletes them explicitly.
89
96
  */
90
- assertNoUntracked(cwd) {
91
- const untracked = this.untrackedFiles(cwd);
97
+ async assertNoUntracked(cwd) {
98
+ const untracked = await this.untrackedFiles(cwd);
92
99
  if (untracked === '')
93
100
  return;
94
101
  throw new rules_config_1.CliExitError(1, '\n' + SEP +
@@ -103,25 +110,29 @@ let GitExec = class GitExec {
103
110
  /**
104
111
  * Run a git command that is expected to succeed; abort the process with a clear message if it
105
112
  * fails. Used for fetch/pull/checkout/commit where silently continuing on failure would operate on
106
- * stale or wrong state.
113
+ * stale or wrong state. Its output goes straight to the terminal.
107
114
  */
108
- runGitChecked(args, errMsg) {
109
- const result = (0, child_process_1.spawnSync)('git', args, { stdio: 'inherit' });
110
- if (result.status !== 0) {
111
- throw new rules_config_1.CliExitError(1, `❌ ${errMsg} (git ${args.join(' ')} exited ${String(result.status)})`);
115
+ async runGitChecked(args, errMsg) {
116
+ const result = await this.git.passThrough(args);
117
+ if (!result.ok) {
118
+ throw new rules_config_1.CliExitError(1, `❌ ${errMsg} (git ${args.join(' ')} exited ${String(result.code)})`);
112
119
  }
113
120
  }
121
+ /** Run git with its output on the terminal and return its exit code — for a caller that decides itself. */
122
+ async passThrough(args, cwd) {
123
+ return (await this.git.passThrough(args, cwd)).code;
124
+ }
114
125
  /**
115
126
  * Push HEAD to origin/<currentBranch>. Uses --force-with-lease for an existing remote branch (the
116
127
  * 3-point squash rewrites history) and -u for a brand-new branch.
117
128
  */
118
- ensurePushed(currentBranch) {
119
- const remoteExists = (0, child_process_1.spawnSync)('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;
129
+ async ensurePushed(currentBranch) {
130
+ const remoteExists = (await this.git.run(['ls-remote', '--exit-code', '--heads', 'origin', currentBranch])).ok;
120
131
  if (remoteExists) {
121
- this.runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');
132
+ await this.runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');
122
133
  }
123
134
  else {
124
- this.runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');
135
+ await this.runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');
125
136
  }
126
137
  }
127
138
  /**
@@ -130,18 +141,22 @@ let GitExec = class GitExec {
130
141
  * conflict?). Distinct from {@link runGitChecked}, which exists for the commands where continuing on
131
142
  * failure would operate on wrong state.
132
143
  */
133
- tryGit(args, cwd) {
134
- const out = (0, child_process_1.spawnSync)('git', args, { encoding: 'utf8', cwd });
135
- return new GitOutcome(out.status ?? 1, (out.stdout ?? '').trim(), (out.stderr ?? '').trim());
144
+ async tryGit(args, cwd) {
145
+ const out = await this.git.run(args, cwd);
146
+ return new GitOutcome(out.code, out.stdout.trim(), out.stderr.trim());
147
+ }
148
+ /** `git branch --show-current` in `cwd` — '' on a detached HEAD. Must succeed. */
149
+ currentBranch(cwd) {
150
+ return this.gitQuery(['branch', '--show-current'], cwd, 'Failed to read the current branch (git branch --show-current).');
136
151
  }
137
152
  /** Read-only git query that MUST succeed, trimmed. Public sibling of the private raw form. */
138
- gitQuery(args, cwd, failMsg) {
139
- return this.rawGitQuery(args, cwd, failMsg).trim();
153
+ async gitQuery(args, cwd, failMsg) {
154
+ return (await this.rawGitQuery(args, cwd, failMsg)).trim();
140
155
  }
141
156
  // The untrimmed sibling — see porcelainStatus for why trimming is not always safe.
142
- rawGitQuery(args, cwd, failMsg) {
143
- const out = (0, child_process_1.spawnSync)('git', args, { encoding: 'utf8', cwd });
144
- if (out.status !== 0) {
157
+ async rawGitQuery(args, cwd, failMsg) {
158
+ const out = await this.git.run(args, cwd);
159
+ if (!out.ok) {
145
160
  throw new rules_config_1.CliExitError(1, `❌ ${failMsg}`);
146
161
  }
147
162
  return out.stdout;
@@ -151,6 +166,7 @@ exports.GitExec = GitExec;
151
166
  exports.GitExec = GitExec = tslib_1.__decorate([
152
167
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
153
168
  tslib_1.__metadata("design:paramtypes", [rules_config_1.RepoRootFinder,
154
- git_status_1.GitStatusParser])
169
+ git_status_1.GitStatusParser,
170
+ tooling_common_1.GitProcessApi])
155
171
  ], GitExec);
156
172
  //# sourceMappingURL=git-exec.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"git-exec.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/git-exec.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuE;AACvE,yCAA2D;AAC3D,6CAA+D;AAE/D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AACvE,oGAAoG;AACpG,qGAAqG;AACrG,MAAM,qBAAqB,GAAG,2BAA2B,CAAC;AAE1D;;;GAGG;AACH,MAAa,UAAU;IACnB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,MAAM,CAAS;IAEf,YAAY,MAAc,EAAE,MAAc,EAAE,MAAc;QACtD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED,IAAI,EAAE;QACF,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;IAC7B,CAAC;CACJ;AAdD,gCAcC;AAED,6EAA6E;AAEtE,IAAM,OAAO,GAAb,MAAM,OAAO;IAEK;IACA;IAFrB,YACqB,cAA8B,EAC9B,YAA6B;QAD7B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,iBAAY,GAAZ,YAAY,CAAiB;IAC/C,CAAC;IAEJ;;;;;;;;;;;;OAYG;IACH,eAAe,CAAC,GAAW;QACvB,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC,QAAQ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IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACjG,CAAC;IAED,8FAA8F;IAC9F,QAAQ,CAAC,IAAc,EAAE,GAAW,EAAE,OAAe;QACjD,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;IACvD,CAAC;IAED,mFAAmF;IAC3E,WAAW,CAAC,IAAc,EAAE,GAAW,EAAE,OAAe;QAC5D,MAAM,GAAG,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAC9D,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACnB,MAAM,IAAI,2BAAY,CAAC,CAAC,EAAE,KAAK,OAAO,EAAE,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,GAAG,CAAC,MAAM,CAAC;IACtB,CAAC;CACJ,CAAA;AA/HY,0BAAO;kBAAP,OAAO;IADnB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,4BAAe;GAHzC,OAAO,CA+HnB","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError, RepoRootFinder } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitStatusEntry, GitStatusParser } from './git-status';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n// The AI-facing doc the failure messages point at (generated under `.webpieces/instruct-ai`, at the\n// REPO ROOT — resolved absolute so the AI opens it regardless of the cwd it reads the message from).\nconst GIT_WORKFLOW_DOC_NAME = 'webpieces.git-workflow.md';\n\n/**\n * The result of a git command that was allowed to fail. Data-only (per CLAUDE.md) so a caller asks\n * `outcome.ok` rather than re-deriving \"did it work\" from a status number at every site.\n */\nexport class GitOutcome {\n status: number;\n stdout: string;\n stderr: string;\n\n constructor(status: number, stdout: string, stderr: string) {\n this.status = status;\n this.stdout = stdout;\n this.stderr = stderr;\n }\n\n get ok(): boolean {\n return this.status === 0;\n }\n}\n\n/** Shared git precondition checks + push logic for the PR/merge workflow. */\n@injectable(bindingScopeValues.Singleton)\nexport class GitExec {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly statusParser: GitStatusParser,\n ) {}\n\n /**\n * Raw `git status --porcelain` with ONLY the trailing newline(s) stripped — never `.trim()`.\n *\n * There used to be a trimmed sibling here (`uncommittedFiles`) and it was a data-destroying trap:\n * porcelain column 1 is the index state and column 2 the worktree state, so an unstaged\n * modification is \" M path\"; `trim()` eats that leading space and the line then reads \"M path\",\n * i.e. STAGED — the exact inverse of the truth. It is deleted. This method is for EMPTINESS\n * (\"is the tree dirty at all?\") and for PRINTING; anything that reasons about the two columns\n * calls {@link statusEntries} and reads booleans instead of re-parsing a string.\n *\n * Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so\n * `.webpieces/` tooling artifacts never count. Empty string = fully committed.\n */\n porcelainStatus(cwd: string): string {\n return this.rawGitQuery(['status', '--porcelain'], cwd,\n 'Failed to run `git status --porcelain` to check the working tree.').replace(/\\n+$/, '');\n }\n\n /**\n * The same status, PARSED: two status columns, an unquoted path, and explicit\n * `isStaged()`/`isUnstaged()`/`isUntracked()` answers. Use this for every semantic question.\n */\n statusEntries(cwd: string): GitStatusEntry[] {\n return this.statusParser.parse(this.porcelainStatus(cwd));\n }\n\n // Untracked files only (respects .gitignore). Empty string = none.\n untrackedFiles(cwd: string): string {\n return this.gitQuery(['ls-files', '--others', '--exclude-standard'], cwd, 'Failed to list untracked files (git ls-files --others).');\n }\n\n /**\n * Precondition for every PR/merge entry point: the working tree must be fully committed. The\n * webpieces tooling deliberately does NOT `git add`/`commit` the developer's work for them. Aborts\n * with instructions if anything is uncommitted (tracked or untracked, excluding gitignored).\n */\n assertCleanTree(cwd: string): void {\n const dirty = this.porcelainStatus(cwd);\n if (dirty === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: You have uncommitted or untracked changes\\n' +\n SEP + '\\n' +\n 'The webpieces PR tooling will NOT commit your work for you. Commit your\\n' +\n 'changes, and either commit or delete any untracked files, then re-run.\\n\\n' +\n 'Working tree (git status --porcelain):\\n' +\n dirty + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Narrower guard for the merge-resolve commit point, where tracked resolutions are legitimately in\n * the tree but untracked files must NOT be swept into the squash commit. Lists any untracked files\n * and aborts so the AI commits or deletes them explicitly.\n */\n assertNoUntracked(cwd: string): void {\n const untracked = this.untrackedFiles(cwd);\n if (untracked === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: Untracked files present during merge finalize\\n' +\n SEP + '\\n' +\n 'The tooling will not sweep untracked files into the squash commit. Commit\\n' +\n 'or delete these, then re-run:\\n\\n' +\n untracked + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Run a git command that is expected to succeed; abort the process with a clear message if it\n * fails. Used for fetch/pull/checkout/commit where silently continuing on failure would operate on\n * stale or wrong state.\n */\n runGitChecked(args: string[], errMsg: string): void {\n const result = spawnSync('git', args, { stdio: 'inherit' });\n if (result.status !== 0) {\n throw new CliExitError(1, `❌ ${errMsg} (git ${args.join(' ')} exited ${String(result.status)})`);\n }\n }\n\n /**\n * Push HEAD to origin/<currentBranch>. Uses --force-with-lease for an existing remote branch (the\n * 3-point squash rewrites history) and -u for a brand-new branch.\n */\n ensurePushed(currentBranch: string): void {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n this.runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');\n } else {\n this.runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');\n }\n }\n\n /**\n * Run a git command that MAY legitimately fail and report the outcome instead of aborting — for the\n * questions whose \"no\" is an answer rather than an error (does this remote ref exist? did this merge\n * conflict?). Distinct from {@link runGitChecked}, which exists for the commands where continuing on\n * failure would operate on wrong state.\n */\n tryGit(args: string[], cwd: string): GitOutcome {\n const out = spawnSync('git', args, { encoding: 'utf8', cwd });\n return new GitOutcome(out.status ?? 1, (out.stdout ?? '').trim(), (out.stderr ?? '').trim());\n }\n\n /** Read-only git query that MUST succeed, trimmed. Public sibling of the private raw form. */\n gitQuery(args: string[], cwd: string, failMsg: string): string {\n return this.rawGitQuery(args, cwd, failMsg).trim();\n }\n\n // The untrimmed sibling — see porcelainStatus for why trimming is not always safe.\n private rawGitQuery(args: string[], cwd: string, failMsg: string): string {\n const out = spawnSync('git', args, { encoding: 'utf8', cwd });\n if (out.status !== 0) {\n throw new CliExitError(1, `❌ ${failMsg}`);\n }\n return out.stdout;\n }\n}\n"]}
1
+ {"version":3,"file":"git-exec.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/git-exec.ts"],"names":[],"mappings":";;;;AAAA,0DAAuE;AACvE,8DAA0D;AAC1D,yCAA2D;AAC3D,6CAA+D;AAE/D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AACvE,oGAAoG;AACpG,qGAAqG;AACrG,MAAM,qBAAqB,GAAG,2BAA2B,CAAC;AAE1D;;;GAGG;AACH,MAAa,UAAU;IACnB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,MAAM,CAAS;IAEf,YAAY,MAAc,EAAE,MAAc,EAAE,MAAc;QACtD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;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C,WAAW,CAAC,IAAc,EAAE,GAAW,EAAE,OAAe;QAClE,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC1C,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;YACV,MAAM,IAAI,2BAAY,CAAC,CAAC,EAAE,KAAK,OAAO,EAAE,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,GAAG,CAAC,MAAM,CAAC;IACtB,CAAC;CACJ,CAAA;AA3IY,0BAAO;kBAAP,OAAO;IADnB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,4BAAe;QACxB,8BAAa;GAJ9B,OAAO,CA2InB","sourcesContent":["import { CliExitError, RepoRootFinder } from '@webpieces/rules-config';\nimport { GitProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitStatusEntry, GitStatusParser } from './git-status';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n// The AI-facing doc the failure messages point at (generated under `.webpieces/instruct-ai`, at the\n// REPO ROOT — resolved absolute so the AI opens it regardless of the cwd it reads the message from).\nconst GIT_WORKFLOW_DOC_NAME = 'webpieces.git-workflow.md';\n\n/**\n * The result of a git command that was allowed to fail. Data-only (per CLAUDE.md) so a caller asks\n * `outcome.ok` rather than re-deriving \"did it work\" from a status number at every site.\n */\nexport class GitOutcome {\n status: number;\n stdout: string;\n stderr: string;\n\n constructor(status: number, stdout: string, stderr: string) {\n this.status = status;\n this.stdout = stdout;\n this.stderr = stderr;\n }\n\n get ok(): boolean {\n return this.status === 0;\n }\n}\n\n/**\n * Shared git precondition checks + push logic for the PR/merge workflow. Every git it runs goes through\n * the injected {@link GitProcessApi} edge (#1381), so a feature test scripts git's answers instead of\n * building a repository.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GitExec {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly statusParser: GitStatusParser,\n private readonly git: GitProcessApi,\n ) {}\n\n /**\n * Raw `git status --porcelain` with ONLY the trailing newline(s) stripped — never `.trim()`.\n *\n * There used to be a trimmed sibling here (`uncommittedFiles`) and it was a data-destroying trap:\n * porcelain column 1 is the index state and column 2 the worktree state, so an unstaged\n * modification is \" M path\"; `trim()` eats that leading space and the line then reads \"M path\",\n * i.e. STAGED — the exact inverse of the truth. It is deleted. This method is for EMPTINESS\n * (\"is the tree dirty at all?\") and for PRINTING; anything that reasons about the two columns\n * calls {@link statusEntries} and reads booleans instead of re-parsing a string.\n *\n * Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so\n * `.webpieces/` tooling artifacts never count. Empty string = fully committed.\n */\n async porcelainStatus(cwd: string): Promise<string> {\n const raw = await this.rawGitQuery(['status', '--porcelain'], cwd,\n 'Failed to run `git status --porcelain` to check the working tree.');\n return raw.replace(/\\n+$/, '');\n }\n\n /**\n * The same status, PARSED: two status columns, an unquoted path, and explicit\n * `isStaged()`/`isUnstaged()`/`isUntracked()` answers. Use this for every semantic question.\n */\n async statusEntries(cwd: string): Promise<GitStatusEntry[]> {\n return this.statusParser.parse(await this.porcelainStatus(cwd));\n }\n\n // Untracked files only (respects .gitignore). Empty string = none.\n untrackedFiles(cwd: string): Promise<string> {\n return this.gitQuery(['ls-files', '--others', '--exclude-standard'], cwd, 'Failed to list untracked files (git ls-files --others).');\n }\n\n /**\n * Precondition for every PR/merge entry point: the working tree must be fully committed. The\n * webpieces tooling deliberately does NOT `git add`/`commit` the developer's work for them. Aborts\n * with instructions if anything is uncommitted (tracked or untracked, excluding gitignored).\n */\n async assertCleanTree(cwd: string): Promise<void> {\n const dirty = await this.porcelainStatus(cwd);\n if (dirty === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: You have uncommitted or untracked changes\\n' +\n SEP + '\\n' +\n 'The webpieces PR tooling will NOT commit your work for you. Commit your\\n' +\n 'changes, and either commit or delete any untracked files, then re-run.\\n\\n' +\n 'Working tree (git status --porcelain):\\n' +\n dirty + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Narrower guard for the merge-resolve commit point, where tracked resolutions are legitimately in\n * the tree but untracked files must NOT be swept into the squash commit. Lists any untracked files\n * and aborts so the AI commits or deletes them explicitly.\n */\n async assertNoUntracked(cwd: string): Promise<void> {\n const untracked = await this.untrackedFiles(cwd);\n if (untracked === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: Untracked files present during merge finalize\\n' +\n SEP + '\\n' +\n 'The tooling will not sweep untracked files into the squash commit. Commit\\n' +\n 'or delete these, then re-run:\\n\\n' +\n untracked + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Run a git command that is expected to succeed; abort the process with a clear message if it\n * fails. Used for fetch/pull/checkout/commit where silently continuing on failure would operate on\n * stale or wrong state. Its output goes straight to the terminal.\n */\n async runGitChecked(args: string[], errMsg: string): Promise<void> {\n const result = await this.git.passThrough(args);\n if (!result.ok) {\n throw new CliExitError(1, `❌ ${errMsg} (git ${args.join(' ')} exited ${String(result.code)})`);\n }\n }\n\n /** Run git with its output on the terminal and return its exit code — for a caller that decides itself. */\n async passThrough(args: string[], cwd?: string): Promise<number> {\n return (await this.git.passThrough(args, cwd)).code;\n }\n\n /**\n * Push HEAD to origin/<currentBranch>. Uses --force-with-lease for an existing remote branch (the\n * 3-point squash rewrites history) and -u for a brand-new branch.\n */\n async ensurePushed(currentBranch: string): Promise<void> {\n const remoteExists = (await this.git.run(['ls-remote', '--exit-code', '--heads', 'origin', currentBranch])).ok;\n if (remoteExists) {\n await this.runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');\n } else {\n await this.runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');\n }\n }\n\n /**\n * Run a git command that MAY legitimately fail and report the outcome instead of aborting — for the\n * questions whose \"no\" is an answer rather than an error (does this remote ref exist? did this merge\n * conflict?). Distinct from {@link runGitChecked}, which exists for the commands where continuing on\n * failure would operate on wrong state.\n */\n async tryGit(args: string[], cwd: string): Promise<GitOutcome> {\n const out = await this.git.run(args, cwd);\n return new GitOutcome(out.code, out.stdout.trim(), out.stderr.trim());\n }\n\n /** `git branch --show-current` in `cwd` — '' on a detached HEAD. Must succeed. */\n currentBranch(cwd: string): Promise<string> {\n return this.gitQuery(['branch', '--show-current'], cwd, 'Failed to read the current branch (git branch --show-current).');\n }\n\n /** Read-only git query that MUST succeed, trimmed. Public sibling of the private raw form. */\n async gitQuery(args: string[], cwd: string, failMsg: string): Promise<string> {\n return (await this.rawGitQuery(args, cwd, failMsg)).trim();\n }\n\n // The untrimmed sibling — see porcelainStatus for why trimming is not always safe.\n private async rawGitQuery(args: string[], cwd: string, failMsg: string): Promise<string> {\n const out = await this.git.run(args, cwd);\n if (!out.ok) {\n throw new CliExitError(1, `❌ ${failMsg}`);\n }\n return out.stdout;\n }\n}\n"]}