@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
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MergeStart = exports.MergeStartResult = exports.MergeContext = 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 tooling_common_1 = require("@webpieces/tooling-common");
@@ -62,19 +61,23 @@ let MergeStart = class MergeStart {
62
61
  branchNaming;
63
62
  gitExec;
64
63
  mergeState;
65
- constructor(gatherInfo, branchNaming, gitExec, mergeState) {
64
+ git;
65
+ processes;
66
+ constructor(gatherInfo, branchNaming, gitExec, mergeState, git, processes) {
66
67
  this.gatherInfo = gatherInfo;
67
68
  this.branchNaming = branchNaming;
68
69
  this.gitExec = gitExec;
69
70
  this.mergeState = mergeState;
71
+ this.git = git;
72
+ this.processes = processes;
70
73
  }
71
74
  async mergeStart(repoRoot, verb, home, finishCommand) {
72
- const currentBranch = (0, child_process_1.execSync)('git branch --show-current', { encoding: 'utf8' }).trim();
75
+ const currentBranch = await this.gitExec.currentBranch(process.cwd());
73
76
  if (currentBranch.endsWith('Squash')) {
74
77
  throw new rules_config_1.CliExitError(1, `❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}`);
75
78
  }
76
79
  // One number `n` for this sync drives BOTH the backup branch and its `merge-<n>/` context dir.
77
- const slot = this.chooseSyncSlot(home, currentBranch);
80
+ const slot = await this.chooseSyncSlot(home, currentBranch);
78
81
  const backupBranch = slot.backupBranch;
79
82
  const mergeDir = slot.runDir;
80
83
  process.stdout.write('\n' + SEP + '🔄 Squash-Merge Update from Main\n' + SEP + '\n');
@@ -83,39 +86,39 @@ let MergeStart = class MergeStart {
83
86
  if (info.alreadyUpToDate) {
84
87
  process.stdout.write('ℹ️ Branch already even with main; nothing to merge, continuing to push/build.\n');
85
88
  }
86
- const prNumber = this.detectPr(this.branchNaming.baseBranchName(currentBranch));
89
+ const prNumber = await this.detectPr(this.branchNaming.baseBranchName(currentBranch));
87
90
  process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\n` : 'No existing PR (one can be created later).\n');
88
- this.createBackup(currentBranch, backupBranch);
91
+ await this.createBackup(currentBranch, backupBranch);
89
92
  // Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash` — every intermediate
90
93
  // state, not just the last one. It is what lets the `<feature>PreMerge<n>` snapshot BRANCH be
91
94
  // disposable (branches count toward the branch cap; a written-down hash does not), and it is the
92
95
  // ref the archive tag is cut from when the PR lands.
93
- this.mergeState.writePreMergeHash(home, slot.n, this.fullSha(currentBranch));
96
+ this.mergeState.writePreMergeHash(home, slot.n, await this.fullSha(currentBranch));
94
97
  const backupEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'BACKUP');
95
98
  backupEvent.fromBranch = currentBranch;
96
99
  backupEvent.toBranch = backupBranch;
97
100
  (0, repo_workflow_core_1.logBranchMutation)(repoRoot, backupEvent);
98
101
  const squashBranch = `${currentBranch}Squash`;
99
- if ((0, child_process_1.spawnSync)('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {
102
+ if (await this.branchExists(squashBranch)) {
100
103
  throw new rules_config_1.CliExitError(1, `❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}`);
101
104
  }
102
105
  // Branch the squash off origin/main directly — worktree-native. origin/main was already fetched
103
106
  // in gatherInfo(), and A/B/C are computed purely from origin/main, so the merge base is identical
104
107
  // to the old checkout-main + pull path.
105
- const originMainSha = this.shortSha('origin/main');
106
- this.gitExec.runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');
108
+ const originMainSha = await this.shortSha('origin/main');
109
+ await this.gitExec.runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');
107
110
  const baseEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'PULL');
108
111
  baseEvent.newMain = originMainSha;
109
112
  (0, repo_workflow_core_1.logBranchMutation)(repoRoot, baseEvent);
110
113
  process.stdout.write('\n' + SEP + `🔀 Squash merging ${currentBranch}\n` + SEP + '\n');
111
- const merge = (0, child_process_1.spawnSync)('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });
112
- if (merge.status !== 0) {
113
- this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);
114
- this.logConflict(repoRoot, verb, mergeDir);
114
+ const merge = await this.git.passThrough(['merge', '--squash', currentBranch]);
115
+ if (!merge.ok) {
116
+ await this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);
117
+ await this.logConflict(repoRoot, verb, mergeDir);
115
118
  return new MergeStartResult('conflict', null, mergeDir);
116
119
  }
117
120
  (0, repo_workflow_core_1.logBranchMutation)(repoRoot, new repo_workflow_core_1.BranchMutationEvent(verb, 'SQUASH'));
118
- const nothingStaged = (0, child_process_1.spawnSync)('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;
121
+ const nothingStaged = (await this.git.run(['diff-index', '--quiet', '--cached', 'HEAD', '--'])).ok;
119
122
  if (nothingStaged) {
120
123
  process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\n');
121
124
  }
@@ -123,7 +126,7 @@ let MergeStart = class MergeStart {
123
126
  // Internal, transient subject for the single squash commit on the feature branch. It NO LONGER
124
127
  // reaches main's history: finish-upsert-pr squash-merges the PR with an explicit
125
128
  // `gh pr merge --subject <PR title> --body-file <commit summary>`, so main carries the PR title.
126
- this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');
129
+ await this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');
127
130
  // Clean merge ⇒ hashes only, no conflicts.md. Its ABSENCE is what marks this merge clean.
128
131
  this.mergeState.recordCleanMerge(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);
129
132
  }
@@ -131,40 +134,42 @@ let MergeStart = class MergeStart {
131
134
  }
132
135
  // Detect the PR by its STABLE feature branch (a leftover `…wpN` still resolves to the one name the
133
136
  // PR lives on).
134
- detectPr(baseBranch) {
135
- const result = (0, child_process_1.spawnSync)('gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'], { encoding: 'utf8' });
136
- return result.status === 0 ? (result.stdout ?? '').trim() : '';
137
+ async detectPr(baseBranch) {
138
+ const result = await this.processes.run('gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number']);
139
+ return result.ok ? result.stdout.trim() : '';
137
140
  }
138
141
  // Pick this sync's slot number MONOTONICALLY from the durable audit dirs, then step past any
139
142
  // existing `<branch>PreMerge<n>` branch so the same `n` is free for the paired backup branch.
140
- chooseSyncSlot(home, currentBranch) {
141
- const branchExists = (name) => (0, child_process_1.spawnSync)('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;
143
+ async chooseSyncSlot(home, currentBranch) {
142
144
  let n = this.mergeState.nextMergeSlotNumber(home);
143
- while (branchExists(this.branchNaming.preMergeBackupName(currentBranch, n)))
145
+ while (await this.branchExists(this.branchNaming.preMergeBackupName(currentBranch, n)))
144
146
  n += 1;
145
147
  return new SyncSlot(this.branchNaming.preMergeBackupName(currentBranch, n), this.mergeState.mergeRunDirFor(home, n), n);
146
148
  }
147
149
  // Snapshot the pre-merge state onto the caller-chosen `backupBranch`, never overwriting.
148
- createBackup(currentBranch, backupBranch) {
150
+ async branchExists(name) {
151
+ return (await this.git.run(['show-ref', '--verify', '--quiet', `refs/heads/${name}`])).ok;
152
+ }
153
+ async createBackup(currentBranch, backupBranch) {
149
154
  process.stdout.write('\n' + SEP + '💾 Creating Pre-Merge Backup\n' + SEP + '\n');
150
- this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');
151
- this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');
155
+ await this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');
156
+ await this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');
152
157
  process.stdout.write(`✅ Backup created: ${backupBranch}\n\n`);
153
158
  }
154
- saveConflictContext(conflictedFiles, mergeDir, forkPoint, featureHead, mainHead) {
159
+ async saveConflictContext(conflictedFiles, mergeDir, forkPoint, featureHead, mainHead) {
155
160
  for (const file of conflictedFiles) {
156
161
  const fileDir = this.mergeState.perFileContextDir(mergeDir, file);
157
162
  fs.mkdirSync(fileDir, { recursive: true });
158
- const fork = (0, child_process_1.spawnSync)('git', ['show', `${forkPoint}:${file}`], { encoding: 'utf8' });
159
- fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.status === 0 ? (fork.stdout ?? '') : '(file did not exist)\n');
160
- const feature = (0, child_process_1.spawnSync)('git', ['show', `${featureHead}:${file}`], { encoding: 'utf8' });
161
- fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.status === 0 ? (feature.stdout ?? '') : '(file did not exist)\n');
162
- const main = (0, child_process_1.spawnSync)('git', ['show', `${mainHead}:${file}`], { encoding: 'utf8' });
163
- fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.status === 0 ? (main.stdout ?? '') : '(file did not exist)\n');
164
- const ba = (0, child_process_1.spawnSync)('git', ['diff', forkPoint, featureHead, '--', file], { encoding: 'utf8' });
165
- fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout ?? '');
166
- const ca = (0, child_process_1.spawnSync)('git', ['diff', forkPoint, mainHead, '--', file], { encoding: 'utf8' });
167
- fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout ?? '');
163
+ const fork = await this.git.run(['show', `${forkPoint}:${file}`]);
164
+ fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.ok ? fork.stdout : '(file did not exist)\n');
165
+ const feature = await this.git.run(['show', `${featureHead}:${file}`]);
166
+ fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.ok ? feature.stdout : '(file did not exist)\n');
167
+ const main = await this.git.run(['show', `${mainHead}:${file}`]);
168
+ fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.ok ? main.stdout : '(file did not exist)\n');
169
+ const ba = await this.git.run(['diff', forkPoint, featureHead, '--', file]);
170
+ fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout);
171
+ const ca = await this.git.run(['diff', forkPoint, mainHead, '--', file]);
172
+ fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout);
168
173
  }
