@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.
- package/package.json +6 -6
- package/src/scripts/commands/await-checks-command.d.ts +6 -3
- package/src/scripts/commands/await-checks-command.js +17 -12
- package/src/scripts/commands/await-checks-command.js.map +1 -1
- package/src/scripts/commands/await-reviews-command.d.ts +1 -1
- package/src/scripts/commands/await-reviews-command.js +3 -3
- package/src/scripts/commands/await-reviews-command.js.map +1 -1
- package/src/scripts/commands/check-pr-command.d.ts +3 -1
- package/src/scripts/commands/check-pr-command.js +12 -9
- package/src/scripts/commands/check-pr-command.js.map +1 -1
- package/src/scripts/commands/cleanup-command.js +12 -12
- package/src/scripts/commands/cleanup-command.js.map +1 -1
- package/src/scripts/commands/finish-push-dev-command.js +3 -4
- package/src/scripts/commands/finish-push-dev-command.js.map +1 -1
- package/src/scripts/commands/finish-update-command.js +1 -1
- package/src/scripts/commands/finish-update-command.js.map +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -1
- package/src/scripts/commands/finish-upsert-pr-command.js +65 -62
- package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/human-post-pr-command.d.ts +8 -6
- package/src/scripts/commands/human-post-pr-command.js +33 -32
- package/src/scripts/commands/human-post-pr-command.js.map +1 -1
- package/src/scripts/commands/land-pr-command.d.ts +5 -1
- package/src/scripts/commands/land-pr-command.js +37 -23
- package/src/scripts/commands/land-pr-command.js.map +1 -1
- package/src/scripts/commands/main-checkout.d.ts +4 -1
- package/src/scripts/commands/main-checkout.js +22 -22
- package/src/scripts/commands/main-checkout.js.map +1 -1
- package/src/scripts/commands/push-dev-command.js +28 -29
- package/src/scripts/commands/push-dev-command.js.map +1 -1
- package/src/scripts/commands/reap-worktree-command.js +4 -5
- package/src/scripts/commands/reap-worktree-command.js.map +1 -1
- package/src/scripts/commands/review-upsert-pr-command.js +10 -10
- package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/start-update-command.d.ts +1 -1
- package/src/scripts/commands/start-update-command.js +3 -3
- package/src/scripts/commands/start-update-command.js.map +1 -1
- package/src/scripts/commands/start-upsert-pr-command.js +4 -4
- package/src/scripts/commands/start-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/sync-main-command.js +6 -6
- package/src/scripts/commands/sync-main-command.js.map +1 -1
- package/src/scripts/commands/upsert-hotfix-pr-command.d.ts +6 -4
- package/src/scripts/commands/upsert-hotfix-pr-command.js +46 -43
- package/src/scripts/commands/upsert-hotfix-pr-command.js.map +1 -1
- package/src/scripts/commands/working-tree-gate.d.ts +4 -1
- package/src/scripts/commands/working-tree-gate.js +14 -11
- package/src/scripts/commands/working-tree-gate.js.map +1 -1
- package/src/scripts/commands/worktree-cleanup.d.ts +4 -4
- package/src/scripts/commands/worktree-cleanup.js +4 -4
- package/src/scripts/commands/worktree-cleanup.js.map +1 -1
- package/src/scripts/commands/write-review-command.js +4 -6
- package/src/scripts/commands/write-review-command.js.map +1 -1
- package/src/scripts/commands/write-review-fixes-command.js +3 -4
- package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
- package/src/scripts/git-finishUpsertPr.js +2 -2
- package/src/scripts/git-finishUpsertPr.js.map +1 -1
- package/src/scripts/git-gatherInfo.js +6 -7
- package/src/scripts/git-gatherInfo.js.map +1 -1
- package/src/scripts/pr-gate-container.d.ts +9 -0
- package/src/scripts/pr-gate-container.js +19 -0
- package/src/scripts/pr-gate-container.js.map +1 -0
- package/src/scripts/workflow/await-loop.d.ts +1 -1
- package/src/scripts/workflow/await-loop.js +1 -1
- package/src/scripts/workflow/await-loop.js.map +1 -1
- package/src/scripts/workflow/build-affected.js +1 -1
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/build-artifact-gate.d.ts +1 -1
- package/src/scripts/workflow/build-artifact-gate.js +3 -3
- package/src/scripts/workflow/build-artifact-gate.js.map +1 -1
- package/src/scripts/workflow/build-gate-log.d.ts +9 -6
- package/src/scripts/workflow/build-gate-log.js +34 -40
- package/src/scripts/workflow/build-gate-log.js.map +1 -1
- package/src/scripts/workflow/checklist-detector.d.ts +2 -2
- package/src/scripts/workflow/checklist-detector.js +4 -4
- package/src/scripts/workflow/checklist-detector.js.map +1 -1
- package/src/scripts/workflow/checklist-scanner.d.ts +1 -1
- package/src/scripts/workflow/checklist-scanner.js +11 -11
- package/src/scripts/workflow/checklist-scanner.js.map +1 -1
- package/src/scripts/workflow/checklist-scope-hasher.d.ts +1 -1
- package/src/scripts/workflow/checklist-scope-hasher.js +2 -2
- package/src/scripts/workflow/checklist-scope-hasher.js.map +1 -1
- package/src/scripts/workflow/dev-deploy-refs.d.ts +5 -5
- package/src/scripts/workflow/dev-deploy-refs.js +8 -8
- package/src/scripts/workflow/dev-deploy-refs.js.map +1 -1
- package/src/scripts/workflow/dev-resolve-runner.d.ts +3 -3
- package/src/scripts/workflow/dev-resolve-runner.js +30 -30
- package/src/scripts/workflow/dev-resolve-runner.js.map +1 -1
- package/src/scripts/workflow/diff-basis.d.ts +4 -2
- package/src/scripts/workflow/diff-basis.js +18 -15
- package/src/scripts/workflow/diff-basis.js.map +1 -1
- package/src/scripts/workflow/diff-materializer.d.ts +5 -3
- package/src/scripts/workflow/diff-materializer.js +18 -15
- package/src/scripts/workflow/diff-materializer.js.map +1 -1
- package/src/scripts/workflow/gated-pr-publisher.d.ts +8 -6
- package/src/scripts/workflow/gated-pr-publisher.js +23 -22
- package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/generated-artifact-registry.d.ts +4 -2
- package/src/scripts/workflow/generated-artifact-registry.js +11 -8
- package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
- package/src/scripts/workflow/git-exec.d.ts +22 -12
- package/src/scripts/workflow/git-exec.js +45 -29
- package/src/scripts/workflow/git-exec.js.map +1 -1
- package/src/scripts/workflow/git-findForkPoint.d.ts +6 -2
- package/src/scripts/workflow/git-findForkPoint.js +31 -23
- package/src/scripts/workflow/git-findForkPoint.js.map +1 -1
- package/src/scripts/workflow/git-readAiBranchName.d.ts +4 -2
- package/src/scripts/workflow/git-readAiBranchName.js +8 -5
- package/src/scripts/workflow/git-readAiBranchName.js.map +1 -1
- package/src/scripts/workflow/hotfix-pr-publisher.d.ts +4 -3
- package/src/scripts/workflow/hotfix-pr-publisher.js +7 -6
- package/src/scripts/workflow/hotfix-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/landed-tree-resolver.d.ts +4 -2
- package/src/scripts/workflow/landed-tree-resolver.js +11 -8
- package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
- package/src/scripts/workflow/landed-worktree-reaper.d.ts +4 -2
- package/src/scripts/workflow/landed-worktree-reaper.js +12 -9
- package/src/scripts/workflow/landed-worktree-reaper.js.map +1 -1
- package/src/scripts/workflow/merge-end.d.ts +5 -4
- package/src/scripts/workflow/merge-end.js +28 -27
- package/src/scripts/workflow/merge-end.js.map +1 -1
- package/src/scripts/workflow/merge-start.d.ts +5 -1
- package/src/scripts/workflow/merge-start.js +56 -49
- package/src/scripts/workflow/merge-start.js.map +1 -1
- package/src/scripts/workflow/open-pr-check.d.ts +4 -2
- package/src/scripts/workflow/open-pr-check.js +11 -8
- package/src/scripts/workflow/open-pr-check.js.map +1 -1
- package/src/scripts/workflow/pr-comment-upserter.d.ts +5 -3
- package/src/scripts/workflow/pr-comment-upserter.js +15 -14
- package/src/scripts/workflow/pr-comment-upserter.js.map +1 -1
- package/src/scripts/workflow/pr-context-writer.d.ts +1 -1
- package/src/scripts/workflow/pr-context-writer.js +3 -3
- package/src/scripts/workflow/pr-context-writer.js.map +1 -1
- package/src/scripts/workflow/pr-merger.d.ts +8 -5
- package/src/scripts/workflow/pr-merger.js +32 -27
- package/src/scripts/workflow/pr-merger.js.map +1 -1
- package/src/scripts/workflow/provenance-enforcer.d.ts +4 -2
- package/src/scripts/workflow/provenance-enforcer.js +19 -17
- package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
- package/src/scripts/workflow/review-round-state.d.ts +7 -6
- package/src/scripts/workflow/review-round-state.js +33 -38
- package/src/scripts/workflow/review-round-state.js.map +1 -1
- package/src/scripts/workflow/run-update.js +1 -1
- package/src/scripts/workflow/run-update.js.map +1 -1
- package/src/scripts/workflow/squash-settings-enforcer.d.ts +6 -3
- package/src/scripts/workflow/squash-settings-enforcer.js +19 -14
- package/src/scripts/workflow/squash-settings-enforcer.js.map +1 -1
- package/src/scripts/wp-await-checks.js +2 -2
- package/src/scripts/wp-await-checks.js.map +1 -1
- package/src/scripts/wp-await-reviews.js +2 -2
- package/src/scripts/wp-await-reviews.js.map +1 -1
- package/src/scripts/wp-build.js +2 -2
- package/src/scripts/wp-build.js.map +1 -1
- package/src/scripts/wp-check-pr.js +2 -2
- package/src/scripts/wp-check-pr.js.map +1 -1
- package/src/scripts/wp-cleanup.js +2 -2
- package/src/scripts/wp-cleanup.js.map +1 -1
- package/src/scripts/wp-finish-push-dev.js +2 -2
- package/src/scripts/wp-finish-push-dev.js.map +1 -1
- package/src/scripts/wp-finish-update.js +2 -2
- package/src/scripts/wp-finish-update.js.map +1 -1
- package/src/scripts/wp-human-post-pr.js +2 -2
- package/src/scripts/wp-human-post-pr.js.map +1 -1
- package/src/scripts/wp-land-pr.js +2 -2
- package/src/scripts/wp-land-pr.js.map +1 -1
- package/src/scripts/wp-push-dev.js +2 -2
- package/src/scripts/wp-push-dev.js.map +1 -1
- package/src/scripts/wp-reap-worktree.js +2 -2
- package/src/scripts/wp-reap-worktree.js.map +1 -1
- package/src/scripts/wp-review-upsert-pr.js +2 -2
- package/src/scripts/wp-review-upsert-pr.js.map +1 -1
- package/src/scripts/wp-start-update.js +2 -2
- package/src/scripts/wp-start-update.js.map +1 -1
- package/src/scripts/wp-start-upsert-pr.js +2 -2
- package/src/scripts/wp-start-upsert-pr.js.map +1 -1
- package/src/scripts/wp-sync-main.js +2 -2
- package/src/scripts/wp-sync-main.js.map +1 -1
- package/src/scripts/wp-upsert-hotfix-pr.js +2 -2
- package/src/scripts/wp-upsert-hotfix-pr.js.map +1 -1
- package/src/scripts/wp-write-review-fixes.js +2 -2
- package/src/scripts/wp-write-review-fixes.js.map +1 -1
- package/src/scripts/wp-write-review.js +2 -2
- package/src/scripts/wp-write-review.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/pr-gate",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.977",
|
|
4
4
|
"description": "Gated PR system: 3-point squash-merge, merge validation gate, and red/yellow/green PR dashboard. Standalone scripts, no Nx dependency required.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -16,18 +16,18 @@
|
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@inversifyjs/binding-decorators": "1.1.5",
|
|
19
|
-
"@webpieces/hook-runtime": "0.4.
|
|
20
|
-
"@webpieces/rules-config": "0.4.
|
|
19
|
+
"@webpieces/hook-runtime": "0.4.977",
|
|
20
|
+
"@webpieces/rules-config": "0.4.977",
|
|
21
21
|
"inversify": "7.10.4",
|
|
22
22
|
"reflect-metadata": "0.2.2",
|
|
23
|
-
"@webpieces/tooling-common": "0.4.
|
|
24
|
-
"@webpieces/repo-workflow-core": "0.4.
|
|
23
|
+
"@webpieces/tooling-common": "0.4.977",
|
|
24
|
+
"@webpieces/repo-workflow-core": "0.4.977"
|
|
25
25
|
},
|
|
26
26
|
"publishConfig": {
|
|
27
27
|
"access": "public"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@webpieces/tooling-testkit": "0.4.
|
|
30
|
+
"@webpieces/tooling-testkit": "0.4.977"
|
|
31
31
|
},
|
|
32
32
|
"types": "./src/index.d.ts",
|
|
33
33
|
"bin": {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { NativeProcessApi } from '@webpieces/tooling-common';
|
|
1
2
|
import { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';
|
|
2
3
|
import { StageOutputLog } from '../workflow/stage-output-log';
|
|
3
4
|
/** What `wp-await-checks` was asked to wait on. Data-only (a class, per CLAUDE.md). */
|
|
@@ -42,7 +43,8 @@ export declare class AwaitChecksOptions {
|
|
|
42
43
|
export declare class AwaitChecksCommand {
|
|
43
44
|
private readonly awaitLoop;
|
|
44
45
|
private readonly stageConsole;
|
|
45
|
-
|
|
46
|
+
private readonly processes;
|
|
47
|
+
constructor(awaitLoop: AwaitLoop, stageConsole: StageOutputLog, processes: NativeProcessApi);
|
|
46
48
|
run(opts: AwaitChecksOptions): Promise<void>;
|
|
47
49
|
}
|
|
48
50
|
/** One check run's rollup state, as GitHub reports it. Data-only. */
|
|
@@ -75,11 +77,12 @@ export declare class ChecksState {
|
|
|
75
77
|
*/
|
|
76
78
|
export declare class ChecksWaitProbe implements WaitProbe {
|
|
77
79
|
private readonly prNumber;
|
|
80
|
+
private readonly processes;
|
|
78
81
|
readonly label = "CI checks";
|
|
79
82
|
readonly pollMs = 15000;
|
|
80
83
|
private state;
|
|
81
|
-
constructor(prNumber: string);
|
|
82
|
-
done(): boolean
|
|
84
|
+
constructor(prNumber: string, processes: NativeProcessApi);
|
|
85
|
+
done(): Promise<boolean>;
|
|
83
86
|
describe(): string;
|
|
84
87
|
settledReport(outcome: WaitOutcome): string;
|
|
85
88
|
stillWaitingReport(outcome: WaitOutcome): string;
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.AwaitChecksArgs = exports.ChecksWaitProbe = exports.ChecksState = exports.AwaitChecksCommand = exports.AwaitChecksOptions = 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 await_loop_1 = require("../workflow/await-loop");
|
|
9
9
|
const stage_output_log_1 = require("../workflow/stage-output-log");
|
|
@@ -55,12 +55,14 @@ exports.AwaitChecksOptions = AwaitChecksOptions;
|
|
|
55
55
|
let AwaitChecksCommand = class AwaitChecksCommand {
|
|
56
56
|
awaitLoop;
|
|
57
57
|
stageConsole;
|
|
58
|
-
|
|
58
|
+
processes;
|
|
59
|
+
constructor(awaitLoop, stageConsole, processes) {
|
|
59
60
|
this.awaitLoop = awaitLoop;
|
|
60
61
|
this.stageConsole = stageConsole;
|
|
62
|
+
this.processes = processes;
|
|
61
63
|
}
|
|
62
64
|
async run(opts) {
|
|
63
|
-
const probe = new ChecksWaitProbe(opts.prNumber);
|
|
65
|
+
const probe = new ChecksWaitProbe(opts.prNumber, this.processes);
|
|
64
66
|
const outcome = await this.awaitLoop.run(probe);
|
|
65
67
|
this.stageConsole.say(outcome.done ? probe.settledReport(outcome) : probe.stillWaitingReport(outcome));
|
|
66
68
|
}
|
|
@@ -69,7 +71,8 @@ exports.AwaitChecksCommand = AwaitChecksCommand;
|
|
|
69
71
|
exports.AwaitChecksCommand = AwaitChecksCommand = tslib_1.__decorate([
|
|
70
72
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
71
73
|
tslib_1.__metadata("design:paramtypes", [await_loop_1.AwaitLoop,
|
|
72
|
-
stage_output_log_1.StageOutputLog
|
|
74
|
+
stage_output_log_1.StageOutputLog,
|
|
75
|
+
tooling_common_1.NativeProcessApi])
|
|
73
76
|
], AwaitChecksCommand);
|
|
74
77
|
/** One check run's rollup state, as GitHub reports it. Data-only. */
|
|
75
78
|
class ChecksState {
|
|
@@ -117,16 +120,18 @@ exports.ChecksState = ChecksState;
|
|
|
117
120
|
*/
|
|
118
121
|
class ChecksWaitProbe {
|
|
119
122
|
prNumber;
|
|
123
|
+
processes;
|
|
120
124
|
label = 'CI checks';
|
|
121
125
|
// A network round trip per poll, so this is deliberately slow. CI on this repo runs ~1 minute; a
|
|
122
126
|
// 15-second poll finds it within a heartbeat of finishing and costs ~36 API calls per full wait.
|
|
123
127
|
pollMs = 15_000;
|
|
124
128
|
state = new ChecksState(0, 0, 0, true);
|
|
125
|
-
constructor(prNumber) {
|
|
129
|
+
constructor(prNumber, processes) {
|
|
126
130
|
this.prNumber = prNumber;
|
|
131
|
+
this.processes = processes;
|
|
127
132
|
}
|
|
128
|
-
done() {
|
|
129
|
-
this.state = this.read();
|
|
133
|
+
async done() {
|
|
134
|
+
this.state = await this.read();
|
|
130
135
|
return this.state.settled;
|
|
131
136
|
}
|
|
132
137
|
describe() {
|
|
@@ -149,12 +154,12 @@ class ChecksWaitProbe {
|
|
|
149
154
|
* must never be able to end the wait, because the only thing worse than waiting too long is
|
|
150
155
|
* announcing an outcome nobody observed.
|
|
151
156
|
*/
|
|
152
|
-
read() {
|
|
153
|
-
const result =
|
|
154
|
-
'--jq', '[.statusCheckRollup[] | (.status // .state)] | @tsv']
|
|
155
|
-
if (result.
|
|
157
|
+
async read() {
|
|
158
|
+
const result = await this.processes.run('gh', ['pr', 'view', this.prNumber, '--json', 'statusCheckRollup',
|
|
159
|
+
'--jq', '[.statusCheckRollup[] | (.status // .state)] | @tsv']);
|
|
160
|
+
if (!result.ok)
|
|
156
161
|
return new ChecksState(0, 0, 0, true);
|
|
157
|
-
return this.classify(
|
|
162
|
+
return this.classify(result.stdout.trim());
|
|
158
163
|
}
|
|
159
164
|
// `status` is COMPLETED / IN_PROGRESS / QUEUED for a check run; a plain commit status has no
|
|
160
165
|
// `status` and its `state` is SUCCESS / PENDING / FAILURE / ERROR. The jq above collapses the two
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"await-checks-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-checks-command.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAE3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AC,KAAK,CAAC,KAAK,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QACpF,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAClF,OAAO,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;CACJ;AAzDD,0CAyDC;AAED,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC;AAClH,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,CAAC,CAAC;AAEzI;;;GAGG;AACH,MAAa,eAAe;IACxB,2EAA2E;IAC3E,KAAK,CAAC,KAAa;QACf,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,2BAAY,CAAC,CAAC,EACpB,oFAAoF;kBAClF,iEAAiE,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,IAAI,kBAAkB,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;CACJ;AAVD,0CAUC","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/** What `wp-await-checks` was asked to wait on. Data-only (a class, per CLAUDE.md). */\nexport class AwaitChecksOptions {\n /** The PR number, exactly as `--pr` gave it. REQUIRED — there is no \"guess which PR\" branch. */\n prNumber: string;\n\n // REQUIRED, no default. A defaulted \"current branch's PR\" would be a second spelling of the one\n // question this command asks, reachable by typing less, and the failure mode is watching the wrong\n // PR go green.\n constructor(prNumber: string) {\n this.prNumber = prNumber;\n }\n}\n\n/**\n * `wp-await-checks --pr <n>` — BLOCK until GitHub's checks for that PR stop being in flight, then print\n * where they landed.\n *\n * ─── OFFERED, NEVER INSTRUCTED ─────────────────────────────────────────────────────────────────────\n * This exists for the see-it-land case, and for nothing else. `wp-finish-upsert-pr` still ends with\n * \"Nothing else is owed by the tooling — a person merges it. You can stop here.\", and that stays the\n * DEFAULT: several of this repo's workflows deliberately stop at a green PR, and landing is the\n * developer's call, not the tooling's. Nothing here or in the finish banner tells an agent to wait —\n * the banner names this command as an option and says out loud that stopping is still correct.\n *\n * What it replaces is the `echo .` keep-alive an agent falls back to when it has decided to see the PR\n * land. See {@link AwaitLoop} for when a blocking command is the right wait at all — this is offered as\n * the efficient alternative to polling, and nothing here rules on turn-level behaviour (issue #902).\n *\n * ─── `gh pr checks <n> --watch` EXISTS, AND WHEN TO REACH FOR EACH ─────────────────────────────────\n * It is a real blocking wait, not a spin, and `wait-spin-guard` never denies it — 224 subagent and 84\n * main-agent uses in the measured window. So this command does not pretend it is absent, and it is not\n * a replacement for it. The difference is one property and it decides the choice:\n *\n * `gh pr checks <n> --watch` has NO BOUNDED EXIT. On a CI run longer than the harness's 600s\n * silence ceiling it is KILLED having printed nothing, and the wait is\n * simply lost. Right for a short, known-fast run you are watching.\n * `pnpm wp-await-checks` heartbeats throughout and RETURNS CLEANLY at 540s saying \"run me\n * again\", so a 100-minute wait costs ~11 calls instead of a killed\n * command and a restart. Right for any wait that might outlast the\n * ceiling, which is any wait you cannot bound in advance.\n *\n * ─── It reports, it does not judge ─────────────────────────────────────────────────────────────────\n * A red check is an ANSWER, so the wait ends and the state is printed. Deciding what a failure means is\n * the caller's, and turning a red check into a non-zero exit here would make \"the checks finished\" and\n * \"the checks passed\" the same signal — which is exactly how a red PR gets reported as landed.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitChecksCommand {\n constructor(\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n async run(opts: AwaitChecksOptions): Promise<void> {\n const probe = new ChecksWaitProbe(opts.prNumber);\n const outcome = await this.awaitLoop.run(probe);\n this.stageConsole.say(outcome.done ? probe.settledReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/** One check run's rollup state, as GitHub reports it. Data-only. */\nexport class ChecksState {\n /** How many checks GitHub currently lists. 0 means it has not created any yet — QUEUED, not absent. */\n total: number;\n pending: number;\n failed: number;\n /** True when `gh` could not be asked at all — the wait keeps going rather than claiming an answer. */\n unreadable: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(total: number, pending: number, failed: number, unreadable: boolean) {\n this.total = total;\n this.pending = pending;\n this.failed = failed;\n this.unreadable = unreadable;\n }\n\n /**\n * Settled means GitHub has created checks AND none of them is still running.\n *\n * `total === 0` is deliberately NOT settled. An empty rollup seconds after a push means the workflow\n * has not been created yet — QUEUED — and treating it as \"no checks, all clear\" is how a PR gets\n * called green before CI has started. The wait's own ceiling is what ends that case, and it ends it\n * by saying \"still waiting\", which is the truth.\n */\n get settled(): boolean {\n return !this.unreadable && this.total > 0 && this.pending === 0;\n }\n\n describe(): string {\n if (this.unreadable) return 'gh could not be read';\n if (this.total === 0) return 'no checks reported yet (queued)';\n return `${String(this.total - this.pending)} of ${String(this.total)} done, `\n + `${String(this.failed)} failed`;\n }\n}\n\n/**\n * The CI wait: one `gh pr view` per poll, classified into {@link ChecksState}.\n *\n * `gh pr view --json statusCheckRollup` rather than `gh pr checks`, because the rollup field is the\n * stable JSON surface and returns an EMPTY array — not an error exit — for a PR whose checks have not\n * been created yet. `gh pr checks` exits non-zero in several distinct \"nothing to report\" situations,\n * which would make \"queued\" and \"gh is broken\" the same observation.\n */\nexport class ChecksWaitProbe implements WaitProbe {\n readonly label = 'CI checks';\n // A network round trip per poll, so this is deliberately slow. CI on this repo runs ~1 minute; a\n // 15-second poll finds it within a heartbeat of finishing and costs ~36 API calls per full wait.\n readonly pollMs = 15_000;\n\n private state: ChecksState = new ChecksState(0, 0, 0, true);\n\n constructor(private readonly prNumber: string) {}\n\n done(): boolean {\n this.state = this.read();\n return this.state.settled;\n }\n\n describe(): string {\n return this.state.describe();\n }\n\n settledReport(outcome: WaitOutcome): string {\n const verdict = this.state.failed === 0\n ? `🟢 All ${String(this.state.total)} check(s) passed`\n : `🔴 ${String(this.state.failed)} of ${String(this.state.total)} check(s) FAILED`;\n return `\\n${verdict} after ${String(outcome.waitedSeconds)}s.\\n`\n + ` Read the detail with: gh pr checks ${this.prNumber}\\n`;\n }\n\n stillWaitingReport(outcome: WaitOutcome): string {\n return `\\n⏳ Checks are still in flight after ${String(outcome.waitedSeconds)}s (${this.state.describe()})`\n + ` — run me again: pnpm wp-await-checks --pr ${this.prNumber}\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command.)\\n';\n }\n\n /**\n * One read of the rollup. Fails to `unreadable` rather than to \"settled\": a `gh` that cannot answer\n * must never be able to end the wait, because the only thing worse than waiting too long is\n * announcing an outcome nobody observed.\n */\n private read(): ChecksState {\n const result = spawnSync(\n 'gh',\n ['pr', 'view', this.prNumber, '--json', 'statusCheckRollup',\n '--jq', '[.statusCheckRollup[] | (.status // .state)] | @tsv'],\n { encoding: 'utf8' });\n if (result.status !== 0) return new ChecksState(0, 0, 0, true);\n return this.classify((result.stdout ?? '').trim());\n }\n\n // `status` is COMPLETED / IN_PROGRESS / QUEUED for a check run; a plain commit status has no\n // `status` and its `state` is SUCCESS / PENDING / FAILURE / ERROR. The jq above collapses the two\n // into one token per check, and everything that is not finished counts as pending.\n private classify(tsv: string): ChecksState {\n const tokens = tsv === '' ? [] : tsv.split(/\\s+/);\n const pending = tokens.filter((t: string): boolean => PENDING_TOKENS.has(t)).length;\n const failed = tokens.filter((t: string): boolean => FAILED_TOKENS.has(t)).length;\n return new ChecksState(tokens.length, pending, failed, false);\n }\n}\n\nconst PENDING_TOKENS: ReadonlySet<string> = new Set(['QUEUED', 'IN_PROGRESS', 'PENDING', 'WAITING', 'REQUESTED']);\nconst FAILED_TOKENS: ReadonlySet<string> = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE']);\n\n/**\n * `--pr` is required, and this is where that is enforced — before the loop starts, so a caller that\n * forgot it is told immediately rather than after a nine-minute wait on nothing.\n */\nexport class AwaitChecksArgs {\n /** The PR number from argv, or a CliExitError naming the flag it needs. */\n parse(value: string): AwaitChecksOptions {\n if (!/^\\d+$/.test(value.trim())) {\n throw new CliExitError(2,\n '❌ wp-await-checks needs the PR number to wait on: pnpm wp-await-checks --pr <n>\\n'\n + ' `gh pr view --json number` prints it for the current branch.');\n }\n return new AwaitChecksOptions(value.trim());\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"await-checks-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-checks-command.ts"],"names":[],"mappings":";;;;AAAA,0DAAuD;AACvD,8DAA6D;AAC7D,yCAA2D;AAE3D,uDAA2E;AAC3E,mEAA8D;AAE9D,uFAAuF;AACvF,MAAa,kBAAkB;IAC3B,gGAAgG;IAChG,QAAQ,CAAS;IAEjB,gGAAgG;IAChG,mGAAmG;IACnG,eAAe;IACf,YAAY,QAAgB;QACxB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAVD,gDAUC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAEN;IACA;IACA;IAHrB,YACqB,SAAoB,EACpB,YAA4B,EAC5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AAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAClF,OAAO,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;CACJ;AA3DD,0CA2DC;AAED,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC;AAClH,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,iBAAiB,EAAE,iBAAiB,CAAC,CAAC,CAAC;AAEzI;;;GAGG;AACH,MAAa,eAAe;IACxB,2EAA2E;IAC3E,KAAK,CAAC,KAAa;QACf,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,2BAAY,CAAC,CAAC,EACpB,oFAAoF;kBAClF,iEAAiE,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,IAAI,kBAAkB,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;CACJ;AAVD,0CAUC","sourcesContent":["import { CliExitError } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/** What `wp-await-checks` was asked to wait on. Data-only (a class, per CLAUDE.md). */\nexport class AwaitChecksOptions {\n /** The PR number, exactly as `--pr` gave it. REQUIRED — there is no \"guess which PR\" branch. */\n prNumber: string;\n\n // REQUIRED, no default. A defaulted \"current branch's PR\" would be a second spelling of the one\n // question this command asks, reachable by typing less, and the failure mode is watching the wrong\n // PR go green.\n constructor(prNumber: string) {\n this.prNumber = prNumber;\n }\n}\n\n/**\n * `wp-await-checks --pr <n>` — BLOCK until GitHub's checks for that PR stop being in flight, then print\n * where they landed.\n *\n * ─── OFFERED, NEVER INSTRUCTED ─────────────────────────────────────────────────────────────────────\n * This exists for the see-it-land case, and for nothing else. `wp-finish-upsert-pr` still ends with\n * \"Nothing else is owed by the tooling — a person merges it. You can stop here.\", and that stays the\n * DEFAULT: several of this repo's workflows deliberately stop at a green PR, and landing is the\n * developer's call, not the tooling's. Nothing here or in the finish banner tells an agent to wait —\n * the banner names this command as an option and says out loud that stopping is still correct.\n *\n * What it replaces is the `echo .` keep-alive an agent falls back to when it has decided to see the PR\n * land. See {@link AwaitLoop} for when a blocking command is the right wait at all — this is offered as\n * the efficient alternative to polling, and nothing here rules on turn-level behaviour (issue #902).\n *\n * ─── `gh pr checks <n> --watch` EXISTS, AND WHEN TO REACH FOR EACH ─────────────────────────────────\n * It is a real blocking wait, not a spin, and `wait-spin-guard` never denies it — 224 subagent and 84\n * main-agent uses in the measured window. So this command does not pretend it is absent, and it is not\n * a replacement for it. The difference is one property and it decides the choice:\n *\n * `gh pr checks <n> --watch` has NO BOUNDED EXIT. On a CI run longer than the harness's 600s\n * silence ceiling it is KILLED having printed nothing, and the wait is\n * simply lost. Right for a short, known-fast run you are watching.\n * `pnpm wp-await-checks` heartbeats throughout and RETURNS CLEANLY at 540s saying \"run me\n * again\", so a 100-minute wait costs ~11 calls instead of a killed\n * command and a restart. Right for any wait that might outlast the\n * ceiling, which is any wait you cannot bound in advance.\n *\n * ─── It reports, it does not judge ─────────────────────────────────────────────────────────────────\n * A red check is an ANSWER, so the wait ends and the state is printed. Deciding what a failure means is\n * the caller's, and turning a red check into a non-zero exit here would make \"the checks finished\" and\n * \"the checks passed\" the same signal — which is exactly how a red PR gets reported as landed.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitChecksCommand {\n constructor(\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async run(opts: AwaitChecksOptions): Promise<void> {\n const probe = new ChecksWaitProbe(opts.prNumber, this.processes);\n const outcome = await this.awaitLoop.run(probe);\n this.stageConsole.say(outcome.done ? probe.settledReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/** One check run's rollup state, as GitHub reports it. Data-only. */\nexport class ChecksState {\n /** How many checks GitHub currently lists. 0 means it has not created any yet — QUEUED, not absent. */\n total: number;\n pending: number;\n failed: number;\n /** True when `gh` could not be asked at all — the wait keeps going rather than claiming an answer. */\n unreadable: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(total: number, pending: number, failed: number, unreadable: boolean) {\n this.total = total;\n this.pending = pending;\n this.failed = failed;\n this.unreadable = unreadable;\n }\n\n /**\n * Settled means GitHub has created checks AND none of them is still running.\n *\n * `total === 0` is deliberately NOT settled. An empty rollup seconds after a push means the workflow\n * has not been created yet — QUEUED — and treating it as \"no checks, all clear\" is how a PR gets\n * called green before CI has started. The wait's own ceiling is what ends that case, and it ends it\n * by saying \"still waiting\", which is the truth.\n */\n get settled(): boolean {\n return !this.unreadable && this.total > 0 && this.pending === 0;\n }\n\n describe(): string {\n if (this.unreadable) return 'gh could not be read';\n if (this.total === 0) return 'no checks reported yet (queued)';\n return `${String(this.total - this.pending)} of ${String(this.total)} done, `\n + `${String(this.failed)} failed`;\n }\n}\n\n/**\n * The CI wait: one `gh pr view` per poll, classified into {@link ChecksState}.\n *\n * `gh pr view --json statusCheckRollup` rather than `gh pr checks`, because the rollup field is the\n * stable JSON surface and returns an EMPTY array — not an error exit — for a PR whose checks have not\n * been created yet. `gh pr checks` exits non-zero in several distinct \"nothing to report\" situations,\n * which would make \"queued\" and \"gh is broken\" the same observation.\n */\nexport class ChecksWaitProbe implements WaitProbe {\n readonly label = 'CI checks';\n // A network round trip per poll, so this is deliberately slow. CI on this repo runs ~1 minute; a\n // 15-second poll finds it within a heartbeat of finishing and costs ~36 API calls per full wait.\n readonly pollMs = 15_000;\n\n private state: ChecksState = new ChecksState(0, 0, 0, true);\n\n constructor(\n private readonly prNumber: string,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async done(): Promise<boolean> {\n this.state = await this.read();\n return this.state.settled;\n }\n\n describe(): string {\n return this.state.describe();\n }\n\n settledReport(outcome: WaitOutcome): string {\n const verdict = this.state.failed === 0\n ? `🟢 All ${String(this.state.total)} check(s) passed`\n : `🔴 ${String(this.state.failed)} of ${String(this.state.total)} check(s) FAILED`;\n return `\\n${verdict} after ${String(outcome.waitedSeconds)}s.\\n`\n + ` Read the detail with: gh pr checks ${this.prNumber}\\n`;\n }\n\n stillWaitingReport(outcome: WaitOutcome): string {\n return `\\n⏳ Checks are still in flight after ${String(outcome.waitedSeconds)}s (${this.state.describe()})`\n + ` — run me again: pnpm wp-await-checks --pr ${this.prNumber}\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command.)\\n';\n }\n\n /**\n * One read of the rollup. Fails to `unreadable` rather than to \"settled\": a `gh` that cannot answer\n * must never be able to end the wait, because the only thing worse than waiting too long is\n * announcing an outcome nobody observed.\n */\n private async read(): Promise<ChecksState> {\n const result = await this.processes.run(\n 'gh',\n ['pr', 'view', this.prNumber, '--json', 'statusCheckRollup',\n '--jq', '[.statusCheckRollup[] | (.status // .state)] | @tsv']);\n if (!result.ok) return new ChecksState(0, 0, 0, true);\n return this.classify(result.stdout.trim());\n }\n\n // `status` is COMPLETED / IN_PROGRESS / QUEUED for a check run; a plain commit status has no\n // `status` and its `state` is SUCCESS / PENDING / FAILURE / ERROR. The jq above collapses the two\n // into one token per check, and everything that is not finished counts as pending.\n private classify(tsv: string): ChecksState {\n const tokens = tsv === '' ? [] : tsv.split(/\\s+/);\n const pending = tokens.filter((t: string): boolean => PENDING_TOKENS.has(t)).length;\n const failed = tokens.filter((t: string): boolean => FAILED_TOKENS.has(t)).length;\n return new ChecksState(tokens.length, pending, failed, false);\n }\n}\n\nconst PENDING_TOKENS: ReadonlySet<string> = new Set(['QUEUED', 'IN_PROGRESS', 'PENDING', 'WAITING', 'REQUESTED']);\nconst FAILED_TOKENS: ReadonlySet<string> = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE']);\n\n/**\n * `--pr` is required, and this is where that is enforced — before the loop starts, so a caller that\n * forgot it is told immediately rather than after a nine-minute wait on nothing.\n */\nexport class AwaitChecksArgs {\n /** The PR number from argv, or a CliExitError naming the flag it needs. */\n parse(value: string): AwaitChecksOptions {\n if (!/^\\d+$/.test(value.trim())) {\n throw new CliExitError(2,\n '❌ wp-await-checks needs the PR number to wait on: pnpm wp-await-checks --pr <n>\\n'\n + ' `gh pr view --json number` prints it for the current branch.');\n }\n return new AwaitChecksOptions(value.trim());\n }\n}\n"]}
|
|
@@ -72,7 +72,7 @@ export declare class ReviewerWaitProbe implements WaitProbe {
|
|
|
72
72
|
* `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX
|
|
73
73
|
* (four characters of JSON), not a thing to wait longer for.
|
|
74
74
|
*/
|
|
75
|
-
done(): boolean
|
|
75
|
+
done(): Promise<boolean>;
|
|
76
76
|
describe(): string;
|
|
77
77
|
/** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */
|
|
78
78
|
verdictReport(outcome: WaitOutcome): string;
|
|
@@ -58,7 +58,7 @@ let AwaitReviewsCommand = class AwaitReviewsCommand {
|
|
|
58
58
|
// contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review
|
|
59
59
|
// was briefed against, and rewriting it mid-review would restate the briefing under the
|
|
60
60
|
// reviewers currently reading it.
|
|
61
|
-
const scan = this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(config.maxReviewerRounds, true, ''));
|
|
61
|
+
const scan = await this.checklistScanner.scan(repoRoot, config.checklists, new checklist_scanner_1.ChecklistScanOptions(config.maxReviewerRounds, true, ''));
|
|
62
62
|
if (scan.reviewersDisabled)
|
|
63
63
|
return this.reportDisabled(scan.suppressed);
|
|
64
64
|
if (scan.applicable.length === 0)
|
|
@@ -70,7 +70,7 @@ let AwaitReviewsCommand = class AwaitReviewsCommand {
|
|
|
70
70
|
// the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)
|
|
71
71
|
// A verdict from an EARLIER round than the one stage ② last briefed is NOT an arrival: it is the red
|
|
72
72
|
// that round re-briefed (issue #1053), and counting it would end the wait on the spot.
|
|
73
|
-
const round = this.receipts.read(repoRoot, this.aiBranchName.getFeatureName())?.round ?? 0;
|
|
73
|
+
const round = this.receipts.read(repoRoot, await this.aiBranchName.getFeatureName())?.round ?? 0;
|
|
74
74
|
const probe = new ReviewerWaitProbe(this.reviewJsonService, scan.summaryPath, scan.outstanding, scan.applicable, round);
|
|
75
75
|
const outcome = await this.awaitLoop.run(probe);
|
|
76
76
|
this.report(probe, outcome);
|
|
@@ -139,7 +139,7 @@ class ReviewerWaitProbe {
|
|
|
139
139
|
* `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX
|
|
140
140
|
* (four characters of JSON), not a thing to wait longer for.
|
|
141
141
|
*/
|
|
142
|
-
done() {
|
|
142
|
+
async done() {
|
|
143
143
|
this.reload();
|
|
144
144
|
return this.pending().length === 0;
|
|
145
145
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"await-reviews-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-reviews-command.ts"],"names":[],"mappings":";;;;AAAA,0DAGiC;AACjC,yCAA2D;AAE3D,uDAA2E;AAC3E,qEAAuF;AACvF,2EAAgE;AAChE,2EAA6E;AAC7E,mEAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IACA;IACA;IACA;IACA;IACA;IAPrB,YACqB,cAA8B,EAC9B,gBAAkC,EAClC,iBAAoC,EACpC,SAAoB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CAAC,WAAW,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClG,CAAC;CACJ;AAxHD,8CAwHC","sourcesContent":["import {\n ChecklistResult, ChecklistVerdict, CK_FAIL, CK_MISSING, CK_BAD_FORMAT, CK_ORANGE, loadAndValidate,\n RepoRootFinder, RequiredChecklist, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/**\n * `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its\n * verdict, then print what each one said.\n *\n * ─── Why a command and not an instruction ──────────────────────────────────────────────────────────\n * An agent that has just spawned four reviewer subagents has nothing to do until they answer, and a\n * worktree-isolated subagent cannot simply wait: ending its turn ends its run. See {@link AwaitLoop}\n * for the full chain and the measurement (18.3% of all fleet tokens in one day spent on `echo .`).\n * A blocking Bash call is the only wait primitive it has, so webpieces provides one.\n *\n * ─── It INVENTS NO STATE ───────────────────────────────────────────────────────────────────────────\n * The set of reviewers a branch owes is `ChecklistScanner`'s answer — the SAME one `wp-review-upsert-pr`\n * lists and `wp-finish-upsert-pr` blocks on — and the verdicts are the `review-round<N>-<id>.json` files those\n * two already read. Nothing here writes anything, and there is no third opinion about who is owed: a\n * waiter that computed its own set could finish while finish still refused, which is the one outcome\n * that would make waiting worse than not waiting.\n *\n * The scan runs ONCE. Its `applicable` set is a function of the diff, which does not change while the\n * agent sits still, so re-scanning per poll would re-run `git diff` every few seconds to re-derive an\n * unchanged answer. Only the verdict FILES are re-read, which is the only thing a reviewer changes.\n *\n * ─── What it does NOT do ───────────────────────────────────────────────────────────────────────────\n * It does not judge. A red verdict is a completed review, so this command RETURNS on it and prints it;\n * refusing the PR over it is `wp-finish-upsert-pr`'s job and stays there. It exits non-zero only when it\n * cannot do its own job at all.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitReviewsCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n private readonly receipts: ReviewStageReceiptService,\n private readonly aiBranchName: AiBranchName,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const config = loadAndValidate(repoRoot).prGate;\n // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review\n // was briefed against, and rewriting it mid-review would restate the briefing under the\n // reviewers currently reading it.\n const scan = this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, ''));\n if (scan.reviewersDisabled) return this.reportDisabled(scan.suppressed);\n if (scan.applicable.length === 0) return this.reportNothingOwed();\n // WAIT on the set finish blocks on (`outstanding`), REPORT on everything that applies. The two\n // sets differ by exactly the optional checklists nobody ran — `required: false` means the PR does\n // not wait for them, and a wait that did would never end, because nothing is ever going to write\n // a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;\n // the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)\n // A verdict from an EARLIER round than the one stage ② last briefed is NOT an arrival: it is the red\n // that round re-briefed (issue #1053), and counting it would end the wait on the spot.\n const round = this.receipts.read(repoRoot, this.aiBranchName.getFeatureName())?.round ?? 0;\n const probe = new ReviewerWaitProbe(\n this.reviewJsonService, scan.summaryPath, scan.outstanding, scan.applicable, round);\n const outcome = await this.awaitLoop.run(probe);\n this.report(probe, outcome);\n }\n\n // Nothing to wait for, and saying so is the whole value: an agent that got no answer here would\n // otherwise assume the wait is still owed and start spinning again.\n private reportNothingOwed(): void {\n this.stageConsole.say('\\n✅ No reviewer was requested for this branch — nothing to wait for.\\n');\n }\n\n private reportDisabled(suppressed: readonly RequiredChecklist[]): void {\n this.stageConsole.say(\n `\\n⚫ Every reviewer is switched off on this machine (experimental.turnOffAllReviewers), so `\n + `${String(suppressed.length)} checklist(s) that would have run are not running. There is `\n + 'nothing to wait for.\\n');\n }\n\n private report(probe: ReviewerWaitProbe, outcome: WaitOutcome): void {\n this.stageConsole.say(outcome.done ? probe.verdictReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/**\n * The reviewer wait itself: which checklists are owed, and what the files on disk say about them right\n * now. It owns the reporting too, because every line it prints is derived from the same verdict read —\n * a report that re-read the files could disagree with the answer that ended the wait.\n */\nexport class ReviewerWaitProbe implements WaitProbe {\n readonly label = 'reviewers';\n // Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough\n // that the command returns within seconds of the last reviewer finishing, which is the point.\n readonly pollMs = 3_000;\n\n private results: ChecklistResult[] = [];\n\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly summaryPath: string,\n private readonly waitedOn: readonly RequiredChecklist[],\n private readonly applicable: readonly RequiredChecklist[],\n // The round stage ② last briefed (0 = none): a verdict from an earlier round is not an answer.\n private readonly briefedRound: number,\n ) {\n this.reload();\n }\n\n /**\n * Done when every awaited reviewer has ANSWERED — not when every answer is a pass.\n *\n * That distinction is the whole contract of a wait, and getting it wrong makes the command useless\n * in the case it matters most. `ReviewJsonService.pendingChecklists` is finish's GATE predicate and\n * counts a RED verdict as still owed, correctly: the PR is refused until the finding is fixed. But\n * a red reviewer has finished; it will never write a different answer on its own, so waiting for it\n * to stop being red is waiting forever. The wait therefore ends on ARRIVAL — a verdict file that\n * exists, whatever it says — and `wp-finish-upsert-pr` keeps sole ownership of the gate.\n *\n * `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX\n * (four characters of JSON), not a thing to wait longer for.\n */\n done(): boolean {\n this.reload();\n return this.pending().length === 0;\n }\n\n describe(): string {\n const owed = this.pending().length;\n const total = this.waitedOn.length;\n return `${String(total - owed)} of ${String(total)} verdicts in`;\n }\n\n /** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */\n verdictReport(outcome: WaitOutcome): string {\n // The headline counts what was WAITED ON; the list below covers everything that APPLIES, so an\n // optional checklist nobody ran shows as ❓ rather than being quietly dropped. Reporting only the\n // waited-on set would let a shorter list imply the others passed.\n const lines = [\n `\\n✅ All ${String(this.waitedOn.length)} awaited reviewer verdict(s) are in after `\n + `${String(outcome.waitedSeconds)}s:\\n`,\n ];\n for (const req of this.applicable) lines.push(this.oneVerdict(req));\n lines.push(this.nextStep());\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * The timeout report. It is a NORMAL exit and says so, because an agent that reads this as a failure\n * goes hunting for a broken reviewer instead of running one more plain command.\n */\n stillWaitingReport(outcome: WaitOutcome): string {\n const owed = this.pending();\n return `\\n⏳ Still waiting after ${String(outcome.waitedSeconds)}s — run me again: pnpm wp-await-reviews\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command, so a\\n'\n + ' long review costs a handful of calls instead of hundreds of keep-alive turns.)\\n\\n'\n + ` ${String(owed.length)} of ${String(this.waitedOn.length)} still owe a verdict: `\n + `${owed.map((r: RequiredChecklist): string => r.id).join(', ')}\\n`;\n }\n\n private oneVerdict(req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, this.results);\n return ` ${this.icon(verdict)} ${verdict.id} — ${verdict.status}${this.detail(verdict)}`;\n }\n\n // Only a NON-passing verdict's detail is printed. A green reviewer's output is already on the PR,\n // and reprinting four of them here would bury the one line that needs acting on.\n private detail(verdict: ChecklistVerdict): string {\n if ((verdict.status !== CK_FAIL && verdict.status !== CK_ORANGE) || verdict.detail === '') return '';\n return `\\n ${verdict.detail.split('\\n').join('\\n ')}`;\n }\n\n private icon(verdict: ChecklistVerdict): string {\n if (verdict.status === CK_FAIL) return '🔴';\n if (verdict.status === CK_ORANGE) return '🟠';\n if (verdict.status === CK_MISSING || verdict.status === CK_BAD_FORMAT) return '❓';\n return '🟢';\n }\n\n // Named because a wait that ends without saying what it unblocked leaves the agent to guess, and\n // guessing here means spinning again. A red verdict changes the next move, so it is called out.\n private nextStep(): string {\n const statuses = this.applicable.map((req: RequiredChecklist): string =>\n this.reviewJsonService.resolveVerdict(req, this.results).status);\n if (statuses.includes(CK_FAIL)) {\n return '\\n A reviewer REFUSED. Fix what it found — re-spawning it against unchanged code buys the\\n'\n + ' same answer — then re-run the review stage.\\n';\n }\n if (statuses.includes(CK_ORANGE)) {\n return '\\n A final-round reviewer marked ORANGE. Fix what it found, best effort, commit, and record the\\n'\n + ' fixes with pnpm wp-write-review-fixes. Do NOT spawn a reviewer: that was the last review round.\\n';\n }\n return '\\n Nothing is owed on the review front.\\n';\n }\n\n // The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is\n // arrival and not the gate's own \"still owed\".\n private pending(): RequiredChecklist[] {\n return this.waitedOn.filter((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_MISSING || this.predates(req));\n }\n\n private predates(req: RequiredChecklist): boolean {\n const result = this.results.find((r: ChecklistResult): boolean => r.id === req.id);\n return result !== undefined && result.round < this.briefedRound;\n }\n\n private reload(): void {\n this.results = this.reviewJsonService.loadChecklistResults(this.summaryPath, this.applicable);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"await-reviews-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/await-reviews-command.ts"],"names":[],"mappings":";;;;AAAA,0DAGiC;AACjC,yCAA2D;AAE3D,uDAA2E;AAC3E,qEAAuF;AACvF,2EAAgE;AAChE,2EAA6E;AAC7E,mEAA8D;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAEP;IACA;IACA;IACA;IACA;IACA;IACA;IAPrB,YACqB,cAA8B,EAC9B,gBAAkC,EAClC,iBAAoC,EACpC,SAAoB,EACpB,YA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,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClG,CAAC;CACJ;AAxHD,8CAwHC","sourcesContent":["import {\n ChecklistResult, ChecklistVerdict, CK_FAIL, CK_MISSING, CK_BAD_FORMAT, CK_ORANGE, loadAndValidate,\n RepoRootFinder, RequiredChecklist, ReviewJsonService,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AwaitLoop, WaitOutcome, WaitProbe } from '../workflow/await-loop';\nimport { ChecklistScanOptions, ChecklistScanner } from '../workflow/checklist-scanner';\nimport { AiBranchName } from '../workflow/git-readAiBranchName';\nimport { ReviewStageReceiptService } from '../workflow/review-stage-receipt';\nimport { StageOutputLog } from '../workflow/stage-output-log';\n\n/**\n * `wp-await-reviews` — BLOCK until every reviewer stage ② requested for this branch has written its\n * verdict, then print what each one said.\n *\n * ─── Why a command and not an instruction ──────────────────────────────────────────────────────────\n * An agent that has just spawned four reviewer subagents has nothing to do until they answer, and a\n * worktree-isolated subagent cannot simply wait: ending its turn ends its run. See {@link AwaitLoop}\n * for the full chain and the measurement (18.3% of all fleet tokens in one day spent on `echo .`).\n * A blocking Bash call is the only wait primitive it has, so webpieces provides one.\n *\n * ─── It INVENTS NO STATE ───────────────────────────────────────────────────────────────────────────\n * The set of reviewers a branch owes is `ChecklistScanner`'s answer — the SAME one `wp-review-upsert-pr`\n * lists and `wp-finish-upsert-pr` blocks on — and the verdicts are the `review-round<N>-<id>.json` files those\n * two already read. Nothing here writes anything, and there is no third opinion about who is owed: a\n * waiter that computed its own set could finish while finish still refused, which is the one outcome\n * that would make waiting worse than not waiting.\n *\n * The scan runs ONCE. Its `applicable` set is a function of the diff, which does not change while the\n * agent sits still, so re-scanning per poll would re-run `git diff` every few seconds to re-derive an\n * unchanged answer. Only the verdict FILES are re-read, which is the only thing a reviewer changes.\n *\n * ─── What it does NOT do ───────────────────────────────────────────────────────────────────────────\n * It does not judge. A red verdict is a completed review, so this command RETURNS on it and prints it;\n * refusing the PR over it is `wp-finish-upsert-pr`'s job and stays there. It exits non-zero only when it\n * cannot do its own job at all.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class AwaitReviewsCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly checklistScanner: ChecklistScanner,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly awaitLoop: AwaitLoop,\n private readonly stageConsole: StageOutputLog,\n private readonly receipts: ReviewStageReceiptService,\n private readonly aiBranchName: AiBranchName,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const config = loadAndValidate(repoRoot).prGate;\n // contextStage '' — a WAIT must not write pr-context.json. That file records the diff a review\n // was briefed against, and rewriting it mid-review would restate the briefing under the\n // reviewers currently reading it.\n const scan = await this.checklistScanner.scan(repoRoot, config.checklists, new ChecklistScanOptions(config.maxReviewerRounds, true, ''));\n if (scan.reviewersDisabled) return this.reportDisabled(scan.suppressed);\n if (scan.applicable.length === 0) return this.reportNothingOwed();\n // WAIT on the set finish blocks on (`outstanding`), REPORT on everything that applies. The two\n // sets differ by exactly the optional checklists nobody ran — `required: false` means the PR does\n // not wait for them, and a wait that did would never end, because nothing is ever going to write\n // a verdict for a reviewer that was deliberately never spawned. (The SET is shared with finish;\n // the PREDICATE is not — see `done()` for why a wait ends on arrival and finish does not.)\n // A verdict from an EARLIER round than the one stage ② last briefed is NOT an arrival: it is the red\n // that round re-briefed (issue #1053), and counting it would end the wait on the spot.\n const round = this.receipts.read(repoRoot, await this.aiBranchName.getFeatureName())?.round ?? 0;\n const probe = new ReviewerWaitProbe(\n this.reviewJsonService, scan.summaryPath, scan.outstanding, scan.applicable, round);\n const outcome = await this.awaitLoop.run(probe);\n this.report(probe, outcome);\n }\n\n // Nothing to wait for, and saying so is the whole value: an agent that got no answer here would\n // otherwise assume the wait is still owed and start spinning again.\n private reportNothingOwed(): void {\n this.stageConsole.say('\\n✅ No reviewer was requested for this branch — nothing to wait for.\\n');\n }\n\n private reportDisabled(suppressed: readonly RequiredChecklist[]): void {\n this.stageConsole.say(\n `\\n⚫ Every reviewer is switched off on this machine (experimental.turnOffAllReviewers), so `\n + `${String(suppressed.length)} checklist(s) that would have run are not running. There is `\n + 'nothing to wait for.\\n');\n }\n\n private report(probe: ReviewerWaitProbe, outcome: WaitOutcome): void {\n this.stageConsole.say(outcome.done ? probe.verdictReport(outcome) : probe.stillWaitingReport(outcome));\n }\n}\n\n/**\n * The reviewer wait itself: which checklists are owed, and what the files on disk say about them right\n * now. It owns the reporting too, because every line it prints is derived from the same verdict read —\n * a report that re-read the files could disagree with the answer that ended the wait.\n */\nexport class ReviewerWaitProbe implements WaitProbe {\n readonly label = 'reviewers';\n // Verdict files are local reads, so polling them costs nothing worth economizing on. Fast enough\n // that the command returns within seconds of the last reviewer finishing, which is the point.\n readonly pollMs = 3_000;\n\n private results: ChecklistResult[] = [];\n\n constructor(\n private readonly reviewJsonService: ReviewJsonService,\n private readonly summaryPath: string,\n private readonly waitedOn: readonly RequiredChecklist[],\n private readonly applicable: readonly RequiredChecklist[],\n // The round stage ② last briefed (0 = none): a verdict from an earlier round is not an answer.\n private readonly briefedRound: number,\n ) {\n this.reload();\n }\n\n /**\n * Done when every awaited reviewer has ANSWERED — not when every answer is a pass.\n *\n * That distinction is the whole contract of a wait, and getting it wrong makes the command useless\n * in the case it matters most. `ReviewJsonService.pendingChecklists` is finish's GATE predicate and\n * counts a RED verdict as still owed, correctly: the PR is refused until the finding is fixed. But\n * a red reviewer has finished; it will never write a different answer on its own, so waiting for it\n * to stop being red is waiting forever. The wait therefore ends on ARRIVAL — a verdict file that\n * exists, whatever it says — and `wp-finish-upsert-pr` keeps sole ownership of the gate.\n *\n * `CK_BAD_FORMAT` counts as arrived too: the file is there and unreadable, which is a thing to FIX\n * (four characters of JSON), not a thing to wait longer for.\n */\n async done(): Promise<boolean> {\n this.reload();\n return this.pending().length === 0;\n }\n\n describe(): string {\n const owed = this.pending().length;\n const total = this.waitedOn.length;\n return `${String(total - owed)} of ${String(total)} verdicts in`;\n }\n\n /** Every reviewer's answer, printed once the wait is over — the reason to wait rather than sleep. */\n verdictReport(outcome: WaitOutcome): string {\n // The headline counts what was WAITED ON; the list below covers everything that APPLIES, so an\n // optional checklist nobody ran shows as ❓ rather than being quietly dropped. Reporting only the\n // waited-on set would let a shorter list imply the others passed.\n const lines = [\n `\\n✅ All ${String(this.waitedOn.length)} awaited reviewer verdict(s) are in after `\n + `${String(outcome.waitedSeconds)}s:\\n`,\n ];\n for (const req of this.applicable) lines.push(this.oneVerdict(req));\n lines.push(this.nextStep());\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * The timeout report. It is a NORMAL exit and says so, because an agent that reads this as a failure\n * goes hunting for a broken reviewer instead of running one more plain command.\n */\n stillWaitingReport(outcome: WaitOutcome): string {\n const owed = this.pending();\n return `\\n⏳ Still waiting after ${String(outcome.waitedSeconds)}s — run me again: pnpm wp-await-reviews\\n`\n + ' (This is not a failure. The wait returns before the harness kills a quiet command, so a\\n'\n + ' long review costs a handful of calls instead of hundreds of keep-alive turns.)\\n\\n'\n + ` ${String(owed.length)} of ${String(this.waitedOn.length)} still owe a verdict: `\n + `${owed.map((r: RequiredChecklist): string => r.id).join(', ')}\\n`;\n }\n\n private oneVerdict(req: RequiredChecklist): string {\n const verdict = this.reviewJsonService.resolveVerdict(req, this.results);\n return ` ${this.icon(verdict)} ${verdict.id} — ${verdict.status}${this.detail(verdict)}`;\n }\n\n // Only a NON-passing verdict's detail is printed. A green reviewer's output is already on the PR,\n // and reprinting four of them here would bury the one line that needs acting on.\n private detail(verdict: ChecklistVerdict): string {\n if ((verdict.status !== CK_FAIL && verdict.status !== CK_ORANGE) || verdict.detail === '') return '';\n return `\\n ${verdict.detail.split('\\n').join('\\n ')}`;\n }\n\n private icon(verdict: ChecklistVerdict): string {\n if (verdict.status === CK_FAIL) return '🔴';\n if (verdict.status === CK_ORANGE) return '🟠';\n if (verdict.status === CK_MISSING || verdict.status === CK_BAD_FORMAT) return '❓';\n return '🟢';\n }\n\n // Named because a wait that ends without saying what it unblocked leaves the agent to guess, and\n // guessing here means spinning again. A red verdict changes the next move, so it is called out.\n private nextStep(): string {\n const statuses = this.applicable.map((req: RequiredChecklist): string =>\n this.reviewJsonService.resolveVerdict(req, this.results).status);\n if (statuses.includes(CK_FAIL)) {\n return '\\n A reviewer REFUSED. Fix what it found — re-spawning it against unchanged code buys the\\n'\n + ' same answer — then re-run the review stage.\\n';\n }\n if (statuses.includes(CK_ORANGE)) {\n return '\\n A final-round reviewer marked ORANGE. Fix what it found, best effort, commit, and record the\\n'\n + ' fixes with pnpm wp-write-review-fixes. Do NOT spawn a reviewer: that was the last review round.\\n';\n }\n return '\\n Nothing is owed on the review front.\\n';\n }\n\n // The awaited checklists whose verdict file has not appeared yet — see `done()` for why this is\n // arrival and not the gate's own \"still owed\".\n private pending(): RequiredChecklist[] {\n return this.waitedOn.filter((req: RequiredChecklist): boolean =>\n this.reviewJsonService.resolveVerdict(req, this.results).status === CK_MISSING || this.predates(req));\n }\n\n private predates(req: RequiredChecklist): boolean {\n const result = this.results.find((r: ChecklistResult): boolean => r.id === req.id);\n return result !== undefined && result.round < this.briefedRound;\n }\n\n private reload(): void {\n this.results = this.reviewJsonService.loadChecklistResults(this.summaryPath, this.applicable);\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { RepoRootFinder, GateTokenService } from '@webpieces/rules-config';
|
|
2
|
+
import { NativeProcessApi } from '@webpieces/tooling-common';
|
|
2
3
|
export declare class PrUnderCheck {
|
|
3
4
|
number: string;
|
|
4
5
|
headSha: string;
|
|
@@ -29,7 +30,8 @@ export declare class PrUnderCheck {
|
|
|
29
30
|
export declare class CheckPrCommand {
|
|
30
31
|
private readonly repoRootFinder;
|
|
31
32
|
private readonly gateTokenService;
|
|
32
|
-
|
|
33
|
+
private readonly processes;
|
|
34
|
+
constructor(repoRootFinder: RepoRootFinder, gateTokenService: GateTokenService, processes: NativeProcessApi);
|
|
33
35
|
run(): Promise<void>;
|
|
34
36
|
private verifyWithRetry;
|
|
35
37
|
private delay;
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.CheckPrCommand = exports.PrUnderCheck = 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
|
// The head sha + body of the PR under check, resolved from `gh`. Data-only.
|
|
9
9
|
class PrUnderCheck {
|
|
@@ -41,9 +41,11 @@ exports.PrUnderCheck = PrUnderCheck;
|
|
|
41
41
|
let CheckPrCommand = class CheckPrCommand {
|
|
42
42
|
repoRootFinder;
|
|
43
43
|
gateTokenService;
|
|
44
|
-
|
|
44
|
+
processes;
|
|
45
|
+
constructor(repoRootFinder, gateTokenService, processes) {
|
|
45
46
|
this.repoRootFinder = repoRootFinder;
|
|
46
47
|
this.gateTokenService = gateTokenService;
|
|
48
|
+
this.processes = processes;
|
|
47
49
|
}
|
|
48
50
|
async run() {
|
|
49
51
|
const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());
|
|
@@ -52,7 +54,7 @@ let CheckPrCommand = class CheckPrCommand {
|
|
|
52
54
|
throw new rules_config_1.CliExitError(0, 'ℹ️ wp-check-pr: no prGate.gateSalt configured — server-side gate token enforcement is disabled. ' +
|
|
53
55
|
'Add a committed "gateSalt" under the pr-gate section of webpieces.config.json to enable it.');
|
|
54
56
|
}
|
|
55
|
-
let pr = this.resolvePr();
|
|
57
|
+
let pr = await this.resolvePr();
|
|
56
58
|
if (pr.headSha === '') {
|
|
57
59
|
throw new rules_config_1.CliExitError(1, '❌ wp-check-pr: could not resolve the PR head sha via `gh`. Ensure the workflow runs on a pull_request ' +
|
|
58
60
|
'event with `gh` authenticated (GH_TOKEN) and the PR number available (WP_PR_NUMBER or GITHUB_REF).');
|
|
@@ -75,7 +77,7 @@ let CheckPrCommand = class CheckPrCommand {
|
|
|
75
77
|
return pr;
|
|
76
78
|
process.stdout.write('… no valid token yet — waiting for the PR body edit to land, then re-checking once…\n');
|
|
77
79
|
await this.delay(15000);
|
|
78
|
-
const refreshed = this.resolvePr();
|
|
80
|
+
const refreshed = await this.resolvePr();
|
|
79
81
|
return refreshed.headSha !== '' ? refreshed : pr;
|
|
80
82
|
}
|
|
81
83
|
delay(ms) {
|
|
@@ -100,7 +102,7 @@ let CheckPrCommand = class CheckPrCommand {
|
|
|
100
102
|
}
|
|
101
103
|
// Resolve the PR (number, head sha, body) from `gh`. Prefers an explicit WP_PR_NUMBER, then the
|
|
102
104
|
// pull_request number in GITHUB_REF (refs/pull/<n>/merge), then `gh`'s current-branch detection.
|
|
103
|
-
resolvePr() {
|
|
105
|
+
async resolvePr() {
|
|
104
106
|
const num = this.prNumber();
|
|
105
107
|
const args = num !== ''
|
|
106
108
|
? [
|
|
@@ -120,11 +122,11 @@ let CheckPrCommand = class CheckPrCommand {
|
|
|
120
122
|
'--jq',
|
|
121
123
|
'"\\(.number)\\t\\(.headRefOid)\\t\\(.body)"',
|
|
122
124
|
];
|
|
123
|
-
const result =
|
|
124
|
-
if (result.
|
|
125
|
+
const result = await this.processes.run('gh', args);
|
|
126
|
+
if (!result.ok)
|
|
125
127
|
return new PrUnderCheck(num, '', '');
|
|
126
128
|
// jq joins body (which may contain tabs/newlines) last, so split on the FIRST two tabs only.
|
|
127
|
-
const out =
|
|
129
|
+
const out = result.stdout.trim();
|
|
128
130
|
const firstTab = out.indexOf('\t');
|
|
129
131
|
const secondTab = firstTab >= 0 ? out.indexOf('\t', firstTab + 1) : -1;
|
|
130
132
|
if (firstTab < 0 || secondTab < 0)
|
|
@@ -148,6 +150,7 @@ exports.CheckPrCommand = CheckPrCommand;
|
|
|
148
150
|
exports.CheckPrCommand = CheckPrCommand = tslib_1.__decorate([
|
|
149
151
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
150
152
|
tslib_1.__metadata("design:paramtypes", [rules_config_1.RepoRootFinder,
|
|
151
|
-
rules_config_1.GateTokenService
|
|
153
|
+
rules_config_1.GateTokenService,
|
|
154
|
+
tooling_common_1.NativeProcessApi])
|
|
152
155
|
], CheckPrCommand);
|
|
153
156
|
//# sourceMappingURL=check-pr-command.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"check-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/check-pr-command.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAKiC;AACjC,yCAA2D;AAE3D,4EAA4E;AAC5E,MAAa,YAAY;IACrB,MAAM,CAAS;IACf,OAAO,CAAS;IAChB,IAAI,CAAS;IAEb,YAAY,MAAc,EAAE,OAAe,EAAE,IAAY;QACrD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;CACJ;AAVD,oCAUC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAEF;IACA;IAFrB,YACqB,cAA8B,EAC9B,gBAAkC;QADlC,mBAAc,GAAd,cAAc,CAAgB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;IACpD,CAAC;IAEJ,KAAK,CAAC,GAAG;QACL,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QACpE,MAAM,QAAQ,GAAG,IAAA,8BAAe,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;QAC3D,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,C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AC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACzB,CAAC;CACJ,CAAA;AAxHY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QACZ,+BAAgB;GAH9C,cAAc,CAwH1B","sourcesContent":["import { spawnSync } from 'child_process';\nimport {\n loadAndValidate,\n RepoRootFinder,\n GateTokenService,\n CliExitError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n// The head sha + body of the PR under check, resolved from `gh`. Data-only.\nexport class PrUnderCheck {\n number: string;\n headSha: string;\n body: string;\n\n constructor(number: string, headSha: string, body: string) {\n this.number = number;\n this.headSha = headSha;\n this.body = body;\n }\n}\n\n/**\n * `wp-check-pr` — the SERVER-SIDE half of the gate, meant to run as a required CI check. It is READ-ONLY:\n * it never touches git state, never pushes, never calls `gh pr create`. It recomputes\n * `HMAC(prGate.gateSalt, PR_head_sha)` from the committed salt and verifies the PR body carries that\n * token. A valid token proves either that the automated gate passed on this exact commit, or that a human\n * explicitly attested and posted it with `wp-human-post-pr`; the visible PR body identifies which path.\n *\n * This is what catches a PR opened OUTSIDE the gated flow — an unhooked teammate who `git push`ed and\n * clicked \"Create pull request\" in the web UI carries no valid token for its head sha and fails here.\n *\n * This job is THE required check — the ONE thing a consumer marks required in branch protection. It used\n * to also post a `webpieces/pr-gate` commit status, because `wp-finish-upsert-pr` pushed BEFORE writing\n * the PR body and a status (newest post wins for a context) could supersede the failure that race caused.\n * GatedPrPublisher now writes the body first, so there is no race to recover from and no second entry to\n * confuse anyone about which one to require. This job's exit code is the whole verdict.\n *\n * A repo with no `gateSalt` configured has not opted in → this is a no-op success (exit 0), so it is safe\n * to add the workflow before turning enforcement on.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and resolved by PrGateApp.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CheckPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly gateTokenService: GateTokenService,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n if (gateSalt.trim() === '') {\n throw new CliExitError(\n 0,\n 'ℹ️ wp-check-pr: no prGate.gateSalt configured — server-side gate token enforcement is disabled. ' +\n 'Add a committed \"gateSalt\" under the pr-gate section of webpieces.config.json to enable it.',\n );\n }\n\n let pr = this.resolvePr();\n if (pr.headSha === '') {\n throw new CliExitError(\n 1,\n '❌ wp-check-pr: could not resolve the PR head sha via `gh`. Ensure the workflow runs on a pull_request ' +\n 'event with `gh` authenticated (GH_TOKEN) and the PR number available (WP_PR_NUMBER or GITHUB_REF).',\n );\n }\n\n pr = await this.verifyWithRetry(pr, gateSalt);\n if (this.gateTokenService.verifyGateToken(pr.body, gateSalt, pr.headSha)) {\n process.stdout.write(this.successMessage(pr));\n return;\n }\n\n // An UNHOOKED push never reaches wp-finish-upsert-pr, so it carries no valid token — fail the job.\n // THIS EXIT CODE IS THE WHOLE SIGNAL: there is no companion commit status any more (see the JSDoc).\n throw new CliExitError(1, this.failureMessage(pr));\n }\n\n // Re-read the PR ONCE after a short delay if the token looks stale. The push-before-body-edit RACE is\n // gone (GatedPrPublisher writes the body first), so this no longer backstops a known ordering bug —\n // it absorbs GitHub's own event/read replication jitter, which matters more now that this job is the\n // single required check. It costs nothing on the success path. Returns the freshest PR.\n private async verifyWithRetry(pr: PrUnderCheck, gateSalt: string): Promise<PrUnderCheck> {\n if (this.gateTokenService.verifyGateToken(pr.body, gateSalt, pr.headSha)) return pr;\n process.stdout.write(\n '… no valid token yet — waiting for the PR body edit to land, then re-checking once…\\n',\n );\n await this.delay(15000);\n const refreshed = this.resolvePr();\n return refreshed.headSha !== '' ? refreshed : pr;\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve: () => void): void => {\n setTimeout(resolve, ms);\n });\n }\n\n // The actionable red-check message: this PR did not come through the gated flow (or hooks are missing).\n protected successMessage(pr: PrUnderCheck): string {\n return `✅ wp-check-pr: valid webpieces gate token for PR #${pr.number} @ ${pr.headSha.slice(0, 12)} — automated gate or explicit human escape hatch (see PR body).\\n`;\n }\n\n protected failureMessage(pr: PrUnderCheck): string {\n return (\n `❌ wp-check-pr: PR #${pr.number} (head ${pr.headSha.slice(0, 12)}) has no valid webpieces gate token.\\n\\n` +\n `This PR was NOT posted through either supported token-minting path — or was pushed afterwards.\\n` +\n `Every commit that lands here needs a current token, so:\\n\\n` +\n ` 1. Install the webpieces hooks if you don't have them.\\n` +\n ` 2. Recreate/update this PR by running the full gated flow, in order:\\n` +\n ` pnpm wp-start-upsert-pr → pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\\n` +\n ` A human who personally inspected the work may instead run interactive pnpm wp-human-post-pr.\\n` +\n ` AI must never answer its human-attestation prompt or run that escape hatch for a human.\\n\\n` +\n `Either supported path re-stamps the PR title, body, and token for the current head commit.`\n );\n }\n\n // Resolve the PR (number, head sha, body) from `gh`. Prefers an explicit WP_PR_NUMBER, then the\n // pull_request number in GITHUB_REF (refs/pull/<n>/merge), then `gh`'s current-branch detection.\n private resolvePr(): PrUnderCheck {\n const num = this.prNumber();\n const args =\n num !== ''\n ? [\n 'pr',\n 'view',\n num,\n '--json',\n 'number,headRefOid,body',\n '--jq',\n '\"\\\\(.number)\\\\t\\\\(.headRefOid)\\\\t\\\\(.body)\"',\n ]\n : [\n 'pr',\n 'view',\n '--json',\n 'number,headRefOid,body',\n '--jq',\n '\"\\\\(.number)\\\\t\\\\(.headRefOid)\\\\t\\\\(.body)\"',\n ];\n const result = spawnSync('gh', args, { encoding: 'utf8', maxBuffer: 1024 * 1024 * 16 });\n if (result.status !== 0) return new PrUnderCheck(num, '', '');\n // jq joins body (which may contain tabs/newlines) last, so split on the FIRST two tabs only.\n const out = (result.stdout ?? '').trim();\n const firstTab = out.indexOf('\\t');\n const secondTab = firstTab >= 0 ? out.indexOf('\\t', firstTab + 1) : -1;\n if (firstTab < 0 || secondTab < 0) return new PrUnderCheck(num, '', '');\n const number = out.slice(0, firstTab);\n const headSha = out.slice(firstTab + 1, secondTab);\n const body = out.slice(secondTab + 1);\n return new PrUnderCheck(number, headSha, body);\n }\n\n private prNumber(): string {\n const explicit = (process.env['WP_PR_NUMBER'] ?? '').trim();\n if (explicit !== '') return explicit;\n // GitHub Actions pull_request: GITHUB_REF = refs/pull/<n>/merge\n const ref = process.env['GITHUB_REF'] ?? '';\n const m = /refs\\/pull\\/(\\d+)\\//.exec(ref);\n return m ? m[1] : '';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"check-pr-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/check-pr-command.ts"],"names":[],"mappings":";;;;AAAA,0DAKiC;AACjC,8DAA6D;AAC7D,yCAA2D;AAE3D,4EAA4E;AAC5E,MAAa,YAAY;IACrB,MAAM,CAAS;IACf,OAAO,CAAS;IAChB,IAAI,CAAS;IAEb,YAAY,MAAc,EAAE,OAAe,EAAE,IAAY;QACrD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;CACJ;AAVD,oCAUC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAEF;IACA;IACA;IAHrB,YACqB,cAA8B,EAC9B,gBAAkC,EAClC,SAA2B;QAF3B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,cAAS,GAAT,SAAS,CAAkB;IAC7C,CAAC;IAEJ,KAAK,CAAC,GAAG;QACL,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC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qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACzB,CAAC;CACJ,CAAA;AAzHY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QACZ,+BAAgB;QACvB,iCAAgB;GAJvC,cAAc,CAyH1B","sourcesContent":["import {\n loadAndValidate,\n RepoRootFinder,\n GateTokenService,\n CliExitError,\n} from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n// The head sha + body of the PR under check, resolved from `gh`. Data-only.\nexport class PrUnderCheck {\n number: string;\n headSha: string;\n body: string;\n\n constructor(number: string, headSha: string, body: string) {\n this.number = number;\n this.headSha = headSha;\n this.body = body;\n }\n}\n\n/**\n * `wp-check-pr` — the SERVER-SIDE half of the gate, meant to run as a required CI check. It is READ-ONLY:\n * it never touches git state, never pushes, never calls `gh pr create`. It recomputes\n * `HMAC(prGate.gateSalt, PR_head_sha)` from the committed salt and verifies the PR body carries that\n * token. A valid token proves either that the automated gate passed on this exact commit, or that a human\n * explicitly attested and posted it with `wp-human-post-pr`; the visible PR body identifies which path.\n *\n * This is what catches a PR opened OUTSIDE the gated flow — an unhooked teammate who `git push`ed and\n * clicked \"Create pull request\" in the web UI carries no valid token for its head sha and fails here.\n *\n * This job is THE required check — the ONE thing a consumer marks required in branch protection. It used\n * to also post a `webpieces/pr-gate` commit status, because `wp-finish-upsert-pr` pushed BEFORE writing\n * the PR body and a status (newest post wins for a context) could supersede the failure that race caused.\n * GatedPrPublisher now writes the body first, so there is no race to recover from and no second entry to\n * confuse anyone about which one to require. This job's exit code is the whole verdict.\n *\n * A repo with no `gateSalt` configured has not opted in → this is a no-op success (exit 0), so it is safe\n * to add the workflow before turning enforcement on.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and resolved by PrGateApp.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CheckPrCommand {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly gateTokenService: GateTokenService,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async run(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n const gateSalt = loadAndValidate(repoRoot).prGate.gateSalt;\n if (gateSalt.trim() === '') {\n throw new CliExitError(\n 0,\n 'ℹ️ wp-check-pr: no prGate.gateSalt configured — server-side gate token enforcement is disabled. ' +\n 'Add a committed \"gateSalt\" under the pr-gate section of webpieces.config.json to enable it.',\n );\n }\n\n let pr = await this.resolvePr();\n if (pr.headSha === '') {\n throw new CliExitError(\n 1,\n '❌ wp-check-pr: could not resolve the PR head sha via `gh`. Ensure the workflow runs on a pull_request ' +\n 'event with `gh` authenticated (GH_TOKEN) and the PR number available (WP_PR_NUMBER or GITHUB_REF).',\n );\n }\n\n pr = await this.verifyWithRetry(pr, gateSalt);\n if (this.gateTokenService.verifyGateToken(pr.body, gateSalt, pr.headSha)) {\n process.stdout.write(this.successMessage(pr));\n return;\n }\n\n // An UNHOOKED push never reaches wp-finish-upsert-pr, so it carries no valid token — fail the job.\n // THIS EXIT CODE IS THE WHOLE SIGNAL: there is no companion commit status any more (see the JSDoc).\n throw new CliExitError(1, this.failureMessage(pr));\n }\n\n // Re-read the PR ONCE after a short delay if the token looks stale. The push-before-body-edit RACE is\n // gone (GatedPrPublisher writes the body first), so this no longer backstops a known ordering bug —\n // it absorbs GitHub's own event/read replication jitter, which matters more now that this job is the\n // single required check. It costs nothing on the success path. Returns the freshest PR.\n private async verifyWithRetry(pr: PrUnderCheck, gateSalt: string): Promise<PrUnderCheck> {\n if (this.gateTokenService.verifyGateToken(pr.body, gateSalt, pr.headSha)) return pr;\n process.stdout.write(\n '… no valid token yet — waiting for the PR body edit to land, then re-checking once…\\n',\n );\n await this.delay(15000);\n const refreshed = await this.resolvePr();\n return refreshed.headSha !== '' ? refreshed : pr;\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve: () => void): void => {\n setTimeout(resolve, ms);\n });\n }\n\n // The actionable red-check message: this PR did not come through the gated flow (or hooks are missing).\n protected successMessage(pr: PrUnderCheck): string {\n return `✅ wp-check-pr: valid webpieces gate token for PR #${pr.number} @ ${pr.headSha.slice(0, 12)} — automated gate or explicit human escape hatch (see PR body).\\n`;\n }\n\n protected failureMessage(pr: PrUnderCheck): string {\n return (\n `❌ wp-check-pr: PR #${pr.number} (head ${pr.headSha.slice(0, 12)}) has no valid webpieces gate token.\\n\\n` +\n `This PR was NOT posted through either supported token-minting path — or was pushed afterwards.\\n` +\n `Every commit that lands here needs a current token, so:\\n\\n` +\n ` 1. Install the webpieces hooks if you don't have them.\\n` +\n ` 2. Recreate/update this PR by running the full gated flow, in order:\\n` +\n ` pnpm wp-start-upsert-pr → pnpm wp-review-upsert-pr → write summary.json → pnpm wp-finish-upsert-pr\\n` +\n ` A human who personally inspected the work may instead run interactive pnpm wp-human-post-pr.\\n` +\n ` AI must never answer its human-attestation prompt or run that escape hatch for a human.\\n\\n` +\n `Either supported path re-stamps the PR title, body, and token for the current head commit.`\n );\n }\n\n // Resolve the PR (number, head sha, body) from `gh`. Prefers an explicit WP_PR_NUMBER, then the\n // pull_request number in GITHUB_REF (refs/pull/<n>/merge), then `gh`'s current-branch detection.\n private async resolvePr(): Promise<PrUnderCheck> {\n const num = this.prNumber();\n const args =\n num !== ''\n ? [\n 'pr',\n 'view',\n num,\n '--json',\n 'number,headRefOid,body',\n '--jq',\n '\"\\\\(.number)\\\\t\\\\(.headRefOid)\\\\t\\\\(.body)\"',\n ]\n : [\n 'pr',\n 'view',\n '--json',\n 'number,headRefOid,body',\n '--jq',\n '\"\\\\(.number)\\\\t\\\\(.headRefOid)\\\\t\\\\(.body)\"',\n ];\n const result = await this.processes.run('gh', args);\n if (!result.ok) return new PrUnderCheck(num, '', '');\n // jq joins body (which may contain tabs/newlines) last, so split on the FIRST two tabs only.\n const out = result.stdout.trim();\n const firstTab = out.indexOf('\\t');\n const secondTab = firstTab >= 0 ? out.indexOf('\\t', firstTab + 1) : -1;\n if (firstTab < 0 || secondTab < 0) return new PrUnderCheck(num, '', '');\n const number = out.slice(0, firstTab);\n const headSha = out.slice(firstTab + 1, secondTab);\n const body = out.slice(secondTab + 1);\n return new PrUnderCheck(number, headSha, body);\n }\n\n private prNumber(): string {\n const explicit = (process.env['WP_PR_NUMBER'] ?? '').trim();\n if (explicit !== '') return explicit;\n // GitHub Actions pull_request: GITHUB_REF = refs/pull/<n>/merge\n const ref = process.env['GITHUB_REF'] ?? '';\n const m = /refs\\/pull\\/(\\d+)\\//.exec(ref);\n return m ? m[1] : '';\n }\n}\n"]}
|
|
@@ -110,7 +110,7 @@ let CleanupCommand = class CleanupCommand {
|
|
|
110
110
|
const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());
|
|
111
111
|
const retention = (0, rules_config_1.loadAndValidate)(repoRoot).prGate.landPr.branchRetention;
|
|
112
112
|
if (options.report) {
|
|
113
|
-
this.reportOnly(repoRoot, retention, options);
|
|
113
|
+
await this.reportOnly(repoRoot, retention, options);
|
|
114
114
|
return;
|
|
115
115
|
}
|
|
116
116
|
await this.cleanUpWorktrees(repoRoot, retention, options);
|
|
@@ -123,9 +123,9 @@ let CleanupCommand = class CleanupCommand {
|
|
|
123
123
|
* because a run that deletes nothing cannot renumber anything. That is what makes it the honest
|
|
124
124
|
* first half of `--report` → read the numbers → `--delete-branches=1,3`.
|
|
125
125
|
*/
|
|
126
|
-
reportOnly(repoRoot, retention, options) {
|
|
126
|
+
async reportOnly(repoRoot, retention, options) {
|
|
127
127
|
process.stdout.write('\n' + SEP + '🔎 wp-cleanup --report — nothing will be deleted\n' + SEP);
|
|
128
|
-
const verdicts = this.worktreeSection.verdicts(repoRoot, options.ignoreStaleLocks);
|
|
128
|
+
const verdicts = await this.worktreeSection.verdicts(repoRoot, options.ignoreStaleLocks);
|
|
129
129
|
const deadTrees = this.worktreeSection.provablyDead(verdicts);
|
|
130
130
|
process.stdout.write(this.wouldReapBlock(WORKTREE_KINDS, deadTrees.map((tree) => `${tree.path} — ${tree.reason}`)));
|
|
131
131
|
const treePromptable = this.worktreeSection.promptable(verdicts);
|
|
@@ -141,7 +141,7 @@ let CleanupCommand = class CleanupCommand {
|
|
|
141
141
|
// lands in `spared`, nothing is touched. That is exactly what a report needs, and it means
|
|
142
142
|
// the classified block below is computed by the identical code path a real run uses, so the
|
|
143
143
|
// numbering it prints IS the numbering the flag will act on.
|
|
144
|
-
const branches = this.branchReaper.reap(repoRoot, 'wp-cleanup', null, repo_workflow_core_1.BRANCH_RETENTION_KEEP).spared;
|
|
144
|
+
const branches = (await this.branchReaper.reap(repoRoot, 'wp-cleanup', null, repo_workflow_core_1.BRANCH_RETENTION_KEEP)).spared;
|
|
145
145
|
process.stdout.write(this.wouldReapBlock(BRANCH_KINDS, branches
|
|
146
146
|
.filter((entry) => AUTO_REAPED_CLASSIFICATIONS.includes(entry.classification))
|
|
147
147
|
.map((entry) => `${entry.branch} — ${entry.reason}`)));
|
|
@@ -167,7 +167,7 @@ let CleanupCommand = class CleanupCommand {
|
|
|
167
167
|
async cleanUpBranches(repoRoot, retention, options) {
|
|
168
168
|
// No cache argument: wp-cleanup recomputes the verdicts itself. The file on disk is allowed to
|
|
169
169
|
// go stale, and stale evidence is fine for BLOCKING but never for DELETING.
|
|
170
|
-
const result = this.branchReaper.reap(repoRoot, 'wp-cleanup', null, retention);
|
|
170
|
+
const result = await this.branchReaper.reap(repoRoot, 'wp-cleanup', null, retention);
|
|
171
171
|
const first = this.report(repoRoot, result);
|
|
172
172
|
process.stdout.write(first);
|
|
173
173
|
const promptable = this.promptable(result.spared);
|
|
@@ -178,7 +178,7 @@ let CleanupCommand = class CleanupCommand {
|
|
|
178
178
|
options.branches.pick(block);
|
|
179
179
|
if (husks.length > 0) {
|
|
180
180
|
process.stdout.write(this.huskBlock(BRANCH_KINDS, husks.map((entry) => entry.branch)));
|
|
181
|
-
process.stdout.write(this.report(repoRoot, this.branchReaper.reapApproved(repoRoot, 'wp-cleanup', husks, retention)));
|
|
181
|
+
process.stdout.write(this.report(repoRoot, await this.branchReaper.reapApproved(repoRoot, 'wp-cleanup', husks, retention)));
|
|
182
182
|
}
|
|
183
183
|
if (block.length === 0) {
|
|
184
184
|
if (first === '' && husks.length === 0)
|
|
@@ -191,7 +191,7 @@ let CleanupCommand = class CleanupCommand {
|
|
|
191
191
|
process.stdout.write(`\nNothing else deleted — the ${String(block.length)} ${BRANCH_KINDS} above were kept.\n`);
|
|
192
192
|
return;
|
|
193
193
|
}
|
|
194
|
-
process.stdout.write(this.report(repoRoot, this.branchReaper.reapApproved(repoRoot, 'wp-cleanup', approved, retention)));
|
|
194
|
+
process.stdout.write(this.report(repoRoot, await this.branchReaper.reapApproved(repoRoot, 'wp-cleanup', approved, retention)));
|
|
195
195
|
}
|
|
196
196
|
/**
|
|
197
197
|
* Reap the provably-dead worktrees and the zero-commit husks, then decide about the rest.
|
|
@@ -202,22 +202,22 @@ let CleanupCommand = class CleanupCommand {
|
|
|
202
202
|
* cleanup command becomes a data-loss command).
|
|
203
203
|
*/
|
|
204
204
|
async cleanUpWorktrees(repoRoot, retention, options) {
|
|
205
|
-
const verdicts = this.worktreeSection.verdicts(repoRoot, options.ignoreStaleLocks);
|
|
205
|
+
const verdicts = await this.worktreeSection.verdicts(repoRoot, options.ignoreStaleLocks);
|
|
206
206
|
const dead = this.worktreeSection.provablyDead(verdicts);
|
|
207
207
|
if (dead.length > 0) {
|
|
208
|
-
process.stdout.write(this.worktreeSection.report(repoRoot, this.worktreeSection.reap(repoRoot, 'wp-cleanup', dead, retention)));
|
|
208
|
+
process.stdout.write(this.worktreeSection.report(repoRoot, await this.worktreeSection.reap(repoRoot, 'wp-cleanup', dead, retention)));
|
|
209
209
|
}
|
|
210
210
|
process.stdout.write(this.worktreeSection.sparedBlock(verdicts, dead));
|
|
211
211
|
const promptable = this.worktreeSection.promptable(verdicts);
|
|
212
212
|
// A zero-commit worktree is a husk ONLY if nobody is holding it. Uncommitted or untracked
|
|
213
213
|
// files are the one thing that says "somebody is", and they are the one thing no archive tag
|
|
214
214
|
// can bring back — so they are checked here rather than left to git's refusal at removal time.
|
|
215
|
-
const husks = this.worktreeSection.withoutUncommitted(this.husks(promptable));
|
|
215
|
+
const husks = await this.worktreeSection.withoutUncommitted(this.husks(promptable));
|
|
216
216
|
const block = this.rest(promptable, husks);
|
|
217
217
|
options.worktrees.pick(block);
|
|
218
218
|
if (husks.length > 0) {
|
|
219
219
|
process.stdout.write(this.huskBlock(WORKTREE_KINDS, husks.map((tree) => `${tree.path} [${tree.branch}]`)));
|
|
220
|
-
process.stdout.write(this.worktreeSection.report(repoRoot, this.worktreeSection.reap(repoRoot, 'wp-cleanup', husks, retention)));
|
|
220
|
+
process.stdout.write(this.worktreeSection.report(repoRoot, await this.worktreeSection.reap(repoRoot, 'wp-cleanup', husks, retention)));
|
|
221
221
|
}
|
|
222
222
|
if (block.length === 0)
|
|
223
223
|
return;
|
|
@@ -227,7 +227,7 @@ let CleanupCommand = class CleanupCommand {
|
|
|
227
227
|
process.stdout.write(`\nNothing else removed — the ${String(block.length)} ${WORKTREE_KINDS} above were kept.\n`);
|
|
228
228
|
return;
|
|
229
229
|
}
|
|
230
|
-
process.stdout.write(this.worktreeSection.report(repoRoot, this.worktreeSection.reap(repoRoot, 'wp-cleanup', approved, retention)));
|
|
230
|
+
process.stdout.write(this.worktreeSection.report(repoRoot, await this.worktreeSection.reap(repoRoot, 'wp-cleanup', approved, retention)));
|
|
231
231
|
}
|
|
232
232
|
// What a bare run with an empty repo says. It points at --help because the flags are the whole
|
|
233
233
|
// reason a caller who DOES have something to say never has to be prompted.
|