@webpieces/pr-gate 0.4.823 → 0.4.824
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 +4 -3
- package/src/index.d.ts +1 -1
- package/src/index.js +1 -1
- package/src/index.js.map +1 -1
- package/src/scripts/commands/build-command.d.ts +3 -0
- package/src/scripts/commands/build-command.js +29 -17
- package/src/scripts/commands/build-command.js.map +1 -1
- package/src/scripts/commands/check-pr-command.d.ts +10 -3
- package/src/scripts/commands/check-pr-command.js +31 -10
- package/src/scripts/commands/check-pr-command.js.map +1 -1
- package/src/scripts/commands/human-post-pr-command.d.ts +52 -0
- package/src/scripts/commands/human-post-pr-command.js +260 -0
- package/src/scripts/commands/human-post-pr-command.js.map +1 -0
- package/src/scripts/pr-gate-app.d.ts +5 -1
- package/src/scripts/pr-gate-app.js +10 -1
- package/src/scripts/pr-gate-app.js.map +1 -1
- package/src/scripts/workflow/build-affected.d.ts +3 -0
- package/src/scripts/workflow/build-affected.js +16 -3
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/build-gate-log.d.ts +4 -1
- package/src/scripts/workflow/build-gate-log.js +20 -5
- package/src/scripts/workflow/build-gate-log.js.map +1 -1
- package/src/scripts/workflow/build-log-follower.d.ts +13 -0
- package/src/scripts/workflow/build-log-follower.js +48 -0
- package/src/scripts/workflow/build-log-follower.js.map +1 -0
- package/src/scripts/workflow/gated-pr-publisher.d.ts +1 -1
- package/src/scripts/workflow/gated-pr-publisher.js +20 -7
- package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/push-dev-state.js +30 -17
- package/src/scripts/workflow/push-dev-state.js.map +1 -1
- package/src/scripts/wp-human-post-pr.d.ts +2 -0
- package/src/scripts/wp-human-post-pr.js +15 -0
- package/src/scripts/wp-human-post-pr.js.map +1 -0
- package/src/scripts/workflow/git-validateUpToDate.d.ts +0 -1
- package/src/scripts/workflow/git-validateUpToDate.js +0 -70
- package/src/scripts/workflow/git-validateUpToDate.js.map +0 -1
|
@@ -8,6 +8,7 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
8
8
|
const inversify_1 = require("inversify");
|
|
9
9
|
const gate_log_file_1 = require("./gate-log-file");
|
|
10
10
|
const stage_output_log_1 = require("./stage-output-log");
|
|
11
|
+
const build_log_follower_1 = require("./build-log-follower");
|
|
11
12
|
// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
12
13
|
// The build gate already builds everything. When the output only ever went to the CONSOLE, an agent that
|
|
13
14
|
// wanted a different slice of it re-ran the WHOLE BUILD to get it: one measured session spent 23.9 minutes
|
|
@@ -124,13 +125,16 @@ let BuildGateLog = class BuildGateLog {
|
|
|
124
125
|
/**
|
|
125
126
|
* Run `buildCommand` with its stdout AND stderr redirected in full to `logPath`, printing a heartbeat
|
|
126
127
|
* every HEARTBEAT_MS so the caller can see it is alive. Returns the BUILD's raw termination facts.
|
|
127
|
-
* Nothing is truncated
|
|
128
|
+
* Nothing is truncated. Ordinary AI-facing callers do not stream; the explicitly human-attested
|
|
129
|
+
* PR escape hatch may wrap this with runStreaming(), which follows the same durable file live.
|
|
128
130
|
*/
|
|
129
131
|
async run(repoRoot, buildCommand, logPath) {
|
|
130
132
|
this.files.rotate(logPath);
|
|
131
133
|
const fd = fs.openSync(logPath, 'w');
|
|
132
134
|
const heartbeat = new BuildLogHeartbeat(this.files, logPath, this.files.displayPath(repoRoot, logPath));
|
|
133
|
-
const timer = setInterval(() => {
|
|
135
|
+
const timer = setInterval(() => {
|
|
136
|
+
this.stageConsole.say(`${heartbeat.tick()}\n`);
|
|
137
|
+
}, exports.HEARTBEAT_MS);
|
|
134
138
|
// webpieces-disable no-unmanaged-exceptions -- chokepoint: the timer and the fd MUST be released
|
|
135
139
|
// whatever the child does, and the exit code is returned rather than thrown so runBuildGate owns
|
|
136
140
|
// the one CliExitError.
|
|
@@ -143,6 +147,15 @@ let BuildGateLog = class BuildGateLog {
|
|
|
143
147
|
fs.closeSync(fd);
|
|
144
148
|
}
|
|
145
149
|
}
|
|
150
|
+
/** Human-only variant: preserve the durable log and follow its appended bytes live. */
|
|
151
|
+
runStreaming(repoRoot, buildCommand, logPath) {
|
|
152
|
+
// run() synchronously rotates and opens the file before reaching its first await, so the follower
|
|
153
|
+
// cannot accidentally replay the previous build that was at this path.
|
|
154
|
+
const completion = this.run(repoRoot, buildCommand, logPath);
|
|
155
|
+
const follower = new build_log_follower_1.BuildLogFollower(logPath, this.stageConsole);
|
|
156
|
+
follower.start();
|
|
157
|
+
return completion.finally(() => follower.stop());
|
|
158
|
+
}
|
|
146
159
|
/**
|
|
147
160
|
* The success summary: the caller is told WHERE the full output is, not handed the output.
|
|
148
161
|
*/
|
|
@@ -159,11 +172,11 @@ let BuildGateLog = class BuildGateLog {
|
|
|
159
172
|
* agent guessing or rebuilding — so it is told to surface the contradiction to the human and stop.
|
|
160
173
|
*/
|
|
161
174
|
failureMessage(buildCommand, logPath, termination) {
|
|
162
|
-
return `\nBuild Failed: ${buildCommand}\n${this.files.pointer(logPath)}\n` +
|
|
175
|
+
return (`\nBuild Failed: ${buildCommand}\n${this.files.pointer(logPath)}\n` +
|
|
163
176
|
`${this.terminationRecord(termination)}\n` +
|
|
164
177
|
`Last ${exports.FAILURE_TAIL_LINES} lines of that log:\n${this.files.tail(logPath, exports.FAILURE_TAIL_LINES)}\n` +
|
|
165
178
|
`Read that FILE for the failures. Do NOT re-run the build to see them.\n` +
|
|
166
|
-
`If you do not see failures in that log, report that to the user and stop.\n
|
|
179
|
+
`If you do not see failures in that log, report that to the user and stop.\n`);
|
|
167
180
|
}
|
|
168
181
|
// Resolve, and wait for, the child's close code AND signal. A spawn that never starts (a shell that is
|
|
169
182
|
// missing, a cwd that vanished) fails CLOSED to 1 — calling a build that never ran green is the one
|
|
@@ -200,7 +213,9 @@ let BuildGateLog = class BuildGateLog {
|
|
|
200
213
|
const name = this.fileNameFor(repoRoot, stage);
|
|
201
214
|
// `wp-build`'s log sits at the ROOT of the state dir, not under `logs/`, because it is the one log
|
|
202
215
|
// path a person types from memory. Everything else keeps the per-commit names in `logs/`.
|
|
203
|
-
return stage === exports.BUILD_STAGE
|
|
216
|
+
return stage === exports.BUILD_STAGE
|
|
217
|
+
? this.files.localPath(repoRoot, name)
|
|
218
|
+
: this.files.logsPath(repoRoot, name);
|
|
204
219
|
}
|
|
205
220
|
// Anything that is not a filename-safe character becomes '-', so `dean/feat` cannot create directories.
|
|
206
221
|
slug(value) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-gate-log.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-gate-log.ts"],"names":[],"mappings":";;;;AAAA,iDAA+D;AAC/D,+CAAyB;AACzB,0DAA2D;AAC3D,yCAA2D;AAE3D,mDAA8C;AAC9C,yDAAoD;AAEpD,0GAA0G;AAC1G,yGAAyG;AACzG,2GAA2G;AAC3G,mGAAmG;AACnG,kGAAkG;AAClG,EAAE;AACF,uGAAuG;AACvG,kGAAkG;AAClG,EAAE;AACF,0GAA0G;AAC1G,sGAAsG;AACtG,wGAAwG;AACxG,2GAA2G;AAC3G,2GAA2G;AAC3G,wGAAwG;AACxG,qGAAqG;AACrG,EAAE;AACF,0GAA0G;AAC1G,0GAA0G;AAC1G,0GAA0G;AAC1G,kGAAkG;AAClG,EAAE;AACF,uGAAuG;AACvG,0GAA0G;AAC1G,uGAAuG;AAEvG;uEACuE;AAC1D,QAAA,YAAY,GAAG,MAAM,CAAC;AAEnC;;sCAEsC;AACzB,QAAA,kBAAkB,GAAG,EAAE,CAAC;AAErC;;GAEG;AACU,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,YAAY,GAAG,QAAQ,CAAC;AACrC,uGAAuG;AAC1F,QAAA,WAAW,GAAG,OAAO,CAAC;AAEnC,8FAA8F;AACjF,QAAA,cAAc,GAAG,WAAW,CAAC;AAE1C;;;;;;;GAOG;AACH,MAAa,iBA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,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC9G,CAAC;IAED,wGAAwG;IAChG,IAAI,CAAC,KAAa;QACtB,OAAO,KAAK,CAAC,OAAO,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,qGAAqG;IACrG,8DAA8D;IACtD,GAAG,CAAC,QAAgB,EAAE,IAAc;QACxC,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QACjF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QACnC,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,CAAC;CACJ,CAAA;AAxHY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGT,2BAAW;QACJ,iCAAc;GAHxC,YAAY,CAwHxB","sourcesContent":["import { spawn, spawnSync, ChildProcess } from 'child_process';\nimport * as fs from 'fs';\nimport { BuildTermination } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GateLogFile } from './gate-log-file';\nimport { StageOutputLog } from './stage-output-log';\n\n// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────\n// The build gate already builds everything. When the output only ever went to the CONSOLE, an agent that\n// wanted a different slice of it re-ran the WHOLE BUILD to get it: one measured session spent 23.9 minutes\n// across nine `nx affected` runs, five of them with NO code change in between — `| tail -50`, then\n// `> /tmp/file`, then `| grep`, then `| sed -n '1100,1230p'`. ~19 minutes spent re-reading a log.\n//\n// So the build's output is not streamed; it is REDIRECTED, in full, to a file whose path the caller is\n// handed on completion. Reading a different slice is then a `grep` of a FILE, not a second build.\n//\n// ─── Why a redirect and not `tee` ──────────────────────────────────────────────────────────────────────\n// An earlier cut of this used `cmd 2>&1 | tee log`, to keep the terminal byte-identical. That is what\n// makes the transcript expensive in the first place — an AI caller carries every line of it in context.\n// The redirect keeps the console to a handful of lines (a heartbeat, then a pointer at the file), which is\n// the entire productivity claim. Losing `tee` also deletes the `$?`-into-a-side-file dance it needed: in a\n// pipeline the shell reports TEE's status, which is 0 whether the build passed or failed, so the status\n// had to be smuggled out through a side file. With no pipe, the child's own exit code IS the answer.\n//\n// ─── Why async (`spawn`, not `spawnSync`) ──────────────────────────────────────────────────────────────\n// `spawnSync` blocks the event loop for the length of the build, so NOTHING can print while it runs — and\n// a silent terminal for 3–7 minutes is indistinguishable from a hang. The heartbeat is the reason this is\n// async, and it is why `run` returns a Promise and `BuildAffected.runBuildGate` is async with it.\n//\n// It is also the reason the heartbeat goes through `StageOutputLog.say` rather than `process.stdout` —\n// stage ② and stage ③ capture their own console output to a file, and a heartbeat captured into a file is\n// a heartbeat nobody can see. The 600-second watchdog that kills a silent command does not read files.\n\n/** How often the heartbeat reports the log's size. Hardcoded: a knob here would be a knob the PR gate's\n * own build never receives, and the two must stay the same command. */\nexport const HEARTBEAT_MS = 10_000;\n\n/** How many trailing log lines the failure message echoes, so the immediate cause is visible without a\n * second command. Small on purpose — the FULL log is one grep away and the message must not become the\n * transcript it exists to replace. */\nexport const FAILURE_TAIL_LINES = 20;\n\n/**\n * Which stage's gate is being captured. The value decides the log FILENAME.\n */\nexport const REVIEW_STAGE = 'review';\nexport const FINISH_STAGE = 'finish';\n// `wp-build`, which is not a stage of the PR flow but runs the SAME gate (BuildAffected.runBuildGate).\nexport const BUILD_STAGE = 'build';\n\n/** The one fixed log name — see BuildGateLog.fileNameFor for why only `wp-build` gets one. */\nexport const BUILD_LOG_NAME = 'build.log';\n\n/**\n * The heartbeat's state: the line count reported on the PREVIOUS tick, so a tick that has not moved can\n * say so. Stateful per RUN, which is why it is constructed per run rather than injected.\n *\n * `still` is the load-bearing word. A build that is linking, or waiting on a cold nx cache, produces no\n * output for minutes; without `still` the caller sees the same number twice and cannot tell a stalled\n * BUILD from a stalled REPORTER.\n */\nexport class BuildLogHeartbeat {\n private previous: number | null = null;\n\n constructor(\n private readonly files: GateLogFile,\n private readonly logPath: string,\n private readonly displayPath: string,\n ) {}\n\n /** One heartbeat line — `<path> size <n> lines`, plus ` still` when <n> has not moved. */\n tick(): string {\n const count = this.files.lineCount(this.logPath);\n const still = this.previous !== null && count === this.previous ? ' still' : '';\n this.previous = count;\n return `${this.displayPath} size ${count} lines${still}`;\n }\n}\n\n/**\n * Captures the build gate's full output to a file, reports progress while it runs, and renders the\n * pointer the caller is handed instead of a rebuild instruction.\n *\n * WHERE the file goes, how the previous run is kept, and what the pointer reads like are `GateLogFile`'s\n * — one mechanism, shared with the stage console log, so there is a single answer to \"where is it?\".\n *\n * ─── Two naming schemes, one rule each ─────────────────────────────────────────────────────────────────\n * • `wp-build` (BUILD_STAGE) writes ONE fixed path, `.webpieces/build.log`. It is fixed because a HUMAN\n * OR AN AGENT TYPES IT — `grep -n error .webpieces/build.log` has to be writable from memory, and a\n * name carrying a branch and a sha is not. History comes from the rotation instead.\n * • stage ② and stage ③ write `logs/build-gate-<stage>-<branch>-<shortSha>.log`, because those two\n * gates CAN run against one commit and a failure message from one must not be pointing at a file the\n * other overwrote. Nobody types those names; the failure message prints them.\n *\n * ─── Concurrency ───────────────────────────────────────────────────────────────────────────────────────\n * The DIRECTORY is `dotWebpieces.local()`-scoped — `<primary>/.webpieces/worktrees/<git worktree name>/`\n * in a linked worktree — so \"N agents in N worktrees\" is safe by construction rather than by naming. The\n * residual case is two builds in the SAME worktree at once, which is already unsupported: both would be\n * driving one git index.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildGateLog {\n constructor(\n private readonly files: GateLogFile,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n /** Absolute path of the log for `stage` at the current HEAD, creating its directory. */\n pathFor(repoRoot: string, stage: string): string {\n return this.resolvePath(repoRoot, stage);\n }\n\n /** The same path, and '' when no log has been WRITTEN there yet. Used by finish's skip path. */\n existingLogFor(repoRoot: string, stage: string): string {\n const file = this.resolvePath(repoRoot, stage);\n return fs.existsSync(file) ? file : '';\n }\n\n /** `build.log` for `wp-build`; `build-gate-<stage>-<branch>-<shortSha>.log` for the PR-flow stages. */\n fileNameFor(repoRoot: string, stage: string): string {\n if (stage === BUILD_STAGE) return BUILD_LOG_NAME;\n const branch = this.slug(this.git(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']));\n const sha = this.slug(this.git(repoRoot, ['rev-parse', '--short', 'HEAD']));\n return `build-gate-${this.slug(stage)}-${branch === '' ? 'nobranch' : branch}-${sha === '' ? 'nosha' : sha}.log`;\n }\n\n /**\n * Run `buildCommand` with its stdout AND stderr redirected in full to `logPath`, printing a heartbeat\n * every HEARTBEAT_MS so the caller can see it is alive. Returns the BUILD's raw termination facts.\n * Nothing is truncated and nothing is streamed.\n */\n async run(repoRoot: string, buildCommand: string, logPath: string): Promise<BuildTermination> {\n this.files.rotate(logPath);\n const fd = fs.openSync(logPath, 'w');\n const heartbeat = new BuildLogHeartbeat(this.files, logPath, this.files.displayPath(repoRoot, logPath));\n const timer = setInterval((): void => { this.stageConsole.say(`${heartbeat.tick()}\\n`); }, HEARTBEAT_MS);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the timer and the fd MUST be released\n // whatever the child does, and the exit code is returned rather than thrown so runBuildGate owns\n // the one CliExitError.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await this.awaitExit(spawn(buildCommand, { cwd: repoRoot, shell: true, stdio: ['ignore', fd, fd] }), fd);\n } finally {\n clearInterval(timer);\n fs.closeSync(fd);\n }\n }\n\n /**\n * The success summary: the caller is told WHERE the full output is, not handed the output.\n */\n successMessage(logPath: string): string {\n return `\\nBuild success\\n${this.files.pointer(logPath)}`;\n }\n\n /**\n * The ENTIRE message the caller gets on a failed build. It names the log, echoes the last\n * FAILURE_TAIL_LINES lines so the immediate cause needs no second command, and forbids the rebuild\n * this whole file exists to prevent.\n *\n * The last sentence is not filler. If the log holds no visible failure then something upstream is wrong\n * (a runner that died without printing, a truncated redirect), and the worst possible response is an\n * agent guessing or rebuilding — so it is told to surface the contradiction to the human and stop.\n */\n failureMessage(buildCommand: string, logPath: string, termination: BuildTermination): string {\n return `\\nBuild Failed: ${buildCommand}\\n${this.files.pointer(logPath)}\\n` +\n `${this.terminationRecord(termination)}\\n` +\n `Last ${FAILURE_TAIL_LINES} lines of that log:\\n${this.files.tail(logPath, FAILURE_TAIL_LINES)}\\n` +\n `Read that FILE for the failures. Do NOT re-run the build to see them.\\n` +\n `If you do not see failures in that log, report that to the user and stop.\\n`;\n }\n\n // Resolve, and wait for, the child's close code AND signal. A spawn that never starts (a shell that is\n // missing, a cwd that vanished) fails CLOSED to 1 — calling a build that never ran green is the one\n // outcome that must be impossible — and the reason is APPENDED TO THE LOG, so the failure message's\n // pointer still leads to it rather than to an empty file.\n private awaitExit(child: ChildProcess, fd: number): Promise<BuildTermination> {\n return new Promise<BuildTermination>((resolve: (termination: BuildTermination) => void): void => {\n let settled = false;\n child.on('error', (err: Error): void => {\n if (settled) return;\n settled = true;\n fs.writeSync(fd, `\\nThe build command could not be started: ${err.message}\\n`);\n resolve(new BuildTermination(1, null));\n });\n child.on('close', (code: number | null, signal: NodeJS.Signals | null): void => {\n if (settled) return;\n settled = true;\n const termination = new BuildTermination(code, signal);\n if (code === null || signal !== null) fs.writeSync(fd, `\\n${this.terminationRecord(termination)}\\n`);\n resolve(termination);\n });\n });\n }\n\n /** One stable, human-readable spelling shared by the FullLog and the immediate failure output. */\n private terminationRecord(termination: BuildTermination): string {\n const code = termination.code === null ? 'null' : String(termination.code);\n const signal = termination.signal === null ? 'none' : termination.signal;\n return `Build process termination: exit code ${code}; signal ${signal}.`;\n }\n\n private resolvePath(repoRoot: string, stage: string): string {\n const name = this.fileNameFor(repoRoot, stage);\n // `wp-build`'s log sits at the ROOT of the state dir, not under `logs/`, because it is the one log\n // path a person types from memory. Everything else keeps the per-commit names in `logs/`.\n return stage === BUILD_STAGE ? this.files.localPath(repoRoot, name) : this.files.logsPath(repoRoot, name);\n }\n\n // Anything that is not a filename-safe character becomes '-', so `dean/feat` cannot create directories.\n private slug(value: string): string {\n return value.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');\n }\n\n // One local git read. Fails SOFT to '' — a missing branch/sha degrades the FILENAME, and degrading a\n // filename may never be the reason a build gate does not run.\n private git(repoRoot: string, args: string[]): string {\n const result = spawnSync('git', ['-C', repoRoot, ...args], { encoding: 'utf8' });\n if (result.status !== 0) return '';\n return (result.stdout ?? '').trim();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build-gate-log.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-gate-log.ts"],"names":[],"mappings":";;;;AAAA,iDAA+D;AAC/D,+CAAyB;AACzB,0DAA2D;AAC3D,yCAA2D;AAE3D,mDAA8C;AAC9C,yDAAoD;AACpD,6DAAwD;AAExD,0GAA0G;AAC1G,yGAAyG;AACzG,2GAA2G;AAC3G,mGAAmG;AACnG,kGAAkG;AAClG,EAAE;AACF,uGAAuG;AACvG,kGAAkG;AAClG,EAAE;AACF,0GAA0G;AAC1G,sGAAsG;AACtG,wGAAwG;AACxG,2GAA2G;AAC3G,2GAA2G;AAC3G,wGAAwG;AACxG,qGAAqG;AACrG,EAAE;AACF,0GAA0G;AAC1G,0GAA0G;AAC1G,0GAA0G;AAC1G,kGAAkG;AAClG,EAAE;AACF,uGAAuG;AACvG,0GAA0G;AAC1G,uGAAuG;AAEvG;uEACuE;AAC1D,QAAA,YAAY,GAAG,MAAM,CAAC;AAEnC;;sCAEsC;AACzB,QAAA,kBAAkB,GAAG,EAAE,CAAC;AAErC;;GAEG;AACU,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,YAAY,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AAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGT,2BAAW;QACJ,iCAAc;GAHxC,YAAY,CAuJxB","sourcesContent":["import { spawn, spawnSync, ChildProcess } from 'child_process';\nimport * as fs from 'fs';\nimport { BuildTermination } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GateLogFile } from './gate-log-file';\nimport { StageOutputLog } from './stage-output-log';\nimport { BuildLogFollower } from './build-log-follower';\n\n// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────\n// The build gate already builds everything. When the output only ever went to the CONSOLE, an agent that\n// wanted a different slice of it re-ran the WHOLE BUILD to get it: one measured session spent 23.9 minutes\n// across nine `nx affected` runs, five of them with NO code change in between — `| tail -50`, then\n// `> /tmp/file`, then `| grep`, then `| sed -n '1100,1230p'`. ~19 minutes spent re-reading a log.\n//\n// So the build's output is not streamed; it is REDIRECTED, in full, to a file whose path the caller is\n// handed on completion. Reading a different slice is then a `grep` of a FILE, not a second build.\n//\n// ─── Why a redirect and not `tee` ──────────────────────────────────────────────────────────────────────\n// An earlier cut of this used `cmd 2>&1 | tee log`, to keep the terminal byte-identical. That is what\n// makes the transcript expensive in the first place — an AI caller carries every line of it in context.\n// The redirect keeps the console to a handful of lines (a heartbeat, then a pointer at the file), which is\n// the entire productivity claim. Losing `tee` also deletes the `$?`-into-a-side-file dance it needed: in a\n// pipeline the shell reports TEE's status, which is 0 whether the build passed or failed, so the status\n// had to be smuggled out through a side file. With no pipe, the child's own exit code IS the answer.\n//\n// ─── Why async (`spawn`, not `spawnSync`) ──────────────────────────────────────────────────────────────\n// `spawnSync` blocks the event loop for the length of the build, so NOTHING can print while it runs — and\n// a silent terminal for 3–7 minutes is indistinguishable from a hang. The heartbeat is the reason this is\n// async, and it is why `run` returns a Promise and `BuildAffected.runBuildGate` is async with it.\n//\n// It is also the reason the heartbeat goes through `StageOutputLog.say` rather than `process.stdout` —\n// stage ② and stage ③ capture their own console output to a file, and a heartbeat captured into a file is\n// a heartbeat nobody can see. The 600-second watchdog that kills a silent command does not read files.\n\n/** How often the heartbeat reports the log's size. Hardcoded: a knob here would be a knob the PR gate's\n * own build never receives, and the two must stay the same command. */\nexport const HEARTBEAT_MS = 10_000;\n\n/** How many trailing log lines the failure message echoes, so the immediate cause is visible without a\n * second command. Small on purpose — the FULL log is one grep away and the message must not become the\n * transcript it exists to replace. */\nexport const FAILURE_TAIL_LINES = 20;\n\n/**\n * Which stage's gate is being captured. The value decides the log FILENAME.\n */\nexport const REVIEW_STAGE = 'review';\nexport const FINISH_STAGE = 'finish';\n// `wp-build`, which is not a stage of the PR flow but runs the SAME gate (BuildAffected.runBuildGate).\nexport const BUILD_STAGE = 'build';\n\n/** The one fixed log name — see BuildGateLog.fileNameFor for why only `wp-build` gets one. */\nexport const BUILD_LOG_NAME = 'build.log';\n\n/**\n * The heartbeat's state: the line count reported on the PREVIOUS tick, so a tick that has not moved can\n * say so. Stateful per RUN, which is why it is constructed per run rather than injected.\n *\n * `still` is the load-bearing word. A build that is linking, or waiting on a cold nx cache, produces no\n * output for minutes; without `still` the caller sees the same number twice and cannot tell a stalled\n * BUILD from a stalled REPORTER.\n */\nexport class BuildLogHeartbeat {\n private previous: number | null = null;\n\n constructor(\n private readonly files: GateLogFile,\n private readonly logPath: string,\n private readonly displayPath: string,\n ) {}\n\n /** One heartbeat line — `<path> size <n> lines`, plus ` still` when <n> has not moved. */\n tick(): string {\n const count = this.files.lineCount(this.logPath);\n const still = this.previous !== null && count === this.previous ? ' still' : '';\n this.previous = count;\n return `${this.displayPath} size ${count} lines${still}`;\n }\n}\n\n/**\n * Captures the build gate's full output to a file, reports progress while it runs, and renders the\n * pointer the caller is handed instead of a rebuild instruction.\n *\n * WHERE the file goes, how the previous run is kept, and what the pointer reads like are `GateLogFile`'s\n * — one mechanism, shared with the stage console log, so there is a single answer to \"where is it?\".\n *\n * ─── Two naming schemes, one rule each ─────────────────────────────────────────────────────────────────\n * • `wp-build` (BUILD_STAGE) writes ONE fixed path, `.webpieces/build.log`. It is fixed because a HUMAN\n * OR AN AGENT TYPES IT — `grep -n error .webpieces/build.log` has to be writable from memory, and a\n * name carrying a branch and a sha is not. History comes from the rotation instead.\n * • stage ② and stage ③ write `logs/build-gate-<stage>-<branch>-<shortSha>.log`, because those two\n * gates CAN run against one commit and a failure message from one must not be pointing at a file the\n * other overwrote. Nobody types those names; the failure message prints them.\n *\n * ─── Concurrency ───────────────────────────────────────────────────────────────────────────────────────\n * The DIRECTORY is `dotWebpieces.local()`-scoped — `<primary>/.webpieces/worktrees/<git worktree name>/`\n * in a linked worktree — so \"N agents in N worktrees\" is safe by construction rather than by naming. The\n * residual case is two builds in the SAME worktree at once, which is already unsupported: both would be\n * driving one git index.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildGateLog {\n constructor(\n private readonly files: GateLogFile,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n /** Absolute path of the log for `stage` at the current HEAD, creating its directory. */\n pathFor(repoRoot: string, stage: string): string {\n return this.resolvePath(repoRoot, stage);\n }\n\n /** The same path, and '' when no log has been WRITTEN there yet. Used by finish's skip path. */\n existingLogFor(repoRoot: string, stage: string): string {\n const file = this.resolvePath(repoRoot, stage);\n return fs.existsSync(file) ? file : '';\n }\n\n /** `build.log` for `wp-build`; `build-gate-<stage>-<branch>-<shortSha>.log` for the PR-flow stages. */\n fileNameFor(repoRoot: string, stage: string): string {\n if (stage === BUILD_STAGE) return BUILD_LOG_NAME;\n const branch = this.slug(this.git(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']));\n const sha = this.slug(this.git(repoRoot, ['rev-parse', '--short', 'HEAD']));\n return `build-gate-${this.slug(stage)}-${branch === '' ? 'nobranch' : branch}-${sha === '' ? 'nosha' : sha}.log`;\n }\n\n /**\n * Run `buildCommand` with its stdout AND stderr redirected in full to `logPath`, printing a heartbeat\n * every HEARTBEAT_MS so the caller can see it is alive. Returns the BUILD's raw termination facts.\n * Nothing is truncated. Ordinary AI-facing callers do not stream; the explicitly human-attested\n * PR escape hatch may wrap this with runStreaming(), which follows the same durable file live.\n */\n async run(repoRoot: string, buildCommand: string, logPath: string): Promise<BuildTermination> {\n this.files.rotate(logPath);\n const fd = fs.openSync(logPath, 'w');\n const heartbeat = new BuildLogHeartbeat(\n this.files,\n logPath,\n this.files.displayPath(repoRoot, logPath),\n );\n const timer = setInterval((): void => {\n this.stageConsole.say(`${heartbeat.tick()}\\n`);\n }, HEARTBEAT_MS);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the timer and the fd MUST be released\n // whatever the child does, and the exit code is returned rather than thrown so runBuildGate owns\n // the one CliExitError.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await this.awaitExit(\n spawn(buildCommand, { cwd: repoRoot, shell: true, stdio: ['ignore', fd, fd] }),\n fd,\n );\n } finally {\n clearInterval(timer);\n fs.closeSync(fd);\n }\n }\n\n /** Human-only variant: preserve the durable log and follow its appended bytes live. */\n runStreaming(\n repoRoot: string,\n buildCommand: string,\n logPath: string,\n ): Promise<BuildTermination> {\n // run() synchronously rotates and opens the file before reaching its first await, so the follower\n // cannot accidentally replay the previous build that was at this path.\n const completion = this.run(repoRoot, buildCommand, logPath);\n const follower = new BuildLogFollower(logPath, this.stageConsole);\n follower.start();\n return completion.finally((): void => follower.stop());\n }\n\n /**\n * The success summary: the caller is told WHERE the full output is, not handed the output.\n */\n successMessage(logPath: string): string {\n return `\\nBuild success\\n${this.files.pointer(logPath)}`;\n }\n\n /**\n * The ENTIRE message the caller gets on a failed build. It names the log, echoes the last\n * FAILURE_TAIL_LINES lines so the immediate cause needs no second command, and forbids the rebuild\n * this whole file exists to prevent.\n *\n * The last sentence is not filler. If the log holds no visible failure then something upstream is wrong\n * (a runner that died without printing, a truncated redirect), and the worst possible response is an\n * agent guessing or rebuilding — so it is told to surface the contradiction to the human and stop.\n */\n failureMessage(buildCommand: string, logPath: string, termination: BuildTermination): string {\n return (\n `\\nBuild Failed: ${buildCommand}\\n${this.files.pointer(logPath)}\\n` +\n `${this.terminationRecord(termination)}\\n` +\n `Last ${FAILURE_TAIL_LINES} lines of that log:\\n${this.files.tail(logPath, FAILURE_TAIL_LINES)}\\n` +\n `Read that FILE for the failures. Do NOT re-run the build to see them.\\n` +\n `If you do not see failures in that log, report that to the user and stop.\\n`\n );\n }\n\n // Resolve, and wait for, the child's close code AND signal. A spawn that never starts (a shell that is\n // missing, a cwd that vanished) fails CLOSED to 1 — calling a build that never ran green is the one\n // outcome that must be impossible — and the reason is APPENDED TO THE LOG, so the failure message's\n // pointer still leads to it rather than to an empty file.\n private awaitExit(child: ChildProcess, fd: number): Promise<BuildTermination> {\n return new Promise<BuildTermination>(\n (resolve: (termination: BuildTermination) => void): void => {\n let settled = false;\n child.on('error', (err: Error): void => {\n if (settled) return;\n settled = true;\n fs.writeSync(fd, `\\nThe build command could not be started: ${err.message}\\n`);\n resolve(new BuildTermination(1, null));\n });\n child.on('close', (code: number | null, signal: NodeJS.Signals | null): void => {\n if (settled) return;\n settled = true;\n const termination = new BuildTermination(code, signal);\n if (code === null || signal !== null)\n fs.writeSync(fd, `\\n${this.terminationRecord(termination)}\\n`);\n resolve(termination);\n });\n },\n );\n }\n\n /** One stable, human-readable spelling shared by the FullLog and the immediate failure output. */\n private terminationRecord(termination: BuildTermination): string {\n const code = termination.code === null ? 'null' : String(termination.code);\n const signal = termination.signal === null ? 'none' : termination.signal;\n return `Build process termination: exit code ${code}; signal ${signal}.`;\n }\n\n private resolvePath(repoRoot: string, stage: string): string {\n const name = this.fileNameFor(repoRoot, stage);\n // `wp-build`'s log sits at the ROOT of the state dir, not under `logs/`, because it is the one log\n // path a person types from memory. Everything else keeps the per-commit names in `logs/`.\n return stage === BUILD_STAGE\n ? this.files.localPath(repoRoot, name)\n : this.files.logsPath(repoRoot, name);\n }\n\n // Anything that is not a filename-safe character becomes '-', so `dean/feat` cannot create directories.\n private slug(value: string): string {\n return value.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');\n }\n\n // One local git read. Fails SOFT to '' — a missing branch/sha degrades the FILENAME, and degrading a\n // filename may never be the reason a build gate does not run.\n private git(repoRoot: string, args: string[]): string {\n const result = spawnSync('git', ['-C', repoRoot, ...args], { encoding: 'utf8' });\n if (result.status !== 0) return '';\n return (result.stdout ?? '').trim();\n }\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { StageOutputLog } from './stage-output-log';
|
|
2
|
+
/** Reads newly appended build-log bytes and mirrors them to the human's terminal until stopped. */
|
|
3
|
+
export declare class BuildLogFollower {
|
|
4
|
+
private readonly logPath;
|
|
5
|
+
private readonly stageConsole;
|
|
6
|
+
private offset;
|
|
7
|
+
private timer;
|
|
8
|
+
private readonly decoder;
|
|
9
|
+
constructor(logPath: string, stageConsole: StageOutputLog);
|
|
10
|
+
start(): void;
|
|
11
|
+
stop(): void;
|
|
12
|
+
private flush;
|
|
13
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BuildLogFollower = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
6
|
+
const string_decoder_1 = require("string_decoder");
|
|
7
|
+
/** Reads newly appended build-log bytes and mirrors them to the human's terminal until stopped. */
|
|
8
|
+
class BuildLogFollower {
|
|
9
|
+
logPath;
|
|
10
|
+
stageConsole;
|
|
11
|
+
offset = 0;
|
|
12
|
+
timer = null;
|
|
13
|
+
decoder = new string_decoder_1.StringDecoder('utf8');
|
|
14
|
+
constructor(logPath, stageConsole) {
|
|
15
|
+
this.logPath = logPath;
|
|
16
|
+
this.stageConsole = stageConsole;
|
|
17
|
+
}
|
|
18
|
+
start() {
|
|
19
|
+
this.timer = setInterval(() => this.flush(), 100);
|
|
20
|
+
}
|
|
21
|
+
stop() {
|
|
22
|
+
if (this.timer !== null)
|
|
23
|
+
clearInterval(this.timer);
|
|
24
|
+
this.timer = null;
|
|
25
|
+
this.flush();
|
|
26
|
+
const remaining = this.decoder.end();
|
|
27
|
+
if (remaining !== '')
|
|
28
|
+
this.stageConsole.say(remaining);
|
|
29
|
+
}
|
|
30
|
+
flush() {
|
|
31
|
+
if (!fs.existsSync(this.logPath))
|
|
32
|
+
return;
|
|
33
|
+
const size = fs.statSync(this.logPath).size;
|
|
34
|
+
if (size <= this.offset)
|
|
35
|
+
return;
|
|
36
|
+
const length = size - this.offset;
|
|
37
|
+
const buffer = Buffer.alloc(length);
|
|
38
|
+
const fd = fs.openSync(this.logPath, 'r');
|
|
39
|
+
const bytesRead = fs.readSync(fd, buffer, 0, length, this.offset);
|
|
40
|
+
fs.closeSync(fd);
|
|
41
|
+
this.offset += bytesRead;
|
|
42
|
+
const text = this.decoder.write(buffer.subarray(0, bytesRead));
|
|
43
|
+
if (text !== '')
|
|
44
|
+
this.stageConsole.say(text);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.BuildLogFollower = BuildLogFollower;
|
|
48
|
+
//# sourceMappingURL=build-log-follower.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-log-follower.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-log-follower.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA+C;AAG/C,mGAAmG;AACnG,MAAa,gBAAgB;IAMJ;IACA;IANb,MAAM,GAAG,CAAC,CAAC;IACX,KAAK,GAA0B,IAAI,CAAC;IAC3B,OAAO,GAAG,IAAI,8BAAa,CAAC,MAAM,CAAC,CAAC;IAErD,YACqB,OAAe,EACf,YAA4B;QAD5B,YAAO,GAAP,OAAO,CAAQ;QACf,iBAAY,GAAZ,YAAY,CAAgB;IAC9C,CAAC;IAEJ,KAAK;QACD,IAAI,CAAC,KAAK,GAAG,WAAW,CAAC,GAAS,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE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Y,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;CACJ;AAnCD,4CAmCC","sourcesContent":["import * as fs from 'fs';\nimport { StringDecoder } from 'string_decoder';\nimport { StageOutputLog } from './stage-output-log';\n\n/** Reads newly appended build-log bytes and mirrors them to the human's terminal until stopped. */\nexport class BuildLogFollower {\n private offset = 0;\n private timer: NodeJS.Timeout | null = null;\n private readonly decoder = new StringDecoder('utf8');\n\n constructor(\n private readonly logPath: string,\n private readonly stageConsole: StageOutputLog,\n ) {}\n\n start(): void {\n this.timer = setInterval((): void => this.flush(), 100);\n }\n\n stop(): void {\n if (this.timer !== null) clearInterval(this.timer);\n this.timer = null;\n this.flush();\n const remaining = this.decoder.end();\n if (remaining !== '') this.stageConsole.say(remaining);\n }\n\n private flush(): void {\n if (!fs.existsSync(this.logPath)) return;\n const size = fs.statSync(this.logPath).size;\n if (size <= this.offset) return;\n const length = size - this.offset;\n const buffer = Buffer.alloc(length);\n const fd = fs.openSync(this.logPath, 'r');\n const bytesRead = fs.readSync(fd, buffer, 0, length, this.offset);\n fs.closeSync(fd);\n this.offset += bytesRead;\n const text = this.decoder.write(buffer.subarray(0, bytesRead));\n if (text !== '') this.stageConsole.say(text);\n }\n}\n"]}
|
|
@@ -37,7 +37,7 @@ export declare class GatedPrPublisher {
|
|
|
37
37
|
*
|
|
38
38
|
* @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha
|
|
39
39
|
*/
|
|
40
|
-
publish(baseBranch: string, title: string, bodyFile: string): PublishedPr;
|
|
40
|
+
publish(baseBranch: string, title: string, bodyFile: string, retryCommand?: string): PublishedPr;
|
|
41
41
|
private editPrOrAbort;
|
|
42
42
|
protected findOpenPr(baseBranch: string): string;
|
|
43
43
|
protected editPr(prNumber: string, title: string, bodyFile: string): boolean;
|
|
@@ -53,18 +53,18 @@ let GatedPrPublisher = class GatedPrPublisher {
|
|
|
53
53
|
*
|
|
54
54
|
* @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha
|
|
55
55
|
*/
|
|
56
|
-
publish(baseBranch, title, bodyFile) {
|
|
56
|
+
publish(baseBranch, title, bodyFile, retryCommand = 'pnpm wp-finish-upsert-pr') {
|
|
57
57
|
const existing = this.findOpenPr(baseBranch);
|
|
58
58
|
// 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.
|
|
59
59
|
if (existing !== '') {
|
|
60
60
|
process.stdout.write(`Updating PR #${existing} (body before push, so CI cannot read a stale token)...\n`);
|
|
61
|
-
this.editPrOrAbort(existing, title, bodyFile);
|
|
61
|
+
this.editPrOrAbort(existing, title, bodyFile, retryCommand);
|
|
62
62
|
// Say the consequence BEFORE the push can fail: from here the PR advertises a token for the
|
|
63
63
|
// local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes
|
|
64
64
|
// RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.
|
|
65
65
|
process.stdout.write(' body updated. Pushing now — if this push FAILS, the PR advertises a token for a commit\n' +
|
|
66
66
|
' the remote does not have, so the webpieces gate check goes RED (never falsely green)\n' +
|
|
67
|
-
|
|
67
|
+
` until you fix the push and re-run ${retryCommand}.\n`);
|
|
68
68
|
}
|
|
69
69
|
// 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.
|
|
70
70
|
this.push(baseBranch);
|
|
@@ -77,12 +77,12 @@ let GatedPrPublisher = class GatedPrPublisher {
|
|
|
77
77
|
// Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would
|
|
78
78
|
// push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose
|
|
79
79
|
// token is still valid for the sha the remote still has. Nothing is half-done either way.
|
|
80
|
-
editPrOrAbort(prNumber, title, bodyFile) {
|
|
80
|
+
editPrOrAbort(prNumber, title, bodyFile, retryCommand) {
|
|
81
81
|
if (this.editPr(prNumber, title, bodyFile))
|
|
82
82
|
return;
|
|
83
83
|
throw new rules_config_1.CliExitError(1, `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\n` +
|
|
84
84
|
` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\n` +
|
|
85
|
-
`
|
|
85
|
+
` ${retryCommand}. The new body is in:\n ${bodyFile}`);
|
|
86
86
|
}
|
|
87
87
|
// The `gh`/push seams, protected so the spec can drive the ordering with no gh, no network, no repo.
|
|
88
88
|
// The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,
|
|
@@ -92,10 +92,23 @@ let GatedPrPublisher = class GatedPrPublisher {
|
|
|
92
92
|
return result.status === 0 ? (result.stdout ?? '').trim() : '';
|
|
93
93
|
}
|
|
94
94
|
editPr(prNumber, title, bodyFile) {
|
|
95
|
-
return (0, child_process_1.spawnSync)('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], {
|
|
95
|
+
return ((0, child_process_1.spawnSync)('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], {
|
|
96
|
+
stdio: 'inherit',
|
|
97
|
+
}).status === 0);
|
|
96
98
|
}
|
|
97
99
|
createPr(baseBranch, title, bodyFile) {
|
|
98
|
-
return (0, child_process_1.spawnSync)('gh', [
|
|
100
|
+
return ((0, child_process_1.spawnSync)('gh', [
|
|
101
|
+
'pr',
|
|
102
|
+
'create',
|
|
103
|
+
'--head',
|
|
104
|
+
baseBranch,
|
|
105
|
+
'--base',
|
|
106
|
+
'main',
|
|
107
|
+
'--title',
|
|
108
|
+
title,
|
|
109
|
+
'--body-file',
|
|
110
|
+
bodyFile,
|
|
111
|
+
], { stdio: 'inherit' }).status === 0);
|
|
99
112
|
}
|
|
100
113
|
// Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the
|
|
101
114
|
// consequence is already printed above, and swallowing it would report a PR that was never updated.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gated-pr-publisher.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gated-pr-publisher.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AAE,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;IACnK,CAAC;IAED,mGAAmG;IACnG,oGAAoG;IAC1F,IAAI,CAAC,UAAkB;QAC7B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;CACJ,CAAA;AAnEY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,gBAAgB,CAmE5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitExec } from './git-exec';\n\n// Which PR the gated body landed on. Data-only.\nexport class PublishedPr {\n // The PR that already existed and was edited; '' when this run had to create one.\n number: string;\n // True only on the create path, when `gh pr create` itself failed — there is no PR to merge.\n createFailed: boolean;\n\n constructor(number: string, createFailed: boolean) {\n this.number = number;\n this.createFailed = createFailed;\n }\n}\n\n/**\n * Owns the ONE ordering constraint that lets the webpieces gate be a single required check: the PR body\n * — which carries `HMAC(gateSalt, HEAD_sha)` — is written BEFORE the push.\n *\n * WHY the order matters. Pushing first fires `pull_request:synchronize`, and CI (`wp-check-pr`) reads the\n * PR body it finds at that instant. If the body edit has not landed yet, that read sees the PREVIOUS\n * run's token, which is bound to the parent sha, and the check goes red on a timing coin-flip. #485\n * papered over this by also posting a `webpieces/pr-gate` commit status, whose newest post supersedes an\n * older one — recovery rather than prevention, and it left consumers with two entries on every PR and no\n * way to tell which one to mark required.\n *\n * The sha is already known locally: nothing about minting `HMAC(gateSalt, git rev-parse HEAD)` needs the\n * remote to have the commit. So write the body first and the `synchronize` read can only ever see the\n * right token. A brand-new PR is unaffected either way — `gh pr create` composes the body after the push,\n * so the `opened` event already sees the final body.\n *\n * THIS IS THE ONLY PUSH IN THE PR FLOW. `wp-start-upsert-pr` used to push twice (its own `ensurePushed`,\n * and the force-push inside the 3-point merge finalize), which put code on the remote before summary.json\n * and the checklists had even run, and fired `synchronize` against a PR body still carrying the previous\n * run's token. Both are gone — the merge finalize now takes `MergeEndOptions.pushRemote=false` in the PR\n * flow. So the single `synchronize` of a cycle arrives strictly after the body edit below, and can only\n * ever read the correct token.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GatedPrPublisher {\n constructor(private readonly gitExec: GitExec) {}\n\n /**\n * Land `bodyFile` on the PR for `baseBranch` and push, in the gate-safe order.\n *\n * @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha\n */\n publish(baseBranch: string, title: string, bodyFile: string): PublishedPr {\n const existing = this.findOpenPr(baseBranch);\n\n // 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.\n if (existing !== '') {\n process.stdout.write(`Updating PR #${existing} (body before push, so CI cannot read a stale token)...\\n`);\n this.editPrOrAbort(existing, title, bodyFile);\n // Say the consequence BEFORE the push can fail: from here the PR advertises a token for the\n // local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes\n // RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.\n process.stdout.write(\n ' body updated. Pushing now — if this push FAILS, the PR advertises a token for a commit\\n' +\n ' the remote does not have, so the webpieces gate check goes RED (never falsely green)\\n' +\n ' until you fix the push and re-run pnpm wp-finish-upsert-pr.\\n',\n );\n }\n\n // 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.\n this.push(baseBranch);\n\n // 3. Only a brand-new PR is created, and only after the push — `gh pr create` needs the remote ref.\n if (existing !== '') return new PublishedPr(existing, false);\n process.stdout.write('Creating PR...\\n');\n return new PublishedPr('', !this.createPr(baseBranch, title, bodyFile));\n }\n\n // Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would\n // push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose\n // token is still valid for the sha the remote still has. Nothing is half-done either way.\n private editPrOrAbort(prNumber: string, title: string, bodyFile: string): void {\n if (this.editPr(prNumber, title, bodyFile)) return;\n throw new CliExitError(1,\n `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\\n` +\n ` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\\n` +\n ` pnpm wp-finish-upsert-pr. The new body is in:\\n ${bodyFile}`);\n }\n\n // The `gh`/push seams, protected so the spec can drive the ordering with no gh, no network, no repo.\n\n // The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,\n // so the create path then fails loudly rather than silently editing the wrong PR).\n protected findOpenPr(baseBranch: string): string {\n const result = spawnSync('gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n protected editPr(prNumber: string, title: string, bodyFile: string): boolean {\n return spawnSync('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], { stdio: 'inherit' }).status === 0;\n }\n\n protected createPr(baseBranch: string, title: string, bodyFile: string): boolean {\n return spawnSync('gh', ['pr', 'create', '--head', baseBranch, '--base', 'main', '--title', title, '--body-file', bodyFile], { stdio: 'inherit' }).status === 0;\n }\n\n // Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the\n // consequence is already printed above, and swallowing it would report a PR that was never updated.\n protected push(baseBranch: string): void {\n this.gitExec.ensurePushed(baseBranch);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gated-pr-publisher.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gated-pr-publisher.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuD;AACvD,yCAA2D;AAC3D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L,IAAI,EACJ;YACI,IAAI;YACJ,QAAQ;YACR,QAAQ;YACR,UAAU;YACV,QAAQ;YACR,MAAM;YACN,SAAS;YACT,KAAK;YACL,aAAa;YACb,QAAQ;SACX,EACD,EAAE,KAAK,EAAE,SAAS,EAAE,CACvB,CAAC,MAAM,KAAK,CAAC,CACjB,CAAC;IACN,CAAC;IAED,mGAAmG;IACnG,oGAAoG;IAC1F,IAAI,CAAC,UAAkB;QAC7B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;CACJ,CAAA;AA1GY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,gBAAgB,CA0G5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitExec } from './git-exec';\n\n// Which PR the gated body landed on. Data-only.\nexport class PublishedPr {\n // The PR that already existed and was edited; '' when this run had to create one.\n number: string;\n // True only on the create path, when `gh pr create` itself failed — there is no PR to merge.\n createFailed: boolean;\n\n constructor(number: string, createFailed: boolean) {\n this.number = number;\n this.createFailed = createFailed;\n }\n}\n\n/**\n * Owns the ONE ordering constraint that lets the webpieces gate be a single required check: the PR body\n * — which carries `HMAC(gateSalt, HEAD_sha)` — is written BEFORE the push.\n *\n * WHY the order matters. Pushing first fires `pull_request:synchronize`, and CI (`wp-check-pr`) reads the\n * PR body it finds at that instant. If the body edit has not landed yet, that read sees the PREVIOUS\n * run's token, which is bound to the parent sha, and the check goes red on a timing coin-flip. #485\n * papered over this by also posting a `webpieces/pr-gate` commit status, whose newest post supersedes an\n * older one — recovery rather than prevention, and it left consumers with two entries on every PR and no\n * way to tell which one to mark required.\n *\n * The sha is already known locally: nothing about minting `HMAC(gateSalt, git rev-parse HEAD)` needs the\n * remote to have the commit. So write the body first and the `synchronize` read can only ever see the\n * right token. A brand-new PR is unaffected either way — `gh pr create` composes the body after the push,\n * so the `opened` event already sees the final body.\n *\n * THIS IS THE ONLY PUSH IN THE PR FLOW. `wp-start-upsert-pr` used to push twice (its own `ensurePushed`,\n * and the force-push inside the 3-point merge finalize), which put code on the remote before summary.json\n * and the checklists had even run, and fired `synchronize` against a PR body still carrying the previous\n * run's token. Both are gone — the merge finalize now takes `MergeEndOptions.pushRemote=false` in the PR\n * flow. So the single `synchronize` of a cycle arrives strictly after the body edit below, and can only\n * ever read the correct token.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GatedPrPublisher {\n constructor(private readonly gitExec: GitExec) {}\n\n /**\n * Land `bodyFile` on the PR for `baseBranch` and push, in the gate-safe order.\n *\n * @param bodyFile the rendered dashboard ALREADY carrying the gate token for the LOCAL head sha\n */\n publish(\n baseBranch: string,\n title: string,\n bodyFile: string,\n retryCommand = 'pnpm wp-finish-upsert-pr',\n ): PublishedPr {\n const existing = this.findOpenPr(baseBranch);\n\n // 1. Body FIRST, so a `synchronize` read arriving the instant after the push finds the right token.\n if (existing !== '') {\n process.stdout.write(\n `Updating PR #${existing} (body before push, so CI cannot read a stale token)...\\n`,\n );\n this.editPrOrAbort(existing, title, bodyFile, retryCommand);\n // Say the consequence BEFORE the push can fail: from here the PR advertises a token for the\n // local HEAD, so a failed push leaves the PR pointing at the old commit and the gate check goes\n // RED. That is the deliberate fail-CLOSED direction, and it self-corrects on the next good run.\n process.stdout.write(\n ' body updated. Pushing now — if this push FAILS, the PR advertises a token for a commit\\n' +\n ' the remote does not have, so the webpieces gate check goes RED (never falsely green)\\n' +\n ` until you fix the push and re-run ${retryCommand}.\\n`,\n );\n }\n\n // 2. THEN push. Nothing was pushed above, so an edit failure left the remote wholly untouched.\n this.push(baseBranch);\n\n // 3. Only a brand-new PR is created, and only after the push — `gh pr create` needs the remote ref.\n if (existing !== '') return new PublishedPr(existing, false);\n process.stdout.write('Creating PR...\\n');\n return new PublishedPr('', !this.createPr(baseBranch, title, bodyFile));\n }\n\n // Edit the PR body/title, aborting BEFORE the push if `gh` failed. Warning-and-continuing here would\n // push code that the PR body does not vouch for; aborting leaves the PR on its previous body, whose\n // token is still valid for the sha the remote still has. Nothing is half-done either way.\n private editPrOrAbort(\n prNumber: string,\n title: string,\n bodyFile: string,\n retryCommand: string,\n ): void {\n if (this.editPr(prNumber, title, bodyFile)) return;\n throw new CliExitError(\n 1,\n `❌ gh pr edit failed on PR #${prNumber} — NOTHING was pushed, so the PR and the remote branch are\\n` +\n ` both unchanged and still consistent. Fix gh (auth / network / permissions) and re-run\\n` +\n ` ${retryCommand}. The new body is in:\\n ${bodyFile}`,\n );\n }\n\n // The `gh`/push seams, protected so the spec can drive the ordering with no gh, no network, no repo.\n\n // The open PR whose head is `baseBranch`, or '' when there is none (or `gh` failed — treated the same,\n // so the create path then fails loudly rather than silently editing the wrong PR).\n protected findOpenPr(baseBranch: string): string {\n const result = spawnSync(\n 'gh',\n ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n protected editPr(prNumber: string, title: string, bodyFile: string): boolean {\n return (\n spawnSync('gh', ['pr', 'edit', prNumber, '--title', title, '--body-file', bodyFile], {\n stdio: 'inherit',\n }).status === 0\n );\n }\n\n protected createPr(baseBranch: string, title: string, bodyFile: string): boolean {\n return (\n spawnSync(\n 'gh',\n [\n 'pr',\n 'create',\n '--head',\n baseBranch,\n '--base',\n 'main',\n '--title',\n title,\n '--body-file',\n bodyFile,\n ],\n { stdio: 'inherit' },\n ).status === 0\n );\n }\n\n // Throws (CliExitError, via runGitChecked) when the push fails — deliberately NOT caught here: the\n // consequence is already printed above, and swallowing it would report a PR that was never updated.\n protected push(baseBranch: string): void {\n this.gitExec.ensurePushed(baseBranch);\n }\n}\n"]}
|
|
@@ -46,9 +46,14 @@ exports.PushDevState = PushDevState;
|
|
|
46
46
|
// (the finishes), or deletes branches (cleanup) — and during a resolve the checkout is a throwaway
|
|
47
47
|
// branch, not the feature branch any of them think they are acting on.
|
|
48
48
|
const BLOCKED_DURING_RESOLVE = [
|
|
49
|
-
'wp-start-update',
|
|
50
|
-
'wp-
|
|
51
|
-
'wp-
|
|
49
|
+
'wp-start-update',
|
|
50
|
+
'wp-finish-update',
|
|
51
|
+
'wp-start-upsert-pr',
|
|
52
|
+
'wp-review-upsert-pr',
|
|
53
|
+
'wp-finish-upsert-pr',
|
|
54
|
+
'wp-human-post-pr',
|
|
55
|
+
'wp-land-pr',
|
|
56
|
+
'wp-cleanup',
|
|
52
57
|
];
|
|
53
58
|
/**
|
|
54
59
|
* Reads, writes and clears the resolve state file, and refuses the other `wp-*` commands while it
|
|
@@ -106,11 +111,15 @@ let PushDevStateStore = class PushDevStateStore {
|
|
|
106
111
|
const state = this.read(repoRoot);
|
|
107
112
|
if (state !== null)
|
|
108
113
|
return state;
|
|
109
|
-
throw new rules_config_1.CliExitError(2, '\n' +
|
|
110
|
-
+
|
|
111
|
-
|
|
112
|
-
+
|
|
113
|
-
|
|
114
|
+
throw new rules_config_1.CliExitError(2, '\n' +
|
|
115
|
+
SEP +
|
|
116
|
+
'⛔ No dev-deploy resolve is in progress\n' +
|
|
117
|
+
SEP +
|
|
118
|
+
'\n' +
|
|
119
|
+
`${rules_config_1.WP_FINISH_PUSH_DEV} resumes a resolve that \`${rules_config_1.WP_PUSH_DEV} --resolve\` started, and there is no\n` +
|
|
120
|
+
`state file at:\n ${this.path(repoRoot)}\n\n` +
|
|
121
|
+
'If you meant to publish your branch to the shared dev server, that is the one-command form:\n' +
|
|
122
|
+
` ${rules_config_1.WP_PUSH_DEV}\n`);
|
|
114
123
|
}
|
|
115
124
|
/**
|
|
116
125
|
* Refuse `attempted` while a resolve is half-finished. Called from the app root for every command in
|
|
@@ -120,15 +129,19 @@ let PushDevStateStore = class PushDevStateStore {
|
|
|
120
129
|
const state = this.read(repoRoot);
|
|
121
130
|
if (state === null)
|
|
122
131
|
return;
|
|
123
|
-
throw new rules_config_1.CliExitError(2, '\n' +
|
|
124
|
-
+
|
|
125
|
-
|
|
126
|
-
+
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
+
throw new rules_config_1.CliExitError(2, '\n' +
|
|
133
|
+
SEP +
|
|
134
|
+
`⛔ A dev-deploy resolve is in progress — \`pnpm ${attempted}\` is blocked\n` +
|
|
135
|
+
SEP +
|
|
136
|
+
'\n' +
|
|
137
|
+
`You are standing on the throwaway branch \`${state.tmpBranch}\`, not on \`${state.originalBranch}\`,\n` +
|
|
138
|
+
`so ${this.blockedCommandList()} would all act on the wrong branch.\n` +
|
|
139
|
+
'That is the whole list; nothing else is blocked.\n\n' +
|
|
140
|
+
'EXPECTED of you right now, and NOT blocked: read the conflicted files and edit them until every\n' +
|
|
141
|
+
'conflict marker is gone. Then finish or bail out:\n' +
|
|
142
|
+
` ${rules_config_1.WP_FINISH_PUSH_DEV} ← commit the resolution, resume the queue, publish the copy\n` +
|
|
143
|
+
` ${rules_config_1.WP_FINISH_PUSH_DEV} --abort ← throw the resolution away and go back to \`${state.originalBranch}\`\n\n` +
|
|
144
|
+
`State file: ${this.path(repoRoot)}\n`);
|
|
132
145
|
}
|
|
133
146
|
// Rendered from BLOCKED_DURING_RESOLVE, never hand-written — see that constant.
|
|
134
147
|
blockedCommandList() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"push-dev-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/push-dev-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,0DAOiC;AACjC,yCAA2D;AAE3D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;GASG;AACH,MAAa,YAAY;IACrB,kGAAkG;IAClG,cAAc,CAAS;IACvB,uFAAuF;IACvF,SAAS,C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,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzF,CAAC;IAED,uFAAuF;IACvF,sBAAsB,CAAC,OAAe;QAClC,OAAO,sBAAsB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACpD,CAAC;CACJ,CAAA;AApFY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEM,2BAAY;GAD9C,iBAAiB,CAoF7B","sourcesContent":["import * as fs from 'fs';\n\nimport {\n CliExitError,\n DotWebpieces,\n PUSH_DEV_STATE_FILE,\n WP_FINISH_PUSH_DEV,\n WP_PUSH_DEV,\n toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The persisted half of the `wp-push-dev --resolve` state machine.\n *\n * A single-shot wrapper is IMPOSSIBLE here and that is why this file exists: `git merge` halts on\n * conflict with markers in the working tree and a non-zero exit, and a human or an AI has to edit files\n * before anything can be committed. So the command must be able to stop, hand the tree over, and be\n * resumed by a second command that knows exactly where it left off.\n *\n * Data-only (per CLAUDE.md) — the behaviour lives in {@link PushDevStateStore}.\n */\nexport class PushDevState {\n /** The branch to return to when the resolve finishes or aborts. NEVER written to by this flow. */\n originalBranch: string;\n /** The local throwaway branch the merges happen on. Deleted on finish and on abort. */\n tmpBranch: string;\n /** `<namespace>/<originalBranch>` — the remote copy this resolve republishes. */\n targetRef: string;\n /** The copy refs still to merge, in the order CI composes them. */\n queue: string[];\n /** The ref currently mid-merge (conflicted), or '' when nothing is halted. */\n current: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(originalBranch: string, tmpBranch: string, targetRef: string, queue: string[], current = '') {\n this.originalBranch = originalBranch;\n this.tmpBranch = tmpBranch;\n this.targetRef = targetRef;\n this.queue = queue;\n this.current = current;\n }\n}\n\n// The wp-* commands that must REFUSE while a resolve is half-finished, and the ONE place that list is\n// written. The blocked-list sentence below RENDERS ITSELF from this array — the same lesson\n// merge-in-progress-guard already learned the hard way: a hand-written \"don't run other commands\"\n// survives every edit to the actual enforcement and ends up forbidding things the flow requires.\n//\n// Why these and not everything: each one either rewrites the current branch (the two starts), pushes it\n// (the finishes), or deletes branches (cleanup) — and during a resolve the checkout is a throwaway\n// branch, not the feature branch any of them think they are acting on.\nconst BLOCKED_DURING_RESOLVE: readonly string[] = [\n 'wp-start-update', 'wp-finish-update',\n 'wp-start-upsert-pr', 'wp-review-upsert-pr', 'wp-finish-upsert-pr',\n 'wp-land-pr', 'wp-cleanup',\n];\n\n/**\n * Reads, writes and clears the resolve state file, and refuses the other `wp-*` commands while it\n * exists.\n *\n * LOCAL scope, deliberately: a resolve halts one worktree's checkout on a throwaway branch, and another\n * worktree has no reason to care. Sharing it would block a colleague's PR flow on state that says\n * nothing about their tree.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PushDevStateStore {\n constructor(private readonly dotWebpieces: DotWebpieces) {}\n\n path(repoRoot: string): string {\n return this.dotWebpieces.localFile(repoRoot, PUSH_DEV_STATE_FILE);\n }\n\n exists(repoRoot: string): boolean {\n return fs.existsSync(this.path(repoRoot));\n }\n\n /** The in-flight resolve, or null when none is. A corrupt file reads as null rather than crashing. */\n read(repoRoot: string): PushDevState | null {\n const file = this.path(repoRoot);\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- a truncated/hand-edited state file must degrade to \"no resolve in progress\" (recoverable via --abort or a fresh --resolve), never crash every wp-* command in the tree\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- JSON.parse is untyped until narrowed on the next line\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<PushDevState>;\n if (typeof raw.originalBranch !== 'string' || typeof raw.tmpBranch !== 'string') return null;\n return new PushDevState(\n raw.originalBranch, raw.tmpBranch, raw.targetRef ?? '',\n Array.isArray(raw.queue) ? raw.queue : [], raw.current ?? '');\n // The parse error carries nothing a caller could act on: the ONLY meaningful reading of an\n // unparseable state file is \"no resolve in progress\", which --abort and a fresh --resolve both\n // recover from.\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n write(repoRoot: string, state: PushDevState): void {\n fs.mkdirSync(this.dotWebpieces.local(repoRoot), { recursive: true });\n fs.writeFileSync(this.path(repoRoot), JSON.stringify(state, null, 2) + '\\n', 'utf8');\n }\n\n clear(repoRoot: string): void {\n const file = this.path(repoRoot);\n if (fs.existsSync(file)) fs.rmSync(file);\n }\n\n /** The read that MUST find a resolve — used by `wp-finish-push-dev`, whose whole job is resuming one. */\n require(repoRoot: string): PushDevState {\n const state = this.read(repoRoot);\n if (state !== null) return state;\n throw new CliExitError(2,\n '\\n' + SEP + '⛔ No dev-deploy resolve is in progress\\n' + SEP + '\\n'\n + `${WP_FINISH_PUSH_DEV} resumes a resolve that \\`${WP_PUSH_DEV} --resolve\\` started, and there is no\\n`\n + `state file at:\\n ${this.path(repoRoot)}\\n\\n`\n + 'If you meant to publish your branch to the shared dev server, that is the one-command form:\\n'\n + ` ${WP_PUSH_DEV}\\n`);\n }\n\n /**\n * Refuse `attempted` while a resolve is half-finished. Called from the app root for every command in\n * {@link BLOCKED_DURING_RESOLVE}, so no individual command has to remember to ask.\n */\n assertIdle(repoRoot: string, attempted: string): void {\n const state = this.read(repoRoot);\n if (state === null) return;\n throw new CliExitError(2,\n '\\n' + SEP + `⛔ A dev-deploy resolve is in progress — \\`pnpm ${attempted}\\` is blocked\\n` + SEP + '\\n'\n + `You are standing on the throwaway branch \\`${state.tmpBranch}\\`, not on \\`${state.originalBranch}\\`,\\n`\n + `so ${this.blockedCommandList()} would all act on the wrong branch.\\n`\n + 'That is the whole list; nothing else is blocked.\\n\\n'\n + 'EXPECTED of you right now, and NOT blocked: read the conflicted files and edit them until every\\n'\n + 'conflict marker is gone. Then finish or bail out:\\n'\n + ` ${WP_FINISH_PUSH_DEV} ← commit the resolution, resume the queue, publish the copy\\n`\n + ` ${WP_FINISH_PUSH_DEV} --abort ← throw the resolution away and go back to \\`${state.originalBranch}\\`\\n\\n`\n + `State file: ${this.path(repoRoot)}\\n`);\n }\n\n // Rendered from BLOCKED_DURING_RESOLVE, never hand-written — see that constant.\n private blockedCommandList(): string {\n return BLOCKED_DURING_RESOLVE.map((c: string): string => `\\`pnpm ${c}\\``).join(', ');\n }\n\n /** Is `command` one of the ones that must refuse mid-resolve? Used by the app root. */\n isBlockedDuringResolve(command: string): boolean {\n return BLOCKED_DURING_RESOLVE.includes(command);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"push-dev-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/push-dev-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,0DAOiC;AACjC,yCAA2D;AAE3D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;GASG;AACH,MAAa,YAAY;IACrB,kGAAkG;IAClG,cAAc,CAAS;IACvB,uFAAuF;IACvF,SAAS,CAAS;IAClB,iFAAiF;IACjF,SAAS,CAAS;IAClB,mEAAmE;IACnE,KAAK,CAAW;IAChB,8EAA8E;IAC9E,OAAO,CAAS;IAEhB,yDAAyD;IACzD,YACI,cAAsB,EACtB,SAAiB,EACjB,SAAiB,EACjB,KAAe,EACf,OAAO,GAAG,EAAE;QAEZ,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AA1BD,oCA0BC;AAED,sGAAsG;AACtG,4FAA4F;AAC5F,kGAAkG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AM;YAC9C,+FAA+F;YAC/F,KAAK,0BAAW,IAAI,CAC3B,CAAC;IACN,CAAC;IAED;;;OAGG;IACH,UAAU,CAAC,QAAgB,EAAE,SAAiB;QAC1C,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClC,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO;QAC3B,MAAM,IAAI,2BAAY,CAClB,CAAC,EACD,IAAI;YACA,GAAG;YACH,kDAAkD,SAAS,iBAAiB;YAC5E,GAAG;YACH,IAAI;YACJ,8CAA8C,KAAK,CAAC,SAAS,gBAAgB,KAAK,CAAC,cAAc,OAAO;YACxG,MAAM,IAAI,CAAC,kBAAkB,EAAE,uCAAuC;YACtE,sDAAsD;YACtD,mGAAmG;YACnG,qDAAqD;YACrD,KAAK,iCAAkB,2EAA2E;YAClG,KAAK,iCAAkB,4DAA4D,KAAK,CAAC,cAAc,QAAQ;YAC/G,eAAe,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAC7C,CAAC;IACN,CAAC;IAED,gFAAgF;IACxE,kBAAkB;QACtB,OAAO,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAS,EAAU,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzF,CAAC;IAED,uFAAuF;IACvF,sBAAsB,CAAC,OAAe;QAClC,OAAO,sBAAsB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACpD,CAAC;CACJ,CAAA;AArGY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEM,2BAAY;GAD9C,iBAAiB,CAqG7B","sourcesContent":["import * as fs from 'fs';\n\nimport {\n CliExitError,\n DotWebpieces,\n PUSH_DEV_STATE_FILE,\n WP_FINISH_PUSH_DEV,\n WP_PUSH_DEV,\n toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The persisted half of the `wp-push-dev --resolve` state machine.\n *\n * A single-shot wrapper is IMPOSSIBLE here and that is why this file exists: `git merge` halts on\n * conflict with markers in the working tree and a non-zero exit, and a human or an AI has to edit files\n * before anything can be committed. So the command must be able to stop, hand the tree over, and be\n * resumed by a second command that knows exactly where it left off.\n *\n * Data-only (per CLAUDE.md) — the behaviour lives in {@link PushDevStateStore}.\n */\nexport class PushDevState {\n /** The branch to return to when the resolve finishes or aborts. NEVER written to by this flow. */\n originalBranch: string;\n /** The local throwaway branch the merges happen on. Deleted on finish and on abort. */\n tmpBranch: string;\n /** `<namespace>/<originalBranch>` — the remote copy this resolve republishes. */\n targetRef: string;\n /** The copy refs still to merge, in the order CI composes them. */\n queue: string[];\n /** The ref currently mid-merge (conflicted), or '' when nothing is halted. */\n current: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n originalBranch: string,\n tmpBranch: string,\n targetRef: string,\n queue: string[],\n current = '',\n ) {\n this.originalBranch = originalBranch;\n this.tmpBranch = tmpBranch;\n this.targetRef = targetRef;\n this.queue = queue;\n this.current = current;\n }\n}\n\n// The wp-* commands that must REFUSE while a resolve is half-finished, and the ONE place that list is\n// written. The blocked-list sentence below RENDERS ITSELF from this array — the same lesson\n// merge-in-progress-guard already learned the hard way: a hand-written \"don't run other commands\"\n// survives every edit to the actual enforcement and ends up forbidding things the flow requires.\n//\n// Why these and not everything: each one either rewrites the current branch (the two starts), pushes it\n// (the finishes), or deletes branches (cleanup) — and during a resolve the checkout is a throwaway\n// branch, not the feature branch any of them think they are acting on.\nconst BLOCKED_DURING_RESOLVE: readonly string[] = [\n 'wp-start-update',\n 'wp-finish-update',\n 'wp-start-upsert-pr',\n 'wp-review-upsert-pr',\n 'wp-finish-upsert-pr',\n 'wp-human-post-pr',\n 'wp-land-pr',\n 'wp-cleanup',\n];\n\n/**\n * Reads, writes and clears the resolve state file, and refuses the other `wp-*` commands while it\n * exists.\n *\n * LOCAL scope, deliberately: a resolve halts one worktree's checkout on a throwaway branch, and another\n * worktree has no reason to care. Sharing it would block a colleague's PR flow on state that says\n * nothing about their tree.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PushDevStateStore {\n constructor(private readonly dotWebpieces: DotWebpieces) {}\n\n path(repoRoot: string): string {\n return this.dotWebpieces.localFile(repoRoot, PUSH_DEV_STATE_FILE);\n }\n\n exists(repoRoot: string): boolean {\n return fs.existsSync(this.path(repoRoot));\n }\n\n /** The in-flight resolve, or null when none is. A corrupt file reads as null rather than crashing. */\n read(repoRoot: string): PushDevState | null {\n const file = this.path(repoRoot);\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- a truncated/hand-edited state file must degrade to \"no resolve in progress\" (recoverable via --abort or a fresh --resolve), never crash every wp-* command in the tree\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- JSON.parse is untyped until narrowed on the next line\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<PushDevState>;\n if (typeof raw.originalBranch !== 'string' || typeof raw.tmpBranch !== 'string')\n return null;\n return new PushDevState(\n raw.originalBranch,\n raw.tmpBranch,\n raw.targetRef ?? '',\n Array.isArray(raw.queue) ? raw.queue : [],\n raw.current ?? '',\n );\n // The parse error carries nothing a caller could act on: the ONLY meaningful reading of an\n // unparseable state file is \"no resolve in progress\", which --abort and a fresh --resolve both\n // recover from.\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n write(repoRoot: string, state: PushDevState): void {\n fs.mkdirSync(this.dotWebpieces.local(repoRoot), { recursive: true });\n fs.writeFileSync(this.path(repoRoot), JSON.stringify(state, null, 2) + '\\n', 'utf8');\n }\n\n clear(repoRoot: string): void {\n const file = this.path(repoRoot);\n if (fs.existsSync(file)) fs.rmSync(file);\n }\n\n /** The read that MUST find a resolve — used by `wp-finish-push-dev`, whose whole job is resuming one. */\n require(repoRoot: string): PushDevState {\n const state = this.read(repoRoot);\n if (state !== null) return state;\n throw new CliExitError(\n 2,\n '\\n' +\n SEP +\n '⛔ No dev-deploy resolve is in progress\\n' +\n SEP +\n '\\n' +\n `${WP_FINISH_PUSH_DEV} resumes a resolve that \\`${WP_PUSH_DEV} --resolve\\` started, and there is no\\n` +\n `state file at:\\n ${this.path(repoRoot)}\\n\\n` +\n 'If you meant to publish your branch to the shared dev server, that is the one-command form:\\n' +\n ` ${WP_PUSH_DEV}\\n`,\n );\n }\n\n /**\n * Refuse `attempted` while a resolve is half-finished. Called from the app root for every command in\n * {@link BLOCKED_DURING_RESOLVE}, so no individual command has to remember to ask.\n */\n assertIdle(repoRoot: string, attempted: string): void {\n const state = this.read(repoRoot);\n if (state === null) return;\n throw new CliExitError(\n 2,\n '\\n' +\n SEP +\n `⛔ A dev-deploy resolve is in progress — \\`pnpm ${attempted}\\` is blocked\\n` +\n SEP +\n '\\n' +\n `You are standing on the throwaway branch \\`${state.tmpBranch}\\`, not on \\`${state.originalBranch}\\`,\\n` +\n `so ${this.blockedCommandList()} would all act on the wrong branch.\\n` +\n 'That is the whole list; nothing else is blocked.\\n\\n' +\n 'EXPECTED of you right now, and NOT blocked: read the conflicted files and edit them until every\\n' +\n 'conflict marker is gone. Then finish or bail out:\\n' +\n ` ${WP_FINISH_PUSH_DEV} ← commit the resolution, resume the queue, publish the copy\\n` +\n ` ${WP_FINISH_PUSH_DEV} --abort ← throw the resolution away and go back to \\`${state.originalBranch}\\`\\n\\n` +\n `State file: ${this.path(repoRoot)}\\n`,\n );\n }\n\n // Rendered from BLOCKED_DURING_RESOLVE, never hand-written — see that constant.\n private blockedCommandList(): string {\n return BLOCKED_DURING_RESOLVE.map((c: string): string => `\\`pnpm ${c}\\``).join(', ');\n }\n\n /** Is `command` one of the ones that must refuse mid-resolve? Used by the app root. */\n isBlockedDuringResolve(command: string): boolean {\n return BLOCKED_DURING_RESOLVE.includes(command);\n }\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
require("reflect-metadata");
|
|
5
|
+
const inversify_1 = require("inversify");
|
|
6
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
7
|
+
const pr_gate_app_1 = require("./pr-gate-app");
|
|
8
|
+
(0, rules_config_1.runMain)(async () => {
|
|
9
|
+
const container = new inversify_1.Container({ autobind: true });
|
|
10
|
+
container
|
|
11
|
+
.get(rules_config_1.CliArgs)
|
|
12
|
+
.assertNoArgs(new rules_config_1.CliUsage('wp-human-post-pr', 'Interactively attest that a human is posting the current clean, current-main feature branch.'));
|
|
13
|
+
await container.get(pr_gate_app_1.PrGateApp).humanPostPr();
|
|
14
|
+
});
|
|
15
|
+
//# sourceMappingURL=wp-human-post-pr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wp-human-post-pr.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/wp-human-post-pr.ts"],"names":[],"mappings":";;;AACA,4BAA0B;AAC1B,yCAAsC;AACtC,0DAAqE;AACrE,+CAA0C;AAE1C,IAAA,sBAAO,EAAC,KAAK,IAAmB,EAAE;IAC9B,MAAM,SAAS,GAAG,IAAI,qBAAS,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,SAAS;SACJ,GAAG,CAAC,sBAAO,CAAC;SACZ,YAAY,CACT,IAAI,uBAAQ,CACR,kBAAkB,EAClB,8FAA8F,CACjG,CACJ,CAAC;IACN,MAAM,SAAS,CAAC,GAAG,CAAC,uBAAS,CAAC,CAAC,WAAW,EAAE,CAAC;AACjD,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport 'reflect-metadata';\nimport { Container } from 'inversify';\nimport { CliArgs, CliUsage, runMain } from '@webpieces/rules-config';\nimport { PrGateApp } from './pr-gate-app';\n\nrunMain(async (): Promise<void> => {\n const container = new Container({ autobind: true });\n container\n .get(CliArgs)\n .assertNoArgs(\n new CliUsage(\n 'wp-human-post-pr',\n 'Interactively attest that a human is posting the current clean, current-main feature branch.',\n ),\n );\n await container.get(PrGateApp).humanPostPr();\n});\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function main(): Promise<void>;
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.main = main;
|
|
4
|
-
const child_process_1 = require("child_process");
|
|
5
|
-
const rules_config_1 = require("@webpieces/rules-config");
|
|
6
|
-
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
7
|
-
async function main() {
|
|
8
|
-
const branch = (0, child_process_1.execSync)('git branch --show-current', { encoding: 'utf8' }).trim();
|
|
9
|
-
if (branch === 'main') {
|
|
10
|
-
process.stdout.write('✅ On main branch - no validation needed\n');
|
|
11
|
-
return;
|
|
12
|
-
}
|
|
13
|
-
process.stdout.write('Validating branch is up to date with origin/main...\n');
|
|
14
|
-
process.stdout.write(`Current branch: ${branch}\n`);
|
|
15
|
-
process.stdout.write('\n');
|
|
16
|
-
process.stdout.write('Fetching latest from origin/main...\n');
|
|
17
|
-
(0, child_process_1.spawnSync)('git', ['fetch', 'origin', 'main', '--quiet'], { stdio: 'inherit' });
|
|
18
|
-
const isUpToDate = (0, child_process_1.spawnSync)('git', ['merge-base', '--is-ancestor', 'origin/main', 'HEAD']).status === 0;
|
|
19
|
-
if (isUpToDate) {
|
|
20
|
-
process.stdout.write('✅ Branch is up to date with origin/main\n');
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
const behindResult = (0, child_process_1.spawnSync)('git', ['rev-list', '--count', 'HEAD..origin/main'], { encoding: 'utf8' });
|
|
24
|
-
const commitsBehind = (behindResult.stdout ?? '').trim();
|
|
25
|
-
const recentResult = (0, child_process_1.spawnSync)('git', ['log', '--oneline', 'HEAD..origin/main'], { encoding: 'utf8' });
|
|
26
|
-
const recentLines = (recentResult.stdout ?? '').split('\n').filter((l) => l).slice(0, 5).join('\n');
|
|
27
|
-
process.stdout.write('\n');
|
|
28
|
-
process.stdout.write(SEP);
|
|
29
|
-
process.stdout.write('❌ ERROR: Branch is NOT up to date with origin/main\n');
|
|
30
|
-
process.stdout.write(SEP);
|
|
31
|
-
process.stdout.write('\n');
|
|
32
|
-
process.stdout.write(`Your branch is ${commitsBehind} commit(s) behind origin/main\n`);
|
|
33
|
-
process.stdout.write('\n');
|
|
34
|
-
process.stdout.write('Recent commits in origin/main not in your branch:\n');
|
|
35
|
-
process.stdout.write(recentLines + '\n');
|
|
36
|
-
process.stdout.write('\n');
|
|
37
|
-
process.stdout.write(SEP);
|
|
38
|
-
process.stdout.write('⚠️ CRITICAL: You must update your branch first!\n');
|
|
39
|
-
process.stdout.write(SEP);
|
|
40
|
-
process.stdout.write('\n');
|
|
41
|
-
process.stdout.write('1. Update your branch with latest main:\n');
|
|
42
|
-
process.stdout.write(new rules_config_1.SyncFlowGuidance().flows().map((l) => ' ' + l).join('\n') + '\n');
|
|
43
|
-
process.stdout.write('\n');
|
|
44
|
-
process.stdout.write('2. ⚠️ IMPORTANT: REVIEW THE CODE AFTER MERGE!\n');
|
|
45
|
-
process.stdout.write(' - Check for merge conflicts\n');
|
|
46
|
-
process.stdout.write(' - Review how your changes interact with new main code\n');
|
|
47
|
-
process.stdout.write(' - Test that everything still works\n');
|
|
48
|
-
process.stdout.write(' - This is where things often go wrong!\n');
|
|
49
|
-
process.stdout.write('\n');
|
|
50
|
-
process.stdout.write('3. After reviewing, run your command again\n');
|
|
51
|
-
process.stdout.write('\n');
|
|
52
|
-
process.stdout.write(SEP);
|
|
53
|
-
process.stdout.write('Why this matters:\n');
|
|
54
|
-
process.stdout.write(SEP);
|
|
55
|
-
process.stdout.write('\n');
|
|
56
|
-
process.stdout.write('- Your test plan should cover how your changes work with\n');
|
|
57
|
-
process.stdout.write(' the LATEST code from main, not outdated code\n');
|
|
58
|
-
process.stdout.write('- Merging main might introduce conflicts or integration\n');
|
|
59
|
-
process.stdout.write(' issues that need testing\n');
|
|
60
|
-
process.stdout.write('- Your changes might interact unexpectedly with new code\n');
|
|
61
|
-
process.stdout.write(' from main\n');
|
|
62
|
-
process.stdout.write('\n');
|
|
63
|
-
process.stdout.write(SEP);
|
|
64
|
-
// The full guidance was already printed to stdout above; throw with an empty message so runMain
|
|
65
|
-
// exits 1 without echoing a redundant line.
|
|
66
|
-
throw new rules_config_1.CliExitError(1, '');
|
|
67
|
-
}
|
|
68
|
-
if (require.main === module)
|
|
69
|
-
(0, rules_config_1.runMain)(main);
|
|
70
|
-
//# sourceMappingURL=git-validateUpToDate.js.map
|