169
174
  }
170
175
  // The LIVE rendering of the same template `.webpieces/instruct-ai/webpieces.mergeprocess.md` is
@@ -202,8 +207,8 @@ let MergeStart = class MergeStart {
202
207
  process.stdout.write('\n' + SEP);
203
208
  }
204
209
  // Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit.
205
- handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand) {
206
- const raw = (0, child_process_1.execSync)('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();
210
+ async handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand) {
211
+ const raw = await this.gitExec.gitQuery(['diff', '--name-only', '--diff-filter=U'], process.cwd(), 'Failed to list conflicted files (git diff --diff-filter=U).');
207
212
  const conflictedFiles = raw.split('\n').filter((f) => f.trim() !== '');
208
213
  fs.mkdirSync(mergeDir, { recursive: true });
209
214
  // `conflicts.md` replaces the old `updatemain-conflicted-files.txt` (which nothing read) AND is
@@ -211,28 +216,28 @@ let MergeStart = class MergeStart {
211
216
  // which is what lets the index classify each merge without a per-branch directory-name scheme.
212
217
  this.mergeState.writeConflicts(mergeDir, conflictedFiles);
213
218
  fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\n');
214
- this.saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);
219
+ await this.saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);
215
220
  const marker = new merge_state_1.MergeMarker(currentBranch, squashBranch, backupBranch, prNumber, conflictedFiles, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead, false);
216
221
  this.mergeState.writeMergeMarker(mergeDir, marker);
217
222
  const docPath = this.writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles, finishCommand);
218
223
  this.printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);
219
224
  }
220
225
  // Short sha of a ref (best-effort — '' if it can't resolve).
