@webpieces/pr-gate 0.4.980 → 0.4.981

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/pr-gate",
3
- "version": "0.4.980",
3
+ "version": "0.4.981",
4
4
  "description": "Gated PR system: 3-point squash-merge, merge validation gate, and red/yellow/green PR dashboard. Standalone scripts, no Nx dependency required.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -16,18 +16,18 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@inversifyjs/binding-decorators": "1.1.5",
19
- "@webpieces/hook-runtime": "0.4.980",
20
- "@webpieces/rules-config": "0.4.980",
19
+ "@webpieces/hook-runtime": "0.4.981",
20
+ "@webpieces/rules-config": "0.4.981",
21
21
  "inversify": "7.10.4",
22
22
  "reflect-metadata": "0.2.2",
23
- "@webpieces/tooling-common": "0.4.980",
24
- "@webpieces/repo-workflow-core": "0.4.980"
23
+ "@webpieces/tooling-common": "0.4.981",
24
+ "@webpieces/repo-workflow-core": "0.4.981"
25
25
  },
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  },
29
29
  "devDependencies": {
30
- "@webpieces/tooling-testkit": "0.4.980"
30
+ "@webpieces/tooling-testkit": "0.4.981"
31
31
  },
32
32
  "types": "./src/index.d.ts",
33
33
  "bin": {
@@ -44,8 +44,8 @@ export declare class BuildOptions {
44
44
  *
45
45
  * ─── The output goes to a FILE, unconditionally ────────────────────────────────────────────────────
46
46
  * Every caller of the gate captures, and there is no flag or config key that selects otherwise. That is
47
- * the reason this bin is worth running: the build's full stdout+stderr land in `.webpieces/build.log`
48
- * (previous run kept as `.webpieces/build.log.bak`), and the console gets a heartbeat plus a pointer at
47
+ * the reason this bin is worth running: the build's full stdout+stderr land in `.webpieces/logs/build.log`
48
+ * (previous run kept as `build.log.bak` beside it), and the console gets the pointer FIRST, a heartbeat, then the pointer again at
49
49
  * that file. A measured session burned ~19 minutes re-running `nx affected` five times with no code
50
50
  * change in between, purely to see a different slice of output that had scrolled past. Reading a
51
51
  * different slice must cost a `grep`, not a build — see BuildGateLog.
@@ -58,8 +58,8 @@ exports.BuildOptions = BuildOptions;
58
58
  *
59
59
  * ─── The output goes to a FILE, unconditionally ────────────────────────────────────────────────────
60
60
  * Every caller of the gate captures, and there is no flag or config key that selects otherwise. That is
61
- * the reason this bin is worth running: the build's full stdout+stderr land in `.webpieces/build.log`
62
- * (previous run kept as `.webpieces/build.log.bak`), and the console gets a heartbeat plus a pointer at
61
+ * the reason this bin is worth running: the build's full stdout+stderr land in `.webpieces/logs/build.log`
62
+ * (previous run kept as `build.log.bak` beside it), and the console gets the pointer FIRST, a heartbeat, then the pointer again at
63
63
  * that file. A measured session burned ~19 minutes re-running `nx affected` five times with no code
64
64
  * change in between, purely to see a different slice of output that had scrolled past. Reading a
65
65
  * different slice must cost a `grep`, not a build — see BuildGateLog.
@@ -1 +1 @@
1
- {"version":3,"file":"build-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/build-command.ts"],"names":[],"mappings":";;;;AAAA,0DAOiC;AACjC,yCAA2D;AAE3D,+DAA6E;AAC7E,+DAAyD;AAEzD,yFAAyF;AAC5E,QAAA,0BAA0B,GAAG,4BAA4B,CAAC;AAEvE;;;;;;;GAOG;AACH,MAAa,YAAY;IACrB,KAAK,CAAU;IAEf,qGAAqG;IACrG,kGAAkG;IAClG,kGAAkG;IAClG,8FAA8F;IAC9F,yDAAyD;IACzD,YAAY,KAAc;QACtB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAXD,oCAWC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IAEA;IACA;IACA;IACA;IAJrB,YACqB,aAA4B,EAC5B,cAA8B,EAC9B,SAAoB,EACpB,UAA6B;Q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zC,YAAY,CAmGxB","sourcesContent":["import {\n BuildsLog,\n HomeConfigService,\n Option,\n RepoRootFinder,\n RuleFailError,\n RunningBuild,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BUILD_STAGE } from '../workflow/build-gate-log';\n\n/** The rule name the refusal is reported under, so it is greppable from a transcript. */\nexport const TOO_MANY_CONCURRENT_BUILDS = 'too-many-concurrent-builds';\n\n/**\n * What `wp-build` was asked to do. Data-only (a class, per CLAUDE.md), with exactly one field so far.\n *\n * `force` SKIPS THE CONCURRENCY CHECK AND NOTHING ELSE. It does not touch the command, and it must never\n * grow a field that does: `wp-build` runs `commands.pr-gate.buildCommand` verbatim, and a flag that\n * changed the command would make it a different build from the one the PR gate runs — which is the exact\n * drift this bin exists to delete.\n */\nexport class BuildOptions {\n force: boolean;\n\n // REQUIRED, no default. `new BuildOptions()` and `new BuildOptions(false)` would be two spellings of\n // one decision, and the bare form would keep compiling unchanged if this class ever grew a second\n // field — silently meaning \"not forced\" at a call site that was never revisited. That is the same\n // argument HomeConfig's constructor makes about its own four required parameters; a defaulted\n // parameter is exactly the shim this repo does not ship.\n constructor(force: boolean) {\n this.force = force;\n }\n}\n\n/**\n * `wp-build` — run THE project's build, and nothing else.\n *\n * ─── Why this bin exists ───────────────────────────────────────────────────────────────────────────\n * The correct verification command has lived in `commands.pr-gate.buildCommand` all along, and NOTHING\n * SURFACED IT. So every repo hand-composed its own verify chain, and those chains drifted: one sibling\n * repo's `ci:local` was `prettier --check .` (whole repo) + `wp-ci` (whole monorepo) +\n * `nx affected -t test` with NO `--base` (whole repo again) — three whole-world passes on an inner\n * loop, none of them the command the gate runs. `wp-build` closes that by making the configured value\n * the only thing anyone has to type.\n *\n * ─── It composes NOTHING, deliberately ─────────────────────────────────────────────────────────────\n * This command runs `commands.pr-gate.buildCommand` VERBATIM and adds no leg of its own — no format\n * check, no lint pass, no extra test run. Composition is exactly what drifted. Anything that must run\n * on every build belongs INSIDE `buildCommand`, where the PR gate runs it too; a leg added here would\n * be a leg the gate never sees, which is the same defect one level in.\n *\n * ─── ONE resolver, and ONE gate ────────────────────────────────────────────────────────────────────\n * `BuildAffected.runBuildGate` is the single code path that resolves the command\n * (`resolveBuildCommand`), announces it, runs it, captures its output to a log file, and renders the\n * failure. `wp-build` calls THAT — it does not re-read the config key and does not hand-write a second\n * failure string. A second reader is a second thing that can drift, and a second failure message is a\n * second thing that can teach a command the gate does not run; drift is the entire reason this bin\n * exists, so reproducing it one level in would be self-defeating.\n *\n * Only `BuildGateOptions` differs from stage ② and stage ③ — the label, the command to re-run, the\n * headline, and the log-file stage id.\n *\n * ─── The output goes to a FILE, unconditionally ────────────────────────────────────────────────────\n * Every caller of the gate captures, and there is no flag or config key that selects otherwise. That is\n * the reason this bin is worth running: the build's full stdout+stderr land in `.webpieces/build.log`\n * (previous run kept as `.webpieces/build.log.bak`), and the console gets a heartbeat plus a pointer at\n * that file. A measured session burned ~19 minutes re-running `nx affected` five times with no code\n * change in between, purely to see a different slice of output that had scrolled past. Reading a\n * different slice must cost a `grep`, not a build — see BuildGateLog.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildCommand {\n constructor(\n private readonly buildAffected: BuildAffected,\n private readonly repoRootFinder: RepoRootFinder,\n private readonly buildsLog: BuildsLog,\n private readonly homeConfig: HomeConfigService,\n ) {}\n\n run(opts: BuildOptions): Promise<void> {\n return this.runGate(opts, false);\n }\n\n /** Human-terminal form used by wp-human-post-pr; build.log remains complete while output is live. */\n runStreaming(opts: BuildOptions): Promise<void> {\n return this.runGate(opts, true);\n }\n\n private runGate(opts: BuildOptions, stream: boolean): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n if (!opts.force) this.assertMachineHasRoom();\n // runBuildGate announces the resolved command, runs it, and throws CliExitError on failure so\n // runMain owns the exit — the same three things it does for stage ② and stage ③. It also writes\n // this build's START/DONE pair to the ledger the check above just read.\n const gateOptions = new BuildGateOptions(\n '🛠️ wp-build',\n 'pnpm wp-build',\n 'Build failed.',\n BUILD_STAGE,\n );\n return stream\n ? this.buildAffected.runBuildGateStreaming(repoRoot, gateOptions)\n : this.buildAffected.runBuildGate(repoRoot, gateOptions);\n }\n\n /**\n * Refuse when this MACHINE is already running `maxConcurrentBuilds` builds.\n *\n * ─── WHY ONLY HERE, AND NEVER ON THE GATE STAGES ─────────────────────────────────────────────────\n * `wp-review-upsert-pr` and `wp-finish-upsert-pr` are the SANCTIONED path, and a refusal there wedges\n * a PR that has nowhere else to go. So they always run — and their builds still write ledger rows, so\n * they count toward what refuses an ad-hoc `wp-build`. The asymmetry is the whole design: the thing\n * that gets throttled is the extra build, not the one the process needs.\n *\n * The cures are `Option`s handed to `RuleFailError`, which `runMain` renders through\n * `formatFixOptions`. They are never numbered by hand in the message — the framework owns\n * \"Fix Option N:\", and a hand-numbered list in a string literal is an automatic review reject.\n */\n private assertMachineHasRoom(): void {\n const live = this.buildsLog.running();\n const max = this.homeConfig.load().maxConcurrentBuilds;\n if (live.length < max) return;\n throw new RuleFailError(\n TOO_MANY_CONCURRENT_BUILDS,\n `This machine is already running ${String(live.length)} build(s), and the limit is ` +\n `${String(max)}. Starting another makes all of them slower — CPU contention between agents ` +\n `building at once was measured at ~3.2x total test time.\\n\\n${this.describe(live)}`,\n undefined,\n undefined,\n [\n new Option(\n 'Re-use the gate you should be running anyway: `pnpm wp-start-upsert-pr` then\\n' +\n '`pnpm wp-review-upsert-pr`. Stage ② runs the SAME `commands.pr-gate.buildCommand`\\n' +\n 'this would have run, so its green is the same evidence — and it posts the PR.',\n true,\n ),\n new Option(\n 'Wait for one of the builds above to finish and run `pnpm wp-build` again. A build\\n' +\n 'that has already died leaves no row: the count only holds live processes.',\n ),\n new Option(\n 'Verify only what you are editing instead of the whole affected set:\\n' +\n '`pnpm exec vitest run <one spec file>`, or `pnpm nx run <project>:test`.',\n ),\n new Option(\n 'Raise the limit for THIS machine, if it genuinely has the cores: put\\n' +\n '`{\"experimental\": {\"maxConcurrentBuilds\": <n>}}` in `~/.webpieces/config.json`.',\n ),\n new Option(\n 'If you are really stuck and cannot use a gate and really really need wp-build\\n' +\n 'then use `pnpm wp-build --force`.',\n ),\n ],\n );\n }\n\n // One line per live build: which repo, which worktree, on what branch, and how long it has been\n // going. Age is what tells a reader whether to wait thirty seconds or go and look at a stuck agent.\n private describe(live: readonly RunningBuild[]): string {\n return live\n .map((build: RunningBuild): string => {\n const age = Math.max(0, Math.round((Date.now() - build.startedMs) / 1000));\n return (\n ` • ${build.repo} [tree=${build.tree || 'primary'}] ` +\n `branch=${build.branch || '?'} by=${build.by} pid=${String(build.pid)} ` +\n `running for ${String(age)}s`\n );\n })\n .join('\\n');\n }\n}\n"]}
1
+ {"version":3,"file":"build-command.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/commands/build-command.ts"],"names":[],"mappings":";;;;AAAA,0DAOiC;AACjC,yCAA2D;AAE3D,+DAA6E;AAC7E,+DAAyD;AAEzD,yFAAyF;AAC5E,QAAA,0BAA0B,GAAG,4BAA4B,CAAC;AAEvE;;;;;;;GAOG;AACH,MAAa,YAAY;IACrB,KAAK,CAAU;IAEf,qGAAqG;IACrG,kGAAkG;IAClG,kGAAkG;IAClG,8FAA8F;IAC9F,yDAAyD;IACzD,YAAY,KAAc;QACtB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAXD,oCAWC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IAEA;IACA;IACA;IACA;IAJrB,YACqB,aAA4B,EAC5B,cAA8B,EAC9B,SAAoB,EACpB,UAA6B;QAH7B,kBAAa,GAAb,aAAa,CAAe;QAC5B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,cAAS,GAAT,SAAS,CAAW;QACpB,eAAU,GAAV,UAAU,CAAmB;I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AS,EACT,SAAS,EACT;YACI,IAAI,qBAAM,CACN,gFAAgF;gBAC5E,qFAAqF;gBACrF,+EAA+E,EACnF,IAAI,CACP;YACD,IAAI,qBAAM,CACN,qFAAqF;gBACjF,2EAA2E,CAClF;YACD,IAAI,qBAAM,CACN,uEAAuE;gBACnE,0EAA0E,CACjF;YACD,IAAI,qBAAM,CACN,wEAAwE;gBACpE,iFAAiF,CACxF;YACD,IAAI,qBAAM,CACN,iFAAiF;gBAC7E,mCAAmC,CAC1C;SACJ,CACJ,CAAC;IACN,CAAC;IAED,gGAAgG;IAChG,oGAAoG;IAC5F,QAAQ,CAAC,IAA6B;QAC1C,OAAO,IAAI;aACN,GAAG,CAAC,CAAC,KAAmB,EAAU,EAAE;YACjC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;YAC3E,OAAO,CACH,OAAO,KAAK,CAAC,IAAI,UAAU,KAAK,CAAC,IAAI,IAAI,SAAS,IAAI;gBACtD,UAAU,KAAK,CAAC,MAAM,IAAI,GAAG,OAAO,KAAK,CAAC,EAAE,QAAQ,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG;gBACxE,eAAe,MAAM,CAAC,GAAG,CAAC,GAAG,CAChC,CAAC;QACN,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;CACJ,CAAA;AAnGY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGD,8BAAa;QACZ,6BAAc;QACnB,wBAAS;QACR,gCAAiB;GALzC,YAAY,CAmGxB","sourcesContent":["import {\n BuildsLog,\n HomeConfigService,\n Option,\n RepoRootFinder,\n RuleFailError,\n RunningBuild,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { BuildAffected, BuildGateOptions } from '../workflow/build-affected';\nimport { BUILD_STAGE } from '../workflow/build-gate-log';\n\n/** The rule name the refusal is reported under, so it is greppable from a transcript. */\nexport const TOO_MANY_CONCURRENT_BUILDS = 'too-many-concurrent-builds';\n\n/**\n * What `wp-build` was asked to do. Data-only (a class, per CLAUDE.md), with exactly one field so far.\n *\n * `force` SKIPS THE CONCURRENCY CHECK AND NOTHING ELSE. It does not touch the command, and it must never\n * grow a field that does: `wp-build` runs `commands.pr-gate.buildCommand` verbatim, and a flag that\n * changed the command would make it a different build from the one the PR gate runs — which is the exact\n * drift this bin exists to delete.\n */\nexport class BuildOptions {\n force: boolean;\n\n // REQUIRED, no default. `new BuildOptions()` and `new BuildOptions(false)` would be two spellings of\n // one decision, and the bare form would keep compiling unchanged if this class ever grew a second\n // field — silently meaning \"not forced\" at a call site that was never revisited. That is the same\n // argument HomeConfig's constructor makes about its own four required parameters; a defaulted\n // parameter is exactly the shim this repo does not ship.\n constructor(force: boolean) {\n this.force = force;\n }\n}\n\n/**\n * `wp-build` — run THE project's build, and nothing else.\n *\n * ─── Why this bin exists ───────────────────────────────────────────────────────────────────────────\n * The correct verification command has lived in `commands.pr-gate.buildCommand` all along, and NOTHING\n * SURFACED IT. So every repo hand-composed its own verify chain, and those chains drifted: one sibling\n * repo's `ci:local` was `prettier --check .` (whole repo) + `wp-ci` (whole monorepo) +\n * `nx affected -t test` with NO `--base` (whole repo again) — three whole-world passes on an inner\n * loop, none of them the command the gate runs. `wp-build` closes that by making the configured value\n * the only thing anyone has to type.\n *\n * ─── It composes NOTHING, deliberately ─────────────────────────────────────────────────────────────\n * This command runs `commands.pr-gate.buildCommand` VERBATIM and adds no leg of its own — no format\n * check, no lint pass, no extra test run. Composition is exactly what drifted. Anything that must run\n * on every build belongs INSIDE `buildCommand`, where the PR gate runs it too; a leg added here would\n * be a leg the gate never sees, which is the same defect one level in.\n *\n * ─── ONE resolver, and ONE gate ────────────────────────────────────────────────────────────────────\n * `BuildAffected.runBuildGate` is the single code path that resolves the command\n * (`resolveBuildCommand`), announces it, runs it, captures its output to a log file, and renders the\n * failure. `wp-build` calls THAT — it does not re-read the config key and does not hand-write a second\n * failure string. A second reader is a second thing that can drift, and a second failure message is a\n * second thing that can teach a command the gate does not run; drift is the entire reason this bin\n * exists, so reproducing it one level in would be self-defeating.\n *\n * Only `BuildGateOptions` differs from stage ② and stage ③ — the label, the command to re-run, the\n * headline, and the log-file stage id.\n *\n * ─── The output goes to a FILE, unconditionally ────────────────────────────────────────────────────\n * Every caller of the gate captures, and there is no flag or config key that selects otherwise. That is\n * the reason this bin is worth running: the build's full stdout+stderr land in `.webpieces/logs/build.log`\n * (previous run kept as `build.log.bak` beside it), and the console gets the pointer FIRST, a heartbeat, then the pointer again at\n * that file. A measured session burned ~19 minutes re-running `nx affected` five times with no code\n * change in between, purely to see a different slice of output that had scrolled past. Reading a\n * different slice must cost a `grep`, not a build — see BuildGateLog.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildCommand {\n constructor(\n private readonly buildAffected: BuildAffected,\n private readonly repoRootFinder: RepoRootFinder,\n private readonly buildsLog: BuildsLog,\n private readonly homeConfig: HomeConfigService,\n ) {}\n\n run(opts: BuildOptions): Promise<void> {\n return this.runGate(opts, false);\n }\n\n /** Human-terminal form used by wp-human-post-pr; build.log remains complete while output is live. */\n runStreaming(opts: BuildOptions): Promise<void> {\n return this.runGate(opts, true);\n }\n\n private runGate(opts: BuildOptions, stream: boolean): Promise<void> {\n const repoRoot = this.repoRootFinder.resolveRepoRoot(process.cwd());\n if (!opts.force) this.assertMachineHasRoom();\n // runBuildGate announces the resolved command, runs it, and throws CliExitError on failure so\n // runMain owns the exit — the same three things it does for stage ② and stage ③. It also writes\n // this build's START/DONE pair to the ledger the check above just read.\n const gateOptions = new BuildGateOptions(\n '🛠️ wp-build',\n 'pnpm wp-build',\n 'Build failed.',\n BUILD_STAGE,\n );\n return stream\n ? this.buildAffected.runBuildGateStreaming(repoRoot, gateOptions)\n : this.buildAffected.runBuildGate(repoRoot, gateOptions);\n }\n\n /**\n * Refuse when this MACHINE is already running `maxConcurrentBuilds` builds.\n *\n * ─── WHY ONLY HERE, AND NEVER ON THE GATE STAGES ─────────────────────────────────────────────────\n * `wp-review-upsert-pr` and `wp-finish-upsert-pr` are the SANCTIONED path, and a refusal there wedges\n * a PR that has nowhere else to go. So they always run — and their builds still write ledger rows, so\n * they count toward what refuses an ad-hoc `wp-build`. The asymmetry is the whole design: the thing\n * that gets throttled is the extra build, not the one the process needs.\n *\n * The cures are `Option`s handed to `RuleFailError`, which `runMain` renders through\n * `formatFixOptions`. They are never numbered by hand in the message — the framework owns\n * \"Fix Option N:\", and a hand-numbered list in a string literal is an automatic review reject.\n */\n private assertMachineHasRoom(): void {\n const live = this.buildsLog.running();\n const max = this.homeConfig.load().maxConcurrentBuilds;\n if (live.length < max) return;\n throw new RuleFailError(\n TOO_MANY_CONCURRENT_BUILDS,\n `This machine is already running ${String(live.length)} build(s), and the limit is ` +\n `${String(max)}. Starting another makes all of them slower — CPU contention between agents ` +\n `building at once was measured at ~3.2x total test time.\\n\\n${this.describe(live)}`,\n undefined,\n undefined,\n [\n new Option(\n 'Re-use the gate you should be running anyway: `pnpm wp-start-upsert-pr` then\\n' +\n '`pnpm wp-review-upsert-pr`. Stage ② runs the SAME `commands.pr-gate.buildCommand`\\n' +\n 'this would have run, so its green is the same evidence — and it posts the PR.',\n true,\n ),\n new Option(\n 'Wait for one of the builds above to finish and run `pnpm wp-build` again. A build\\n' +\n 'that has already died leaves no row: the count only holds live processes.',\n ),\n new Option(\n 'Verify only what you are editing instead of the whole affected set:\\n' +\n '`pnpm exec vitest run <one spec file>`, or `pnpm nx run <project>:test`.',\n ),\n new Option(\n 'Raise the limit for THIS machine, if it genuinely has the cores: put\\n' +\n '`{\"experimental\": {\"maxConcurrentBuilds\": <n>}}` in `~/.webpieces/config.json`.',\n ),\n new Option(\n 'If you are really stuck and cannot use a gate and really really need wp-build\\n' +\n 'then use `pnpm wp-build --force`.',\n ),\n ],\n );\n }\n\n // One line per live build: which repo, which worktree, on what branch, and how long it has been\n // going. Age is what tells a reader whether to wait thirty seconds or go and look at a stuck agent.\n private describe(live: readonly RunningBuild[]): string {\n return live\n .map((build: RunningBuild): string => {\n const age = Math.max(0, Math.round((Date.now() - build.startedMs) / 1000));\n return (\n ` • ${build.repo} [tree=${build.tree || 'primary'}] ` +\n `branch=${build.branch || '?'} by=${build.by} pid=${String(build.pid)} ` +\n `running for ${String(age)}s`\n );\n })\n .join('\\n');\n }\n}\n"]}
@@ -88,8 +88,13 @@ let BuildAffected = class BuildAffected {
88
88
  // `say`, so it survives a stage that is capturing its own console (see StageOutputLog): the
89
89
  // command being run and the result of running it are exactly what a caller watching a long build
90
90
  // needs to see live.
91
- this.stageConsole.say(`\n${opts.label}: ${buildCommand}\n`);
91
+ //
92
+ // The log's path goes out FIRST, before the command line and before any work (issue #1393): for
93
+ // `wp-build` it is the very first line on stdout, so a caller that backgrounds the build, or whose
94
+ // harness captures the console into a file of its own, already knows which file to read.
92
95
  const logPath = await this.buildLog.pathFor(repoRoot, opts.stage);
96
+ this.stageConsole.say(this.buildLog.startLine(logPath));
97
+ this.stageConsole.say(`\n${opts.label}: ${buildCommand}\n`);
93
98
  const ticket = this.buildsLog.start(opts.stage, repoRoot);
94
99
  let termination = new rules_config_1.BuildTermination(1, null);
95
100
  // webpieces-disable no-unmanaged-exceptions -- chokepoint: the DONE row must be written whether the
@@ -1 +1 @@
1
- {"version":3,"file":"build-affected.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-affected.ts"],"names":[],"mappings":";;;;AAAA,0DAAkJ;AAClJ,sEAA+D;AAC/D,yCAA2D;AAC3D,qDAAgD;AAChD,yDAAoD;AAEpD,iGAAiG;AACjG,8FAA8F;AAC9F,iGAAiG;AACjG,oFAAoF;AACpF,oGAAoG;AACpG,iEAAiE;AAEjE;;;;GAIG;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KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC;QACpF,IAAI,SAAS,KAAK,CAAC,EAAE,CAAC;YAClB,MAAM,IAAI,2BAAY,CAClB,SAAS,EACT,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,CAAC,CAC7D,CAAC;QACN,CAAC;QACD,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IACjE,CAAC;IAED;;;;;;;OAOG;IACK,WAAW,CACf,IAAsB,EACtB,YAAoB,EACpB,OAAe,EACf,WAA6B;QAE7B,OAAO,CACH,OAAO,IAAI,CAAC,eAAe,IAAI;YAC/B,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,YAAY,EAAE,OAAO,EAAE,WAAW,CAAC;YAChE,wCAAwC,IAAI,CAAC,YAAY,KAAK,CACjE,CAAC;IACN,CAAC;CACJ,CAAA;AAlGY,sCAAa;wBAAb,aAAa;IADzB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGN,6BAAY;QACX,wBAAS;QACN,iCAAc;QACZ,mCAAc;GAL1C,aAAa,CAkGzB","sourcesContent":["import { loadAndValidate, CliExitError, DEFAULT_BUILD_COMMAND, BuildsLog, BuildTermination, HOTFIX_BUILD_COMMAND } from '@webpieces/rules-config';\nimport { BranchIdentity } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BuildGateLog } from './build-gate-log';\nimport { StageOutputLog } from './stage-output-log';\n\n// Single source of truth for RUNNING the build gate. `wp-start-upsert-pr` runs NO build; stage ②\n// (`wp-review-upsert-pr`) runs it authoritatively before any reviewer is spawned, and stage ③\n// (`wp-finish-upsert-pr`) re-runs it only when HEAD has moved since. nx `affected` only rebuilds\n// changed projects. The fallback command itself lives in @webpieces/rules-config as\n// DEFAULT_BUILD_COMMAND — whole-repo-build-guard prints the same string, and one definition is what\n// keeps the refusal message naming the build that actually runs.\n\n/**\n * The caller-supplied framing for the build gate (label, re-run command, failure headline, stage id). Kept\n * as a parameter object so runBuildGate stays agnostic of who invokes it. A class (not an object literal)\n * per the codebase's data-structure convention.\n */\nexport class BuildGateOptions {\n label: string; // section header shown above the gate\n rerunCommand: string; // command the AI re-runs after fixing the build\n failureHeadline: string; // first line printed on failure\n // WHICH stage's gate this is — REVIEW_STAGE, FINISH_STAGE or BUILD_STAGE. Required, with no default:\n // it decides the captured log's filename, and a default would silently make two stages share one file.\n stage: string;\n\n constructor(label: string, rerunCommand: string, failureHeadline: string, stage: string) {\n this.label = label;\n this.rerunCommand = rerunCommand;\n this.failureHeadline = failureHeadline;\n this.stage = stage;\n }\n}\n\n/** Runs the authoritative nx-affected build gate for wp-review-upsert-pr and wp-finish-upsert-pr. */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildAffected {\n constructor(\n private readonly buildLog: BuildGateLog,\n private readonly buildsLog: BuildsLog,\n private readonly stageConsole: StageOutputLog,\n private readonly branchIdentity: BranchIdentity,\n ) {}\n\n /**\n * Resolve the exact build command this gate will run: the project's configured\n * PrGateConfig.buildCommand, or the default affected-ci command when none is set.\n */\n resolveBuildCommand(repoRoot: string): string {\n if (this.branchIdentity.isHotfix()) return HOTFIX_BUILD_COMMAND;\n const configured = loadAndValidate(repoRoot).prGate.buildCommand;\n return configured !== undefined && configured.trim() !== ''\n ? configured\n : DEFAULT_BUILD_COMMAND;\n }\n\n /**\n * Run the configured build gate with consistent framing, throwing CliExitError(buildCode) on\n * failure so the bin's main()/runMain owns the exit. THE single source of truth for running a build:\n * wp-build, wp-review-upsert-pr and wp-finish-upsert-pr all call THIS (only the BuildGateOptions\n * differ), and there is no other way to reach the spawn.\n *\n * ─── EVERY BUILD ON THIS MACHINE IS LEDGERED FROM HERE ───────────────────────────────────────────\n * A START row goes into `~/.webpieces/builds.log` before the spawn and a DONE row after it, in a\n * `finally` so a throw on the failure path still closes the pair. `opts.stage` — `build` | `review` |\n * `finish` — IS the caller id the row records; there is deliberately no second `caller` field, since\n * two spellings of one fact is the shim `.claude/rules/no-backwards-compat.md` rejects.\n *\n * The ledger is best-effort by construction (see BuildsLog): it can never throw, so no build can die\n * because a log file was busy.\n */\n async runBuildGate(repoRoot: string, opts: BuildGateOptions): Promise<void> {\n return this.run(repoRoot, opts, false);\n }\n\n /** The human escape hatch uses the same gate but follows build.log on the terminal while it runs. */\n async runBuildGateStreaming(repoRoot: string, opts: BuildGateOptions): Promise<void> {\n return this.run(repoRoot, opts, true);\n }\n\n private async run(repoRoot: string, opts: BuildGateOptions, stream: boolean): Promise<void> {\n const buildCommand = this.resolveBuildCommand(repoRoot);\n // TWO lines on the happy path — the command, then the result. The old framing spent a banner and a\n // paragraph explaining how to reproduce a build that was about to pass anyway; that explanation is\n // only useful when the build FAILS, so it now lives solely on the failure path below.\n //\n // `say`, so it survives a stage that is capturing its own console (see StageOutputLog): the\n // command being run and the result of running it are exactly what a caller watching a long build\n // needs to see live.\n this.stageConsole.say(`\\n${opts.label}: ${buildCommand}\\n`);\n const logPath = await this.buildLog.pathFor(repoRoot, opts.stage);\n const ticket = this.buildsLog.start(opts.stage, repoRoot);\n let termination = new BuildTermination(1, null);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the DONE row must be written whether the\n // build passed, failed, or the spawn itself blew up; the throw is re-raised untouched below\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n termination = stream\n ? await this.buildLog.runStreaming(repoRoot, buildCommand, logPath)\n : await this.buildLog.run(repoRoot, buildCommand, logPath);\n } finally {\n this.buildsLog.finish(ticket, termination);\n }\n const buildCode =\n termination.code === null || termination.signal !== null ? 1 : termination.code;\n if (buildCode !== 0) {\n throw new CliExitError(\n buildCode,\n this.failureText(opts, buildCommand, logPath, termination),\n );\n }\n this.stageConsole.say(this.buildLog.successMessage(logPath));\n }\n\n /**\n * The failure text: this gate's own headline, then the pointer at the log the build already wrote.\n *\n * There is no second, streamed variant any more. Capturing used to be behind an EXPERIMENTAL\n * machine-local opt-in, which meant the refusal an agent read depended on a file almost nobody had —\n * and the un-captured branch's advice was \"run the build again yourself\", which is the single most\n * expensive thing an agent can be told. Reading a FILE is now the only answer this gate gives.\n */\n private failureText(\n opts: BuildGateOptions,\n buildCommand: string,\n logPath: string,\n termination: BuildTermination,\n ): string {\n return (\n `\\n❌ ${opts.failureHeadline}\\n` +\n this.buildLog.failureMessage(buildCommand, logPath, termination) +\n `Fix what that log shows, then re-run ${opts.rerunCommand}.\\n`\n );\n }\n}\n"]}
1
+ {"version":3,"file":"build-affected.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-affected.ts"],"names":[],"mappings":";;;;AAAA,0DAAkJ;AAClJ,sEAA+D;AAC/D,yCAA2D;AAC3D,qDAAgD;AAChD,yDAAoD;AAEpD,iGAAiG;AACjG,8FAA8F;AAC9F,iGAAiG;AACjG,oFAAoF;AACpF,oGAAoG;AACpG,iEAAiE;AAEjE;;;;GAIG;AACH,MAAa,gBAAgB;IACzB,KAAK,CAAS,CAAC,sCAAsC;IACrD,YAAY,CAAS,CAAC,gDAAgD;IACtE,eAAe,CAAS,CAAC,gCAAgC;IACzD,qGAAqG;IACrG,uGAAuG;IACvG,KAAK,CAAS;IAEd,YAAY,KAAa,EAAE,YAAoB,EAAE,eAAuB,EAAE,KAAa;QACnF,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAdD,4CAcC;AAED,qGAAqG;AAE9F,IAAM,aAAa,GAAnB,MAAM,aAAa;IAED;IACA;IACA;IACA;IAJrB,YACqB,QAAsB,EACtB,SAAoB,EACpB,YAA4B,EAC5B,cAA8B;Q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WAAW,CACf,IAAsB,EACtB,YAAoB,EACpB,OAAe,EACf,WAA6B;QAE7B,OAAO,CACH,OAAO,IAAI,CAAC,eAAe,IAAI;YAC/B,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,YAAY,EAAE,OAAO,EAAE,WAAW,CAAC;YAChE,wCAAwC,IAAI,CAAC,YAAY,KAAK,CACjE,CAAC;IACN,CAAC;CACJ,CAAA;AAvGY,sCAAa;wBAAb,aAAa;IADzB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGN,6BAAY;QACX,wBAAS;QACN,iCAAc;QACZ,mCAAc;GAL1C,aAAa,CAuGzB","sourcesContent":["import { loadAndValidate, CliExitError, DEFAULT_BUILD_COMMAND, BuildsLog, BuildTermination, HOTFIX_BUILD_COMMAND } from '@webpieces/rules-config';\nimport { BranchIdentity } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BuildGateLog } from './build-gate-log';\nimport { StageOutputLog } from './stage-output-log';\n\n// Single source of truth for RUNNING the build gate. `wp-start-upsert-pr` runs NO build; stage ②\n// (`wp-review-upsert-pr`) runs it authoritatively before any reviewer is spawned, and stage ③\n// (`wp-finish-upsert-pr`) re-runs it only when HEAD has moved since. nx `affected` only rebuilds\n// changed projects. The fallback command itself lives in @webpieces/rules-config as\n// DEFAULT_BUILD_COMMAND — whole-repo-build-guard prints the same string, and one definition is what\n// keeps the refusal message naming the build that actually runs.\n\n/**\n * The caller-supplied framing for the build gate (label, re-run command, failure headline, stage id). Kept\n * as a parameter object so runBuildGate stays agnostic of who invokes it. A class (not an object literal)\n * per the codebase's data-structure convention.\n */\nexport class BuildGateOptions {\n label: string; // section header shown above the gate\n rerunCommand: string; // command the AI re-runs after fixing the build\n failureHeadline: string; // first line printed on failure\n // WHICH stage's gate this is — REVIEW_STAGE, FINISH_STAGE or BUILD_STAGE. Required, with no default:\n // it decides the captured log's filename, and a default would silently make two stages share one file.\n stage: string;\n\n constructor(label: string, rerunCommand: string, failureHeadline: string, stage: string) {\n this.label = label;\n this.rerunCommand = rerunCommand;\n this.failureHeadline = failureHeadline;\n this.stage = stage;\n }\n}\n\n/** Runs the authoritative nx-affected build gate for wp-review-upsert-pr and wp-finish-upsert-pr. */\n@injectable(bindingScopeValues.Singleton)\nexport class BuildAffected {\n constructor(\n private readonly buildLog: BuildGateLog,\n private readonly buildsLog: BuildsLog,\n private readonly stageConsole: StageOutputLog,\n private readonly branchIdentity: BranchIdentity,\n ) {}\n\n /**\n * Resolve the exact build command this gate will run: the project's configured\n * PrGateConfig.buildCommand, or the default affected-ci command when none is set.\n */\n resolveBuildCommand(repoRoot: string): string {\n if (this.branchIdentity.isHotfix()) return HOTFIX_BUILD_COMMAND;\n const configured = loadAndValidate(repoRoot).prGate.buildCommand;\n return configured !== undefined && configured.trim() !== ''\n ? configured\n : DEFAULT_BUILD_COMMAND;\n }\n\n /**\n * Run the configured build gate with consistent framing, throwing CliExitError(buildCode) on\n * failure so the bin's main()/runMain owns the exit. THE single source of truth for running a build:\n * wp-build, wp-review-upsert-pr and wp-finish-upsert-pr all call THIS (only the BuildGateOptions\n * differ), and there is no other way to reach the spawn.\n *\n * ─── EVERY BUILD ON THIS MACHINE IS LEDGERED FROM HERE ───────────────────────────────────────────\n * A START row goes into `~/.webpieces/builds.log` before the spawn and a DONE row after it, in a\n * `finally` so a throw on the failure path still closes the pair. `opts.stage` — `build` | `review` |\n * `finish` — IS the caller id the row records; there is deliberately no second `caller` field, since\n * two spellings of one fact is the shim `.claude/rules/no-backwards-compat.md` rejects.\n *\n * The ledger is best-effort by construction (see BuildsLog): it can never throw, so no build can die\n * because a log file was busy.\n */\n async runBuildGate(repoRoot: string, opts: BuildGateOptions): Promise<void> {\n return this.run(repoRoot, opts, false);\n }\n\n /** The human escape hatch uses the same gate but follows build.log on the terminal while it runs. */\n async runBuildGateStreaming(repoRoot: string, opts: BuildGateOptions): Promise<void> {\n return this.run(repoRoot, opts, true);\n }\n\n private async run(repoRoot: string, opts: BuildGateOptions, stream: boolean): Promise<void> {\n const buildCommand = this.resolveBuildCommand(repoRoot);\n // TWO lines on the happy path — the command, then the result. The old framing spent a banner and a\n // paragraph explaining how to reproduce a build that was about to pass anyway; that explanation is\n // only useful when the build FAILS, so it now lives solely on the failure path below.\n //\n // `say`, so it survives a stage that is capturing its own console (see StageOutputLog): the\n // command being run and the result of running it are exactly what a caller watching a long build\n // needs to see live.\n //\n // The log's path goes out FIRST, before the command line and before any work (issue #1393): for\n // `wp-build` it is the very first line on stdout, so a caller that backgrounds the build, or whose\n // harness captures the console into a file of its own, already knows which file to read.\n const logPath = await this.buildLog.pathFor(repoRoot, opts.stage);\n this.stageConsole.say(this.buildLog.startLine(logPath));\n this.stageConsole.say(`\\n${opts.label}: ${buildCommand}\\n`);\n const ticket = this.buildsLog.start(opts.stage, repoRoot);\n let termination = new BuildTermination(1, null);\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: the DONE row must be written whether the\n // build passed, failed, or the spawn itself blew up; the throw is re-raised untouched below\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n termination = stream\n ? await this.buildLog.runStreaming(repoRoot, buildCommand, logPath)\n : await this.buildLog.run(repoRoot, buildCommand, logPath);\n } finally {\n this.buildsLog.finish(ticket, termination);\n }\n const buildCode =\n termination.code === null || termination.signal !== null ? 1 : termination.code;\n if (buildCode !== 0) {\n throw new CliExitError(\n buildCode,\n this.failureText(opts, buildCommand, logPath, termination),\n );\n }\n this.stageConsole.say(this.buildLog.successMessage(logPath));\n }\n\n /**\n * The failure text: this gate's own headline, then the pointer at the log the build already wrote.\n *\n * There is no second, streamed variant any more. Capturing used to be behind an EXPERIMENTAL\n * machine-local opt-in, which meant the refusal an agent read depended on a file almost nobody had —\n * and the un-captured branch's advice was \"run the build again yourself\", which is the single most\n * expensive thing an agent can be told. Reading a FILE is now the only answer this gate gives.\n */\n private failureText(\n opts: BuildGateOptions,\n buildCommand: string,\n logPath: string,\n termination: BuildTermination,\n ): string {\n return (\n `\\n❌ ${opts.failureHeadline}\\n` +\n this.buildLog.failureMessage(buildCommand, logPath, termination) +\n `Fix what that log shows, then re-run ${opts.rerunCommand}.\\n`\n );\n }\n}\n"]}
@@ -41,19 +41,20 @@ export declare class BuildLogHeartbeat {
41
41
  * WHERE the file goes, how the previous run is kept, and what the pointer reads like are `GateLogFile`'s
42
42
  * — one mechanism, shared with the stage console log, so there is a single answer to "where is it?".
43
43
  *
44
- * ─── Two naming schemes, one rule each ─────────────────────────────────────────────────────────────────
45
- * • `wp-build` (BUILD_STAGE) writes ONE fixed path, `.webpieces/build.log`. It is fixed because a HUMAN
46
- * OR AN AGENT TYPES IT — `grep -n error .webpieces/build.log` has to be writable from memory, and a
47
- * name carrying a branch and a sha is not. History comes from the rotation instead.
48
- * • stage ② and stage ③ write `logs/build-gate-<stage>-<branch>-<shortSha>.log`, because those two
49
- * gates CAN run against one commit and a failure message from one must not be pointing at a file the
50
- * other overwrote. Nobody types those names; the failure message prints them.
44
+ * ─── One directory, two naming schemes, one rule each ──────────────────────────────────────────────────
45
+ * Every build log sits in `<tree>/.webpieces/logs/` (GateLogFile.logsPath — inside the checkout the
46
+ * command ran in, a linked worktree's own root included; issue #1393).
47
+ * • `wp-build` (BUILD_STAGE) writes ONE fixed name, `build.log`. History comes from the rotation.
48
+ * • stage ② and stage ③ write `build-gate-<stage>-<branch>-<shortSha>.log`, because those two gates CAN
49
+ * run against one commit and a failure message from one must not be pointing at a file the other
50
+ * overwrote.
51
+ * Nobody needs to type either name: the absolute path is printed as the FIRST line of the build, before
52
+ * it starts, and again in the closing pointer.
51
53
  *
52
54
  * ─── Concurrency ───────────────────────────────────────────────────────────────────────────────────────
53
- * The DIRECTORY is `dotWebpieces.local()`-scoped — `<primary>/.webpieces/worktrees/<git worktree name>/`
54
- * in a linked worktree — so "N agents in N worktrees" is safe by construction rather than by naming. The
55
- * residual case is two builds in the SAME worktree at once, which is already unsupported: both would be
56
- * driving one git index.
55
+ * The DIRECTORY is per checkout — a linked worktree writes under its own root — so "N agents in N
56
+ * worktrees" is safe by construction rather than by naming. The residual case is two builds in the SAME
57
+ * worktree at once, which is already unsupported: both would be driving one git index.
57
58
  */
58
59
  export declare class BuildGateLog {
59
60
  private readonly files;
@@ -76,6 +77,8 @@ export declare class BuildGateLog {
76
77
  run(repoRoot: string, buildCommand: string, logPath: string): Promise<BuildTermination>;
77
78
  /** Human-only variant: preserve the durable log and follow its appended bytes live. */
78
79
  runStreaming(repoRoot: string, buildCommand: string, logPath: string): Promise<BuildTermination>;
80
+ /** The `FullLog : <path>` line printed before the build starts — see GateLogFile.startLine. */
81
+ startLine(logPath: string): string;
79
82
  /**
80
83
  * The success summary: the caller is told WHERE the full output is, not handed the output.
81
84
  */
@@ -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
- * ─── Two naming schemes, one rule each ─────────────────────────────────────────────────────────────────
88
- * • `wp-build` (BUILD_STAGE) writes ONE fixed path, `.webpieces/build.log`. It is fixed because a HUMAN
89
- * OR AN AGENT TYPES IT — `grep -n error .webpieces/build.log` has to be writable from memory, and a
90
- * name carrying a branch and a sha is not. History comes from the rotation instead.
91
- * • stage ② and stage ③ write `logs/build-gate-<stage>-<branch>-<shortSha>.log`, because those two
92
- * gates CAN run against one commit and a failure message from one must not be pointing at a file the
93
- * other overwrote. Nobody types those names; the failure message prints them.
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 `dotWebpieces.local()`-scoped — `<primary>/.webpieces/worktrees/<git worktree name>/`
97
- * in a linked worktree — so "N agents in N worktrees" is safe by construction rather than by naming. The
98
- * residual case is two builds in the SAME worktree at once, which is already unsupported: both would be
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
- const name = await this.fileNameFor(repoRoot, stage);
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","sourceR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tD,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;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,YA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AAM,CAAC;QACzE,OAAO,wCAAwC,IAAI,YAAY,MAAM,GAAG,CAAC;IAC7E,CAAC;IAEO,KAAK,CAAC,WAAW,CAAC,QAAgB,EAAE,KAAa;QACrD,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC;IAClF,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 * ─── 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.aiWritable()` —
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
- * `aiWritable()` for why `pr-review/` has to sit in the worktree). The repo-wide `shared()` dir is never
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 `aiWritable()` are the SAME path
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.aiWritable()` —
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
- * `aiWritable()` for why `pr-review/` has to sit in the worktree). The repo-wide `shared()` dir is never
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() — merge-info/, instruct-ai/, logs/ in <primary>/.webpieces/worktrees/<name>
57
- // aiWritable() — pr-review/ in <worktree>/.webpieces, where the agent can actually write it
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 `aiWritable()` are the SAME path
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.aiWritable(repoRoot)];
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;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AAE,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.aiWritable()` —\n * which are one and the same directory in the primary clone and two in a linked worktree (see\n * `aiWritable()` for why `pr-review/` has 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/, logs/ in <primary>/.webpieces/worktrees/<name>\n // aiWritable() — pr-review/ in <worktree>/.webpieces, where the agent can actually write it\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 `aiWritable()` 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.aiWritable(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"]}
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,6GAA6G;QAC7G,uHAAuH;QACvH,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAE/B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,GAAG,GAAG,oCAAoC,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;QACrF,KAAK,MAAM,IAAI,IAAI,KAAK;YAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,aAAa,IAAI,IAAI,CAAC,CAAC;QACtE,OAAO,CAAC,MAAM,CAAC,KAAK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Finder, 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"]}
@@ -7,16 +7,10 @@
7
7
  */
8
8
  export declare class GateLogFile {
9
9
  /**
10
- * `<local()>/logs/<name>` — the ONE log directory, per worktree namespace. Creates the directory.
11
- * Use for anything a MESSAGE points at; nobody types these names.
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 (a linked
40
- * worktree's state lives under the PRIMARY clone, so it usually does not), absolute otherwise.
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')`. In a LINKED WORKTREE `local()`
23
- // resolves to `<primary>/.webpieces/worktrees/<git worktree name>/`, so:
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 history OUTLIVES the worktree — `wp-cleanup` reaps a tree's directory and the logs it wrote are
26
- // still there under the primary clone, which is exactly when you want them;
27
- // • it self-limits, because `.webpieces/worktrees/**` is already swept once a namespace goes stale.
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
- * `<local()>/logs/<name>` — the ONE log directory, per worktree namespace. Creates the directory.
41
- * Use for anything a MESSAGE points at; nobody types these names.
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.logsFile(repoRoot, name));
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 (a linked
88
- * worktree's state lives under the PRIMARY clone, so it usually does not), absolute otherwise.
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,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,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC;IACjE,CAAC;IAED;;;;OAIG;IACH,SAAS,CAAC,QAAgB,EAAE,IAAY;QACpC,OAAO,IAAI,CAAC,SAAS,CAAC,6BAAY,CAAC,SAAS,CAAC,QAAQ,EA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AC,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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AAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAS,EAAU,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC/E,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,uBAAuB,OAAO,KAAK,KAAK,CAAC,OAAO,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;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.
@@ -1 +1 @@
1
- {"version":3,"file":"stage-output-log.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/stage-output-log.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAAgF;AAChF,iEAA6D;AAC7D,yCAA2D;AAE3D,mDAA8C;AAE9C,0GAA0G;AAC1G,2GAA2G;AAC3G,0GAA0G;AAC1G,yGAAyG;AACzG,+CAA+C;AAC/C,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AACzG,yGAAyG;AACzG,uGAAuG;AACvG,uGAAuG;AACvG,sEAAsE;AACtE,EAAE;AACF,oGAAoG;AACpG,uGAAuG;AACvG,wGAAwG;AACxG,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,yGAAyG;AACzG,0GAA0G;AAC1G,oGAAoG;AACpG,qGAAqG;AACrG,0GAA0G;AAC1G,EAAE;AACF,wGAAwG;AACxG,wGAAwG;AACxG,uFAAuF;AACvF,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AAEzG,kGAAkG;AACrF,QAAA,kBAAkB,GAAG,yBAAyB,CAAC;AAE5D,6BAA6B;AAChB,QAAA,kBAAkB,GAAG,yBAAyB,CAAC;AAQ5D;;;;;;;GAOG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IACM;IAA7B,YAA6B,KAAkB;QAAlB,UAAK,GAAL,KAAK,CAAa;IAAG,CAAC;IAEnD,oGAAoG;IACpG,yEAAyE;IACjE,OAAO,GAAG,EAAE,CAAC;IACb,EAAE,GAAG,CAAC,CAAC,CAAC;IACR,QAAQ,GAAuB,IAAI,CAAC;IAE5C;;;;;;;OAOG;IACH,KAAK,CAAC,WAAW,CAAI,QAAgB,EAAE,QAAgB,EAAE,IAAsB;QAC3E,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QACtG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CA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IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAED,2BAAW;GADtC,cAAc,CAwF1B","sourcesContent":["import * as fs from 'fs';\nimport { RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GateLogFile } from './gate-log-file';\n\n// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────\n// `wp-build` already solved this for the BUILD: its output goes to a FILE and the console gets a heartbeat\n// plus a pointer. Stage ② and stage ③ had not been given the same treatment, so they printed everything —\n// merge validation, the active-hatch report, the checklist scan, the diff extraction, the dashboard, the\n// gh round trips — straight down the terminal.\n//\n// The consequence was measured, and it is not \"a long transcript\". An agent that expects a wall of output\n// bounds it by reflex: `pnpm wp-review-upsert-pr 2>&1 | tail -50`. A PIPE WITHHOLDS EVERY BYTE UNTIL THE\n// COMMAND EXITS, so the harness sees a command that has printed nothing for 600 seconds and kills it — a\n// full build's worth of work thrown away, and then usually re-run the same way. In this repo's primary\n// tree alone the call log holds 85 piped `wp-*` invocations, 42 of them on a command that runs a build\n// (`wp-review-upsert-pr` 22, `wp-finish-upsert-pr` 17, `wp-build` 3).\n//\n// Shrinking the output is therefore the FIRST half of the fix and the guard against the pipe is the\n// second, in that order. Blocking the pipe while the command still printed a thousand lines would only\n// have traded a watchdog kill for a flooded context, and an agent would have routed around it with `>`.\n//\n// ─── Why it INTERCEPTS stdout instead of every writer calling it ───────────────────────────────────────\n// There are ~160 `process.stdout.write` sites across this package, in classes shared by six other bins.\n// Threading a logger through all of them would be a far larger diff with far more ways to miss one — and\n// a MISSED one is the whole failure, because a single verbose writer that still reaches the console keeps\n// the output big enough to be piped. Interception inverts the default: everything a stage prints is\n// captured unless it says out loud that it must be seen NOW, and the \"say it out loud\" list is short\n// enough to read (`say()` — the build heartbeat, the build result, the review instructions, the PR link).\n//\n// The interception is installed and removed by `withCapture`, in a `finally`, so a throw cannot leave a\n// process with a patched stdout. Child processes that inherit fd 1 write straight past it, which is why\n// the build gate redirects its child to a file of its own rather than relying on this.\n//\n// Also deliberately NOT intercepted: stderr. Failures must stay on the terminal — `runMain` renders every\n// thrown CliExitError / RuleFailError there, and a refusal an agent cannot see is worse than a long one.\n\n/** Stage ②'s console log. Named for the command, because that is what a reader is looking for. */\nexport const REVIEW_CONSOLE_LOG = 'wp-review-upsert-pr.log';\n\n/** Stage ③'s console log. */\nexport const FINISH_CONSOLE_LOG = 'wp-finish-upsert-pr.log';\n\n/** The write function this class swaps out and restores — Node's own `process.stdout.write`. */\ntype StdoutWrite = typeof process.stdout.write;\n\n/** The optional completion callback Node's `write` accepts, in either of its two argument positions. */\ntype StdoutCallback = (err?: Error) => void;\n\n/**\n * Captures a stage's verbose console output to a file, keeps the handful of lines the caller must act on\n * immediately on the terminal, and hands back the one-line pointer at the file.\n *\n * Singleton, and stateful FOR THE DURATION OF ONE `withCapture` call: a bin runs exactly one stage.\n * Re-entering it is a programming error, not a supported mode, and it throws rather than silently\n * capturing into the inner file and restoring the outer one.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class StageOutputLog {\n constructor(private readonly files: GateLogFile) {}\n\n // The open log, or '' when nothing is being captured. `say` works either way — outside a capture it\n // is a plain write to the terminal, which is what every other bin wants.\n private logPath = '';\n private fd = -1;\n private original: StdoutWrite | null = null;\n\n /**\n * Run `body` with this process's stdout captured to `<logs>/<fileName>`, then restore stdout and\n * print the pointer at the file.\n *\n * The pointer is printed in a `finally`, so it is there on the FAILURE path too — which is the path\n * where a reader most needs it, and the one where an uncaptured stage would have scrolled the cause\n * off the top of the terminal.\n */\n async withCapture<T>(repoRoot: string, fileName: string, body: () => Promise<T>): Promise<T> {\n if (this.original !== null) throw new Error(`StageOutputLog is already capturing to ${this.logPath}`);\n this.logPath = this.files.logsPath(repoRoot, fileName);\n this.files.rotate(this.logPath);\n this.fd = fs.openSync(this.logPath, 'w');\n // The REFERENCE, not a bound copy: `release` puts this exact function back, so a caller that\n // installed its own stdout before us (a spec, a wrapping bin) gets ITS function back rather than\n // a wrapper around it, and repeated captures cannot stack bound layers.\n this.original = process.stdout.write;\n process.stdout.write = this.intercept.bind(this) as StdoutWrite;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: stdout MUST be restored and the fd\n // closed whatever `body` does; the throw is re-raised untouched.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await body();\n // webpieces-disable no-any-unknown -- JavaScript may reject with any value; normalize for the diagnostic log\n } catch (err: unknown) {\n const error = toError(err);\n // Match runMain's terminal rendering, including a rule refusal's actionable options.\n const message =\n error instanceof RuleFailError ? renderRuleFailForHuman(error) : error.message;\n this.appendToLog(message + '\\n');\n throw err; // the global handler still owns terminal rendering and the exit status\n } finally {\n this.release();\n }\n }\n\n /**\n * Print `text` to the TERMINAL as well as the log — for the few things a caller must act on before it\n * can do anything else: the build heartbeat (a silent command is a killed command), the build result,\n * the review instructions, the PR link, and anything naming a file to read.\n *\n * Outside a capture this is an ordinary write, so a class that calls it is not coupled to the stage.\n */\n say(text: string): void {\n this.appendToLog(text);\n // `.call`, because `original` is the raw reference rather than a bound copy — see withCapture.\n (this.original ?? process.stdout.write).call(process.stdout, text);\n }\n\n // The stdout replacement. Node calls this with (chunk), (chunk, encoding), (chunk, callback) or\n // (chunk, encoding, callback); a callback that is never invoked can stall a writer, so it is always\n // called. Returning true means \"not backpressured\", which is honest for a synchronous file write.\n private intercept(\n chunk: string | Uint8Array, encodingOrCallback?: BufferEncoding | StdoutCallback, callback?: StdoutCallback,\n ): boolean {\n this.appendToLog(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'));\n const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n if (done !== undefined) done();\n return true;\n }\n\n // Restore stdout, close the log, and print the pointer at it. Idempotent: a second call after the\n // `finally` has already run is a no-op rather than a double pointer.\n private release(): void {\n if (this.original === null) return;\n const restore = this.original;\n this.original = null;\n process.stdout.write = restore;\n fs.closeSync(this.fd);\n this.fd = -1;\n restore.call(process.stdout, `\\n${this.files.pointer(this.logPath)}`);\n this.logPath = '';\n }\n\n // Nothing is captured when no capture is open — `say` still reaches the terminal, which is the point.\n private appendToLog(text: string): void {\n if (this.fd === -1) return;\n fs.writeSync(this.fd, text);\n }\n}\n"]}
1
+ {"version":3,"file":"stage-output-log.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/stage-output-log.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,0DAAgF;AAChF,iEAA6D;AAC7D,yCAA2D;AAE3D,mDAA8C;AAE9C,0GAA0G;AAC1G,2GAA2G;AAC3G,0GAA0G;AAC1G,yGAAyG;AACzG,+CAA+C;AAC/C,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AACzG,yGAAyG;AACzG,uGAAuG;AACvG,uGAAuG;AACvG,sEAAsE;AACtE,EAAE;AACF,oGAAoG;AACpG,uGAAuG;AACvG,wGAAwG;AACxG,EAAE;AACF,0GAA0G;AAC1G,wGAAwG;AACxG,yGAAyG;AACzG,0GAA0G;AAC1G,oGAAoG;AACpG,qGAAqG;AACrG,0GAA0G;AAC1G,EAAE;AACF,wGAAwG;AACxG,wGAAwG;AACxG,uFAAuF;AACvF,EAAE;AACF,0GAA0G;AAC1G,yGAAyG;AAEzG,kGAAkG;AACrF,QAAA,kBAAkB,GAAG,yBAAyB,CAAC;AAE5D,6BAA6B;AAChB,QAAA,kBAAkB,GAAG,yBAAyB,CAAC;AAQ5D;;;;;;;GAOG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IACM;IAA7B,YAA6B,KAAkB;QAAlB,UAAK,GAAL,KAAK,CAAa;IAAG,CAAC;IAEnD,oGAAoG;IACpG,yEAAyE;IACjE,OAAO,GAAG,EAAE,CAAC;IACb,EAAE,GAAG,CAAC,CAAC,CAAC;IACR,QAAQ,GAAuB,IAAI,CAAC;IAE5C;;;;;;;OAOG;IACH,KAAK,CAAC,WAAW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CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACtB,CAAC;IAED,sGAAsG;IAC9F,WAAW,CAAC,IAAY;QAC5B,IAAI,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;YAAE,OAAO;QAC3B,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACJ,CAAA;AA7FY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAED,2BAAW;GADtC,cAAc,CA6F1B","sourcesContent":["import * as fs from 'fs';\nimport { RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GateLogFile } from './gate-log-file';\n\n// ─── Why ───────────────────────────────────────────────────────────────────────────────────────────────\n// `wp-build` already solved this for the BUILD: its output goes to a FILE and the console gets a heartbeat\n// plus a pointer. Stage ② and stage ③ had not been given the same treatment, so they printed everything —\n// merge validation, the active-hatch report, the checklist scan, the diff extraction, the dashboard, the\n// gh round trips — straight down the terminal.\n//\n// The consequence was measured, and it is not \"a long transcript\". An agent that expects a wall of output\n// bounds it by reflex: `pnpm wp-review-upsert-pr 2>&1 | tail -50`. A PIPE WITHHOLDS EVERY BYTE UNTIL THE\n// COMMAND EXITS, so the harness sees a command that has printed nothing for 600 seconds and kills it — a\n// full build's worth of work thrown away, and then usually re-run the same way. In this repo's primary\n// tree alone the call log holds 85 piped `wp-*` invocations, 42 of them on a command that runs a build\n// (`wp-review-upsert-pr` 22, `wp-finish-upsert-pr` 17, `wp-build` 3).\n//\n// Shrinking the output is therefore the FIRST half of the fix and the guard against the pipe is the\n// second, in that order. Blocking the pipe while the command still printed a thousand lines would only\n// have traded a watchdog kill for a flooded context, and an agent would have routed around it with `>`.\n//\n// ─── Why it INTERCEPTS stdout instead of every writer calling it ───────────────────────────────────────\n// There are ~160 `process.stdout.write` sites across this package, in classes shared by six other bins.\n// Threading a logger through all of them would be a far larger diff with far more ways to miss one — and\n// a MISSED one is the whole failure, because a single verbose writer that still reaches the console keeps\n// the output big enough to be piped. Interception inverts the default: everything a stage prints is\n// captured unless it says out loud that it must be seen NOW, and the \"say it out loud\" list is short\n// enough to read (`say()` — the build heartbeat, the build result, the review instructions, the PR link).\n//\n// The interception is installed and removed by `withCapture`, in a `finally`, so a throw cannot leave a\n// process with a patched stdout. Child processes that inherit fd 1 write straight past it, which is why\n// the build gate redirects its child to a file of its own rather than relying on this.\n//\n// Also deliberately NOT intercepted: stderr. Failures must stay on the terminal — `runMain` renders every\n// thrown CliExitError / RuleFailError there, and a refusal an agent cannot see is worse than a long one.\n\n/** Stage ②'s console log. Named for the command, because that is what a reader is looking for. */\nexport const REVIEW_CONSOLE_LOG = 'wp-review-upsert-pr.log';\n\n/** Stage ③'s console log. */\nexport const FINISH_CONSOLE_LOG = 'wp-finish-upsert-pr.log';\n\n/** The write function this class swaps out and restores — Node's own `process.stdout.write`. */\ntype StdoutWrite = typeof process.stdout.write;\n\n/** The optional completion callback Node's `write` accepts, in either of its two argument positions. */\ntype StdoutCallback = (err?: Error) => void;\n\n/**\n * Captures a stage's verbose console output to a file, keeps the handful of lines the caller must act on\n * immediately on the terminal, and hands back the one-line pointer at the file.\n *\n * Singleton, and stateful FOR THE DURATION OF ONE `withCapture` call: a bin runs exactly one stage.\n * Re-entering it is a programming error, not a supported mode, and it throws rather than silently\n * capturing into the inner file and restoring the outer one.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class StageOutputLog {\n constructor(private readonly files: GateLogFile) {}\n\n // The open log, or '' when nothing is being captured. `say` works either way — outside a capture it\n // is a plain write to the terminal, which is what every other bin wants.\n private logPath = '';\n private fd = -1;\n private original: StdoutWrite | null = null;\n\n /**\n * Run `body` with this process's stdout captured to `<logs>/<fileName>`, then restore stdout and\n * print the pointer at the file.\n *\n * The pointer is printed in a `finally`, so it is there on the FAILURE path too — which is the path\n * where a reader most needs it, and the one where an uncaptured stage would have scrolled the cause\n * off the top of the terminal.\n */\n async withCapture<T>(repoRoot: string, fileName: string, body: () => Promise<T>): Promise<T> {\n if (this.original !== null) throw new Error(`StageOutputLog is already capturing to ${this.logPath}`);\n this.logPath = this.files.logsPath(repoRoot, fileName);\n this.files.rotate(this.logPath);\n this.fd = fs.openSync(this.logPath, 'w');\n // The FIRST line the stage prints, before any work (issue #1393): the file now exists, and a\n // caller that backgrounds the stage — or whose harness captures its console into a file the caller\n // may not be allowed to read — knows where everything below is going. The same pointer closes\n // the stage in release().\n this.say(this.files.startLine(this.logPath));\n // The REFERENCE, not a bound copy: `release` puts this exact function back, so a caller that\n // installed its own stdout before us (a spec, a wrapping bin) gets ITS function back rather than\n // a wrapper around it, and repeated captures cannot stack bound layers.\n this.original = process.stdout.write;\n process.stdout.write = this.intercept.bind(this) as StdoutWrite;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: stdout MUST be restored and the fd\n // closed whatever `body` does; the throw is re-raised untouched.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await body();\n // webpieces-disable no-any-unknown -- JavaScript may reject with any value; normalize for the diagnostic log\n } catch (err: unknown) {\n const error = toError(err);\n // Match runMain's terminal rendering, including a rule refusal's actionable options.\n const message =\n error instanceof RuleFailError ? renderRuleFailForHuman(error) : error.message;\n this.appendToLog(message + '\\n');\n throw err; // the global handler still owns terminal rendering and the exit status\n } finally {\n this.release();\n }\n }\n\n /**\n * Print `text` to the TERMINAL as well as the log — for the few things a caller must act on before it\n * can do anything else: the build heartbeat (a silent command is a killed command), the build result,\n * the review instructions, the PR link, and anything naming a file to read.\n *\n * Outside a capture this is an ordinary write, so a class that calls it is not coupled to the stage.\n */\n say(text: string): void {\n this.appendToLog(text);\n // `.call`, because `original` is the raw reference rather than a bound copy — see withCapture.\n (this.original ?? process.stdout.write).call(process.stdout, text);\n }\n\n // The stdout replacement. Node calls this with (chunk), (chunk, encoding), (chunk, callback) or\n // (chunk, encoding, callback); a callback that is never invoked can stall a writer, so it is always\n // called. Returning true means \"not backpressured\", which is honest for a synchronous file write.\n private intercept(\n chunk: string | Uint8Array, encodingOrCallback?: BufferEncoding | StdoutCallback, callback?: StdoutCallback,\n ): boolean {\n this.appendToLog(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'));\n const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n if (done !== undefined) done();\n return true;\n }\n\n // Restore stdout, close the log, and print the pointer at it. Idempotent: a second call after the\n // `finally` has already run is a no-op rather than a double pointer.\n private release(): void {\n if (this.original === null) return;\n const restore = this.original;\n this.original = null;\n process.stdout.write = restore;\n fs.closeSync(this.fd);\n this.fd = -1;\n restore.call(process.stdout, `\\n${this.files.pointer(this.logPath)}`);\n this.logPath = '';\n }\n\n // Nothing is captured when no capture is open — `say` still reaches the terminal, which is the point.\n private appendToLog(text: string): void {\n if (this.fd === -1) return;\n fs.writeSync(this.fd, text);\n }\n}\n"]}