@webpieces/pr-gate 0.4.980 → 0.4.982
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/build-command.d.ts +2 -2
- package/src/scripts/commands/build-command.js +2 -2
- package/src/scripts/commands/build-command.js.map +1 -1
- package/src/scripts/commands/push-dev-command.d.ts +20 -1
- package/src/scripts/commands/push-dev-command.js +42 -4
- package/src/scripts/commands/push-dev-command.js.map +1 -1
- package/src/scripts/pr-gate-cli-app.js +2 -1
- package/src/scripts/pr-gate-cli-app.js.map +1 -1
- package/src/scripts/workflow/build-affected.js +6 -1
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/build-gate-log.d.ts +14 -11
- package/src/scripts/workflow/build-gate-log.js +17 -17
- package/src/scripts/workflow/build-gate-log.js.map +1 -1
- package/src/scripts/workflow/cleanTmp.d.ts +3 -3
- package/src/scripts/workflow/cleanTmp.js +6 -6
- package/src/scripts/workflow/cleanTmp.js.map +1 -1
- package/src/scripts/workflow/dev-deploy-refs.d.ts +10 -1
- package/src/scripts/workflow/dev-deploy-refs.js +13 -1
- package/src/scripts/workflow/dev-deploy-refs.js.map +1 -1
- package/src/scripts/workflow/gate-log-file.d.ts +11 -10
- package/src/scripts/workflow/gate-log-file.js +22 -18
- package/src/scripts/workflow/gate-log-file.js.map +1 -1
- package/src/scripts/workflow/stage-output-log.js +5 -0
- package/src/scripts/workflow/stage-output-log.js.map +1 -1
|
@@ -84,19 +84,20 @@ exports.BuildLogHeartbeat = BuildLogHeartbeat;
|
|
|
84
84
|
* WHERE the file goes, how the previous run is kept, and what the pointer reads like are `GateLogFile`'s
|
|
85
85
|
* — one mechanism, shared with the stage console log, so there is a single answer to "where is it?".
|
|
86
86
|
*
|
|
87
|
-
* ───
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
* • stage ② and stage ③ write `
|
|
92
|
-
*
|
|
93
|
-
*
|
|
87
|
+
* ─── One directory, two naming schemes, one rule each ──────────────────────────────────────────────────
|
|
88
|
+
* Every build log sits in `<tree>/.webpieces/logs/` (GateLogFile.logsPath — inside the checkout the
|
|
89
|
+
* command ran in, a linked worktree's own root included; issue #1393).
|
|
90
|
+
* • `wp-build` (BUILD_STAGE) writes ONE fixed name, `build.log`. History comes from the rotation.
|
|
91
|
+
* • stage ② and stage ③ write `build-gate-<stage>-<branch>-<shortSha>.log`, because those two gates CAN
|
|
92
|
+
* run against one commit and a failure message from one must not be pointing at a file the other
|
|
93
|
+
* overwrote.
|
|
94
|
+
* Nobody needs to type either name: the absolute path is printed as the FIRST line of the build, before
|
|
95
|
+
* it starts, and again in the closing pointer.
|
|
94
96
|
*
|
|
95
97
|
* ─── Concurrency ───────────────────────────────────────────────────────────────────────────────────────
|
|
96
|
-
* The DIRECTORY is
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* driving one git index.
|
|
98
|
+
* The DIRECTORY is per checkout — a linked worktree writes under its own root — so "N agents in N
|
|
99
|
+
* worktrees" is safe by construction rather than by naming. The residual case is two builds in the SAME
|
|
100
|
+
* worktree at once, which is already unsupported: both would be driving one git index.
|
|
100
101
|
*/
|
|
101
102
|
let BuildGateLog = class BuildGateLog {
|
|
102
103
|
files;
|
|
@@ -160,6 +161,10 @@ let BuildGateLog = class BuildGateLog {
|
|
|
160
161
|
follower.start();
|
|
161
162
|
return completion.finally(() => follower.stop());
|
|
162
163
|
}
|
|
164
|
+
/** The `FullLog : <path>` line printed before the build starts — see GateLogFile.startLine. */
|
|
165
|
+
startLine(logPath) {
|
|
166
|
+
return this.files.startLine(logPath);
|
|
167
|
+
}
|
|
163
168
|
/**
|
|
164
169
|
* The success summary: the caller is told WHERE the full output is, not handed the output.
|
|
165
170
|
*/
|
|
@@ -203,12 +208,7 @@ let BuildGateLog = class BuildGateLog {
|
|
|
203
208
|
return `Build process termination: exit code ${code}; signal ${signal}.`;
|
|
204
209
|
}
|
|
205
210
|
async resolvePath(repoRoot, stage) {
|
|
206
|
-
|
|
207
|
-
// `wp-build`'s log sits at the ROOT of the state dir, not under `logs/`, because it is the one log
|
|
208
|
-
// path a person types from memory. Everything else keeps the per-commit names in `logs/`.
|
|
209
|
-
return stage === exports.BUILD_STAGE
|
|
210
|
-
? this.files.localPath(repoRoot, name)
|
|
211
|
-
: this.files.logsPath(repoRoot, name);
|
|
211
|
+
return this.files.logsPath(repoRoot, await this.fileNameFor(repoRoot, stage));
|
|
212
212
|
}
|
|
213
213
|
// Anything that is not a filename-safe character becomes '-', so `dean/feat` cannot create directories.
|
|
214
214
|
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,+CAAyB;AACzB,0DAA2D;AAC3D,8DAA8G;AAC9G,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,sIAAsI;AACtI,kHAAkH;AAClH,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,OA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,EAAE,KAAK,CAAC,CAAC;QACrD,mGAAmG;QACnG,0FAA0F;QAC1F,OAAO,KAAK,KAAK,mBAAW;YACxB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC;YACtC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC9C,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,KAAK,CAAC,MAAM,CAAC,QAAgB,EAAE,IAAc;QACjD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;QAC7D,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,OAAO,EAAE,CAAC;QAC1B,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAChC,CAAC;CACJ,CAAA;AA3IY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGT,2BAAW;QACJ,iCAAc;QACvB,8BAAa;QACP,iCAAgB;GALvC,YAAY,CA2IxB","sourcesContent":["import * as fs from 'fs';\nimport { BuildTermination } from '@webpieces/rules-config';\nimport { gitCheckout, GitProcessApi, NativeProcessApi, ShellTerminationDto } from '@webpieces/tooling-common';\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 (a child that does not block, not a synchronous spawn) ──────────────────────────────────────────────────────────────\n// A synchronous spawn 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 private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /** Absolute path of the log for `stage` at the current HEAD, creating its directory. */\n pathFor(repoRoot: string, stage: string): Promise<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 async existingLogFor(repoRoot: string, stage: string): Promise<string> {\n const file = await 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 async fileNameFor(repoRoot: string, stage: string): Promise<string> {\n if (stage === BUILD_STAGE) return BUILD_LOG_NAME;\n const branch = this.slug(gitCheckout.branch(repoRoot) ?? '');\n const sha = this.slug(await this.gitOut(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 this.recordTermination(await this.processes.runShellToFile(buildCommand, repoRoot, fd), fd);\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 // The child's close code AND signal. A command that never starts (a shell that is missing, a cwd that\n // vanished) fails CLOSED to 1 — calling a build that never ran green is the one outcome that must be\n // impossible — and the reason is APPENDED TO THE LOG, so the failure message's pointer still leads to\n // it rather than to an empty file.\n private recordTermination(ended: ShellTerminationDto, fd: number): BuildTermination {\n if (ended.startError !== null) {\n fs.writeSync(fd, `\\nThe build command could not be started: ${ended.startError}\\n`);\n return new BuildTermination(1, null);\n }\n const termination = new BuildTermination(ended.code, ended.signal);\n if (ended.code === null || ended.signal !== null)\n fs.writeSync(fd, `\\n${this.terminationRecord(termination)}\\n`);\n return termination;\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 async resolvePath(repoRoot: string, stage: string): Promise<string> {\n const name = await 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 async gitOut(repoRoot: string, args: string[]): Promise<string> {\n const result = await this.git.run(['-C', repoRoot, ...args]);\n if (!result.ok) 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,+CAAyB;AACzB,0DAA2D;AAC3D,8DAA8G;AAC9G,yCAA2D;AAE3D,mDAA8C;AAC9C,yDAAoD;AACpD,6DAAwD;AAExD,0GAA0G;AAC1G,yGAAyG;AACzG,2GAA2G;AAC3G,mGAAmG;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CAAA;AA3IY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGT,2BAAW;QACJ,iCAAc;QACvB,8BAAa;QACP,iCAAgB;GALvC,YAAY,CA2IxB","sourcesContent":["import * as fs from 'fs';\nimport { BuildTermination } from '@webpieces/rules-config';\nimport { gitCheckout, GitProcessApi, NativeProcessApi, ShellTerminationDto } from '@webpieces/tooling-common';\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 (a child that does not block, not a synchronous spawn) ──────────────────────────────────────────────────────────────\n// A synchronous spawn 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 * ─── One directory, two naming schemes, one rule each ──────────────────────────────────────────────────\n * Every build log sits in `<tree>/.webpieces/logs/` (GateLogFile.logsPath — inside the checkout the\n * command ran in, a linked worktree's own root included; issue #1393).\n * • `wp-build` (BUILD_STAGE) writes ONE fixed name, `build.log`. History comes from the rotation.\n * • stage ② and stage ③ write `build-gate-<stage>-<branch>-<shortSha>.log`, because those two gates CAN\n * run against one commit and a failure message from one must not be pointing at a file the other\n * overwrote.\n * Nobody needs to type either name: the absolute path is printed as the FIRST line of the build, before\n * it starts, and again in the closing pointer.\n *\n * ─── Concurrency ───────────────────────────────────────────────────────────────────────────────────────\n * The DIRECTORY is per checkout — a linked worktree writes under its own root — so \"N agents in N\n * worktrees\" is safe by construction rather than by naming. The residual case is two builds in the SAME\n * worktree at once, which is already unsupported: both would be 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 private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /** Absolute path of the log for `stage` at the current HEAD, creating its directory. */\n pathFor(repoRoot: string, stage: string): Promise<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 async existingLogFor(repoRoot: string, stage: string): Promise<string> {\n const file = await 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 async fileNameFor(repoRoot: string, stage: string): Promise<string> {\n if (stage === BUILD_STAGE) return BUILD_LOG_NAME;\n const branch = this.slug(gitCheckout.branch(repoRoot) ?? '');\n const sha = this.slug(await this.gitOut(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 this.recordTermination(await this.processes.runShellToFile(buildCommand, repoRoot, fd), fd);\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 /** The `FullLog : <path>` line printed before the build starts — see GateLogFile.startLine. */\n startLine(logPath: string): string {\n return this.files.startLine(logPath);\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 // The child's close code AND signal. A command that never starts (a shell that is missing, a cwd that\n // vanished) fails CLOSED to 1 — calling a build that never ran green is the one outcome that must be\n // impossible — and the reason is APPENDED TO THE LOG, so the failure message's pointer still leads to\n // it rather than to an empty file.\n private recordTermination(ended: ShellTerminationDto, fd: number): BuildTermination {\n if (ended.startError !== null) {\n fs.writeSync(fd, `\\nThe build command could not be started: ${ended.startError}\\n`);\n return new BuildTermination(1, null);\n }\n const termination = new BuildTermination(ended.code, ended.signal);\n if (ended.code === null || ended.signal !== null)\n fs.writeSync(fd, `\\n${this.terminationRecord(termination)}\\n`);\n return termination;\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 async resolvePath(repoRoot: string, stage: string): Promise<string> {\n return this.files.logsPath(repoRoot, await this.fileNameFor(repoRoot, stage));\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 async gitOut(repoRoot: string, args: string[]): Promise<string> {\n const result = await this.git.run(['-C', repoRoot, ...args]);\n if (!result.ok) return '';\n return result.stdout.trim();\n }\n}\n"]}
|
|
@@ -10,9 +10,9 @@ import { DotWebpieces } from '@webpieces/tooling-common';
|
|
|
10
10
|
* the active logs, the *-status.json state files), and every writer `mkdirSync(..., { recursive: true })`s
|
|
11
11
|
* its target first — so pruning a stale home dir is harmless; the next write recreates it.
|
|
12
12
|
*
|
|
13
|
-
* The roots are the two PER-WORKTREE scopes — `DotWebpieces.local()` and `DotWebpieces.
|
|
13
|
+
* The roots are the two PER-WORKTREE scopes — `DotWebpieces.local()` and `DotWebpieces.aiFacing()` —
|
|
14
14
|
* which are one and the same directory in the primary clone and two in a linked worktree (see
|
|
15
|
-
* `
|
|
15
|
+
* `aiFacing()` for why `pr-review/` and the printed logs have to sit in the worktree). The repo-wide `shared()` dir is never
|
|
16
16
|
* swept: its entries belong to every worktree at once.
|
|
17
17
|
* This used to sweep a second, machine-global root (`~/.webpieces/prs/...`, which survived `rm -rf <clone>`
|
|
18
18
|
* and so had no other owner). That store is gone — the gated merge body is the PR's own description now.
|
|
@@ -37,7 +37,7 @@ export declare class CleanTmp {
|
|
|
37
37
|
constructor(repoRootFinder: RepoRootFinder, sweeper: AgedTreeSweeper, tmpSweeper: TmpScratchSweeper, dotDir?: DotWebpieces);
|
|
38
38
|
cleanTmp(): Promise<void>;
|
|
39
39
|
/**
|
|
40
|
-
* The per-worktree roots that exist, de-duplicated. `local()` and `
|
|
40
|
+
* The per-worktree roots that exist, de-duplicated. `local()` and `aiFacing()` are the SAME path
|
|
41
41
|
* in the primary clone — sweeping it twice would double-count and print every removal twice — and
|
|
42
42
|
* two different paths in a linked worktree, where BOTH need reaping or `pr-review/` accumulates in
|
|
43
43
|
* the worktree forever.
|
|
@@ -18,9 +18,9 @@ const SEP = '━━━━━━━━━━━━━━━━━━━━━━
|
|
|
18
18
|
* the active logs, the *-status.json state files), and every writer `mkdirSync(..., { recursive: true })`s
|
|
19
19
|
* its target first — so pruning a stale home dir is harmless; the next write recreates it.
|
|
20
20
|
*
|
|
21
|
-
* The roots are the two PER-WORKTREE scopes — `DotWebpieces.local()` and `DotWebpieces.
|
|
21
|
+
* The roots are the two PER-WORKTREE scopes — `DotWebpieces.local()` and `DotWebpieces.aiFacing()` —
|
|
22
22
|
* which are one and the same directory in the primary clone and two in a linked worktree (see
|
|
23
|
-
* `
|
|
23
|
+
* `aiFacing()` for why `pr-review/` and the printed logs have to sit in the worktree). The repo-wide `shared()` dir is never
|
|
24
24
|
* swept: its entries belong to every worktree at once.
|
|
25
25
|
* This used to sweep a second, machine-global root (`~/.webpieces/prs/...`, which survived `rm -rf <clone>`
|
|
26
26
|
* and so had no other owner). That store is gone — the gated merge body is the PR's own description now.
|
|
@@ -53,8 +53,8 @@ let CleanTmp = class CleanTmp {
|
|
|
53
53
|
// The two per-worktree scopes, and only those. It must never sweep the repo-wide dir, whose
|
|
54
54
|
// entries (merged-branches.json, the main-sync status and its lock) belong to every worktree at
|
|
55
55
|
// once. In the primary clone these collapse to the same path and it is swept once.
|
|
56
|
-
// local()
|
|
57
|
-
//
|
|
56
|
+
// local() — merge-info/, instruct-ai/, the tooling's own logs/ in <primary>/.webpieces/worktrees/<name>
|
|
57
|
+
// aiFacing() — pr-review/ and the printed build/stage logs/ in <worktree>/.webpieces, where the agent can reach them
|
|
58
58
|
const bases = this.sweepBases(repoRoot);
|
|
59
59
|
if (bases.length === 0)
|
|
60
60
|
return;
|
|
@@ -83,13 +83,13 @@ let CleanTmp = class CleanTmp {
|
|
|
83
83
|
process.stdout.write('\n' + SEP + '\n');
|
|
84
84
|
}
|
|
85
85
|
/**
|
|
86
|
-
* The per-worktree roots that exist, de-duplicated. `local()` and `
|
|
86
|
+
* The per-worktree roots that exist, de-duplicated. `local()` and `aiFacing()` are the SAME path
|
|
87
87
|
* in the primary clone — sweeping it twice would double-count and print every removal twice — and
|
|
88
88
|
* two different paths in a linked worktree, where BOTH need reaping or `pr-review/` accumulates in
|
|
89
89
|
* the worktree forever.
|
|
90
90
|
*/
|
|
91
91
|
sweepBases(repoRoot) {
|
|
92
|
-
const candidates = [this.dotDir.local(repoRoot), this.dotDir.
|
|
92
|
+
const candidates = [this.dotDir.local(repoRoot), this.dotDir.aiFacing(repoRoot)];
|
|
93
93
|
const seen = new Set();
|
|
94
94
|
return candidates.filter((base) => {
|
|
95
95
|
if (seen.has(base) || !fs.existsSync(base))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanTmp.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/cleanTmp.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqJ;AACrJ,8DAAuE;AACvE,yCAA2D;AAE3D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEI,IAAM,QAAQ,GAAd,MAAM,QAAQ;IAEI;IACA;IACA;IACA;IAJrB,YACqB,cAA8B,EAC9B,OAAwB,EACxB,UAA6B,EAC7B,SAAuB,6BAAY;QAHnC,mBAAc,GAAd,cAAc,CAAgB;QAC9B,YAAO,GAAP,OAAO,CAAiB;QACxB,eAAU,GAAV,UAAU,CAAmB;QAC7B,WAAM,GAAN,MAAM,CAA6B;IACrD,CAAC;IAEJ,KAAK,CAAC,QAAQ;QACV,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QACpE,4FAA4F;QAC5F,gGAAgG;QAChG,mFAAmF;QACnF,
|
|
1
|
+
{"version":3,"file":"cleanTmp.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/cleanTmp.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqJ;AACrJ,8DAAuE;AACvE,yCAA2D;AAE3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/B,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,IAAY,EAAW,EAAE;YAC/C,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,KAAK,CAAC;YACzD,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;IACP,CAAC;IAED,gGAAgG;IACxF,QAAQ,CAAC,IAAY;QACzB,OAAO,CAAC,OAAe,EAAE,KAAc,EAAQ,EAAE;YAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC;YAC1C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACjG,CAAC,CAAC;IACN,CAAC;CACJ,CAAA;AAnEY,4BAAQ;mBAAR,QAAQ;IADpB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QACrB,8BAAe;QACZ,gCAAiB;QACrB,6BAAY;GALhC,QAAQ,CAmEpB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { AgedTreeSweeper, RETENTION_DAYS, RepoRootFinder, SweepCount, TMP_SCRATCH_RETENTION_DAYS, TmpScratchSweeper } from '@webpieces/rules-config';\nimport { DotWebpieces, dotWebpieces } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * 30-day garbage collection of this tree's `.webpieces` scratch state.\n *\n * Runs at the end of every merge/PR flow (see merge-end.ts). Any file older than the cutoff is deleted\n * and any directory left empty afterwards is pruned; the root itself is never removed.\n *\n * Everything the tooling still needs is rewritten on each run under a fresh mtime (instruct-ai/ docs,\n * the active logs, the *-status.json state files), and every writer `mkdirSync(..., { recursive: true })`s\n * its target first — so pruning a stale home dir is harmless; the next write recreates it.\n *\n * The roots are the two PER-WORKTREE scopes — `DotWebpieces.local()` and `DotWebpieces.aiFacing()` —\n * which are one and the same directory in the primary clone and two in a linked worktree (see\n * `aiFacing()` for why `pr-review/` and the printed logs have to sit in the worktree). The repo-wide `shared()` dir is never\n * swept: its entries belong to every worktree at once.\n * This used to sweep a second, machine-global root (`~/.webpieces/prs/...`, which survived `rm -rf <clone>`\n * and so had no other owner). That store is gone — the gated merge body is the PR's own description now.\n * See `decisions/0005-the-pr-description-is-the-merge-body.md`.\n *\n * ─── That removal came with a claim that was false, and this is the correction ─────────────────────\n * This docblock used to end \"and with it the only artifact webpieces ever wrote outside a repo\". It was\n * not: every `packages/tooling/**` spec mints its fixture with `fs.mkdtempSync(os.tmpdir(), 'wp-...')`,\n * and so did two runtime paths. Nothing reaped any of them, and because THIS comment asserted there was\n * nothing out there to reap, nobody went looking. Measured on one developer machine: 270,200 abandoned\n * `wp-*` directories in `$TMPDIR`.\n *\n * The fix is ownership at the call site — `SpecTempDirs` for fixtures, `RepoScratchDirs` (which lands\n * under the `.webpieces` scope swept below) for the two runtime paths. `TmpScratchSweeper` is the\n * backstop for the residue an exit handler cannot cover: a SIGKILLed worker, a lost power rail.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CleanTmp {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly sweeper: AgedTreeSweeper,\n private readonly tmpSweeper: TmpScratchSweeper,\n private readonly dotDir: DotWebpieces = dotWebpieces,\n ) {}\n\n async cleanTmp(): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n // The two per-worktree scopes, and only those. It must never sweep the repo-wide dir, whose\n // entries (merged-branches.json, the main-sync status and its lock) belong to every worktree at\n // once. In the primary clone these collapse to the same path and it is swept once.\n // local() — merge-info/, instruct-ai/, the tooling's own logs/ in <primary>/.webpieces/worktrees/<name>\n // aiFacing() — pr-review/ and the printed build/stage logs/ in <worktree>/.webpieces, where the agent can reach them\n const bases = this.sweepBases(repoRoot);\n if (bases.length === 0) return;\n\n process.stdout.write('\\n' + SEP + '🧹 Garbage-Collecting .webpieces\\n' + SEP + '\\n');\n for (const base of bases) process.stdout.write(`Location: ${base}\\n`);\n process.stdout.write(`Retention: ${RETENTION_DAYS} days (older files reaped; empty dirs pruned)\\n\\n`);\n\n const cutoffMs = RETENTION_DAYS * 24 * 60 * 60 * 1000;\n const total = new SweepCount();\n for (const base of bases) total.add(this.sweeper.sweep(base, cutoffMs, this.reporter(base)));\n\n // The `$TMPDIR` backstop. Counted into the same total so one line reports one cleanup, and run\n // last because it is the only part that touches a directory webpieces does not own.\n const tmpCutoffMs = TMP_SCRATCH_RETENTION_DAYS * 24 * 60 * 60 * 1000;\n total.add(this.tmpSweeper.sweep(tmpCutoffMs, (removed: string): void => {\n process.stdout.write(` 🗑️ dir: ${removed}/\\n`);\n }));\n\n if (total.empty) {\n process.stdout.write(` ✅ Nothing older than ${RETENTION_DAYS} days; no empty directories\\n`);\n } else {\n const fileWord = total.files === 1 ? 'file' : 'files';\n const dirWord = total.dirs === 1 ? 'directory' : 'directories';\n process.stdout.write(`\\n ✅ Reaped ${total.files} old ${fileWord} and pruned ${total.dirs} empty ${dirWord}\\n`);\n }\n\n process.stdout.write('\\n' + SEP + '\\n');\n }\n\n /**\n * The per-worktree roots that exist, de-duplicated. `local()` and `aiFacing()` are the SAME path\n * in the primary clone — sweeping it twice would double-count and print every removal twice — and\n * two different paths in a linked worktree, where BOTH need reaping or `pr-review/` accumulates in\n * the worktree forever.\n */\n private sweepBases(repoRoot: string): string[] {\n const candidates = [this.dotDir.local(repoRoot), this.dotDir.aiFacing(repoRoot)];\n const seen = new Set<string>();\n return candidates.filter((base: string): boolean => {\n if (seen.has(base) || !fs.existsSync(base)) return false;\n seen.add(base);\n return true;\n });\n }\n\n // One line per removal, relative to the root it came from, so the two roots read as one report.\n private reporter(base: string): (removed: string, isDir: boolean) => void {\n return (removed: string, isDir: boolean): void => {\n const label = isDir ? 'dir: ' : 'file: ';\n process.stdout.write(` 🗑️ ${label} ${path.relative(base, removed)}${isDir ? '/' : ''}\\n`);\n };\n }\n}\n"]}
|
|
@@ -27,7 +27,7 @@ export declare class DevCopy {
|
|
|
27
27
|
export declare class DevDeployRefs {
|
|
28
28
|
private readonly gitExec;
|
|
29
29
|
constructor(gitExec: GitExec);
|
|
30
|
-
/** The `pr-gate.devDeploy` block — `dev-include` / `dev` unless the consumer overrode it. */
|
|
30
|
+
/** The `pr-gate.devDeploy` block — `dev-include` / `dev` / `dev-remove` unless the consumer overrode it. */
|
|
31
31
|
config(repoRoot: string): DevDeployConfig;
|
|
32
32
|
/** The checked-out branch name, or `'HEAD'` on a detached HEAD (which {@link assertPushable} refuses). */
|
|
33
33
|
currentBranch(repoRoot: string): string;
|
|
@@ -60,6 +60,15 @@ export declare class DevDeployRefs {
|
|
|
60
60
|
* value of the "did my code land in dev" check is that it is a claim about one specific commit.
|
|
61
61
|
*/
|
|
62
62
|
headSha(repoRoot: string, ref?: string): Promise<string>;
|
|
63
|
+
/**
|
|
64
|
+
* Fetch `origin/main` and return its sha — what the `--remove` marker points at (#1395).
|
|
65
|
+
*
|
|
66
|
+
* The marker carries no content, so any sha the remote already has would do; `main`'s tip is chosen
|
|
67
|
+
* because it is guaranteed to exist on origin (the push sends no objects) and it is what the
|
|
68
|
+
* consumer's workflow composes from anyway. Fetched rather than read from the local tracking ref, so a
|
|
69
|
+
* clone that has not fetched in weeks does not point the marker at an arbitrarily old commit.
|
|
70
|
+
*/
|
|
71
|
+
freshMainTip(repoRoot: string): Promise<string>;
|
|
63
72
|
/** The remote sha of one copy, or '' when that copy does not exist yet. */
|
|
64
73
|
remoteSha(repoRoot: string, ref: string): Promise<string>;
|
|
65
74
|
/**
|
|
@@ -43,7 +43,7 @@ let DevDeployRefs = class DevDeployRefs {
|
|
|
43
43
|
constructor(gitExec) {
|
|
44
44
|
this.gitExec = gitExec;
|
|
45
45
|
}
|
|
46
|
-
/** The `pr-gate.devDeploy` block — `dev-include` / `dev` unless the consumer overrode it. */
|
|
46
|
+
/** The `pr-gate.devDeploy` block — `dev-include` / `dev` / `dev-remove` unless the consumer overrode it. */
|
|
47
47
|
config(repoRoot) {
|
|
48
48
|
return (0, rules_config_1.loadAndValidate)(repoRoot).prGate.devDeploy;
|
|
49
49
|
}
|
|
@@ -117,6 +117,18 @@ let DevDeployRefs = class DevDeployRefs {
|
|
|
117
117
|
headSha(repoRoot, ref = 'HEAD') {
|
|
118
118
|
return this.gitExec.gitQuery(['-C', repoRoot, 'rev-parse', ref], repoRoot, `Failed to read the sha of ${ref} (git rev-parse).`);
|
|
119
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Fetch `origin/main` and return its sha — what the `--remove` marker points at (#1395).
|
|
122
|
+
*
|
|
123
|
+
* The marker carries no content, so any sha the remote already has would do; `main`'s tip is chosen
|
|
124
|
+
* because it is guaranteed to exist on origin (the push sends no objects) and it is what the
|
|
125
|
+
* consumer's workflow composes from anyway. Fetched rather than read from the local tracking ref, so a
|
|
126
|
+
* clone that has not fetched in weeks does not point the marker at an arbitrarily old commit.
|
|
127
|
+
*/
|
|
128
|
+
async freshMainTip(repoRoot) {
|
|
129
|
+
await this.gitExec.runGitChecked(['-C', repoRoot, 'fetch', 'origin', `+refs/heads/${MAIN}:refs/remotes/origin/${MAIN}`], `Failed to fetch origin/${MAIN}, which the --remove marker points at. Nothing was removed`);
|
|
130
|
+
return this.headSha(repoRoot, `refs/remotes/origin/${MAIN}`);
|
|
131
|
+
}
|
|
120
132
|
/** The remote sha of one copy, or '' when that copy does not exist yet. */
|
|
121
133
|
async remoteSha(repoRoot, ref) {
|
|
122
134
|
const out = await this.gitExec.gitQuery(['ls-remote', '--heads', 'origin', ref], repoRoot, `Failed to look up origin/${ref} (git ls-remote).`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-deploy-refs.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/dev-deploy-refs.ts"],"names":[],"mappings":";;;;AAAA,0DAAsG;AACtG,yCAA2D;AAC3D,8DAAwD;AAExD,yCAAqC;AAErC,MAAM,GAAG,GAAG,0DAA0D,CAAC;AACvE,MAAM,IAAI,GAAG,MAAM,CAAC;AACpB,MAAM,QAAQ,GAAG,MAAM,CAAC;AAExB;;;;GAIG;AACH,MAAa,OAAO;IAChB,iFAAiF;IACjF,GAAG,CAAS;IACZ,GAAG,CAAS;IACZ,uFAAuF;IACvF,YAAY,CAAS;IAErB,YAAY,GAAW,EAAE,GAAW,EAAE,YAAoB;QACtD,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAZD,0BAYC;AAED;;;;;;;;;;GAUG;AAEI,IAAM,aAAa,GAAnB,MAAM,aAAa;IACO;IAA7B,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IAEjD,6FAA6F;IAC7F,MAAM,CAAC,QAAgB;QACnB,OAAO,IAAA,8BAAe,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC;IACtD,CAAC;IAED,0GAA0G;IAC1G,aAAa,CAAC,QAAgB;QAC1B,OAAO,4BAAW,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;;;;;;OAUG;IACH,cAAc,CAAC,GAAoB,EAAE,MAAc;QAC/C,IAAI,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YACvC,MAAM,IAAI,2BAAY,CAAC,CAAC,EAAE,IAAI,CAAC,O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M,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,CAAC;IAEO,OAAO,CAAC,QAAgB,EAAE,IAAY;QAC1C,OAAO,IAAI,GAAG,GAAG,GAAG,KAAK,QAAQ,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,GAAG,WAAW,0BAAW,mCAAmC,CAAC;IAC1H,CAAC;CACJ,CAAA;AA1HY,sCAAa;wBAAb,aAAa;IADzB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,aAAa,CA0HzB","sourcesContent":["import { CliExitError, DevDeployConfig, loadAndValidate, WP_PUSH_DEV } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { gitCheckout } from '@webpieces/tooling-common';\n\nimport { GitExec } from './git-exec';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\nconst MAIN = 'main';\nconst DETACHED = 'HEAD';\n\n/**\n * One live copy in the dev namespace: the remote ref and the sha it points at. Data-only per CLAUDE.md —\n * `--list` prints it and the clobber guard compares against `sha`, and neither should be re-parsing\n * `ls-remote` output.\n */\nexport class DevCopy {\n /** The full ref name WITHOUT `refs/heads/`, e.g. `dev-include/dean/ONE-2275`. */\n ref: string;\n sha: string;\n /** The feature branch this is a copy OF — `ref` with the namespace prefix stripped. */\n sourceBranch: string;\n\n constructor(ref: string, sha: string, sourceBranch: string) {\n this.ref = ref;\n this.sha = sha;\n this.sourceBranch = sourceBranch;\n }\n}\n\n/**\n * Ref derivation and preconditions for the dev-deploy flow — the half of `wp-push-dev` that decides WHICH\n * refs are in play, kept out of the commands so both `wp-push-dev` and `wp-finish-push-dev` answer those\n * questions identically.\n *\n * THE INVARIANT THIS FILE EXISTS TO PROTECT: the feature branch is the PR head, so it must never acquire\n * another developer's commits — landing that PR would ship their unreviewed work to production. Every\n * write this flow performs therefore targets either the `<namespace>/<feature>` copy or a local throwaway\n * branch, and NOTHING here ever moves `<feature>` itself. That is why a conflict resolution needs the copy\n * to live in: it is the only place the resolution can be recorded without contaminating the PR.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DevDeployRefs {\n constructor(private readonly gitExec: GitExec) {}\n\n /** The `pr-gate.devDeploy` block — `dev-include` / `dev` unless the consumer overrode it. */\n config(repoRoot: string): DevDeployConfig {\n return loadAndValidate(repoRoot).prGate.devDeploy;\n }\n\n /** The checked-out branch name, or `'HEAD'` on a detached HEAD (which {@link assertPushable} refuses). */\n currentBranch(repoRoot: string): string {\n return gitCheckout.requireBranch(repoRoot);\n }\n\n /**\n * Refuse every branch that must never be the SOURCE of a dev copy, before anything is fetched or\n * pushed.\n *\n * `main` and the composed dev branch are refused for the same reason from opposite ends: `main` is the\n * trunk (whatever is on it already deploys, so copying it is meaningless), and the dev branch is a\n * BUILD ARTIFACT that CI recomputes from `origin/main` on every run — copying it would publish a\n * composition of everyone's work under one developer's name, and it would be wiped on the next CI run\n * anyway. A branch already inside the namespace is refused because publishing a copy of a copy nests\n * the prefix (`dev-include/dev-include/…`) and nothing would ever clean it up.\n */\n assertPushable(cfg: DevDeployConfig, branch: string): void {\n if (branch === DETACHED || branch === '') {\n throw new CliExitError(2, this.refusal(\n 'Detached HEAD',\n 'There is no branch name to derive the dev copy from. Check out your feature branch first:\\n'\n + ' git checkout <your-feature-branch>\\n'));\n }\n if (branch === MAIN) {\n throw new CliExitError(2, this.refusal(\n `Refusing to publish a dev copy of \\`${MAIN}\\``,\n `\\`${MAIN}\\` is the trunk — whatever is on it already deploys, so a dev copy of it means nothing.\\n`\n + 'Check out the feature branch you actually want on the dev server and re-run.\\n'));\n }\n if (branch === cfg.devBranch) {\n throw new CliExitError(2, this.refusal(\n `Refusing to publish a dev copy of \\`${cfg.devBranch}\\``,\n `\\`${cfg.devBranch}\\` is a BUILD ARTIFACT, not a source branch: your CI resets it to origin/${MAIN},\\n`\n + `merges every \\`${cfg.copyRefGlob()}\\` ref into it, and force-pushes — every run. Copying it would\\n`\n + \"publish a composition of everybody's work under your branch's name, and the next CI run would\\n\"\n + 'wipe it. Check out your own feature branch and re-run.\\n'));\n }\n if (branch === cfg.branchNamespace || branch.startsWith(`${cfg.branchNamespace}/`)) {\n throw new CliExitError(2, this.refusal(\n `Refusing to publish a dev copy of a dev copy (\\`${branch}\\`)`,\n `\\`${cfg.branchNamespace}/\\` holds the disposable copies this command WRITES; you are standing on one.\\n`\n + `Publishing from here would nest the prefix (\\`${cfg.branchNamespace}/${branch}\\`) and nothing ever\\n`\n + 'cleans that up. Check out the real feature branch and re-run.\\n'));\n }\n }\n\n /**\n * Every live copy in the namespace, sorted by ref name.\n *\n * The sort is not cosmetic: `--resolve` with no argument queues these in exactly this order, and the\n * consumer's CI composes `dev` in the same order, so what a developer resolves locally is the\n * composition CI will actually build. A different order can produce a different (still valid) merge\n * result, which would make the local resolution a guess about CI rather than a rehearsal of it.\n */\n async liveCopies(repoRoot: string, cfg: DevDeployConfig): Promise<DevCopy[]> {\n const out = await this.gitExec.gitQuery(['ls-remote', '--heads', 'origin', cfg.copyRefGlob()], repoRoot,\n `Failed to list the dev copies (git ls-remote --heads origin '${cfg.copyRefGlob()}').`);\n const copies: DevCopy[] = [];\n for (const line of out.split('\\n')) {\n if (line.trim() === '') continue;\n const fields = line.split(/\\s+/);\n const sha = fields[0];\n const ref = fields[1];\n if (sha === undefined || ref === undefined || !ref.startsWith('refs/heads/')) continue;\n const shortRef = ref.slice('refs/heads/'.length);\n copies.push(new DevCopy(shortRef, sha, shortRef.slice(cfg.branchNamespace.length + 1)));\n }\n return copies.sort((a: DevCopy, b: DevCopy): number => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));\n }\n\n /**\n * The sha of a local ref (default HEAD).\n *\n * Read AFTER a push so the watch hints quote the sha that is provably published. Quoting the copy\n * REF instead would be a moving target — it advances the next time anybody publishes — and the whole\n * value of the \"did my code land in dev\" check is that it is a claim about one specific commit.\n */\n headSha(repoRoot: string, ref = 'HEAD'): Promise<string> {\n return this.gitExec.gitQuery(['-C', repoRoot, 'rev-parse', ref], repoRoot,\n `Failed to read the sha of ${ref} (git rev-parse).`);\n }\n\n /** The remote sha of one copy, or '' when that copy does not exist yet. */\n async remoteSha(repoRoot: string, ref: string): Promise<string> {\n const out = await this.gitExec.gitQuery(['ls-remote', '--heads', 'origin', ref], repoRoot,\n `Failed to look up origin/${ref} (git ls-remote).`);\n const line = out.split('\\n').find((l: string): boolean => l.trim() !== '');\n if (line === undefined) return '';\n return line.split(/\\s+/)[0] ?? '';\n }\n\n /**\n * Fetch the named copy refs into `refs/remotes/origin/<ref>` so the local merges below run against\n * fresh state. A no-op for an empty list, and a hard failure otherwise: a resolve queued against\n * stale refs rehearses a composition CI will not build.\n */\n async fetchCopies(repoRoot: string, refs: string[]): Promise<void> {\n if (refs.length === 0) return;\n const specs = refs.map((r: string): string => `+refs/heads/${r}:refs/remotes/origin/${r}`);\n await this.gitExec.runGitChecked(['-C', repoRoot, 'fetch', 'origin', ...specs],\n 'Failed to fetch the dev copy refs from origin');\n }\n\n /** How many commits `origin/<ref>` has that `HEAD` does not — the clobber signal. 0 = safe to publish. */\n async commitsOnlyOnRemote(repoRoot: string, ref: string): Promise<number> {\n const out = await this.gitExec.gitQuery(['rev-list', '--count', `HEAD..refs/remotes/origin/${ref}`], repoRoot,\n `Failed to compare HEAD against origin/${ref} (git rev-list --count).`);\n const count = Number(out);\n return Number.isInteger(count) ? count : 0;\n }\n\n private refusal(headline: string, body: string): string {\n return '\\n' + SEP + `⛔ ${headline}\\n` + SEP + '\\n' + body + `\\nRun \\`${WP_PUSH_DEV} --help\\` for the full command.\\n`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dev-deploy-refs.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-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nD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,UAAU,EAAE,SAAS,EAAE,6BAA6B,GAAG,EAAE,CAAC,EAAE,QAAQ,EACzG,yCAAyC,GAAG,0BAA0B,CAAC,CAAC;QAC5E,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,CAAC;IAEO,OAAO,CAAC,QAAgB,EAAE,IAAY;QAC1C,OAAO,IAAI,GAAG,GAAG,GAAG,KAAK,QAAQ,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,GAAG,WAAW,0BAAW,mCAAmC,CAAC;IAC1H,CAAC;CACJ,CAAA;AAxIY,sCAAa;wBAAb,aAAa;IADzB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEC,kBAAO;GADpC,aAAa,CAwIzB","sourcesContent":["import { CliExitError, DevDeployConfig, loadAndValidate, WP_PUSH_DEV } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { gitCheckout } from '@webpieces/tooling-common';\n\nimport { GitExec } from './git-exec';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\nconst MAIN = 'main';\nconst DETACHED = 'HEAD';\n\n/**\n * One live copy in the dev namespace: the remote ref and the sha it points at. Data-only per CLAUDE.md —\n * `--list` prints it and the clobber guard compares against `sha`, and neither should be re-parsing\n * `ls-remote` output.\n */\nexport class DevCopy {\n /** The full ref name WITHOUT `refs/heads/`, e.g. `dev-include/dean/ONE-2275`. */\n ref: string;\n sha: string;\n /** The feature branch this is a copy OF — `ref` with the namespace prefix stripped. */\n sourceBranch: string;\n\n constructor(ref: string, sha: string, sourceBranch: string) {\n this.ref = ref;\n this.sha = sha;\n this.sourceBranch = sourceBranch;\n }\n}\n\n/**\n * Ref derivation and preconditions for the dev-deploy flow — the half of `wp-push-dev` that decides WHICH\n * refs are in play, kept out of the commands so both `wp-push-dev` and `wp-finish-push-dev` answer those\n * questions identically.\n *\n * THE INVARIANT THIS FILE EXISTS TO PROTECT: the feature branch is the PR head, so it must never acquire\n * another developer's commits — landing that PR would ship their unreviewed work to production. Every\n * write this flow performs therefore targets either the `<namespace>/<feature>` copy or a local throwaway\n * branch, and NOTHING here ever moves `<feature>` itself. That is why a conflict resolution needs the copy\n * to live in: it is the only place the resolution can be recorded without contaminating the PR.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DevDeployRefs {\n constructor(private readonly gitExec: GitExec) {}\n\n /** The `pr-gate.devDeploy` block — `dev-include` / `dev` / `dev-remove` unless the consumer overrode it. */\n config(repoRoot: string): DevDeployConfig {\n return loadAndValidate(repoRoot).prGate.devDeploy;\n }\n\n /** The checked-out branch name, or `'HEAD'` on a detached HEAD (which {@link assertPushable} refuses). */\n currentBranch(repoRoot: string): string {\n return gitCheckout.requireBranch(repoRoot);\n }\n\n /**\n * Refuse every branch that must never be the SOURCE of a dev copy, before anything is fetched or\n * pushed.\n *\n * `main` and the composed dev branch are refused for the same reason from opposite ends: `main` is the\n * trunk (whatever is on it already deploys, so copying it is meaningless), and the dev branch is a\n * BUILD ARTIFACT that CI recomputes from `origin/main` on every run — copying it would publish a\n * composition of everyone's work under one developer's name, and it would be wiped on the next CI run\n * anyway. A branch already inside the namespace is refused because publishing a copy of a copy nests\n * the prefix (`dev-include/dev-include/…`) and nothing would ever clean it up.\n */\n assertPushable(cfg: DevDeployConfig, branch: string): void {\n if (branch === DETACHED || branch === '') {\n throw new CliExitError(2, this.refusal(\n 'Detached HEAD',\n 'There is no branch name to derive the dev copy from. Check out your feature branch first:\\n'\n + ' git checkout <your-feature-branch>\\n'));\n }\n if (branch === MAIN) {\n throw new CliExitError(2, this.refusal(\n `Refusing to publish a dev copy of \\`${MAIN}\\``,\n `\\`${MAIN}\\` is the trunk — whatever is on it already deploys, so a dev copy of it means nothing.\\n`\n + 'Check out the feature branch you actually want on the dev server and re-run.\\n'));\n }\n if (branch === cfg.devBranch) {\n throw new CliExitError(2, this.refusal(\n `Refusing to publish a dev copy of \\`${cfg.devBranch}\\``,\n `\\`${cfg.devBranch}\\` is a BUILD ARTIFACT, not a source branch: your CI resets it to origin/${MAIN},\\n`\n + `merges every \\`${cfg.copyRefGlob()}\\` ref into it, and force-pushes — every run. Copying it would\\n`\n + \"publish a composition of everybody's work under your branch's name, and the next CI run would\\n\"\n + 'wipe it. Check out your own feature branch and re-run.\\n'));\n }\n if (branch === cfg.branchNamespace || branch.startsWith(`${cfg.branchNamespace}/`)) {\n throw new CliExitError(2, this.refusal(\n `Refusing to publish a dev copy of a dev copy (\\`${branch}\\`)`,\n `\\`${cfg.branchNamespace}/\\` holds the disposable copies this command WRITES; you are standing on one.\\n`\n + `Publishing from here would nest the prefix (\\`${cfg.branchNamespace}/${branch}\\`) and nothing ever\\n`\n + 'cleans that up. Check out the real feature branch and re-run.\\n'));\n }\n }\n\n /**\n * Every live copy in the namespace, sorted by ref name.\n *\n * The sort is not cosmetic: `--resolve` with no argument queues these in exactly this order, and the\n * consumer's CI composes `dev` in the same order, so what a developer resolves locally is the\n * composition CI will actually build. A different order can produce a different (still valid) merge\n * result, which would make the local resolution a guess about CI rather than a rehearsal of it.\n */\n async liveCopies(repoRoot: string, cfg: DevDeployConfig): Promise<DevCopy[]> {\n const out = await this.gitExec.gitQuery(['ls-remote', '--heads', 'origin', cfg.copyRefGlob()], repoRoot,\n `Failed to list the dev copies (git ls-remote --heads origin '${cfg.copyRefGlob()}').`);\n const copies: DevCopy[] = [];\n for (const line of out.split('\\n')) {\n if (line.trim() === '') continue;\n const fields = line.split(/\\s+/);\n const sha = fields[0];\n const ref = fields[1];\n if (sha === undefined || ref === undefined || !ref.startsWith('refs/heads/')) continue;\n const shortRef = ref.slice('refs/heads/'.length);\n copies.push(new DevCopy(shortRef, sha, shortRef.slice(cfg.branchNamespace.length + 1)));\n }\n return copies.sort((a: DevCopy, b: DevCopy): number => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));\n }\n\n /**\n * The sha of a local ref (default HEAD).\n *\n * Read AFTER a push so the watch hints quote the sha that is provably published. Quoting the copy\n * REF instead would be a moving target — it advances the next time anybody publishes — and the whole\n * value of the \"did my code land in dev\" check is that it is a claim about one specific commit.\n */\n headSha(repoRoot: string, ref = 'HEAD'): Promise<string> {\n return this.gitExec.gitQuery(['-C', repoRoot, 'rev-parse', ref], repoRoot,\n `Failed to read the sha of ${ref} (git rev-parse).`);\n }\n\n /**\n * Fetch `origin/main` and return its sha — what the `--remove` marker points at (#1395).\n *\n * The marker carries no content, so any sha the remote already has would do; `main`'s tip is chosen\n * because it is guaranteed to exist on origin (the push sends no objects) and it is what the\n * consumer's workflow composes from anyway. Fetched rather than read from the local tracking ref, so a\n * clone that has not fetched in weeks does not point the marker at an arbitrarily old commit.\n */\n async freshMainTip(repoRoot: string): Promise<string> {\n await this.gitExec.runGitChecked(['-C', repoRoot, 'fetch', 'origin', `+refs/heads/${MAIN}:refs/remotes/origin/${MAIN}`],\n `Failed to fetch origin/${MAIN}, which the --remove marker points at. Nothing was removed`);\n return this.headSha(repoRoot, `refs/remotes/origin/${MAIN}`);\n }\n\n /** The remote sha of one copy, or '' when that copy does not exist yet. */\n async remoteSha(repoRoot: string, ref: string): Promise<string> {\n const out = await this.gitExec.gitQuery(['ls-remote', '--heads', 'origin', ref], repoRoot,\n `Failed to look up origin/${ref} (git ls-remote).`);\n const line = out.split('\\n').find((l: string): boolean => l.trim() !== '');\n if (line === undefined) return '';\n return line.split(/\\s+/)[0] ?? '';\n }\n\n /**\n * Fetch the named copy refs into `refs/remotes/origin/<ref>` so the local merges below run against\n * fresh state. A no-op for an empty list, and a hard failure otherwise: a resolve queued against\n * stale refs rehearses a composition CI will not build.\n */\n async fetchCopies(repoRoot: string, refs: string[]): Promise<void> {\n if (refs.length === 0) return;\n const specs = refs.map((r: string): string => `+refs/heads/${r}:refs/remotes/origin/${r}`);\n await this.gitExec.runGitChecked(['-C', repoRoot, 'fetch', 'origin', ...specs],\n 'Failed to fetch the dev copy refs from origin');\n }\n\n /** How many commits `origin/<ref>` has that `HEAD` does not — the clobber signal. 0 = safe to publish. */\n async commitsOnlyOnRemote(repoRoot: string, ref: string): Promise<number> {\n const out = await this.gitExec.gitQuery(['rev-list', '--count', `HEAD..refs/remotes/origin/${ref}`], repoRoot,\n `Failed to compare HEAD against origin/${ref} (git rev-list --count).`);\n const count = Number(out);\n return Number.isInteger(count) ? count : 0;\n }\n\n private refusal(headline: string, body: string): string {\n return '\\n' + SEP + `⛔ ${headline}\\n` + SEP + '\\n' + body + `\\nRun \\`${WP_PUSH_DEV} --help\\` for the full command.\\n`;\n }\n}\n"]}
|
|
@@ -7,16 +7,10 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export declare class GateLogFile {
|
|
9
9
|
/**
|
|
10
|
-
* `<
|
|
11
|
-
*
|
|
10
|
+
* `<tree>/.webpieces/logs/<name>` — the ONE directory every log a command points its caller at
|
|
11
|
+
* lives in, inside the checkout the command ran in. Creates the directory.
|
|
12
12
|
*/
|
|
13
13
|
logsPath(repoRoot: string, name: string): string;
|
|
14
|
-
/**
|
|
15
|
-
* `<local()>/<name>` — the ROOT of the state dir, for the one log a PERSON types from memory
|
|
16
|
-
* (`.webpieces/build.log`). Creates the directory. Reach for `logsPath` unless the path itself has
|
|
17
|
-
* to be memorable.
|
|
18
|
-
*/
|
|
19
|
-
localPath(repoRoot: string, name: string): string;
|
|
20
14
|
/** Where the PREVIOUS run of `logPath` is kept — always `<logPath>.bak`. */
|
|
21
15
|
backupPathFor(logPath: string): string;
|
|
22
16
|
/**
|
|
@@ -27,6 +21,13 @@ export declare class GateLogFile {
|
|
|
27
21
|
* and a reader never has to work out which of N dated files is the one they want.
|
|
28
22
|
*/
|
|
29
23
|
rotate(logPath: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* The line a command prints BEFORE it does any work: the same `FullLog : <path>` the closing pointer
|
|
26
|
+
* repeats (issue #1393). A caller that backgrounds the command, or whose harness captures its console
|
|
27
|
+
* into a file of its own, then knows where to read from the first line on — it never has to reach
|
|
28
|
+
* for the harness's capture file, which an unattended agent may be refused.
|
|
29
|
+
*/
|
|
30
|
+
startLine(logPath: string): string;
|
|
30
31
|
/**
|
|
31
32
|
* The two lines that name a log — identical on success and on failure, so there is exactly one shape
|
|
32
33
|
* to recognise.
|
|
@@ -36,8 +37,8 @@ export declare class GateLogFile {
|
|
|
36
37
|
*/
|
|
37
38
|
pointer(logPath: string): string;
|
|
38
39
|
/**
|
|
39
|
-
* The path as a progress line should show it: relative to the repo when it sits inside it (
|
|
40
|
-
*
|
|
40
|
+
* The path as a progress line should show it: relative to the repo when it sits inside it (it always
|
|
41
|
+
* does now that logs live in the tree's own `.webpieces/logs/`), absolute otherwise.
|
|
41
42
|
*/
|
|
42
43
|
displayPath(repoRoot: string, logPath: string): string;
|
|
43
44
|
/**
|
|
@@ -19,12 +19,15 @@ const inversify_1 = require("inversify");
|
|
|
19
19
|
// can `grep` it without first working out which subsystem wrote it.
|
|
20
20
|
//
|
|
21
21
|
// ─── WHERE the files land, and why that shape ──────────────────────────────────────────────────────────
|
|
22
|
-
// Through `dotWebpieces` — never `path.join(repoRoot, '.webpieces')
|
|
23
|
-
//
|
|
22
|
+
// Through `dotWebpieces.aiFacing()` — never `path.join(repoRoot, '.webpieces')` — into ONE directory,
|
|
23
|
+
// `<tree>/.webpieces/logs/`, where `<tree>` is the checkout the command ran in: the primary clone, or a
|
|
24
|
+
// LINKED WORKTREE's own root (issue #1393). So:
|
|
24
25
|
// • N agents in N worktrees never write one another's log, by construction rather than by naming;
|
|
25
|
-
// • the
|
|
26
|
-
//
|
|
27
|
-
//
|
|
26
|
+
// • the path a command prints is INSIDE the tree the agent is working in. An agent whose reads are
|
|
27
|
+
// scoped to its worktree (auto mode's classifier, a sandbox, Codex's workspace-write) can always
|
|
28
|
+
// read it. These logs used to live under `<primary>/.webpieces/worktrees/<name>/`, outside the
|
|
29
|
+
// worktree, and three unattended runs died at a refused read of exactly that path;
|
|
30
|
+
// • it self-limits: the logs die with the worktree, and `cleanTmp` already prunes the AI-facing root.
|
|
28
31
|
// Nothing here needs a retention policy of its own.
|
|
29
32
|
/** The suffix of the ONE previous generation kept beside a log. */
|
|
30
33
|
const BACKUP_SUFFIX = '.bak';
|
|
@@ -37,19 +40,11 @@ const BACKUP_SUFFIX = '.bak';
|
|
|
37
40
|
*/
|
|
38
41
|
let GateLogFile = class GateLogFile {
|
|
39
42
|
/**
|
|
40
|
-
* `<
|
|
41
|
-
*
|
|
43
|
+
* `<tree>/.webpieces/logs/<name>` — the ONE directory every log a command points its caller at
|
|
44
|
+
* lives in, inside the checkout the command ran in. Creates the directory.
|
|
42
45
|
*/
|
|
43
46
|
logsPath(repoRoot, name) {
|
|
44
|
-
return this.ensureDir(tooling_common_1.dotWebpieces.
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* `<local()>/<name>` — the ROOT of the state dir, for the one log a PERSON types from memory
|
|
48
|
-
* (`.webpieces/build.log`). Creates the directory. Reach for `logsPath` unless the path itself has
|
|
49
|
-
* to be memorable.
|
|
50
|
-
*/
|
|
51
|
-
localPath(repoRoot, name) {
|
|
52
|
-
return this.ensureDir(tooling_common_1.dotWebpieces.localFile(repoRoot, name));
|
|
47
|
+
return this.ensureDir(tooling_common_1.dotWebpieces.aiFacingFile(repoRoot, tooling_common_1.LOGS_STATE_DIR, name));
|
|
53
48
|
}
|
|
54
49
|
/** Where the PREVIOUS run of `logPath` is kept — always `<logPath>.bak`. */
|
|
55
50
|
backupPathFor(logPath) {
|
|
@@ -69,6 +64,15 @@ let GateLogFile = class GateLogFile {
|
|
|
69
64
|
fs.rmSync(this.backupPathFor(logPath), { force: true });
|
|
70
65
|
fs.renameSync(logPath, this.backupPathFor(logPath));
|
|
71
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* The line a command prints BEFORE it does any work: the same `FullLog : <path>` the closing pointer
|
|
69
|
+
* repeats (issue #1393). A caller that backgrounds the command, or whose harness captures its console
|
|
70
|
+
* into a file of its own, then knows where to read from the first line on — it never has to reach
|
|
71
|
+
* for the harness's capture file, which an unattended agent may be refused.
|
|
72
|
+
*/
|
|
73
|
+
startLine(logPath) {
|
|
74
|
+
return `FullLog : ${logPath}\n`;
|
|
75
|
+
}
|
|
72
76
|
/**
|
|
73
77
|
* The two lines that name a log — identical on success and on failure, so there is exactly one shape
|
|
74
78
|
* to recognise.
|
|
@@ -84,8 +88,8 @@ let GateLogFile = class GateLogFile {
|
|
|
84
88
|
return `FullLog : ${logPath}\n${backedUp}\n`;
|
|
85
89
|
}
|
|
86
90
|
/**
|
|
87
|
-
* The path as a progress line should show it: relative to the repo when it sits inside it (
|
|
88
|
-
*
|
|
91
|
+
* The path as a progress line should show it: relative to the repo when it sits inside it (it always
|
|
92
|
+
* does now that logs live in the tree's own `.webpieces/logs/`), absolute otherwise.
|
|
89
93
|
*/
|
|
90
94
|
displayPath(repoRoot, logPath) {
|
|
91
95
|
const relative = path.relative(repoRoot, logPath);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gate-log-file.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gate-log-file.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAyD;AACzD,iEAA6D;AAC7D,yCAA2D;AAE3D,0GAA0G;AAC1G,yGAAyG;AACzG,2GAA2G;AAC3G,yGAAyG;AACzG,yGAAyG;AACzG,cAAc;AACd,EAAE;AACF,yGAAyG;AACzG,yGAAyG;AACzG,oEAAoE;AACpE,EAAE;AACF,0GAA0G;AAC1G,qGAAqG;AACrG,yEAAyE;AACzE,oGAAoG;AACpG,0GAA0G;AAC1G,gFAAgF;AAChF,sGAAsG;AACtG,w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O,KAAK,CAAC;QACjE,CAAC;IACL,CAAC;IAED,yGAAyG;IACzG,SAAS,CAAC,OAAe;QACrB,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC;YAAE,OAAO,CAAC,CAAC;QACtC,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,CAAC,CAAC;QAC1B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACnE,CAAC;IAEO,SAAS,CAAC,IAAY;QAC1B,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ,CAAA;AAhGY,kCAAW;sBAAX,WAAW;IADvB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,WAAW,CAgGvB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n// ─── Why this class exists ─────────────────────────────────────────────────────────────────────────────\n// TWO things in this package write a big blob of output to a file and hand the caller a one-line pointer\n// instead of the blob: the BUILD (BuildGateLog) and the STAGE CONSOLE (StageOutputLog). They are different\n// subjects — one spawns a child and heartbeats, the other intercepts this process's own stdout — but the\n// FILE half is identical: where the file lands, how the previous run is kept, and what the pointer at it\n// reads like.\n//\n// That half lives here, once. Cloning it would have given the two logs two answers to \"where is it?\" and\n// two rotation policies, and the whole value of the pointer is that a reader recognises it instantly and\n// can `grep` it without first working out which subsystem wrote it.\n//\n// ─── WHERE the files land, and why that shape ──────────────────────────────────────────────────────────\n// Through `dotWebpieces` — never `path.join(repoRoot, '.webpieces')`. In a LINKED WORKTREE `local()`\n// resolves to `<primary>/.webpieces/worktrees/<git worktree name>/`, so:\n// • N agents in N worktrees never write one another's log, by construction rather than by naming;\n// • the history OUTLIVES the worktree — `wp-cleanup` reaps a tree's directory and the logs it wrote are\n// still there under the primary clone, which is exactly when you want them;\n// • it self-limits, because `.webpieces/worktrees/**` is already swept once a namespace goes stale.\n// Nothing here needs a retention policy of its own.\n\n/** The suffix of the ONE previous generation kept beside a log. */\nconst BACKUP_SUFFIX = '.bak';\n\n/**\n * The file mechanics shared by every captured log in the PR gate: WHERE it goes, keeping the previous\n * run, the pointer the caller prints instead of the output, and the failure tail.\n *\n * It knows nothing about builds, stages or console interception — its callers own all of that. Singleton\n * because it is pure behaviour over paths; it holds no state.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GateLogFile {\n /**\n * `<local()>/logs/<name>` — the ONE log directory, per worktree namespace. Creates the directory.\n * Use for anything a MESSAGE points at; nobody types these names.\n */\n logsPath(repoRoot: string, name: string): string {\n return this.ensureDir(dotWebpieces.logsFile(repoRoot, name));\n }\n\n /**\n * `<local()>/<name>` — the ROOT of the state dir, for the one log a PERSON types from memory\n * (`.webpieces/build.log`). Creates the directory. Reach for `logsPath` unless the path itself has\n * to be memorable.\n */\n localPath(repoRoot: string, name: string): string {\n return this.ensureDir(dotWebpieces.localFile(repoRoot, name));\n }\n\n /** Where the PREVIOUS run of `logPath` is kept — always `<logPath>.bak`. */\n backupPathFor(logPath: string): string {\n return `${logPath}${BACKUP_SUFFIX}`;\n }\n\n /**\n * Move an existing log aside to `<log>.bak`, overwriting any previous backup, so the last TWO runs\n * are always on disk. A missing log is the normal first-run state and is not an error.\n *\n * ONE generation, everywhere: a re-run at the same commit does not truncate away the run before it,\n * and a reader never has to work out which of N dated files is the one they want.\n */\n rotate(logPath: string): void {\n fs.mkdirSync(path.dirname(logPath), { recursive: true });\n if (!fs.existsSync(logPath)) return;\n fs.rmSync(this.backupPathFor(logPath), { force: true });\n fs.renameSync(logPath, this.backupPathFor(logPath));\n }\n\n /**\n * The two lines that name a log — identical on success and on failure, so there is exactly one shape\n * to recognise.\n *\n * The backup line states what is TRUE RIGHT NOW: on the very first run in a tree there is no `.bak`\n * yet, and pointing a reader at a file that does not exist is the small lie that costs a wasted `cat`.\n */\n pointer(logPath: string): string {\n const name = path.basename(logPath);\n const backedUp = fs.existsSync(this.backupPathFor(logPath))\n ? `(${name} is backed up to ${name}${BACKUP_SUFFIX} every run so you have the last 2 runs of logs)`\n : `(the previous ${name} is kept as ${name}${BACKUP_SUFFIX} on every run — this is the first, so there is none yet)`;\n return `FullLog : ${logPath}\\n${backedUp}\\n`;\n }\n\n /**\n * The path as a progress line should show it: relative to the repo when it sits inside it (a linked\n * worktree's state lives under the PRIMARY clone, so it usually does not), absolute otherwise.\n */\n displayPath(repoRoot: string, logPath: string): string {\n const relative = path.relative(repoRoot, logPath);\n return relative === '' || relative.startsWith('..') || path.isAbsolute(relative) ? logPath : relative;\n }\n\n /**\n * The log's last `lines` lines, indented, or a plain statement of why there are none.\n *\n * A read that fails is REPORTED, never allowed to throw: this renders a message for something that\n * has ALREADY failed, so an I/O error escaping here would replace the real failure with the\n * renderer's own — the caller would lose the actual error and be handed a filesystem error instead.\n * The full log is still named on the line above, so nothing is hidden by degrading to one line.\n */\n tail(logPath: string, lines: number): string {\n if (!fs.existsSync(logPath)) return ` (no log file at ${logPath})\\n`;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: see above, the failure renderer may not\n // replace the caller's failure with its own.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const all = fs.readFileSync(logPath, 'utf8').split('\\n').filter((l: string): boolean => l !== '');\n if (all.length === 0) return ' (the log is empty)\\n';\n return all.slice(-lines).map((l: string): string => ` ${l}\\n`).join('');\n } catch (err: unknown) {\n const error = toError(err);\n return ` (could not read ${logPath}: ${error.message})\\n`;\n }\n }\n\n /** How many lines the log holds right now. A log that does not exist yet is zero lines, not an error. */\n lineCount(logPath: string): number {\n if (!fs.existsSync(logPath)) return 0;\n const body = fs.readFileSync(logPath, 'utf8');\n if (body === '') return 0;\n return body.split('\\n').length - (body.endsWith('\\n') ? 1 : 0);\n }\n\n private ensureDir(file: string): string {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n return file;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gate-log-file.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gate-log-file.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAyE;AACzE,iEAA6D;AAC7D,yCAA2D;AAE3D,0GAA0G;AAC1G,yGAAyG;AACzG,2GAA2G;AAC3G,yGAAyG;AACzG,yGAAyG;AACzG,cAAc;AACd,EAAE;AACF,yGAAyG;AACzG,yGAAyG;AACzG,oEAAoE;AACpE,EAAE;AACF,0GAA0G;AAC1G,sGAAsG;AACtG,wGAAwG;AACxG,gDAAgD;AAChD,oGAAoG;AACpG,qGAAqG;AACrG,qGAAqG;AACrG,mGAAmG;AACnG,uFAAuF;AACvF,wGAAwG;AACxG,wDAAwD;AAExD,mEAAmE;AACnE,MAAM,aAAa,GAAG,MAAM,CAAC;AAE7B;;;;;;GAMG;AAEI,IAAM,WAAW,GAAjB,MAAM,WAAW;IACpB;;;OAGG;IACH,QAAQ,CAAC,QAAgB,EAAE,IAAY;QACnC,OAAO,IAAI,CAAC,SAAS,CAAC,6BAAY,CAAC,YAAY,CAAC,QAAQ,EAAE,+BAAc,EAAE,IAAI,CAAC,CAAC,CAAC;IACrF,CAAC;IAED,4EAA4E;IAC5E,aAAa,CAAC,OAAe;QACzB,OAAO,GAAG,OAAO,GAAG,aAAa,EAAE,CAAC;IACxC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,OAAe;QAClB,EAAE,CAAC,SAAS,CAAC,I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C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ,CAAA;AAjGY,kCAAW;sBAAX,WAAW;IADvB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,WAAW,CAiGvB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces, LOGS_STATE_DIR } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n// ─── Why this class exists ─────────────────────────────────────────────────────────────────────────────\n// TWO things in this package write a big blob of output to a file and hand the caller a one-line pointer\n// instead of the blob: the BUILD (BuildGateLog) and the STAGE CONSOLE (StageOutputLog). They are different\n// subjects — one spawns a child and heartbeats, the other intercepts this process's own stdout — but the\n// FILE half is identical: where the file lands, how the previous run is kept, and what the pointer at it\n// reads like.\n//\n// That half lives here, once. Cloning it would have given the two logs two answers to \"where is it?\" and\n// two rotation policies, and the whole value of the pointer is that a reader recognises it instantly and\n// can `grep` it without first working out which subsystem wrote it.\n//\n// ─── WHERE the files land, and why that shape ──────────────────────────────────────────────────────────\n// Through `dotWebpieces.aiFacing()` — never `path.join(repoRoot, '.webpieces')` — into ONE directory,\n// `<tree>/.webpieces/logs/`, where `<tree>` is the checkout the command ran in: the primary clone, or a\n// LINKED WORKTREE's own root (issue #1393). So:\n// • N agents in N worktrees never write one another's log, by construction rather than by naming;\n// • the path a command prints is INSIDE the tree the agent is working in. An agent whose reads are\n// scoped to its worktree (auto mode's classifier, a sandbox, Codex's workspace-write) can always\n// read it. These logs used to live under `<primary>/.webpieces/worktrees/<name>/`, outside the\n// worktree, and three unattended runs died at a refused read of exactly that path;\n// • it self-limits: the logs die with the worktree, and `cleanTmp` already prunes the AI-facing root.\n// Nothing here needs a retention policy of its own.\n\n/** The suffix of the ONE previous generation kept beside a log. */\nconst BACKUP_SUFFIX = '.bak';\n\n/**\n * The file mechanics shared by every captured log in the PR gate: WHERE it goes, keeping the previous\n * run, the pointer the caller prints instead of the output, and the failure tail.\n *\n * It knows nothing about builds, stages or console interception — its callers own all of that. Singleton\n * because it is pure behaviour over paths; it holds no state.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GateLogFile {\n /**\n * `<tree>/.webpieces/logs/<name>` — the ONE directory every log a command points its caller at\n * lives in, inside the checkout the command ran in. Creates the directory.\n */\n logsPath(repoRoot: string, name: string): string {\n return this.ensureDir(dotWebpieces.aiFacingFile(repoRoot, LOGS_STATE_DIR, name));\n }\n\n /** Where the PREVIOUS run of `logPath` is kept — always `<logPath>.bak`. */\n backupPathFor(logPath: string): string {\n return `${logPath}${BACKUP_SUFFIX}`;\n }\n\n /**\n * Move an existing log aside to `<log>.bak`, overwriting any previous backup, so the last TWO runs\n * are always on disk. A missing log is the normal first-run state and is not an error.\n *\n * ONE generation, everywhere: a re-run at the same commit does not truncate away the run before it,\n * and a reader never has to work out which of N dated files is the one they want.\n */\n rotate(logPath: string): void {\n fs.mkdirSync(path.dirname(logPath), { recursive: true });\n if (!fs.existsSync(logPath)) return;\n fs.rmSync(this.backupPathFor(logPath), { force: true });\n fs.renameSync(logPath, this.backupPathFor(logPath));\n }\n\n /**\n * The line a command prints BEFORE it does any work: the same `FullLog : <path>` the closing pointer\n * repeats (issue #1393). A caller that backgrounds the command, or whose harness captures its console\n * into a file of its own, then knows where to read from the first line on — it never has to reach\n * for the harness's capture file, which an unattended agent may be refused.\n */\n startLine(logPath: string): string {\n return `FullLog : ${logPath}\\n`;\n }\n\n /**\n * The two lines that name a log — identical on success and on failure, so there is exactly one shape\n * to recognise.\n *\n * The backup line states what is TRUE RIGHT NOW: on the very first run in a tree there is no `.bak`\n * yet, and pointing a reader at a file that does not exist is the small lie that costs a wasted `cat`.\n */\n pointer(logPath: string): string {\n const name = path.basename(logPath);\n const backedUp = fs.existsSync(this.backupPathFor(logPath))\n ? `(${name} is backed up to ${name}${BACKUP_SUFFIX} every run so you have the last 2 runs of logs)`\n : `(the previous ${name} is kept as ${name}${BACKUP_SUFFIX} on every run — this is the first, so there is none yet)`;\n return `FullLog : ${logPath}\\n${backedUp}\\n`;\n }\n\n /**\n * The path as a progress line should show it: relative to the repo when it sits inside it (it always\n * does now that logs live in the tree's own `.webpieces/logs/`), absolute otherwise.\n */\n displayPath(repoRoot: string, logPath: string): string {\n const relative = path.relative(repoRoot, logPath);\n return relative === '' || relative.startsWith('..') || path.isAbsolute(relative) ? logPath : relative;\n }\n\n /**\n * The log's last `lines` lines, indented, or a plain statement of why there are none.\n *\n * A read that fails is REPORTED, never allowed to throw: this renders a message for something that\n * has ALREADY failed, so an I/O error escaping here would replace the real failure with the\n * renderer's own — the caller would lose the actual error and be handed a filesystem error instead.\n * The full log is still named on the line above, so nothing is hidden by degrading to one line.\n */\n tail(logPath: string, lines: number): string {\n if (!fs.existsSync(logPath)) return ` (no log file at ${logPath})\\n`;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: see above, the failure renderer may not\n // replace the caller's failure with its own.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const all = fs.readFileSync(logPath, 'utf8').split('\\n').filter((l: string): boolean => l !== '');\n if (all.length === 0) return ' (the log is empty)\\n';\n return all.slice(-lines).map((l: string): string => ` ${l}\\n`).join('');\n } catch (err: unknown) {\n const error = toError(err);\n return ` (could not read ${logPath}: ${error.message})\\n`;\n }\n }\n\n /** How many lines the log holds right now. A log that does not exist yet is zero lines, not an error. */\n lineCount(logPath: string): number {\n if (!fs.existsSync(logPath)) return 0;\n const body = fs.readFileSync(logPath, 'utf8');\n if (body === '') return 0;\n return body.split('\\n').length - (body.endsWith('\\n') ? 1 : 0);\n }\n\n private ensureDir(file: string): string {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n return file;\n }\n}\n"]}
|
|
@@ -74,6 +74,11 @@ let StageOutputLog = class StageOutputLog {
|
|
|
74
74
|
this.logPath = this.files.logsPath(repoRoot, fileName);
|
|
75
75
|
this.files.rotate(this.logPath);
|
|
76
76
|
this.fd = fs.openSync(this.logPath, 'w');
|
|
77
|
+
// The FIRST line the stage prints, before any work (issue #1393): the file now exists, and a
|
|
78
|
+
// caller that backgrounds the stage — or whose harness captures its console into a file the caller
|
|
79
|
+
// may not be allowed to read — knows where everything below is going. The same pointer closes
|
|
80
|
+
// the stage in release().
|
|
81
|
+
this.say(this.files.startLine(this.logPath));
|
|
77
82
|
// The REFERENCE, not a bound copy: `release` puts this exact function back, so a caller that
|
|
78
83
|
// installed its own stdout before us (a spec, a wrapping bin) gets ITS function back rather than
|
|
79
84
|
// a wrapper around it, and repeated captures cannot stack bound layers.
|