221
- shortSha(ref) {
222
- const result = (0, child_process_1.spawnSync)('git', ['rev-parse', '--short', ref], { encoding: 'utf8' });
223
- return result.status === 0 ? (result.stdout ?? '').trim() : '';
226
+ async shortSha(ref) {
227
+ const result = await this.git.run(['rev-parse', '--short', ref]);
228
+ return result.ok ? result.stdout.trim() : '';
224
229
  }
225
230
  // FULL sha of a ref (best-effort — '' if it can't resolve). Recorded for the pre-merge tips because
226
231
  // those hashes are meant to be used later to restore state, and an abbreviated sha can go ambiguous
227
232
  // as the repo grows.
228
- fullSha(ref) {
229
- const result = (0, child_process_1.spawnSync)('git', ['rev-parse', ref], { encoding: 'utf8' });
230
- return result.status === 0 ? (result.stdout ?? '').trim() : '';
233
+ async fullSha(ref) {
234
+ const result = await this.git.run(['rev-parse', ref]);
235
+ return result.ok ? result.stdout.trim() : '';
231
236
  }
232
237
  // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.
233
- logConflict(repoRoot, verb, mergeDir) {
234
- const raw = (0, child_process_1.spawnSync)('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: repoRoot, encoding: 'utf8' });
235
- const files = (raw.status === 0 ? (raw.stdout ?? '') : '').split('\n').map((f) => f.trim()).filter((f) => f !== '');
238
+ async logConflict(repoRoot, verb, mergeDir) {
239
+ const raw = await this.git.run(['diff', '--name-only', '--diff-filter=U'], repoRoot);
240
+ const files = (raw.ok ? raw.stdout : '').split('\n').map((f) => f.trim()).filter((f) => f !== '');
236
241
  const event = new repo_workflow_core_1.BranchMutationEvent(verb, 'CONFLICT');
237
242
  event.conflict = true;
238
243
  event.conflictFiles = files;
@@ -249,6 +254,8 @@ exports.MergeStart = MergeStart = tslib_1.__decorate([
249
254
  tslib_1.__metadata("design:paramtypes", [git_gatherInfo_1.GatherInfo,
250
255
  branch_naming_1.BranchNaming,
251
256
  git_exec_1.GitExec,
252
- merge_state_1.MergeState])
257
+ merge_state_1.MergeState,
258
+ tooling_common_1.GitProcessApi,
259
+ tooling_common_1.NativeProcessApi])
253
260
  ], MergeStart);
254
261
  //# sourceMappingURL=merge-start.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAyD;AACzD,0DAAsI;AACtI,sEAAqG;AACrG,yCAA2D;AAC3D,sDAA+C;AAC/C,mDAA+C;AAC/C,yCAAqC;AACrC,+CAAwD;AAExD,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAQvE,mGAAmG;AACnG,MAAa,YAAY;IACrB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,YAAY,CAAS;IACrB,QAAQ,CAAS;IAEjB,YAAY,aAAqB,EAAE,YAAoB,EAAE,YAAoB,EAAE,QAAgB;QAC3F,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAA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AC,SAAS,GAAG;YACd,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,mBAAmB,CAAC;YACxC,6BAAY,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,EAAE,gCAAiB,CAAC;SACrE,CAAC;QACF,IAAA,sCAAiB,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAzNY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,2BAAU;QACR,4BAAY;QACjB,kBAAO;QACJ,wBAAU;GALlC,UAAU,CAyNtB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { CliExitError, SyncFlowGuidance, MERGE_PROCESS_DOC, MergeProcessText, MergeRun, loadTemplate } from '@webpieces/rules-config';\nimport { MutationVerb, BranchMutationEvent, logBranchMutation } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GatherInfo } from '../git-gatherInfo';\nimport { BranchNaming } from './branch-naming';\nimport { GitExec } from './git-exec';\nimport { MergeState, MergeMarker } from './merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\n// The four branch names merge-END needs to finalize a merge (swap squash→feature, push, clean up).\nexport class MergeContext {\n currentBranch: string;\n squashBranch: string;\n backupBranch: string;\n prNumber: string;\n\n constructor(currentBranch: string, squashBranch: string, backupBranch: string, prNumber: string) {\n this.currentBranch = currentBranch;\n this.squashBranch = squashBranch;\n this.backupBranch = backupBranch;\n this.prNumber = prNumber;\n }\n}\n\n// Outcome of merge-start: 'clean' carries the context for merge-END to finalize; 'conflict' means the\n// marker + context files were written and the caller should hand back to the AI (exit 2).\nexport class MergeStartResult {\n status: 'clean' | 'conflict';\n context: MergeContext | null;\n runDir: string; // this sync's numbered `merge-<n>/` dir — passed to merge-END so it reads THIS marker\n\n constructor(status: 'clean' | 'conflict', context: MergeContext | null, runDir: string) {\n this.status = status;\n this.context = context;\n this.runDir = runDir;\n }\n}\n\n// The one number `n` for a sync and the things it names: the pre-merge backup branch, its paired\n// conflict-context run dir, and (via `n`) the `preMerge<n>.hash` record of the tip it snapshotted.\nclass SyncSlot {\n backupBranch: string;\n runDir: string;\n n: number;\n\n constructor(backupBranch: string, runDir: string, n: number) {\n this.backupBranch = backupBranch;\n this.runDir = runDir;\n this.n = n;\n }\n}\n\n\n// merge-START: the first half of the 3-point squash-merge lifecycle. Brings origin/main into a fresh\n// `<branch>Squash`, and on conflict writes the 3-point context + unvalidated marker + process doc,\n// then hands control back to the AI. On a clean merge it commits the squash and returns the branch\n// context so the caller (RunUpdate) can run merge-END to finalize. NEVER finalizes or posts a PR.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeStart {\n constructor(\n private readonly gatherInfo: GatherInfo,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n ) {}\n\n async mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult> {\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n if (currentBranch.endsWith('Squash')) {\n throw new CliExitError(1, `❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}`);\n }\n\n // One number `n` for this sync drives BOTH the backup branch and its `merge-<n>/` context dir.\n const slot = this.chooseSyncSlot(home, currentBranch);\n const backupBranch = slot.backupBranch;\n const mergeDir = slot.runDir;\n\n process.stdout.write('\\n' + SEP + '🔄 Squash-Merge Update from Main\\n' + SEP + '\\n');\n const info = await this.gatherInfo.gatherInfo();\n const hashes = info.hashes;\n if (info.alreadyUpToDate) {\n process.stdout.write('ℹ️ Branch already even with main; nothing to merge, continuing to push/build.\\n');\n }\n\n const prNumber = this.detectPr(this.branchNaming.baseBranchName(currentBranch));\n process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\\n` : 'No existing PR (one can be created later).\\n');\n\n this.createBackup(currentBranch, backupBranch);\n // Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash` — every intermediate\n // state, not just the last one. It is what lets the `<feature>PreMerge<n>` snapshot BRANCH be\n // disposable (branches count toward the branch cap; a written-down hash does not), and it is the\n // ref the archive tag is cut from when the PR lands.\n this.mergeState.writePreMergeHash(home, slot.n, this.fullSha(currentBranch));\n const backupEvent = new BranchMutationEvent(verb, 'BACKUP');\n backupEvent.fromBranch = currentBranch;\n backupEvent.toBranch = backupBranch;\n logBranchMutation(repoRoot, backupEvent);\n\n const squashBranch = `${currentBranch}Squash`;\n if (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {\n throw new CliExitError(1, `❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}`);\n }\n\n // Branch the squash off origin/main directly — worktree-native. origin/main was already fetched\n // in gatherInfo(), and A/B/C are computed purely from origin/main, so the merge base is identical\n // to the old checkout-main + pull path.\n const originMainSha = this.shortSha('origin/main');\n this.gitExec.runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');\n const baseEvent = new BranchMutationEvent(verb, 'PULL');\n baseEvent.newMain = originMainSha;\n logBranchMutation(repoRoot, baseEvent);\n\n process.stdout.write('\\n' + SEP + `🔀 Squash merging ${currentBranch}\\n` + SEP + '\\n');\n const merge = spawnSync('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });\n if (merge.status !== 0) {\n this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);\n this.logConflict(repoRoot, verb, mergeDir);\n return new MergeStartResult('conflict', null, mergeDir);\n }\n logBranchMutation(repoRoot, new BranchMutationEvent(verb, 'SQUASH'));\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (nothingStaged) {\n process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\\n');\n } else {\n // Internal, transient subject for the single squash commit on the feature branch. It NO LONGER\n // reaches main's history: finish-upsert-pr squash-merges the PR with an explicit\n // `gh pr merge --subject <PR title> --body-file <commit summary>`, so main carries the PR title.\n this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');\n // Clean merge ⇒ hashes only, no conflicts.md. Its ABSENCE is what marks this merge clean.\n this.mergeState.recordCleanMerge(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n }\n return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);\n }\n\n // Detect the PR by its STABLE feature branch (a leftover `…wpN` still resolves to the one name the\n // PR lives on).\n private detectPr(baseBranch: string): string {\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Pick this sync's slot number MONOTONICALLY from the durable audit dirs, then step past any\n // existing `<branch>PreMerge<n>` branch so the same `n` is free for the paired backup branch.\n private chooseSyncSlot(home: string, currentBranch: string): SyncSlot {\n const branchExists = (name: string): boolean =>\n spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;\n let n = this.mergeState.nextMergeSlotNumber(home);\n while (branchExists(this.branchNaming.preMergeBackupName(currentBranch, n))) n += 1;\n return new SyncSlot(this.branchNaming.preMergeBackupName(currentBranch, n), this.mergeState.mergeRunDirFor(home, n), n);\n }\n\n // Snapshot the pre-merge state onto the caller-chosen `backupBranch`, never overwriting.\n private createBackup(currentBranch: string, backupBranch: string): void {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\n');\n this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n }\n\n private saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n ): void {\n for (const file of conflictedFiles) {\n const fileDir = this.mergeState.perFileContextDir(mergeDir, file);\n fs.mkdirSync(fileDir, { recursive: true });\n\n const fork = spawnSync('git', ['show', `${forkPoint}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.status === 0 ? (fork.stdout ?? '') : '(file did not exist)\\n');\n const feature = spawnSync('git', ['show', `${featureHead}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.status === 0 ? (feature.stdout ?? '') : '(file did not exist)\\n');\n const main = spawnSync('git', ['show', `${mainHead}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.status === 0 ? (main.stdout ?? '') : '(file did not exist)\\n');\n\n const ba = spawnSync('git', ['diff', forkPoint, featureHead, '--', file], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout ?? '');\n const ca = spawnSync('git', ['diff', forkPoint, mainHead, '--', file], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout ?? '');\n }\n }\n\n // The LIVE rendering of the same template `.webpieces/instruct-ai/webpieces.mergeprocess.md` is\n // delivered from — see rules-config/src/merge-process-doc.ts. The text lives there, not here, so\n // the copy every repo receives and the copy a conflicted merge stamps are the same document.\n private mergeProcessDoc(mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const fileList = conflictedFiles.map((f: string): string => `- \\`${f}\\``).join('\\n');\n const run = new MergeRun(\n new SyncFlowGuidance().pairedStart(finishCommand), finishCommand, squashBranch, mergeDir, fileList,\n );\n return new MergeProcessText(loadTemplate(MERGE_PROCESS_DOC)).render(run);\n }\n\n // Returns the absolute path of the written doc.\n private writeMergeProcessDoc(repoRoot: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const docDir = dotWebpieces.localFile(repoRoot, 'instruct-ai');\n fs.mkdirSync(docDir, { recursive: true });\n const docPath = path.join(docDir, MERGE_PROCESS_DOC);\n fs.writeFileSync(docPath, this.mergeProcessDoc(mergeDir, squashBranch, conflictedFiles, finishCommand));\n return docPath;\n }\n\n // The AI-facing \"what just happened / what to do next\" recap on the conflict path.\n private printConflictHandback(\n docPath: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string,\n ): void {\n process.stdout.write('\\n' + SEP + `⚠️ Conflicts in ${conflictedFiles.length} file(s) — handing control back to you\\n` + SEP + '\\n');\n process.stdout.write('Here is exactly what I did and what you need to do:\\n\\n');\n process.stdout.write('What I did:\\n');\n process.stdout.write(' 1. snapshotted your pre-merge state to a PreMerge branch\\n');\n process.stdout.write(' 2. pulled origin/main and squash-merged your work onto it\\n');\n process.stdout.write(` 3. hit conflicts — you are now on the transient branch ${squashBranch}\\n\\n`);\n process.stdout.write('What you need to do:\\n');\n process.stdout.write(` 1. read the merge process doc: ${docPath}\\n`);\n process.stdout.write(` 2. resolve each conflicted file below (its 3-point A/B/C context + diffs are in\\n`);\n process.stdout.write(` ${mergeDir}/updatemain-<file>/), \\`git add\\` it, and write that file's merge-explanation.md\\n`);\n process.stdout.write(` 3. run pnpm ${finishCommand} — it validates, commits, and finalizes (do NOT git commit/push yourself)\\n\\n`);\n process.stdout.write('Conflicted files:\\n');\n for (const file of conflictedFiles) process.stdout.write(` - ${file}\\n`);\n process.stdout.write('\\n' + SEP);\n }\n\n // Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit.\n private handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints, finishCommand: string,\n ): void {\n const raw = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n const conflictedFiles = raw.split('\\n').filter((f: string): boolean => f.trim() !== '');\n fs.mkdirSync(mergeDir, { recursive: true });\n // `conflicts.md` replaces the old `updatemain-conflicted-files.txt` (which nothing read) AND is\n // the 3-point signal itself: this file exists in a run dir if and only if that merge conflicted,\n // which is what lets the index classify each merge without a per-branch directory-name scheme.\n this.mergeState.writeConflicts(mergeDir, conflictedFiles);\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\\n');\n this.saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n\n const marker = new MergeMarker(\n currentBranch, squashBranch, backupBranch, prNumber, conflictedFiles,\n hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead, false,\n );\n this.mergeState.writeMergeMarker(mergeDir, marker);\n const docPath = this.writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles, finishCommand);\n this.printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);\n }\n\n // Short sha of a ref (best-effort — '' if it can't resolve).\n private shortSha(ref: string): string {\n const result = spawnSync('git', ['rev-parse', '--short', ref], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // FULL sha of a ref (best-effort — '' if it can't resolve). Recorded for the pre-merge tips because\n // those hashes are meant to be used later to restore state, and an abbreviated sha can go ambiguous\n // as the repo grows.\n private fullSha(ref: string): string {\n const result = spawnSync('git', ['rev-parse', ref], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.\n private logConflict(repoRoot: string, verb: MutationVerb, mergeDir: string): void {\n const raw = spawnSync('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: repoRoot, encoding: 'utf8' });\n const files = (raw.status === 0 ? (raw.stdout ?? '') : '').split('\\n').map((f: string): string => f.trim()).filter((f: string): boolean => f !== '');\n const event = new BranchMutationEvent(verb, 'CONFLICT');\n event.conflict = true;\n event.conflictFiles = files;\n event.artifacts = [\n path.join(mergeDir, 'updatemain-<file>'),\n dotWebpieces.localFile(repoRoot, 'instruct-ai', MERGE_PROCESS_DOC),\n ];\n logBranchMutation(repoRoot, event);\n }\n}\n"]}
1
+ {"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAA0F;AAC1F,0DAAsI;AACtI,sEAAqG;AACrG,yCAA2D;AAC3D,sDAA+C;AAC/C,mDAA+C;AAC/C,yCAAqC;AACrC,+CAAwD;AAExD,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAQvE,mGAAmG;AACnG,MAAa,YAAY;IACrB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,YAAY,CAAS;IACrB,QAAQ,CAAS;IAEjB,YAAY,aAAqB,EAAE,YAAoB,EAAE,YAAoB,EAAE,QAAgB;QAC3F,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAZD,oCAYC;AAED,sGAAsG;AACtG,0FAA0F;AAC1F,MAAa,gBAAgB;IACzB,MAAM,CAAuB;IAC7B,OAAO,CAAsB;IAC7B,MAAM,CAAS,CAAC,sFAAsF;IAEtG,YAAY,MAA4B,EAAE,OAA4B,EAAE,MAAc;QAClF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;A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,QAAQ,CAAC,CAAC;QACrF,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAS,EAAU,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;QACnI,MAAM,KAAK,GAAG,IAAI,wCAAmB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACxD,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;QACtB,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC;QAC5B,KAAK,CAAC,SAAS,GAAG;YACd,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,mBAAmB,CAAC;YACxC,6BAAY,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,EAAE,gCAAiB,CAAC;SACrE,CAAC;QACF,IAAA,sCAAiB,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AA5NY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,2BAAU;QACR,4BAAY;QACjB,kBAAO;QACJ,wBAAU;QACjB,8BAAa;QACP,iCAAgB;GAPvC,UAAU,CA4NtB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces, GitProcessApi, NativeProcessApi } from '@webpieces/tooling-common';\nimport { CliExitError, SyncFlowGuidance, MERGE_PROCESS_DOC, MergeProcessText, MergeRun, loadTemplate } from '@webpieces/rules-config';\nimport { MutationVerb, BranchMutationEvent, logBranchMutation } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GatherInfo } from '../git-gatherInfo';\nimport { BranchNaming } from './branch-naming';\nimport { GitExec } from './git-exec';\nimport { MergeState, MergeMarker } from './merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\n// The four branch names merge-END needs to finalize a merge (swap squash→feature, push, clean up).\nexport class MergeContext {\n currentBranch: string;\n squashBranch: string;\n backupBranch: string;\n prNumber: string;\n\n constructor(currentBranch: string, squashBranch: string, backupBranch: string, prNumber: string) {\n this.currentBranch = currentBranch;\n this.squashBranch = squashBranch;\n this.backupBranch = backupBranch;\n this.prNumber = prNumber;\n }\n}\n\n// Outcome of merge-start: 'clean' carries the context for merge-END to finalize; 'conflict' means the\n// marker + context files were written and the caller should hand back to the AI (exit 2).\nexport class MergeStartResult {\n status: 'clean' | 'conflict';\n context: MergeContext | null;\n runDir: string; // this sync's numbered `merge-<n>/` dir — passed to merge-END so it reads THIS marker\n\n constructor(status: 'clean' | 'conflict', context: MergeContext | null, runDir: string) {\n this.status = status;\n this.context = context;\n this.runDir = runDir;\n }\n}\n\n// The one number `n` for a sync and the things it names: the pre-merge backup branch, its paired\n// conflict-context run dir, and (via `n`) the `preMerge<n>.hash` record of the tip it snapshotted.\nclass SyncSlot {\n backupBranch: string;\n runDir: string;\n n: number;\n\n constructor(backupBranch: string, runDir: string, n: number) {\n this.backupBranch = backupBranch;\n this.runDir = runDir;\n this.n = n;\n }\n}\n\n\n// merge-START: the first half of the 3-point squash-merge lifecycle. Brings origin/main into a fresh\n// `<branch>Squash`, and on conflict writes the 3-point context + unvalidated marker + process doc,\n// then hands control back to the AI. On a clean merge it commits the squash and returns the branch\n// context so the caller (RunUpdate) can run merge-END to finalize. NEVER finalizes or posts a PR.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeStart {\n constructor(\n private readonly gatherInfo: GatherInfo,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult> {\n const currentBranch = await this.gitExec.currentBranch(process.cwd());\n if (currentBranch.endsWith('Squash')) {\n throw new CliExitError(1, `❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}`);\n }\n\n // One number `n` for this sync drives BOTH the backup branch and its `merge-<n>/` context dir.\n const slot = await this.chooseSyncSlot(home, currentBranch);\n const backupBranch = slot.backupBranch;\n const mergeDir = slot.runDir;\n\n process.stdout.write('\\n' + SEP + '🔄 Squash-Merge Update from Main\\n' + SEP + '\\n');\n const info = await this.gatherInfo.gatherInfo();\n const hashes = info.hashes;\n if (info.alreadyUpToDate) {\n process.stdout.write('ℹ️ Branch already even with main; nothing to merge, continuing to push/build.\\n');\n }\n\n const prNumber = await this.detectPr(this.branchNaming.baseBranchName(currentBranch));\n process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\\n` : 'No existing PR (one can be created later).\\n');\n\n await this.createBackup(currentBranch, backupBranch);\n // Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash` — every intermediate\n // state, not just the last one. It is what lets the `<feature>PreMerge<n>` snapshot BRANCH be\n // disposable (branches count toward the branch cap; a written-down hash does not), and it is the\n // ref the archive tag is cut from when the PR lands.\n this.mergeState.writePreMergeHash(home, slot.n, await this.fullSha(currentBranch));\n const backupEvent = new BranchMutationEvent(verb, 'BACKUP');\n backupEvent.fromBranch = currentBranch;\n backupEvent.toBranch = backupBranch;\n logBranchMutation(repoRoot, backupEvent);\n\n const squashBranch = `${currentBranch}Squash`;\n if (await this.branchExists(squashBranch)) {\n throw new CliExitError(1, `❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}`);\n }\n\n // Branch the squash off origin/main directly — worktree-native. origin/main was already fetched\n // in gatherInfo(), and A/B/C are computed purely from origin/main, so the merge base is identical\n // to the old checkout-main + pull path.\n const originMainSha = await this.shortSha('origin/main');\n await this.gitExec.runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');\n const baseEvent = new BranchMutationEvent(verb, 'PULL');\n baseEvent.newMain = originMainSha;\n logBranchMutation(repoRoot, baseEvent);\n\n process.stdout.write('\\n' + SEP + `🔀 Squash merging ${currentBranch}\\n` + SEP + '\\n');\n const merge = await this.git.passThrough(['merge', '--squash', currentBranch]);\n if (!merge.ok) {\n await this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);\n await this.logConflict(repoRoot, verb, mergeDir);\n return new MergeStartResult('conflict', null, mergeDir);\n }\n logBranchMutation(repoRoot, new BranchMutationEvent(verb, 'SQUASH'));\n\n const nothingStaged = (await this.git.run(['diff-index', '--quiet', '--cached', 'HEAD', '--'])).ok;\n if (nothingStaged) {\n process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\\n');\n } else {\n // Internal, transient subject for the single squash commit on the feature branch. It NO LONGER\n // reaches main's history: finish-upsert-pr squash-merges the PR with an explicit\n // `gh pr merge --subject <PR title> --body-file <commit summary>`, so main carries the PR title.\n await this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');\n // Clean merge ⇒ hashes only, no conflicts.md. Its ABSENCE is what marks this merge clean.\n this.mergeState.recordCleanMerge(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n }\n return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);\n }\n\n // Detect the PR by its STABLE feature branch (a leftover `…wpN` still resolves to the one name the\n // PR lives on).\n private async detectPr(baseBranch: string): Promise<string> {\n const result = await this.processes.run(\n 'gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n );\n return result.ok ? result.stdout.trim() : '';\n }\n\n // Pick this sync's slot number MONOTONICALLY from the durable audit dirs, then step past any\n // existing `<branch>PreMerge<n>` branch so the same `n` is free for the paired backup branch.\n private async chooseSyncSlot(home: string, currentBranch: string): Promise<SyncSlot> {\n let n = this.mergeState.nextMergeSlotNumber(home);\n while (await this.branchExists(this.branchNaming.preMergeBackupName(currentBranch, n))) n += 1;\n return new SyncSlot(this.branchNaming.preMergeBackupName(currentBranch, n), this.mergeState.mergeRunDirFor(home, n), n);\n }\n\n // Snapshot the pre-merge state onto the caller-chosen `backupBranch`, never overwriting.\n private async branchExists(name: string): Promise<boolean> {\n return (await this.git.run(['show-ref', '--verify', '--quiet', `refs/heads/${name}`])).ok;\n }\n\n private async createBackup(currentBranch: string, backupBranch: string): Promise<void> {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\n');\n await this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n await this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n }\n\n private async saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n ): Promise<void> {\n for (const file of conflictedFiles) {\n const fileDir = this.mergeState.perFileContextDir(mergeDir, file);\n fs.mkdirSync(fileDir, { recursive: true });\n\n const fork = await this.git.run(['show', `${forkPoint}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.ok ? fork.stdout : '(file did not exist)\\n');\n const feature = await this.git.run(['show', `${featureHead}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.ok ? feature.stdout : '(file did not exist)\\n');\n const main = await this.git.run(['show', `${mainHead}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.ok ? main.stdout : '(file did not exist)\\n');\n\n const ba = await this.git.run(['diff', forkPoint, featureHead, '--', file]);\n fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout);\n const ca = await this.git.run(['diff', forkPoint, mainHead, '--', file]);\n fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout);\n }\n }\n\n // The LIVE rendering of the same template `.webpieces/instruct-ai/webpieces.mergeprocess.md` is\n // delivered from — see rules-config/src/merge-process-doc.ts. The text lives there, not here, so\n // the copy every repo receives and the copy a conflicted merge stamps are the same document.\n private mergeProcessDoc(mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const fileList = conflictedFiles.map((f: string): string => `- \\`${f}\\``).join('\\n');\n const run = new MergeRun(\n new SyncFlowGuidance().pairedStart(finishCommand), finishCommand, squashBranch, mergeDir, fileList,\n );\n return new MergeProcessText(loadTemplate(MERGE_PROCESS_DOC)).render(run);\n }\n\n // Returns the absolute path of the written doc.\n private writeMergeProcessDoc(repoRoot: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const docDir = dotWebpieces.localFile(repoRoot, 'instruct-ai');\n fs.mkdirSync(docDir, { recursive: true });\n const docPath = path.join(docDir, MERGE_PROCESS_DOC);\n fs.writeFileSync(docPath, this.mergeProcessDoc(mergeDir, squashBranch, conflictedFiles, finishCommand));\n return docPath;\n }\n\n // The AI-facing \"what just happened / what to do next\" recap on the conflict path.\n private printConflictHandback(\n docPath: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string,\n ): void {\n process.stdout.write('\\n' + SEP + `⚠️ Conflicts in ${conflictedFiles.length} file(s) — handing control back to you\\n` + SEP + '\\n');\n process.stdout.write('Here is exactly what I did and what you need to do:\\n\\n');\n process.stdout.write('What I did:\\n');\n process.stdout.write(' 1. snapshotted your pre-merge state to a PreMerge branch\\n');\n process.stdout.write(' 2. pulled origin/main and squash-merged your work onto it\\n');\n process.stdout.write(` 3. hit conflicts — you are now on the transient branch ${squashBranch}\\n\\n`);\n process.stdout.write('What you need to do:\\n');\n process.stdout.write(` 1. read the merge process doc: ${docPath}\\n`);\n process.stdout.write(` 2. resolve each conflicted file below (its 3-point A/B/C context + diffs are in\\n`);\n process.stdout.write(` ${mergeDir}/updatemain-<file>/), \\`git add\\` it, and write that file's merge-explanation.md\\n`);\n process.stdout.write(` 3. run pnpm ${finishCommand} — it validates, commits, and finalizes (do NOT git commit/push yourself)\\n\\n`);\n process.stdout.write('Conflicted files:\\n');\n for (const file of conflictedFiles) process.stdout.write(` - ${file}\\n`);\n process.stdout.write('\\n' + SEP);\n }\n\n // Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit.\n private async handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints, finishCommand: string,\n ): Promise<void> {\n const raw = await this.gitExec.gitQuery(['diff', '--name-only', '--diff-filter=U'], process.cwd(), 'Failed to list conflicted files (git diff --diff-filter=U).');\n const conflictedFiles = raw.split('\\n').filter((f: string): boolean => f.trim() !== '');\n fs.mkdirSync(mergeDir, { recursive: true });\n // `conflicts.md` replaces the old `updatemain-conflicted-files.txt` (which nothing read) AND is\n // the 3-point signal itself: this file exists in a run dir if and only if that merge conflicted,\n // which is what lets the index classify each merge without a per-branch directory-name scheme.\n this.mergeState.writeConflicts(mergeDir, conflictedFiles);\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\\n');\n await this.saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n\n const marker = new MergeMarker(\n currentBranch, squashBranch, backupBranch, prNumber, conflictedFiles,\n hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead, false,\n );\n this.mergeState.writeMergeMarker(mergeDir, marker);\n const docPath = this.writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles, finishCommand);\n this.printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);\n }\n\n // Short sha of a ref (best-effort — '' if it can't resolve).\n private async shortSha(ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', '--short', ref]);\n return result.ok ? result.stdout.trim() : '';\n }\n\n // FULL sha of a ref (best-effort — '' if it can't resolve). Recorded for the pre-merge tips because\n // those hashes are meant to be used later to restore state, and an abbreviated sha can go ambiguous\n // as the repo grows.\n private async fullSha(ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', ref]);\n return result.ok ? result.stdout.trim() : '';\n }\n\n // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.\n private async logConflict(repoRoot: string, verb: MutationVerb, mergeDir: string): Promise<void> {\n const raw = await this.git.run(['diff', '--name-only', '--diff-filter=U'], repoRoot);\n const files = (raw.ok ? raw.stdout : '').split('\\n').map((f: string): string => f.trim()).filter((f: string): boolean => f !== '');\n const event = new BranchMutationEvent(verb, 'CONFLICT');\n event.conflict = true;\n event.conflictFiles = files;\n event.artifacts = [\n path.join(mergeDir, 'updatemain-<file>'),\n dotWebpieces.localFile(repoRoot, 'instruct-ai', MERGE_PROCESS_DOC),\n ];\n logBranchMutation(repoRoot, event);\n }\n}\n"]}
@@ -1,7 +1,9 @@
1
+ import { NativeProcessApi } from '@webpieces/tooling-common';
1
2
  import { BranchNaming } from './branch-naming';
2
3
  /** Hard gate: whether an OPEN PR already tracks a feature branch (by its stable base name). */
3
4
  export declare class OpenPrCheck {
4
5
  private readonly branchNaming;
5
- constructor(branchNaming: BranchNaming);
6
- openPrForBranch(repoRoot: string, currentBranch: string): string;
6
+ private readonly processes;
7
+ constructor(branchNaming: BranchNaming, processes: NativeProcessApi);
8
+ openPrForBranch(repoRoot: string, currentBranch: string): Promise<string>;
7
9
  }
@@ -2,26 +2,28 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OpenPrCheck = 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 branch_naming_1 = require("./branch-naming");
9
9
  const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
10
10
  /** Hard gate: whether an OPEN PR already tracks a feature branch (by its stable base name). */
11
11
  let OpenPrCheck = class OpenPrCheck {
12
12
  branchNaming;
13
- constructor(branchNaming) {
13
+ processes;
14
+ constructor(branchNaming, processes) {
14
15
  this.branchNaming = branchNaming;
16
+ this.processes = processes;
15
17
  }
16
18
  // The open PR (if any) tracking a feature branch, looked up by its STABLE base name. Returns '' ONLY
17
19
  // when GitHub answered and there is genuinely no open PR. HARD GATE: FAILS FAST if `gh` cannot
18
20
  // answer — we must NOT degrade "couldn't ask GitHub" into "no PR" (a 3-point update makes a new
19
21
  // branch generation and the existing PR would be stranded on the OLD branch). Refuse rather than guess.
20
- openPrForBranch(repoRoot, currentBranch) {
22
+ async openPrForBranch(repoRoot, currentBranch) {
21
23
  const base = this.branchNaming.baseBranchName(currentBranch);
22
- const result = (0, child_process_1.spawnSync)('gh', ['pr', 'list', '--head', base, '--state', 'open', '--json', 'number', '--jq', '.[0].number'], { cwd: repoRoot, encoding: 'utf8' });
23
- if (result.status !== 0) {
24
- const detail = (result.stderr ?? '').trim() || (result.error ? result.error.message : 'gh exited non-zero');
24
+ const result = await this.processes.run('gh', ['pr', 'list', '--head', base, '--state', 'open', '--json', 'number', '--jq', '.[0].number'], repoRoot);
25
+ if (!result.ok) {
26
+ const detail = result.stderr.trim() || 'gh exited non-zero';
25
27
  throw new rules_config_1.CliExitError(2, '\n' + SEP + '❌ Could not ask GitHub whether an open PR exists for this branch\n' + SEP + '\n' +
26
28
  `gh failed for base branch "${base}": ${detail}\n\n` +
27
29
  'This check must NOT be skipped: a 3-point update creates a NEW branch generation, so if a\n' +
@@ -30,12 +32,13 @@ let OpenPrCheck = class OpenPrCheck {
30
32
  'the PR flow: pnpm wp-start-upsert-pr → /wp-merge (only on conflict) →\n' +
31
33
  'pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\n');
32
34
  }
33
- return (result.stdout ?? '').trim();
35
+ return result.stdout.trim();
34
36
  }
35
37
  };
36
38
  exports.OpenPrCheck = OpenPrCheck;
37
39
  exports.OpenPrCheck = OpenPrCheck = tslib_1.__decorate([
38
40
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
39
- tslib_1.__metadata("design:paramtypes", [branch_naming_1.BranchNaming])
41
+ tslib_1.__metadata("design:paramtypes", [branch_naming_1.BranchNaming,
42
+ tooling_common_1.NativeProcessApi])
40
43
  ], OpenPrCheck);
41
44
  //# sourceMappingURL=open-pr-check.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"open-pr-check.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/open-pr-check.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAC3D,mDAA+C;AAE/C,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,+FAA+F;AAExF,IAAM,WAAW,GAAjB,MAAM,WAAW;IACS;IAA7B,YAA6B,YAA0B;QAA1B,iBAAY,GAAZ,YAAY,CAAc;IAAG,CAAC;IAE3D,qGAAqG;IACrG,+FAA+F;IAC/F,gGAAgG;IAChG,wGAAwG;IACxG,eAAe,CAAC,QAAgB,EAAE,aAAqB;QACnD,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC;QAC7D,MAAM,MAAM,GAAG,IAAA,yBAAS,EACpB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAClG,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CACtC,CAAC;QACF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,MAAM,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC;YAC5G,MAAM,IAAI,2BAAY,CAAC,CAAC,EACpB,IAAI,GAAG,GAAG,GAAG,oEAAoE,GAAG,GAAG,GAAG,IAAI;gBAC9F,8BAA8B,IAAI,MAAM,MAAM,MAAM;gBACpD,6FAA6F;gBAC7F,8FAA8F;gBAC9F,4FAA4F;gBAC5F,yEAAyE;gBACzE,4EAA4E,CAC/E,CAAC;QACN,CAAC;QACD,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,CAAC;CACJ,CAAA;AA3BY,kCAAW;sBAAX,WAAW;IADvB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEM,4BAAY;GAD9C,WAAW,CA2BvB","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** Hard gate: whether an OPEN PR already tracks a feature branch (by its stable base name). */\n@injectable(bindingScopeValues.Singleton)\nexport class OpenPrCheck {\n constructor(private readonly branchNaming: BranchNaming) {}\n\n // The open PR (if any) tracking a feature branch, looked up by its STABLE base name. Returns '' ONLY\n // when GitHub answered and there is genuinely no open PR. HARD GATE: FAILS FAST if `gh` cannot\n // answer — we must NOT degrade \"couldn't ask GitHub\" into \"no PR\" (a 3-point update makes a new\n // branch generation and the existing PR would be stranded on the OLD branch). Refuse rather than guess.\n openPrForBranch(repoRoot: string, currentBranch: string): string {\n const base = this.branchNaming.baseBranchName(currentBranch);\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', base, '--state', 'open', '--json', 'number', '--jq', '.[0].number'],\n { cwd: repoRoot, encoding: 'utf8' },\n );\n if (result.status !== 0) {\n const detail = (result.stderr ?? '').trim() || (result.error ? result.error.message : 'gh exited non-zero');\n throw new CliExitError(2,\n '\\n' + SEP + '❌ Could not ask GitHub whether an open PR exists for this branch\\n' + SEP + '\\n' +\n `gh failed for base branch \"${base}\": ${detail}\\n\\n` +\n 'This check must NOT be skipped: a 3-point update creates a NEW branch generation, so if a\\n' +\n 'PR already exists, wp-start-update would leave it pointing at the OLD branch. Fix gh first\\n' +\n '(install / `gh auth login` / restore network), then re-run — or, if a PR does exist, use\\n' +\n 'the PR flow: pnpm wp-start-upsert-pr → /wp-merge (only on conflict) →\\n' +\n 'pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\\n',\n );\n }\n return (result.stdout ?? '').trim();\n }\n}\n"]}
1
+ {"version":3,"file":"open-pr-check.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/open-pr-check.ts"],"names":[],"mappings":";;;;AAAA,0DAAuD;AACvD,8DAA6D;AAC7D,yCAA2D;AAC3D,mDAA+C;AAE/C,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,+FAA+F;AAExF,IAAM,WAAW,GAAjB,MAAM,WAAW;IAEC;IACA;IAFrB,YACqB,YAA0B,EAC1B,SAA2B;QAD3B,iBAAY,GAAZ,YAAY,CAAc;QAC1B,cAAS,GAAT,SAAS,CAAkB;IAC7C,CAAC;IAEJ,qGAAqG;IACrG,+FAA+F;IAC/F,gGAAgG;IAChG,wGAAwG;IACxG,KAAK,CAAC,eAAe,CAAC,QAAgB,EAAE,aAAqB;QACzD,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC;QAC7D,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,CACnC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAClG,QAAQ,CACX,CAAC;QACF,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACb,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,oBAAoB,CAAC;YAC5D,MAAM,IAAI,2BAAY,CAAC,CAAC,EACpB,IAAI,GAAG,GAAG,GAAG,oEAAoE,GAAG,GAAG,GAAG,IAAI;gBAC9F,8BAA8B,IAAI,MAAM,MAAM,MAAM;gBACpD,6FAA6F;gBAC7F,8FAA8F;gBAC9F,4FAA4F;gBAC5F,yEAAyE;gBACzE,4EAA4E,CAC/E,CAAC;QACN,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAChC,CAAC;CACJ,CAAA;AA9BY,kCAAW;sBAAX,WAAW;IADvB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGF,4BAAY;QACf,iCAAgB;GAHvC,WAAW,CA8BvB","sourcesContent":["import { CliExitError } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/** Hard gate: whether an OPEN PR already tracks a feature branch (by its stable base name). */\n@injectable(bindingScopeValues.Singleton)\nexport class OpenPrCheck {\n constructor(\n private readonly branchNaming: BranchNaming,\n private readonly processes: NativeProcessApi,\n ) {}\n\n // The open PR (if any) tracking a feature branch, looked up by its STABLE base name. Returns '' ONLY\n // when GitHub answered and there is genuinely no open PR. HARD GATE: FAILS FAST if `gh` cannot\n // answer — we must NOT degrade \"couldn't ask GitHub\" into \"no PR\" (a 3-point update makes a new\n // branch generation and the existing PR would be stranded on the OLD branch). Refuse rather than guess.\n async openPrForBranch(repoRoot: string, currentBranch: string): Promise<string> {\n const base = this.branchNaming.baseBranchName(currentBranch);\n const result = await this.processes.run(\n 'gh', ['pr', 'list', '--head', base, '--state', 'open', '--json', 'number', '--jq', '.[0].number'],\n repoRoot,\n );\n if (!result.ok) {\n const detail = result.stderr.trim() || 'gh exited non-zero';\n throw new CliExitError(2,\n '\\n' + SEP + '❌ Could not ask GitHub whether an open PR exists for this branch\\n' + SEP + '\\n' +\n `gh failed for base branch \"${base}\": ${detail}\\n\\n` +\n 'This check must NOT be skipped: a 3-point update creates a NEW branch generation, so if a\\n' +\n 'PR already exists, wp-start-update would leave it pointing at the OLD branch. Fix gh first\\n' +\n '(install / `gh auth login` / restore network), then re-run — or, if a PR does exist, use\\n' +\n 'the PR flow: pnpm wp-start-upsert-pr → /wp-merge (only on conflict) →\\n' +\n 'pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\\n',\n );\n }\n return result.stdout.trim();\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { NativeProcessApi } from '@webpieces/tooling-common';
1
2
  /** One marker-keyed PR comment to upsert. Data-only, per CLAUDE.md. */
2
3
  export declare class PrCommentRequest {
3
4
  /** The PR number. '' means "no PR resolved" and the upsert is a silent no-op. */
@@ -41,7 +42,9 @@ export declare class PrCommentResult {
41
42
  * judgements do not belong in here.
42
43
  */
43
44
  export declare class PrCommentUpserter {
44
- upsert(request: PrCommentRequest): PrCommentResult;
45
+ private readonly processes;
46
+ constructor(processes: NativeProcessApi);
47
+ upsert(request: PrCommentRequest): Promise<PrCommentResult>;
45
48
  /**
46
49
  * The id of THIS tool's comment on the PR, found by hidden marker, or '' when absent.
47
50
  *
@@ -49,6 +52,5 @@ export declare class PrCommentUpserter {
49
52
  * consistently patching the earliest keeps the comment in a stable position in the thread — which is
50
53
  * what the PR body's "1st comment / 2nd comment" pointer relies on.
51
54
  */
52
- protected findCommentId(prNumber: string, marker: string): string;
53
- protected gh(args: string[]): number;
55
+ private findCommentId;
54
56
  }
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PrCommentUpserter = exports.PrCommentResult = exports.PrCommentRequest = 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"));
7
+ const tooling_common_1 = require("@webpieces/tooling-common");
8
8
  const inversify_1 = require("inversify");
9
9
  /** One marker-keyed PR comment to upsert. Data-only, per CLAUDE.md. */
10
10
  class PrCommentRequest {
@@ -55,17 +55,21 @@ exports.PrCommentResult = PrCommentResult;
55
55
  * judgements do not belong in here.
56
56
  */
57
57
  let PrCommentUpserter = class PrCommentUpserter {
58
- upsert(request) {
58
+ processes;
59
+ constructor(processes) {
60
+ this.processes = processes;
61
+ }
62
+ async upsert(request) {
59
63
  if (request.prNumber === '')
60
64
  return new PrCommentResult('', false, false);
61
65
  fs.mkdirSync(request.payloadDir, { recursive: true });
62
66
  const payload = path.join(request.payloadDir, request.payloadName);
63
67
  fs.writeFileSync(payload, JSON.stringify({ body: request.body }));
64
- const existing = this.findCommentId(request.prNumber, request.marker);
68
+ const existing = await this.findCommentId(request.prNumber, request.marker);
65
69
  const args = existing !== ''
66
70
  ? ['api', '--method', 'PATCH', `repos/{owner}/{repo}/issues/comments/${existing}`, '--input', payload]
67
71
  : ['api', '--method', 'POST', `repos/{owner}/{repo}/issues/${request.prNumber}/comments`, '--input', payload];
68
- if (this.gh(args) !== 0) {
72
+ if (!(await this.processes.run('gh', args)).ok) {
69
73
  process.stderr.write(`⚠️ Could not post the ${request.label} (non-fatal here — see the caller).\n`);
70
74
  return new PrCommentResult(existing, existing !== '', false);
71
75
  }
@@ -79,22 +83,19 @@ let PrCommentUpserter = class PrCommentUpserter {
79
83
  * consistently patching the earliest keeps the comment in a stable position in the thread — which is
80
84
  * what the PR body's "1st comment / 2nd comment" pointer relies on.
81
85
  */
82
- findCommentId(prNumber, marker) {
83
- const res = (0, child_process_1.spawnSync)('gh', [
86
+ async findCommentId(prNumber, marker) {
87
+ const res = await this.processes.run('gh', [
84
88
  'api', '--paginate', `repos/{owner}/{repo}/issues/${prNumber}/comments`,
85
89
  '--jq', `.[] | select(.body | contains("${marker}")) | .id`,
86
- ], { encoding: 'utf8' });
87
- if (res.status !== 0)
90
+ ]);
91
+ if (!res.ok)
88
92
  return '';
89
- return (res.stdout ?? '').trim().split('\n')[0] ?? '';
90
- }
91
- // The gh seam, protected so specs can drive the upsert with no gh, no network and no PR.
92
- gh(args) {
93
- return (0, child_process_1.spawnSync)('gh', args, { encoding: 'utf8' }).status ?? -1;
93
+ return res.stdout.trim().split('\n')[0] ?? '';
94
94
  }
95
95
  };
96
96
  exports.PrCommentUpserter = PrCommentUpserter;
97
97
  exports.PrCommentUpserter = PrCommentUpserter = tslib_1.__decorate([
98
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
98
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
99
+ tslib_1.__metadata("design:paramtypes", [tooling_common_1.NativeProcessApi])
99
100
  ], PrCommentUpserter);
100
101
  //# sourceMappingURL=pr-comment-upserter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pr-comment-upserter.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/pr-comment-upserter.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,uEAAuE;AACvE,MAAa,gBAAgB;IACzB,iFAAiF;IACjF,QAAQ,GAAG,EAAE,CAAC;IACd,mGAAmG;IACnG,MAAM,GAAG,EAAE,CAAC;IACZ,8CAA8C;IAC9C,IAAI,GAAG,EAAE,CAAC;IACV,8EAA8E;IAC9E,UAAU,GAAG,EAAE,CAAC;IA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AM,EAAE,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC;IACpE,CAAC;CACJ,CAAA;AAxCY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,iBAAiB,CAwC7B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One marker-keyed PR comment to upsert. Data-only, per CLAUDE.md. */\nexport class PrCommentRequest {\n /** The PR number. '' means \"no PR resolved\" and the upsert is a silent no-op. */\n prNumber = '';\n /** Hidden HTML-comment marker that identifies THIS tool's comment among all comments on the PR. */\n marker = '';\n /** The full comment body, marker included. */\n body = '';\n /** Directory to stage the JSON payload in — `gh api --input` needs a file. */\n payloadDir = '';\n /** Payload filename, unique per comment kind so two upserts in one run cannot clobber each other. */\n payloadName = '';\n /** Human words for the progress/warning lines, e.g. 'checklist review comment'. */\n label = '';\n}\n\n/** What an upsert did, so the caller can report it without re-deriving anything. */\nexport class PrCommentResult {\n /** '' when nothing was posted (no PR number, or `gh` failed). */\n commentId: string;\n /** True when an existing comment was PATCHed rather than a new one POSTed. */\n updated: boolean;\n ok: boolean;\n\n constructor(commentId: string, updated: boolean, ok: boolean) {\n this.commentId = commentId;\n this.updated = updated;\n this.ok = ok;\n }\n}\n\n/**\n * Upserts a hidden-marker-keyed comment on a PR: find ours, PATCH it if it exists, POST it if not.\n *\n * ONE implementation for BOTH of the gated flow's comments — the full dashboard (1st) and the reviewer\n * checklist (2nd). It exists because the PR description became the git-log body: everything long-form or\n * machine-facing moved into comments, so what had been one inline block of gh plumbing inside\n * FinishUpsertPrCommand became something two callers needed. Per the repo's consolidate-don't-duplicate\n * rule that is one parameterized class, not a copied private method.\n *\n * Idempotency is the whole contract. `wp-finish-upsert-pr` re-runs on every push, and a PR that\n * accumulated a new dashboard comment per push would be unreadable — worse, `wp-check-pr` would have\n * several gate tokens to choose between, and picking the wrong one is a red check on good code.\n *\n * NEVER FATAL by itself. Every caller reaches this after the PR is already up, so a `gh` hiccup warns and\n * returns `ok: false`; it is the CALLER's job to decide whether that matters. It matters for the\n * dashboard comment (it carries the token) and does not for the checklist comment, and those two\n * judgements do not belong in here.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PrCommentUpserter {\n upsert(request: PrCommentRequest): PrCommentResult {\n if (request.prNumber === '') return new PrCommentResult('', false, false);\n\n fs.mkdirSync(request.payloadDir, { recursive: true });\n const payload = path.join(request.payloadDir, request.payloadName);\n fs.writeFileSync(payload, JSON.stringify({ body: request.body }));\n\n const existing = this.findCommentId(request.prNumber, request.marker);\n const args = existing !== ''\n ? ['api', '--method', 'PATCH', `repos/{owner}/{repo}/issues/comments/${existing}`, '--input', payload]\n : ['api', '--method', 'POST', `repos/{owner}/{repo}/issues/${request.prNumber}/comments`, '--input', payload];\n if (this.gh(args) !== 0) {\n process.stderr.write(`⚠️ Could not post the ${request.label} (non-fatal here — see the caller).\\n`);\n return new PrCommentResult(existing, existing !== '', false);\n }\n process.stdout.write(` ${existing !== '' ? 'updated' : 'posted'} the ${request.label} ✓\\n`);\n return new PrCommentResult(existing, existing !== '', true);\n }\n\n /**\n * The id of THIS tool's comment on the PR, found by hidden marker, or '' when absent.\n *\n * Takes the FIRST match. A PR should never have two, but if an older release ever left a duplicate,\n * consistently patching the earliest keeps the comment in a stable position in the thread — which is\n * what the PR body's \"1st comment / 2nd comment\" pointer relies on.\n */\n protected findCommentId(prNumber: string, marker: string): string {\n const res = spawnSync('gh', [\n 'api', '--paginate', `repos/{owner}/{repo}/issues/${prNumber}/comments`,\n '--jq', `.[] | select(.body | contains(\"${marker}\")) | .id`,\n ], { encoding: 'utf8' });\n if (res.status !== 0) return '';\n return (res.stdout ?? '').trim().split('\\n')[0] ?? '';\n }\n\n // The gh seam, protected so specs can drive the upsert with no gh, no network and no PR.\n protected gh(args: string[]): number {\n return spawnSync('gh', args, { encoding: 'utf8' }).status ?? -1;\n }\n}\n"]}
1
+ {"version":3,"file":"pr-comment-upserter.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/pr-comment-upserter.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAA6D;AAC7D,yCAA2D;AAE3D,uEAAuE;AACvE,MAAa,gBAAgB;IACzB,iFAAiF;IACjF,QAAQ,GAAG,EAAE,CAAC;IACd,mGAAmG;IACnG,MAAM,GAAG,EAAE,CAAC;IACZ,8CAA8C;IAC9C,IAAI,GAAG,EAAE,CAAC;IACV,8EAA8E;IAC9E,UAAU,GAAG,EAAE,CAAC;IAChB,qGAAqG;IACrG,WAAW,GAAG,EAAE,CAAC;IACjB,mFAAmF;IACnF,KAAK,GAAG,EAAE,CAAC;CACd;AAbD,4CAaC;AAED,oFAAoF;AACpF,MAAa,eAAe;IACxB,iEAAiE;IACjE,SAAS,CAAS;IAClB,8EAA8E;IAC9E,OAAO,CAAU;IACjB,EAAE,CAAU;IAEZ,YAAY,SAAiB,EAAE,OAAgB,EAAE,EAAW;QACxD,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACjB,CAAC;CACJ;AAZD,0CAYC;AAED;;;;;;;;;;;;;;;;;GAiBG;AAEI,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IACG;IAA7B,YAA6B,SAA2B;QAA3B,cAAS,GAAT,SAAS,CAAkB;IAAG,CAAC;IAE5D,KAAK,CAAC,MAAM,CAAC,OAAyB;QAClC,IAAI,OAAO,CAAC,QAAQ,KAAK,EAAE;YAAE,OAAO,IAAI,eAAe,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;QAE1E,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,C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aAAa,CAAC,QAAgB,EAAE,MAAc;QACxD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE;YACvC,KAAK,EAAE,YAAY,EAAE,+BAA+B,QAAQ,WAAW;YACvE,MAAM,EAAE,kCAAkC,MAAM,WAAW;SAC9D,CAAC,CAAC;QACH,IAAI,CAAC,GAAG,CAAC,EAAE;YAAE,OAAO,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAClD,CAAC;CACJ,CAAA;AArCY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEG,iCAAgB;GAD/C,iBAAiB,CAqC7B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/** One marker-keyed PR comment to upsert. Data-only, per CLAUDE.md. */\nexport class PrCommentRequest {\n /** The PR number. '' means \"no PR resolved\" and the upsert is a silent no-op. */\n prNumber = '';\n /** Hidden HTML-comment marker that identifies THIS tool's comment among all comments on the PR. */\n marker = '';\n /** The full comment body, marker included. */\n body = '';\n /** Directory to stage the JSON payload in — `gh api --input` needs a file. */\n payloadDir = '';\n /** Payload filename, unique per comment kind so two upserts in one run cannot clobber each other. */\n payloadName = '';\n /** Human words for the progress/warning lines, e.g. 'checklist review comment'. */\n label = '';\n}\n\n/** What an upsert did, so the caller can report it without re-deriving anything. */\nexport class PrCommentResult {\n /** '' when nothing was posted (no PR number, or `gh` failed). */\n commentId: string;\n /** True when an existing comment was PATCHed rather than a new one POSTed. */\n updated: boolean;\n ok: boolean;\n\n constructor(commentId: string, updated: boolean, ok: boolean) {\n this.commentId = commentId;\n this.updated = updated;\n this.ok = ok;\n }\n}\n\n/**\n * Upserts a hidden-marker-keyed comment on a PR: find ours, PATCH it if it exists, POST it if not.\n *\n * ONE implementation for BOTH of the gated flow's comments — the full dashboard (1st) and the reviewer\n * checklist (2nd). It exists because the PR description became the git-log body: everything long-form or\n * machine-facing moved into comments, so what had been one inline block of gh plumbing inside\n * FinishUpsertPrCommand became something two callers needed. Per the repo's consolidate-don't-duplicate\n * rule that is one parameterized class, not a copied private method.\n *\n * Idempotency is the whole contract. `wp-finish-upsert-pr` re-runs on every push, and a PR that\n * accumulated a new dashboard comment per push would be unreadable — worse, `wp-check-pr` would have\n * several gate tokens to choose between, and picking the wrong one is a red check on good code.\n *\n * NEVER FATAL by itself. Every caller reaches this after the PR is already up, so a `gh` hiccup warns and\n * returns `ok: false`; it is the CALLER's job to decide whether that matters. It matters for the\n * dashboard comment (it carries the token) and does not for the checklist comment, and those two\n * judgements do not belong in here.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PrCommentUpserter {\n constructor(private readonly processes: NativeProcessApi) {}\n\n async upsert(request: PrCommentRequest): Promise<PrCommentResult> {\n if (request.prNumber === '') return new PrCommentResult('', false, false);\n\n fs.mkdirSync(request.payloadDir, { recursive: true });\n const payload = path.join(request.payloadDir, request.payloadName);\n fs.writeFileSync(payload, JSON.stringify({ body: request.body }));\n\n const existing = await this.findCommentId(request.prNumber, request.marker);\n const args = existing !== ''\n ? ['api', '--method', 'PATCH', `repos/{owner}/{repo}/issues/comments/${existing}`, '--input', payload]\n : ['api', '--method', 'POST', `repos/{owner}/{repo}/issues/${request.prNumber}/comments`, '--input', payload];\n if (!(await this.processes.run('gh', args)).ok) {\n process.stderr.write(`⚠️ Could not post the ${request.label} (non-fatal here — see the caller).\\n`);\n return new PrCommentResult(existing, existing !== '', false);\n }\n process.stdout.write(` ${existing !== '' ? 'updated' : 'posted'} the ${request.label} ✓\\n`);\n return new PrCommentResult(existing, existing !== '', true);\n }\n\n /**\n * The id of THIS tool's comment on the PR, found by hidden marker, or '' when absent.\n *\n * Takes the FIRST match. A PR should never have two, but if an older release ever left a duplicate,\n * consistently patching the earliest keeps the comment in a stable position in the thread — which is\n * what the PR body's \"1st comment / 2nd comment\" pointer relies on.\n */\n private async findCommentId(prNumber: string, marker: string): Promise<string> {\n const res = await this.processes.run('gh', [\n 'api', '--paginate', `repos/{owner}/{repo}/issues/${prNumber}/comments`,\n '--jq', `.[] | select(.body | contains(\"${marker}\")) | .id`,\n ]);\n if (!res.ok) return '';\n return res.stdout.trim().split('\\n')[0] ?? '';\n }\n}\n"]}