@webpieces/pr-gate 0.4.909 → 0.4.911
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/src/scripts/commands/build-command.d.ts +2 -2
- package/src/scripts/commands/build-command.js +2 -2
- package/src/scripts/commands/build-command.js.map +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.js +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
- package/src/scripts/workflow/build-gate-log.d.ts +3 -3
- package/src/scripts/workflow/build-gate-log.js +3 -3
- package/src/scripts/workflow/build-gate-log.js.map +1 -1
- package/src/scripts/workflow/cleanTmp.d.ts +2 -2
- package/src/scripts/workflow/cleanTmp.js +5 -5
- package/src/scripts/workflow/cleanTmp.js.map +1 -1
- package/src/scripts/workflow/diff-materializer.d.ts +1 -1
- package/src/scripts/workflow/diff-materializer.js +1 -1
- package/src/scripts/workflow/diff-materializer.js.map +1 -1
- package/src/scripts/workflow/gate-log-file.d.ts +1 -1
- package/src/scripts/workflow/gate-log-file.js +4 -4
- package/src/scripts/workflow/gate-log-file.js.map +1 -1
- package/src/scripts/workflow/git-exec.d.ts +1 -1
- package/src/scripts/workflow/git-exec.js +2 -2
- package/src/scripts/workflow/git-exec.js.map +1 -1
- package/src/scripts/workflow/landed-tree-resolver.d.ts +1 -1
- package/src/scripts/workflow/landed-tree-resolver.js +1 -1
- package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
- package/src/scripts/workflow/merge-end.js +1 -1
- package/src/scripts/workflow/merge-end.js.map +1 -1
- package/src/scripts/workflow/merge-info-index.d.ts +2 -2
- package/src/scripts/workflow/merge-info-index.js +2 -2
- package/src/scripts/workflow/merge-info-index.js.map +1 -1
- package/src/scripts/workflow/merge-start.js +1 -1
- package/src/scripts/workflow/merge-start.js.map +1 -1
- package/src/scripts/workflow/merge-state.d.ts +6 -6
- package/src/scripts/workflow/merge-state.js +7 -7
- package/src/scripts/workflow/merge-state.js.map +1 -1
- package/src/scripts/workflow/provenance-enforcer.d.ts +1 -1
- package/src/scripts/workflow/provenance-enforcer.js +1 -1
- package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
- package/src/scripts/workflow/repo-config-testkit.js +9 -3
- package/src/scripts/workflow/repo-config-testkit.js.map +1 -1
- package/src/scripts/workflow/review-round-text.js +1 -1
- package/src/scripts/workflow/review-round-text.js.map +1 -1
- package/src/scripts/workflow/reviewer-identity.d.ts +1 -1
- package/src/scripts/workflow/reviewer-identity.js +1 -1
- package/src/scripts/workflow/reviewer-identity.js.map +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AgedTreeSweeper, RepoRootFinder, TmpScratchSweeper } from '@webpieces/rules-config';
|
|
2
2
|
import { DotWebpieces } from '@webpieces/tooling-common';
|
|
3
3
|
/**
|
|
4
|
-
* 30-day garbage collection of this tree's `.webpieces` scratch state.
|
|
4
|
+
* 30-day garbage collection of this tree's `.webpieces-logs` scratch state.
|
|
5
5
|
*
|
|
6
6
|
* Runs at the end of every merge/PR flow (see merge-end.ts). Any file older than the cutoff is deleted
|
|
7
7
|
* and any directory left empty afterwards is pruned; the root itself is never removed.
|
|
@@ -26,7 +26,7 @@ import { DotWebpieces } from '@webpieces/tooling-common';
|
|
|
26
26
|
* `wp-*` directories in `$TMPDIR`.
|
|
27
27
|
*
|
|
28
28
|
* The fix is ownership at the call site — `SpecTempDirs` for fixtures, `RepoScratchDirs` (which lands
|
|
29
|
-
* under the `.webpieces` scope swept below) for the two runtime paths. `TmpScratchSweeper` is the
|
|
29
|
+
* under the `.webpieces-logs` scope swept below) for the two runtime paths. `TmpScratchSweeper` is the
|
|
30
30
|
* backstop for the residue an exit handler cannot cover: a SIGKILLed worker, a lost power rail.
|
|
31
31
|
*/
|
|
32
32
|
export declare class CleanTmp {
|
|
@@ -9,7 +9,7 @@ const tooling_common_1 = require("@webpieces/tooling-common");
|
|
|
9
9
|
const inversify_1 = require("inversify");
|
|
10
10
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
11
11
|
/**
|
|
12
|
-
* 30-day garbage collection of this tree's `.webpieces` scratch state.
|
|
12
|
+
* 30-day garbage collection of this tree's `.webpieces-logs` scratch state.
|
|
13
13
|
*
|
|
14
14
|
* Runs at the end of every merge/PR flow (see merge-end.ts). Any file older than the cutoff is deleted
|
|
15
15
|
* and any directory left empty afterwards is pruned; the root itself is never removed.
|
|
@@ -34,7 +34,7 @@ const SEP = '━━━━━━━━━━━━━━━━━━━━━━
|
|
|
34
34
|
* `wp-*` directories in `$TMPDIR`.
|
|
35
35
|
*
|
|
36
36
|
* The fix is ownership at the call site — `SpecTempDirs` for fixtures, `RepoScratchDirs` (which lands
|
|
37
|
-
* under the `.webpieces` scope swept below) for the two runtime paths. `TmpScratchSweeper` is the
|
|
37
|
+
* under the `.webpieces-logs` scope swept below) for the two runtime paths. `TmpScratchSweeper` is the
|
|
38
38
|
* backstop for the residue an exit handler cannot cover: a SIGKILLed worker, a lost power rail.
|
|
39
39
|
*/
|
|
40
40
|
let CleanTmp = class CleanTmp {
|
|
@@ -53,12 +53,12 @@ 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/, logs/ in <primary>/.webpieces-logs/worktrees/<name>
|
|
57
|
+
// aiWritable() — pr-review/ in <worktree>/.webpieces-logs, where the agent can actually write it
|
|
58
58
|
const bases = this.sweepBases(repoRoot);
|
|
59
59
|
if (bases.length === 0)
|
|
60
60
|
return;
|
|
61
|
-
process.stdout.write('\n' + SEP + '🧹 Garbage-Collecting .webpieces\n' + SEP + '\n');
|
|
61
|
+
process.stdout.write('\n' + SEP + '🧹 Garbage-Collecting .webpieces-logs\n' + SEP + '\n');
|
|
62
62
|
for (const base of bases)
|
|
63
63
|
process.stdout.write(`Location: ${base}\n`);
|
|
64
64
|
process.stdout.write(`Retention: ${rules_config_1.RETENTION_DAYS} days (older files reaped; empty dirs pruned)\n\n`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanTmp.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/cleanTmp.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqJ;AACrJ,8DAAuE;AACvE,yCAA2D;AAE3D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEI,IAAM,QAAQ,GAAd,MAAM,QAAQ;IAEI;IACA;IACA;IACA;IAJrB,YACqB,cAA8B,EAC9B,OAAwB,EACxB,UAA6B,EAC7B,SAAuB,6BAAY;QAHnC,mBAAc,GAAd,cAAc,CAAgB;QAC9B,YAAO,GAAP,OAAO,CAAiB;QACxB,eAAU,GAAV,UAAU,CAAmB;QAC7B,WAAM,GAAN,MAAM,CAA6B;IACrD,CAAC;IAEJ,KAAK,CAAC,QAAQ;QACV,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QACpE,4FAA4F;QAC5F,gGAAgG;QAChG,mFAAmF;QACnF,
|
|
1
|
+
{"version":3,"file":"cleanTmp.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/cleanTmp.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAqJ;AACrJ,8DAAuE;AACvE,yCAA2D;AAE3D,MAA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O,UAAU,CAAC,MAAM,CAAC,CAAC,IAAY,EAAW,EAAE;YAC/C,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,KAAK,CAAC;YACzD,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;IACP,CAAC;IAED,gGAAgG;IACxF,QAAQ,CAAC,IAAY;QACzB,OAAO,CAAC,OAAe,EAAE,KAAc,EAAQ,EAAE;YAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC;YAC1C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACjG,CAAC,CAAC;IACN,CAAC;CACJ,CAAA;AAnEY,4BAAQ;mBAAR,QAAQ;IADpB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QACrB,8BAAe;QACZ,gCAAiB;QACrB,6BAAY;GALhC,QAAQ,CAmEpB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { AgedTreeSweeper, RETENTION_DAYS, RepoRootFinder, SweepCount, TMP_SCRATCH_RETENTION_DAYS, TmpScratchSweeper } from '@webpieces/rules-config';\nimport { DotWebpieces, dotWebpieces } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * 30-day garbage collection of this tree's `.webpieces-logs` 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-logs` 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-logs/worktrees/<name>\n // aiWritable() — pr-review/ in <worktree>/.webpieces-logs, 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-logs\\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"]}
|
|
@@ -52,7 +52,7 @@ export declare class DiffManifest {
|
|
|
52
52
|
export declare class DiffMaterializer {
|
|
53
53
|
private readonly reviewJsonService;
|
|
54
54
|
constructor(reviewJsonService: ReviewJsonService);
|
|
55
|
-
/** The dir this writes into: `.webpieces/pr-review/<feature>/diff`. */
|
|
55
|
+
/** The dir this writes into: `.webpieces-logs/pr-review/<feature>/diff`. */
|
|
56
56
|
diffDirFor(repoRoot: string, featureName: string): string;
|
|
57
57
|
/**
|
|
58
58
|
* Write `diff/ALL.diff`, `diff/files/*.diff` and `diff/manifest.json`. Returns the manifest.
|
|
@@ -97,7 +97,7 @@ let DiffMaterializer = class DiffMaterializer {
|
|
|
97
97
|
constructor(reviewJsonService) {
|
|
98
98
|
this.reviewJsonService = reviewJsonService;
|
|
99
99
|
}
|
|
100
|
-
/** The dir this writes into: `.webpieces/pr-review/<feature>/diff`. */
|
|
100
|
+
/** The dir this writes into: `.webpieces-logs/pr-review/<feature>/diff`. */
|
|
101
101
|
diffDirFor(repoRoot, featureName) {
|
|
102
102
|
return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), 'diff');
|
|
103
103
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diff-materializer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/diff-materializer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4E;AAC5E,iEAA6D;AAC7D,yCAA2D;AAG3D,2GAA2G;AAC9F,QAAA,mBAAmB,GAAG,G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xD,gBAAgB,CAkN5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { isPathExcluded, ReviewJsonService } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { DiffBasis } from './diff-basis';\n\n// Per-file cap. Over it, the file's diff is truncated WITH a footer naming the command that gets the rest.\nexport const FILE_DIFF_MAX_BYTES = 256 * 1024;\n// Cap for the combined ALL.diff. Over it, whole files are omitted — again, named, never silently.\nexport const ALL_DIFF_MAX_BYTES = 2 * 1024 * 1024;\n\n/**\n * One materialized file's diff. Data-only (per CLAUDE.md).\n *\n * Both paths are recorded TWICE, relative and absolute, deliberately. Relative is the stable identity that\n * survives the repo being cloned somewhere else; absolute is the only form a reviewer subagent can actually\n * open, because its working directory is not guaranteed to be the repo root. Recording only the relative\n * form is what turned \"read this file\" back into a search — the exact cost this whole feature removes.\n */\nexport class DiffManifestEntry {\n file: string; // repo-relative source path\n fileAbs: string; // ABSOLUTE working-tree path; '' for a deleted file, which has no after-state\n diffFile: string; // repo-relative path of the .diff under diff/files/\n diffAbs: string; // ABSOLUTE path of the same .diff\n status: string; // 'M' | 'A' | 'D' | 'U' (untracked) | 'X' (excluded by config)\n bytes: number;\n truncated: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(repoRoot: string, file: string, diffFile: string, status: string, bytes: number, truncated = false) {\n this.file = file;\n // Not `gitTrackedSourceFileAfterChanges`: `status` already says what happened, and a compound name\n // would lie for 'U' (untracked) and for 'D' (no after-state). The path field answers only WHERE.\n this.fileAbs = status === 'D' ? '' : path.join(repoRoot, file);\n this.diffFile = diffFile;\n this.diffAbs = path.resolve(repoRoot, diffFile);\n this.status = status;\n this.bytes = bytes;\n this.truncated = truncated;\n }\n}\n\n/** The authoritative map from a mangled `.diff` name back to its real path, plus what was dropped. */\nexport class DiffManifest {\n // Points A and B. Also exposed as hashForkPoint/hashFeatureHead below, which is the vocabulary the\n // 3-point merge already uses — one grep should find the same sha on both halves of the system.\n base: string;\n head: string;\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string; // point C: main as this clone last saw it. '' when unresolvable.\n dirty: boolean;\n diffCommand: string;\n entries: DiffManifestEntry[];\n excluded: string[]; // matched pr-gate.reviewDiffExclude — present, stubbed, NOT materialized\n omittedFromAllDiff: string[]; // too big for ALL.diff; their per-file .diff still exists\n // Size of the combined view, measured once HERE so the instructions renderer and any future consumer\n // read one number instead of each running its own `wc -l`. A reviewer needs the LINE count specifically:\n // the Read tool truncates at ~2000 lines, silently, which is how a fraction of a change gets reviewed.\n allDiffLines: number;\n allDiffBytes: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n base: string, head: string, dirty: boolean, diffCommand: string,\n entries: DiffManifestEntry[] = [], excluded: string[] = [], omittedFromAllDiff: string[] = [],\n hashMainHead = '',\n ) {\n this.base = base;\n this.head = head;\n // Derived, never passed separately, so the two names for one sha cannot drift into disagreement.\n this.hashForkPoint = base;\n this.hashFeatureHead = head;\n this.hashMainHead = hashMainHead;\n this.dirty = dirty;\n this.diffCommand = diffCommand;\n this.entries = entries;\n this.excluded = excluded;\n this.omittedFromAllDiff = omittedFromAllDiff;\n this.allDiffLines = 0;\n this.allDiffBytes = 0;\n }\n}\n\n/**\n * Extracts this branch's diff ONCE, to disk, so a reviewer subagent reads it instead of reconstructing it.\n *\n * The motivating measurement: a reviewer on consumer-monorepo2 spent 14 of its 26 tool calls on context\n * archaeology, and the very first `git diff` it was told to run returned nothing (see {@link DiffBasis}).\n * Handing it a file it can simply open removes both failure modes — the empty range and the shell-out.\n *\n * Cost discipline: **two git invocations total, regardless of file count.** One `git diff` for everything,\n * split on `diff --git` headers, plus one `ls-files --others` for untracked files. A per-file `git diff`\n * loop would be N spawns for the same bytes.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DiffMaterializer {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n /** The dir this writes into: `.webpieces/pr-review/<feature>/diff`. */\n diffDirFor(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), 'diff');\n }\n\n /**\n * Write `diff/ALL.diff`, `diff/files/*.diff` and `diff/manifest.json`. Returns the manifest.\n *\n * `changedFiles` is the set the CHECKLIST MATCHING used — passed in rather than recomputed, so the diff\n * a reviewer reads covers exactly the files its checklist matched on. Recomputing here is how the two\n * would drift apart again.\n */\n materialize(repoRoot: string, featureName: string, basis: DiffBasis, changedFiles: readonly string[], excludeGlobs: readonly string[]): DiffManifest {\n const dir = this.diffDirFor(repoRoot, featureName);\n const filesDir = path.join(dir, 'files');\n fs.rmSync(dir, { recursive: true, force: true }); // a stale diff read as current is worse than none\n fs.mkdirSync(filesDir, { recursive: true });\n const manifest = new DiffManifest(\n basis.base, basis.headSha, basis.dirty, basis.diffCommand, [], [], [], basis.hashMainHead);\n if (basis.unresolved) return this.writeManifest(dir, manifest);\n const byFile = this.diffByFile(repoRoot, basis);\n const used = new Set<string>();\n for (const file of [...changedFiles].sort()) {\n this.writeOne(repoRoot, filesDir, file, byFile, used, excludeGlobs, manifest);\n }\n this.writeAllDiff(dir, filesDir, manifest);\n return this.writeManifest(dir, manifest);\n }\n\n /**\n * ONE `git diff` for the whole branch, split into per-file patches keyed by repo-relative path.\n * Untracked files never appear in `git diff`, so they are synthesized as all-added patches — the same\n * treatment DiffScope.getFileDiff already gives them, kept consistent so a reviewer sees one format.\n */\n diffByFile(repoRoot: string, basis: DiffBasis): Map<string, string> {\n const args = basis.dirty ? ['diff', basis.base] : ['diff', basis.base, basis.headSha];\n const out = this.gitOut(repoRoot, args);\n const byFile = new Map<string, string>();\n // Split BEFORE each `diff --git` header while keeping the header on its chunk.\n for (const chunk of out.split(/\\n(?=diff --git )/)) {\n if (!chunk.startsWith('diff --git ')) continue;\n const file = this.pathFromHeader(chunk);\n if (file !== '') byFile.set(file, chunk.endsWith('\\n') ? chunk : `${chunk}\\n`);\n }\n for (const file of this.untrackedFiles(repoRoot, basis)) {\n if (!byFile.has(file)) byFile.set(file, this.syntheticAddedDiff(repoRoot, file));\n }\n return byFile;\n }\n\n /**\n * The b-side path out of a `diff --git a/x b/x` header. The b-side is the right one: for a rename it is\n * the name that exists on disk, which is the file a reviewer can actually open.\n */\n private pathFromHeader(chunk: string): string {\n const header = chunk.slice(0, chunk.indexOf('\\n') === -1 ? chunk.length : chunk.indexOf('\\n'));\n const match = header.match(/^diff --git a\\/(.+) b\\/(.+)$/);\n return match ? match[2] : '';\n }\n\n private untrackedFiles(repoRoot: string, basis: DiffBasis): string[] {\n if (!basis.dirty) return [];\n const out = this.gitOut(repoRoot, ['ls-files', '--others', '--exclude-standard']);\n return out === '' ? [] : out.split('\\n').filter((f: string): boolean => f.trim() !== '');\n }\n\n private syntheticAddedDiff(repoRoot: string, file: string): string {\n const abs = path.join(repoRoot, file);\n if (!fs.existsSync(abs)) return '';\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable/binary untracked file yields a note, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const body = fs.readFileSync(abs, 'utf8').split('\\n').map((l: string): string => `+${l}`).join('\\n');\n return `diff --git a/${file} b/${file}\\nnew file (untracked)\\n--- /dev/null\\n+++ b/${file}\\n${body}\\n`;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // a binary/unreadable untracked file gets a NOTE, never a crash\n return `diff --git a/${file} b/${file}\\nnew file (untracked, unreadable as text)\\n`;\n }\n }\n\n /** Write ONE file's diff, recording it (or its exclusion) in the manifest. Never drops a file silently. */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeOne(\n repoRoot: string, filesDir: string, file: string, byFile: Map<string, string>,\n used: Set<string>, excludeGlobs: readonly string[], manifest: DiffManifest,\n ): void {\n const name = this.safeName(file, used);\n const abs = path.join(filesDir, name);\n const rel = path.relative(repoRoot, abs);\n // Excluded files stay in the manifest and keep a stub. Dropping them entirely would read as \"this\n // file did not change\"; they are noise to READ, not facts to hide — and they still match checklists.\n if (excludeGlobs.length > 0 && isPathExcluded(file, [...excludeGlobs])) {\n const stub = `[excluded from materialization by pr-gate.reviewDiffExclude]\\nIf you need it: git diff ${manifest.base} -- ${file}\\n`;\n fs.writeFileSync(abs, stub);\n manifest.excluded.push(file);\n manifest.entries.push(new DiffManifestEntry(repoRoot, file, rel, 'X', stub.length));\n return;\n }\n const raw = byFile.get(file) ?? '';\n const status = this.statusOf(file, raw, repoRoot);\n const body = this.capped(raw, file, manifest.base);\n fs.writeFileSync(abs, body);\n manifest.entries.push(new DiffManifestEntry(repoRoot, file, rel, status, body.length, body !== raw));\n }\n\n private statusOf(file: string, raw: string, repoRoot: string): string {\n if (raw.includes('\\nnew file (untracked)')) return 'U';\n if (raw.includes('\\nnew file mode ')) return 'A';\n if (raw.includes('\\ndeleted file mode ')) return 'D';\n return fs.existsSync(path.join(repoRoot, file)) ? 'M' : 'D';\n }\n\n /**\n * Truncate to the cap WITH a footer. Never silently: a truncated diff that looks whole is how a reviewer\n * reports \"reviewed\" on a tenth of a change — the same trap `formatFileList` states its dropped count for.\n */\n private capped(raw: string, file: string, base: string): string {\n if (raw.length <= FILE_DIFF_MAX_BYTES) return raw;\n return `${raw.slice(0, FILE_DIFF_MAX_BYTES)}\\n` +\n `\\n… TRUNCATED at ${FILE_DIFF_MAX_BYTES} bytes (full diff is ${raw.length} bytes).\\n` +\n ` Read the rest with: git diff ${base} -- ${file}\\n`;\n }\n\n /**\n * `ALL.diff` — the single Read that answers \"what changed on this branch?\". Files are appended smallest\n * first so a cap drops the fewest of them, and anything dropped is named in a HEADER as well as in the\n * manifest.\n *\n * The header used to be a footer, and that was a live correctness bug. `ALL_DIFF_MAX_BYTES` is 2 MB —\n * roughly 30–50k lines — while the Read tool truncates at ~2000. So on the exact PR where files were\n * dropped, a reviewer Reads the first ~5% and the notice telling it files are missing sits in the 95% it\n * never reaches: the in-band signal went invisible precisely when it mattered. A reviewer reads a diff\n * from the start, so the top is the only position that survives a truncated read.\n */\n private writeAllDiff(dir: string, filesDir: string, manifest: DiffManifest): void {\n const ordered = [...manifest.entries].sort((a: DiffManifestEntry, b: DiffManifestEntry): number => a.bytes - b.bytes);\n const parts: string[] = [];\n let total = 0;\n for (const entry of ordered) {\n const body = fs.readFileSync(path.join(filesDir, path.basename(entry.diffFile)), 'utf8');\n if (total + body.length > ALL_DIFF_MAX_BYTES) {\n manifest.omittedFromAllDiff.push(entry.file);\n continue;\n }\n parts.push(body);\n total += body.length;\n }\n const out = this.allDiffHeader(manifest) + parts.join('\\n');\n manifest.allDiffBytes = out.length;\n manifest.allDiffLines = out === '' ? 0 : out.split('\\n').length;\n fs.writeFileSync(path.join(dir, 'ALL.diff'), out);\n }\n\n /**\n * The \"this combined view is NOT the whole change\" notice, at the TOP (see {@link writeAllDiff}). Emitted\n * only when something really is missing — a header on every diff trains a reader to skip the header.\n */\n private allDiffHeader(manifest: DiffManifest): string {\n const truncated = manifest.entries.filter((e: DiffManifestEntry): boolean => e.truncated);\n if (manifest.omittedFromAllDiff.length === 0 && truncated.length === 0) return '';\n const lines = ['=== ⚠️ THIS COMBINED VIEW IS INCOMPLETE — read this notice before the diff below ==='];\n if (manifest.omittedFromAllDiff.length > 0) {\n lines.push(`${manifest.omittedFromAllDiff.length} file(s) are OMITTED here (this view hit the ` +\n `${ALL_DIFF_MAX_BYTES}-byte cap). Each still has its OWN complete diff`, 'under files/ — open those, and see manifest.json:');\n for (const f of manifest.omittedFromAllDiff) lines.push(` ${f}`);\n }\n if (truncated.length > 0) {\n lines.push(`${truncated.length} file(s) below are TRUNCATED at ${FILE_DIFF_MAX_BYTES} bytes; each says so inline where it cuts off:`);\n for (const e of truncated) lines.push(` ${e.file}`);\n }\n lines.push('=== end of notice ===', '');\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * `a/b/c.ts` → `a__b__c.ts.diff`, reusing the SAME `/`→`__` convention MergeState.perFileContextDir\n * already uses for 3-point merge context. One mangling scheme in the repo, not two. A real `__` in a\n * path can collide, so collisions get a numeric suffix and manifest.json stays authoritative.\n */\n private safeName(file: string, used: Set<string>): string {\n const flat = `${file.replace(/\\//g, '__')}.diff`;\n if (!used.has(flat)) {\n used.add(flat);\n return flat;\n }\n for (let n = 2; ; n++) {\n const candidate = `${file.replace(/\\//g, '__')}-${n}.diff`;\n if (!used.has(candidate)) {\n used.add(candidate);\n return candidate;\n }\n }\n }\n\n private writeManifest(dir: string, manifest: DiffManifest): DiffManifest {\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\\n');\n return manifest;\n }\n\n private gitOut(repoRoot: string, args: string[]): string {\n // maxBuffer: a monorepo diff routinely exceeds node's 1MB default, and the failure mode is a\n // truncated capture that looks like a complete one.\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });\n return result.status === 0 ? (result.stdout ?? '') : '';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"diff-materializer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/diff-materializer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4E;AAC5E,iEAA6D;AAC7D,yCAA2D;AAG3D,2GAA2G;AAC9F,QAAA,mBAAmB,GAAG,GAAG,GAAG,IAAI,CAAC;AAC9C,kGAAkG;AACrF,QAAA,kBAAkB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAElD;;;;;;;GAOG;AACH,MAAa,iBAAiB;IAC1B,IAAI,CAAS,CAAO,4BAA4B;IAChD,OAAO,CAAS,CAAI,8EAA8E;IAClG,QAAQ,CAAS,CAAG,oDAAoD;IACxE,OAAO,CAAS,CAAI,kCAAkC;IACtD,MAAM,CAAS,CAAK,+DAA+D;I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,CAAC,SAAS,CAAC,CAAC;gBACpB,OAAO,SAAS,CAAC;YACrB,CAAC;QACL,CAAC;IACL,CAAC;IAEO,aAAa,CAAC,GAAW,EAAE,QAAsB;QACrD,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACvC,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,eAAe,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;QAC5F,OAAO,QAAQ,CAAC;IACpB,CAAC;IAEO,MAAM,CAAC,QAAgB,EAAE,IAAc;QAC3C,6FAA6F;QAC7F,oDAAoD;QACpD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC,CAAC;QACzG,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5D,CAAC;CACJ,CAAA;AAlNY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEW,gCAAiB;GADxD,gBAAgB,CAkN5B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { isPathExcluded, ReviewJsonService } from '@webpieces/rules-config';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { DiffBasis } from './diff-basis';\n\n// Per-file cap. Over it, the file's diff is truncated WITH a footer naming the command that gets the rest.\nexport const FILE_DIFF_MAX_BYTES = 256 * 1024;\n// Cap for the combined ALL.diff. Over it, whole files are omitted — again, named, never silently.\nexport const ALL_DIFF_MAX_BYTES = 2 * 1024 * 1024;\n\n/**\n * One materialized file's diff. Data-only (per CLAUDE.md).\n *\n * Both paths are recorded TWICE, relative and absolute, deliberately. Relative is the stable identity that\n * survives the repo being cloned somewhere else; absolute is the only form a reviewer subagent can actually\n * open, because its working directory is not guaranteed to be the repo root. Recording only the relative\n * form is what turned \"read this file\" back into a search — the exact cost this whole feature removes.\n */\nexport class DiffManifestEntry {\n file: string; // repo-relative source path\n fileAbs: string; // ABSOLUTE working-tree path; '' for a deleted file, which has no after-state\n diffFile: string; // repo-relative path of the .diff under diff/files/\n diffAbs: string; // ABSOLUTE path of the same .diff\n status: string; // 'M' | 'A' | 'D' | 'U' (untracked) | 'X' (excluded by config)\n bytes: number;\n truncated: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(repoRoot: string, file: string, diffFile: string, status: string, bytes: number, truncated = false) {\n this.file = file;\n // Not `gitTrackedSourceFileAfterChanges`: `status` already says what happened, and a compound name\n // would lie for 'U' (untracked) and for 'D' (no after-state). The path field answers only WHERE.\n this.fileAbs = status === 'D' ? '' : path.join(repoRoot, file);\n this.diffFile = diffFile;\n this.diffAbs = path.resolve(repoRoot, diffFile);\n this.status = status;\n this.bytes = bytes;\n this.truncated = truncated;\n }\n}\n\n/** The authoritative map from a mangled `.diff` name back to its real path, plus what was dropped. */\nexport class DiffManifest {\n // Points A and B. Also exposed as hashForkPoint/hashFeatureHead below, which is the vocabulary the\n // 3-point merge already uses — one grep should find the same sha on both halves of the system.\n base: string;\n head: string;\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string; // point C: main as this clone last saw it. '' when unresolvable.\n dirty: boolean;\n diffCommand: string;\n entries: DiffManifestEntry[];\n excluded: string[]; // matched pr-gate.reviewDiffExclude — present, stubbed, NOT materialized\n omittedFromAllDiff: string[]; // too big for ALL.diff; their per-file .diff still exists\n // Size of the combined view, measured once HERE so the instructions renderer and any future consumer\n // read one number instead of each running its own `wc -l`. A reviewer needs the LINE count specifically:\n // the Read tool truncates at ~2000 lines, silently, which is how a fraction of a change gets reviewed.\n allDiffLines: number;\n allDiffBytes: number;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n base: string, head: string, dirty: boolean, diffCommand: string,\n entries: DiffManifestEntry[] = [], excluded: string[] = [], omittedFromAllDiff: string[] = [],\n hashMainHead = '',\n ) {\n this.base = base;\n this.head = head;\n // Derived, never passed separately, so the two names for one sha cannot drift into disagreement.\n this.hashForkPoint = base;\n this.hashFeatureHead = head;\n this.hashMainHead = hashMainHead;\n this.dirty = dirty;\n this.diffCommand = diffCommand;\n this.entries = entries;\n this.excluded = excluded;\n this.omittedFromAllDiff = omittedFromAllDiff;\n this.allDiffLines = 0;\n this.allDiffBytes = 0;\n }\n}\n\n/**\n * Extracts this branch's diff ONCE, to disk, so a reviewer subagent reads it instead of reconstructing it.\n *\n * The motivating measurement: a reviewer on consumer-monorepo2 spent 14 of its 26 tool calls on context\n * archaeology, and the very first `git diff` it was told to run returned nothing (see {@link DiffBasis}).\n * Handing it a file it can simply open removes both failure modes — the empty range and the shell-out.\n *\n * Cost discipline: **two git invocations total, regardless of file count.** One `git diff` for everything,\n * split on `diff --git` headers, plus one `ls-files --others` for untracked files. A per-file `git diff`\n * loop would be N spawns for the same bytes.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is injected by type and drawn in the DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DiffMaterializer {\n constructor(private readonly reviewJsonService: ReviewJsonService) {}\n\n /** The dir this writes into: `.webpieces-logs/pr-review/<feature>/diff`. */\n diffDirFor(repoRoot: string, featureName: string): string {\n return path.join(this.reviewJsonService.prDirFor(repoRoot, featureName), 'diff');\n }\n\n /**\n * Write `diff/ALL.diff`, `diff/files/*.diff` and `diff/manifest.json`. Returns the manifest.\n *\n * `changedFiles` is the set the CHECKLIST MATCHING used — passed in rather than recomputed, so the diff\n * a reviewer reads covers exactly the files its checklist matched on. Recomputing here is how the two\n * would drift apart again.\n */\n materialize(repoRoot: string, featureName: string, basis: DiffBasis, changedFiles: readonly string[], excludeGlobs: readonly string[]): DiffManifest {\n const dir = this.diffDirFor(repoRoot, featureName);\n const filesDir = path.join(dir, 'files');\n fs.rmSync(dir, { recursive: true, force: true }); // a stale diff read as current is worse than none\n fs.mkdirSync(filesDir, { recursive: true });\n const manifest = new DiffManifest(\n basis.base, basis.headSha, basis.dirty, basis.diffCommand, [], [], [], basis.hashMainHead);\n if (basis.unresolved) return this.writeManifest(dir, manifest);\n const byFile = this.diffByFile(repoRoot, basis);\n const used = new Set<string>();\n for (const file of [...changedFiles].sort()) {\n this.writeOne(repoRoot, filesDir, file, byFile, used, excludeGlobs, manifest);\n }\n this.writeAllDiff(dir, filesDir, manifest);\n return this.writeManifest(dir, manifest);\n }\n\n /**\n * ONE `git diff` for the whole branch, split into per-file patches keyed by repo-relative path.\n * Untracked files never appear in `git diff`, so they are synthesized as all-added patches — the same\n * treatment DiffScope.getFileDiff already gives them, kept consistent so a reviewer sees one format.\n */\n diffByFile(repoRoot: string, basis: DiffBasis): Map<string, string> {\n const args = basis.dirty ? ['diff', basis.base] : ['diff', basis.base, basis.headSha];\n const out = this.gitOut(repoRoot, args);\n const byFile = new Map<string, string>();\n // Split BEFORE each `diff --git` header while keeping the header on its chunk.\n for (const chunk of out.split(/\\n(?=diff --git )/)) {\n if (!chunk.startsWith('diff --git ')) continue;\n const file = this.pathFromHeader(chunk);\n if (file !== '') byFile.set(file, chunk.endsWith('\\n') ? chunk : `${chunk}\\n`);\n }\n for (const file of this.untrackedFiles(repoRoot, basis)) {\n if (!byFile.has(file)) byFile.set(file, this.syntheticAddedDiff(repoRoot, file));\n }\n return byFile;\n }\n\n /**\n * The b-side path out of a `diff --git a/x b/x` header. The b-side is the right one: for a rename it is\n * the name that exists on disk, which is the file a reviewer can actually open.\n */\n private pathFromHeader(chunk: string): string {\n const header = chunk.slice(0, chunk.indexOf('\\n') === -1 ? chunk.length : chunk.indexOf('\\n'));\n const match = header.match(/^diff --git a\\/(.+) b\\/(.+)$/);\n return match ? match[2] : '';\n }\n\n private untrackedFiles(repoRoot: string, basis: DiffBasis): string[] {\n if (!basis.dirty) return [];\n const out = this.gitOut(repoRoot, ['ls-files', '--others', '--exclude-standard']);\n return out === '' ? [] : out.split('\\n').filter((f: string): boolean => f.trim() !== '');\n }\n\n private syntheticAddedDiff(repoRoot: string, file: string): string {\n const abs = path.join(repoRoot, file);\n if (!fs.existsSync(abs)) return '';\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable/binary untracked file yields a note, never a crash\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const body = fs.readFileSync(abs, 'utf8').split('\\n').map((l: string): string => `+${l}`).join('\\n');\n return `diff --git a/${file} b/${file}\\nnew file (untracked)\\n--- /dev/null\\n+++ b/${file}\\n${body}\\n`;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // a binary/unreadable untracked file gets a NOTE, never a crash\n return `diff --git a/${file} b/${file}\\nnew file (untracked, unreadable as text)\\n`;\n }\n }\n\n /** Write ONE file's diff, recording it (or its exclusion) in the manifest. Never drops a file silently. */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeOne(\n repoRoot: string, filesDir: string, file: string, byFile: Map<string, string>,\n used: Set<string>, excludeGlobs: readonly string[], manifest: DiffManifest,\n ): void {\n const name = this.safeName(file, used);\n const abs = path.join(filesDir, name);\n const rel = path.relative(repoRoot, abs);\n // Excluded files stay in the manifest and keep a stub. Dropping them entirely would read as \"this\n // file did not change\"; they are noise to READ, not facts to hide — and they still match checklists.\n if (excludeGlobs.length > 0 && isPathExcluded(file, [...excludeGlobs])) {\n const stub = `[excluded from materialization by pr-gate.reviewDiffExclude]\\nIf you need it: git diff ${manifest.base} -- ${file}\\n`;\n fs.writeFileSync(abs, stub);\n manifest.excluded.push(file);\n manifest.entries.push(new DiffManifestEntry(repoRoot, file, rel, 'X', stub.length));\n return;\n }\n const raw = byFile.get(file) ?? '';\n const status = this.statusOf(file, raw, repoRoot);\n const body = this.capped(raw, file, manifest.base);\n fs.writeFileSync(abs, body);\n manifest.entries.push(new DiffManifestEntry(repoRoot, file, rel, status, body.length, body !== raw));\n }\n\n private statusOf(file: string, raw: string, repoRoot: string): string {\n if (raw.includes('\\nnew file (untracked)')) return 'U';\n if (raw.includes('\\nnew file mode ')) return 'A';\n if (raw.includes('\\ndeleted file mode ')) return 'D';\n return fs.existsSync(path.join(repoRoot, file)) ? 'M' : 'D';\n }\n\n /**\n * Truncate to the cap WITH a footer. Never silently: a truncated diff that looks whole is how a reviewer\n * reports \"reviewed\" on a tenth of a change — the same trap `formatFileList` states its dropped count for.\n */\n private capped(raw: string, file: string, base: string): string {\n if (raw.length <= FILE_DIFF_MAX_BYTES) return raw;\n return `${raw.slice(0, FILE_DIFF_MAX_BYTES)}\\n` +\n `\\n… TRUNCATED at ${FILE_DIFF_MAX_BYTES} bytes (full diff is ${raw.length} bytes).\\n` +\n ` Read the rest with: git diff ${base} -- ${file}\\n`;\n }\n\n /**\n * `ALL.diff` — the single Read that answers \"what changed on this branch?\". Files are appended smallest\n * first so a cap drops the fewest of them, and anything dropped is named in a HEADER as well as in the\n * manifest.\n *\n * The header used to be a footer, and that was a live correctness bug. `ALL_DIFF_MAX_BYTES` is 2 MB —\n * roughly 30–50k lines — while the Read tool truncates at ~2000. So on the exact PR where files were\n * dropped, a reviewer Reads the first ~5% and the notice telling it files are missing sits in the 95% it\n * never reaches: the in-band signal went invisible precisely when it mattered. A reviewer reads a diff\n * from the start, so the top is the only position that survives a truncated read.\n */\n private writeAllDiff(dir: string, filesDir: string, manifest: DiffManifest): void {\n const ordered = [...manifest.entries].sort((a: DiffManifestEntry, b: DiffManifestEntry): number => a.bytes - b.bytes);\n const parts: string[] = [];\n let total = 0;\n for (const entry of ordered) {\n const body = fs.readFileSync(path.join(filesDir, path.basename(entry.diffFile)), 'utf8');\n if (total + body.length > ALL_DIFF_MAX_BYTES) {\n manifest.omittedFromAllDiff.push(entry.file);\n continue;\n }\n parts.push(body);\n total += body.length;\n }\n const out = this.allDiffHeader(manifest) + parts.join('\\n');\n manifest.allDiffBytes = out.length;\n manifest.allDiffLines = out === '' ? 0 : out.split('\\n').length;\n fs.writeFileSync(path.join(dir, 'ALL.diff'), out);\n }\n\n /**\n * The \"this combined view is NOT the whole change\" notice, at the TOP (see {@link writeAllDiff}). Emitted\n * only when something really is missing — a header on every diff trains a reader to skip the header.\n */\n private allDiffHeader(manifest: DiffManifest): string {\n const truncated = manifest.entries.filter((e: DiffManifestEntry): boolean => e.truncated);\n if (manifest.omittedFromAllDiff.length === 0 && truncated.length === 0) return '';\n const lines = ['=== ⚠️ THIS COMBINED VIEW IS INCOMPLETE — read this notice before the diff below ==='];\n if (manifest.omittedFromAllDiff.length > 0) {\n lines.push(`${manifest.omittedFromAllDiff.length} file(s) are OMITTED here (this view hit the ` +\n `${ALL_DIFF_MAX_BYTES}-byte cap). Each still has its OWN complete diff`, 'under files/ — open those, and see manifest.json:');\n for (const f of manifest.omittedFromAllDiff) lines.push(` ${f}`);\n }\n if (truncated.length > 0) {\n lines.push(`${truncated.length} file(s) below are TRUNCATED at ${FILE_DIFF_MAX_BYTES} bytes; each says so inline where it cuts off:`);\n for (const e of truncated) lines.push(` ${e.file}`);\n }\n lines.push('=== end of notice ===', '');\n return lines.join('\\n') + '\\n';\n }\n\n /**\n * `a/b/c.ts` → `a__b__c.ts.diff`, reusing the SAME `/`→`__` convention MergeState.perFileContextDir\n * already uses for 3-point merge context. One mangling scheme in the repo, not two. A real `__` in a\n * path can collide, so collisions get a numeric suffix and manifest.json stays authoritative.\n */\n private safeName(file: string, used: Set<string>): string {\n const flat = `${file.replace(/\\//g, '__')}.diff`;\n if (!used.has(flat)) {\n used.add(flat);\n return flat;\n }\n for (let n = 2; ; n++) {\n const candidate = `${file.replace(/\\//g, '__')}-${n}.diff`;\n if (!used.has(candidate)) {\n used.add(candidate);\n return candidate;\n }\n }\n }\n\n private writeManifest(dir: string, manifest: DiffManifest): DiffManifest {\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\\n');\n return manifest;\n }\n\n private gitOut(repoRoot: string, args: string[]): string {\n // maxBuffer: a monorepo diff routinely exceeds node's 1MB default, and the failure mode is a\n // truncated capture that looks like a complete one.\n const result = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });\n return result.status === 0 ? (result.stdout ?? '') : '';\n }\n}\n"]}
|
|
@@ -13,7 +13,7 @@ export declare class GateLogFile {
|
|
|
13
13
|
logsPath(repoRoot: string, name: string): string;
|
|
14
14
|
/**
|
|
15
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
|
|
16
|
+
* (`.webpieces-logs/build.log`). Creates the directory. Reach for `logsPath` unless the path itself has
|
|
17
17
|
* to be memorable.
|
|
18
18
|
*/
|
|
19
19
|
localPath(repoRoot: string, name: string): string;
|
|
@@ -19,12 +19,12 @@ 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` — never `path.join(repoRoot, '.webpieces-logs')`. In a LINKED WORKTREE `local()`
|
|
23
|
+
// resolves to `<primary>/.webpieces-logs/worktrees/<git worktree name>/`, so:
|
|
24
24
|
// • N agents in N worktrees never write one another's log, by construction rather than by naming;
|
|
25
25
|
// • the history OUTLIVES the worktree — `wp-cleanup` reaps a tree's directory and the logs it wrote are
|
|
26
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.
|
|
27
|
+
// • it self-limits, because `.webpieces-logs/worktrees/**` is already swept once a namespace goes stale.
|
|
28
28
|
// Nothing here needs a retention policy of its own.
|
|
29
29
|
/** The suffix of the ONE previous generation kept beside a log. */
|
|
30
30
|
const BACKUP_SUFFIX = '.bak';
|
|
@@ -45,7 +45,7 @@ let GateLogFile = class GateLogFile {
|
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
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
|
|
48
|
+
* (`.webpieces-logs/build.log`). Creates the directory. Reach for `logsPath` unless the path itself has
|
|
49
49
|
* to be memorable.
|
|
50
50
|
*/
|
|
51
51
|
localPath(repoRoot, name) {
|
|
@@ -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,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AAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,CAAC,CAAC;QAC1B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACnE,CAAC;IAEO,SAAS,CAAC,IAAY;QAC1B,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ,CAAA;AAhGY,kCAAW;sBAAX,WAAW;IADvB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,WAAW,CAgGvB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n// ─── Why this class exists ─────────────────────────────────────────────────────────────────────────────\n// TWO things in this package write a big blob of output to a file and hand the caller a one-line pointer\n// instead of the blob: the BUILD (BuildGateLog) and the STAGE CONSOLE (StageOutputLog). They are different\n// subjects — one spawns a child and heartbeats, the other intercepts this process's own stdout — but the\n// FILE half is identical: where the file lands, how the previous run is kept, and what the pointer at it\n// reads like.\n//\n// That half lives here, once. Cloning it would have given the two logs two answers to \"where is it?\" and\n// two rotation policies, and the whole value of the pointer is that a reader recognises it instantly and\n// can `grep` it without first working out which subsystem wrote it.\n//\n// ─── WHERE the files land, and why that shape ──────────────────────────────────────────────────────────\n// Through `dotWebpieces` — never `path.join(repoRoot, '.webpieces')`. In a LINKED WORKTREE `local()`\n// resolves to `<primary>/.webpieces/worktrees/<git worktree name>/`, so:\n// • N agents in N worktrees never write one another's log, by construction rather than by naming;\n// • the history OUTLIVES the worktree — `wp-cleanup` reaps a tree's directory and the logs it wrote are\n// still there under the primary clone, which is exactly when you want them;\n// • it self-limits, because `.webpieces/worktrees/**` is already swept once a namespace goes stale.\n// Nothing here needs a retention policy of its own.\n\n/** The suffix of the ONE previous generation kept beside a log. */\nconst BACKUP_SUFFIX = '.bak';\n\n/**\n * The file mechanics shared by every captured log in the PR gate: WHERE it goes, keeping the previous\n * run, the pointer the caller prints instead of the output, and the failure tail.\n *\n * It knows nothing about builds, stages or console interception — its callers own all of that. Singleton\n * because it is pure behaviour over paths; it holds no state.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GateLogFile {\n /**\n * `<local()>/logs/<name>` — the ONE log directory, per worktree namespace. Creates the directory.\n * Use for anything a MESSAGE points at; nobody types these names.\n */\n logsPath(repoRoot: string, name: string): string {\n return this.ensureDir(dotWebpieces.logsFile(repoRoot, name));\n }\n\n /**\n * `<local()>/<name>` — the ROOT of the state dir, for the one log a PERSON types from memory\n * (`.webpieces/build.log`). Creates the directory. Reach for `logsPath` unless the path itself has\n * to be memorable.\n */\n localPath(repoRoot: string, name: string): string {\n return this.ensureDir(dotWebpieces.localFile(repoRoot, name));\n }\n\n /** Where the PREVIOUS run of `logPath` is kept — always `<logPath>.bak`. */\n backupPathFor(logPath: string): string {\n return `${logPath}${BACKUP_SUFFIX}`;\n }\n\n /**\n * Move an existing log aside to `<log>.bak`, overwriting any previous backup, so the last TWO runs\n * are always on disk. A missing log is the normal first-run state and is not an error.\n *\n * ONE generation, everywhere: a re-run at the same commit does not truncate away the run before it,\n * and a reader never has to work out which of N dated files is the one they want.\n */\n rotate(logPath: string): void {\n fs.mkdirSync(path.dirname(logPath), { recursive: true });\n if (!fs.existsSync(logPath)) return;\n fs.rmSync(this.backupPathFor(logPath), { force: true });\n fs.renameSync(logPath, this.backupPathFor(logPath));\n }\n\n /**\n * The two lines that name a log — identical on success and on failure, so there is exactly one shape\n * to recognise.\n *\n * The backup line states what is TRUE RIGHT NOW: on the very first run in a tree there is no `.bak`\n * yet, and pointing a reader at a file that does not exist is the small lie that costs a wasted `cat`.\n */\n pointer(logPath: string): string {\n const name = path.basename(logPath);\n const backedUp = fs.existsSync(this.backupPathFor(logPath))\n ? `(${name} is backed up to ${name}${BACKUP_SUFFIX} every run so you have the last 2 runs of logs)`\n : `(the previous ${name} is kept as ${name}${BACKUP_SUFFIX} on every run — this is the first, so there is none yet)`;\n return `FullLog : ${logPath}\\n${backedUp}\\n`;\n }\n\n /**\n * The path as a progress line should show it: relative to the repo when it sits inside it (a linked\n * worktree's state lives under the PRIMARY clone, so it usually does not), absolute otherwise.\n */\n displayPath(repoRoot: string, logPath: string): string {\n const relative = path.relative(repoRoot, logPath);\n return relative === '' || relative.startsWith('..') || path.isAbsolute(relative) ? logPath : relative;\n }\n\n /**\n * The log's last `lines` lines, indented, or a plain statement of why there are none.\n *\n * A read that fails is REPORTED, never allowed to throw: this renders a message for something that\n * has ALREADY failed, so an I/O error escaping here would replace the real failure with the\n * renderer's own — the caller would lose the actual error and be handed a filesystem error instead.\n * The full log is still named on the line above, so nothing is hidden by degrading to one line.\n */\n tail(logPath: string, lines: number): string {\n if (!fs.existsSync(logPath)) return ` (no log file at ${logPath})\\n`;\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: see above, the failure renderer may not\n // replace the caller's failure with its own.\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const all = fs.readFileSync(logPath, 'utf8').split('\\n').filter((l: string): boolean => l !== '');\n if (all.length === 0) return ' (the log is empty)\\n';\n return all.slice(-lines).map((l: string): string => ` ${l}\\n`).join('');\n } catch (err: unknown) {\n const error = toError(err);\n return ` (could not read ${logPath}: ${error.message})\\n`;\n }\n }\n\n /** How many lines the log holds right now. A log that does not exist yet is zero lines, not an error. */\n lineCount(logPath: string): number {\n if (!fs.existsSync(logPath)) return 0;\n const body = fs.readFileSync(logPath, 'utf8');\n if (body === '') return 0;\n return body.split('\\n').length - (body.endsWith('\\n') ? 1 : 0);\n }\n\n private ensureDir(file: string): string {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n return file;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gate-log-file.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/gate-log-file.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,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,0GAA0G;AAC1G,8EAA8E;AAC9E,oGAAoG;AACpG,0GAA0G;AAC1G,gFAAgF;AAChF,2GAA2G;AAC3G,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,EAAE,IAAI,CAAC,CAAC,CAAC;IAClE,CAAC;IAED,4EAA4E;IAC5E,aAAa,CAAC,OAAe;QACzB,OAAO,GAAG,OAAO,GAAG,aAAa,EAAE,CAAC;IACxC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,OAAe;QAClB,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,SA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AhGY,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-logs')`. In a LINKED WORKTREE `local()`\n// resolves to `<primary>/.webpieces-logs/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-logs/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-logs/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"]}
|
|
@@ -27,7 +27,7 @@ export declare class GitExec {
|
|
|
27
27
|
* calls {@link statusEntries} and reads booleans instead of re-parsing a string.
|
|
28
28
|
*
|
|
29
29
|
* Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so
|
|
30
|
-
* `.webpieces/` tooling artifacts never count. Empty string = fully committed.
|
|
30
|
+
* `.webpieces-logs/` tooling artifacts never count. Empty string = fully committed.
|
|
31
31
|
*/
|
|
32
32
|
porcelainStatus(cwd: string): string;
|
|
33
33
|
/**
|
|
@@ -7,7 +7,7 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
7
7
|
const inversify_1 = require("inversify");
|
|
8
8
|
const git_status_1 = require("./git-status");
|
|
9
9
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
10
|
-
// The AI-facing doc the failure messages point at (generated under `.webpieces/instruct-ai`, at the
|
|
10
|
+
// The AI-facing doc the failure messages point at (generated under `.webpieces-logs/instruct-ai`, at the
|
|
11
11
|
// REPO ROOT — resolved absolute so the AI opens it regardless of the cwd it reads the message from).
|
|
12
12
|
const GIT_WORKFLOW_DOC_NAME = 'webpieces.git-workflow.md';
|
|
13
13
|
/**
|
|
@@ -47,7 +47,7 @@ let GitExec = class GitExec {
|
|
|
47
47
|
* calls {@link statusEntries} and reads booleans instead of re-parsing a string.
|
|
48
48
|
*
|
|
49
49
|
* Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so
|
|
50
|
-
* `.webpieces/` tooling artifacts never count. Empty string = fully committed.
|
|
50
|
+
* `.webpieces-logs/` tooling artifacts never count. Empty string = fully committed.
|
|
51
51
|
*/
|
|
52
52
|
porcelainStatus(cwd) {
|
|
53
53
|
return this.rawGitQuery(['status', '--porcelain'], cwd, 'Failed to run `git status --porcelain` to check the working tree.').replace(/\n+$/, '');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git-exec.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/git-exec.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuE;AACvE,yCAA2D;AAC3D,6CAA+D;AAE/D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AACvE,oGAAoG;AACpG,qGAAqG;AACrG,MAAM,qBAAqB,GAAG,2BAA2B,CAAC;AAE1D;;;GAGG;AACH,MAAa,UAAU;IACnB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,MAAM,CAAS;IAEf,YAAY,MAAc,EAAE,MAAc,EAAE,MA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IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,4BAAe;GAHzC,OAAO,CA+HnB","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError, RepoRootFinder } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitStatusEntry, GitStatusParser } from './git-status';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n// The AI-facing doc the failure messages point at (generated under `.webpieces/instruct-ai`, at the\n// REPO ROOT — resolved absolute so the AI opens it regardless of the cwd it reads the message from).\nconst GIT_WORKFLOW_DOC_NAME = 'webpieces.git-workflow.md';\n\n/**\n * The result of a git command that was allowed to fail. Data-only (per CLAUDE.md) so a caller asks\n * `outcome.ok` rather than re-deriving \"did it work\" from a status number at every site.\n */\nexport class GitOutcome {\n status: number;\n stdout: string;\n stderr: string;\n\n constructor(status: number, stdout: string, stderr: string) {\n this.status = status;\n this.stdout = stdout;\n this.stderr = stderr;\n }\n\n get ok(): boolean {\n return this.status === 0;\n }\n}\n\n/** Shared git precondition checks + push logic for the PR/merge workflow. */\n@injectable(bindingScopeValues.Singleton)\nexport class GitExec {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly statusParser: GitStatusParser,\n ) {}\n\n /**\n * Raw `git status --porcelain` with ONLY the trailing newline(s) stripped — never `.trim()`.\n *\n * There used to be a trimmed sibling here (`uncommittedFiles`) and it was a data-destroying trap:\n * porcelain column 1 is the index state and column 2 the worktree state, so an unstaged\n * modification is \" M path\"; `trim()` eats that leading space and the line then reads \"M path\",\n * i.e. STAGED — the exact inverse of the truth. It is deleted. This method is for EMPTINESS\n * (\"is the tree dirty at all?\") and for PRINTING; anything that reasons about the two columns\n * calls {@link statusEntries} and reads booleans instead of re-parsing a string.\n *\n * Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so\n * `.webpieces/` tooling artifacts never count. Empty string = fully committed.\n */\n porcelainStatus(cwd: string): string {\n return this.rawGitQuery(['status', '--porcelain'], cwd,\n 'Failed to run `git status --porcelain` to check the working tree.').replace(/\\n+$/, '');\n }\n\n /**\n * The same status, PARSED: two status columns, an unquoted path, and explicit\n * `isStaged()`/`isUnstaged()`/`isUntracked()` answers. Use this for every semantic question.\n */\n statusEntries(cwd: string): GitStatusEntry[] {\n return this.statusParser.parse(this.porcelainStatus(cwd));\n }\n\n // Untracked files only (respects .gitignore). Empty string = none.\n untrackedFiles(cwd: string): string {\n return this.gitQuery(['ls-files', '--others', '--exclude-standard'], cwd, 'Failed to list untracked files (git ls-files --others).');\n }\n\n /**\n * Precondition for every PR/merge entry point: the working tree must be fully committed. The\n * webpieces tooling deliberately does NOT `git add`/`commit` the developer's work for them. Aborts\n * with instructions if anything is uncommitted (tracked or untracked, excluding gitignored).\n */\n assertCleanTree(cwd: string): void {\n const dirty = this.porcelainStatus(cwd);\n if (dirty === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: You have uncommitted or untracked changes\\n' +\n SEP + '\\n' +\n 'The webpieces PR tooling will NOT commit your work for you. Commit your\\n' +\n 'changes, and either commit or delete any untracked files, then re-run.\\n\\n' +\n 'Working tree (git status --porcelain):\\n' +\n dirty + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Narrower guard for the merge-resolve commit point, where tracked resolutions are legitimately in\n * the tree but untracked files must NOT be swept into the squash commit. Lists any untracked files\n * and aborts so the AI commits or deletes them explicitly.\n */\n assertNoUntracked(cwd: string): void {\n const untracked = this.untrackedFiles(cwd);\n if (untracked === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: Untracked files present during merge finalize\\n' +\n SEP + '\\n' +\n 'The tooling will not sweep untracked files into the squash commit. Commit\\n' +\n 'or delete these, then re-run:\\n\\n' +\n untracked + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Run a git command that is expected to succeed; abort the process with a clear message if it\n * fails. Used for fetch/pull/checkout/commit where silently continuing on failure would operate on\n * stale or wrong state.\n */\n runGitChecked(args: string[], errMsg: string): void {\n const result = spawnSync('git', args, { stdio: 'inherit' });\n if (result.status !== 0) {\n throw new CliExitError(1, `❌ ${errMsg} (git ${args.join(' ')} exited ${String(result.status)})`);\n }\n }\n\n /**\n * Push HEAD to origin/<currentBranch>. Uses --force-with-lease for an existing remote branch (the\n * 3-point squash rewrites history) and -u for a brand-new branch.\n */\n ensurePushed(currentBranch: string): void {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n this.runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');\n } else {\n this.runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');\n }\n }\n\n /**\n * Run a git command that MAY legitimately fail and report the outcome instead of aborting — for the\n * questions whose \"no\" is an answer rather than an error (does this remote ref exist? did this merge\n * conflict?). Distinct from {@link runGitChecked}, which exists for the commands where continuing on\n * failure would operate on wrong state.\n */\n tryGit(args: string[], cwd: string): GitOutcome {\n const out = spawnSync('git', args, { encoding: 'utf8', cwd });\n return new GitOutcome(out.status ?? 1, (out.stdout ?? '').trim(), (out.stderr ?? '').trim());\n }\n\n /** Read-only git query that MUST succeed, trimmed. Public sibling of the private raw form. */\n gitQuery(args: string[], cwd: string, failMsg: string): string {\n return this.rawGitQuery(args, cwd, failMsg).trim();\n }\n\n // The untrimmed sibling — see porcelainStatus for why trimming is not always safe.\n private rawGitQuery(args: string[], cwd: string, failMsg: string): string {\n const out = spawnSync('git', args, { encoding: 'utf8', cwd });\n if (out.status !== 0) {\n throw new CliExitError(1, `❌ ${failMsg}`);\n }\n return out.stdout;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"git-exec.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/git-exec.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,0DAAuE;AACvE,yCAA2D;AAC3D,6CAA+D;AAE/D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AACvE,yGAAyG;AACzG,qGAAqG;AACrG,MAAM,qBAAqB,GAAG,2BAA2B,CAAC;AAE1D;;;GAGG;AACH,MAAa,UAAU;IACnB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,MAAM,CAAS;IAEf,YAAY,MAAc,EAAE,MAAc,EAAE,MAAc;QACtD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED,IAAI,EAAE;QACF,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;IAC7B,CAAC;CACJ;AAdD,gCAcC;AAED,6EAA6E;AAEtE,IAAM,OAAO,GAAb,MAAM,OAAO;IAEK;IACA;IAFrB,YACqB,cAA8B,EAC9B,YAA6B;QAD7B,mBAAc,GAAd,cAAc,CAAgB;QAC9B,iBAAY,GAAZ,YAAY,CAAiB;IAC/C,CAAC;IAEJ;;;;;;;;;;;;OAYG;IACH,eAAe,CAAC,GAAW;QACvB,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC,QAAQ,EAAE,aAAa,CAAC,EAAE,GAAG,EAClD,mEAAmE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACjG,CAAC;IAED;;;OAGG;IACH,aAAa,CAAC,GAAW;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9D,CAAC;IAED,mEAAmE;IACnE,cAAc,CAA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ACvD,CAAC;IAED,mFAAmF;IAC3E,WAAW,CAAC,IAAc,EAAE,GAAW,EAAE,OAAe;QAC5D,MAAM,GAAG,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QAC9D,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACnB,MAAM,IAAI,2BAAY,CAAC,CAAC,EAAE,KAAK,OAAO,EAAE,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,GAAG,CAAC,MAAM,CAAC;IACtB,CAAC;CACJ,CAAA;AA/HY,0BAAO;kBAAP,OAAO;IADnB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGA,6BAAc;QAChB,4BAAe;GAHzC,OAAO,CA+HnB","sourcesContent":["import { spawnSync } from 'child_process';\nimport { CliExitError, RepoRootFinder } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitStatusEntry, GitStatusParser } from './git-status';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n// The AI-facing doc the failure messages point at (generated under `.webpieces-logs/instruct-ai`, at the\n// REPO ROOT — resolved absolute so the AI opens it regardless of the cwd it reads the message from).\nconst GIT_WORKFLOW_DOC_NAME = 'webpieces.git-workflow.md';\n\n/**\n * The result of a git command that was allowed to fail. Data-only (per CLAUDE.md) so a caller asks\n * `outcome.ok` rather than re-deriving \"did it work\" from a status number at every site.\n */\nexport class GitOutcome {\n status: number;\n stdout: string;\n stderr: string;\n\n constructor(status: number, stdout: string, stderr: string) {\n this.status = status;\n this.stdout = stdout;\n this.stderr = stderr;\n }\n\n get ok(): boolean {\n return this.status === 0;\n }\n}\n\n/** Shared git precondition checks + push logic for the PR/merge workflow. */\n@injectable(bindingScopeValues.Singleton)\nexport class GitExec {\n constructor(\n private readonly repoRootFinder: RepoRootFinder,\n private readonly statusParser: GitStatusParser,\n ) {}\n\n /**\n * Raw `git status --porcelain` with ONLY the trailing newline(s) stripped — never `.trim()`.\n *\n * There used to be a trimmed sibling here (`uncommittedFiles`) and it was a data-destroying trap:\n * porcelain column 1 is the index state and column 2 the worktree state, so an unstaged\n * modification is \" M path\"; `trim()` eats that leading space and the line then reads \"M path\",\n * i.e. STAGED — the exact inverse of the truth. It is deleted. This method is for EMPTINESS\n * (\"is the tree dirty at all?\") and for PRINTING; anything that reasons about the two columns\n * calls {@link statusEntries} and reads booleans instead of re-parsing a string.\n *\n * Tracked changes (staged + unstaged) AND untracked files, EXCLUDING gitignored paths — so\n * `.webpieces-logs/` tooling artifacts never count. Empty string = fully committed.\n */\n porcelainStatus(cwd: string): string {\n return this.rawGitQuery(['status', '--porcelain'], cwd,\n 'Failed to run `git status --porcelain` to check the working tree.').replace(/\\n+$/, '');\n }\n\n /**\n * The same status, PARSED: two status columns, an unquoted path, and explicit\n * `isStaged()`/`isUnstaged()`/`isUntracked()` answers. Use this for every semantic question.\n */\n statusEntries(cwd: string): GitStatusEntry[] {\n return this.statusParser.parse(this.porcelainStatus(cwd));\n }\n\n // Untracked files only (respects .gitignore). Empty string = none.\n untrackedFiles(cwd: string): string {\n return this.gitQuery(['ls-files', '--others', '--exclude-standard'], cwd, 'Failed to list untracked files (git ls-files --others).');\n }\n\n /**\n * Precondition for every PR/merge entry point: the working tree must be fully committed. The\n * webpieces tooling deliberately does NOT `git add`/`commit` the developer's work for them. Aborts\n * with instructions if anything is uncommitted (tracked or untracked, excluding gitignored).\n */\n assertCleanTree(cwd: string): void {\n const dirty = this.porcelainStatus(cwd);\n if (dirty === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: You have uncommitted or untracked changes\\n' +\n SEP + '\\n' +\n 'The webpieces PR tooling will NOT commit your work for you. Commit your\\n' +\n 'changes, and either commit or delete any untracked files, then re-run.\\n\\n' +\n 'Working tree (git status --porcelain):\\n' +\n dirty + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Narrower guard for the merge-resolve commit point, where tracked resolutions are legitimately in\n * the tree but untracked files must NOT be swept into the squash commit. Lists any untracked files\n * and aborts so the AI commits or deletes them explicitly.\n */\n assertNoUntracked(cwd: string): void {\n const untracked = this.untrackedFiles(cwd);\n if (untracked === '') return;\n throw new CliExitError(1,\n '\\n' + SEP +\n '❌ ERROR: Untracked files present during merge finalize\\n' +\n SEP + '\\n' +\n 'The tooling will not sweep untracked files into the squash commit. Commit\\n' +\n 'or delete these, then re-run:\\n\\n' +\n untracked + '\\n\\n' +\n `See ${this.repoRootFinder.docPathFrom(cwd, GIT_WORKFLOW_DOC_NAME)} for the full merge + PR process.\\n` +\n SEP,\n );\n }\n\n /**\n * Run a git command that is expected to succeed; abort the process with a clear message if it\n * fails. Used for fetch/pull/checkout/commit where silently continuing on failure would operate on\n * stale or wrong state.\n */\n runGitChecked(args: string[], errMsg: string): void {\n const result = spawnSync('git', args, { stdio: 'inherit' });\n if (result.status !== 0) {\n throw new CliExitError(1, `❌ ${errMsg} (git ${args.join(' ')} exited ${String(result.status)})`);\n }\n }\n\n /**\n * Push HEAD to origin/<currentBranch>. Uses --force-with-lease for an existing remote branch (the\n * 3-point squash rewrites history) and -u for a brand-new branch.\n */\n ensurePushed(currentBranch: string): void {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n this.runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');\n } else {\n this.runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');\n }\n }\n\n /**\n * Run a git command that MAY legitimately fail and report the outcome instead of aborting — for the\n * questions whose \"no\" is an answer rather than an error (does this remote ref exist? did this merge\n * conflict?). Distinct from {@link runGitChecked}, which exists for the commands where continuing on\n * failure would operate on wrong state.\n */\n tryGit(args: string[], cwd: string): GitOutcome {\n const out = spawnSync('git', args, { encoding: 'utf8', cwd });\n return new GitOutcome(out.status ?? 1, (out.stdout ?? '').trim(), (out.stderr ?? '').trim());\n }\n\n /** Read-only git query that MUST succeed, trimmed. Public sibling of the private raw form. */\n gitQuery(args: string[], cwd: string, failMsg: string): string {\n return this.rawGitQuery(args, cwd, failMsg).trim();\n }\n\n // The untrimmed sibling — see porcelainStatus for why trimming is not always safe.\n private rawGitQuery(args: string[], cwd: string, failMsg: string): string {\n const out = spawnSync('git', args, { encoding: 'utf8', cwd });\n if (out.status !== 0) {\n throw new CliExitError(1, `❌ ${failMsg}`);\n }\n return out.stdout;\n }\n}\n"]}
|
|
@@ -26,7 +26,7 @@ import { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';
|
|
|
26
26
|
* name-only match is never enough to remove or archive anything — in this process or in the child that
|
|
27
27
|
* re-verifies it (see ReapWorktreeCommand).
|
|
28
28
|
*
|
|
29
|
-
* ─── WHY NOT A `.webpieces/**` RECEIPT ────────────────────────────────────────────────────────────
|
|
29
|
+
* ─── WHY NOT A `.webpieces-logs/**` RECEIPT ────────────────────────────────────────────────────────────
|
|
30
30
|
* The obvious alternative is for `wp-finish-upsert-pr` to write `{ pr, branch, worktreePath, headRefOid }`
|
|
31
31
|
* to a sidecar and for landing to read it back. `decisions/0005-the-pr-description-is-the-merge-body.md`
|
|
32
32
|
* already deleted that pattern once: a recorded claim can only ever be missing, stale, or on the wrong
|
|
@@ -32,7 +32,7 @@ const inversify_1 = require("inversify");
|
|
|
32
32
|
* name-only match is never enough to remove or archive anything — in this process or in the child that
|
|
33
33
|
* re-verifies it (see ReapWorktreeCommand).
|
|
34
34
|
*
|
|
35
|
-
* ─── WHY NOT A `.webpieces/**` RECEIPT ────────────────────────────────────────────────────────────
|
|
35
|
+
* ─── WHY NOT A `.webpieces-logs/**` RECEIPT ────────────────────────────────────────────────────────────
|
|
36
36
|
* The obvious alternative is for `wp-finish-upsert-pr` to write `{ pr, branch, worktreePath, headRefOid }`
|
|
37
37
|
* to a sidecar and for landing to read it back. `decisions/0005-the-pr-description-is-the-merge-body.md`
|
|
38
38
|
* already deleted that pattern once: a recorded claim can only ever be missing, stale, or on the wrong
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"landed-tree-resolver.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-tree-resolver.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,sEAA0E;AAC1E,yCAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,wGAAwG;AAC3F,QAAA,oBAAoB,GAAG,UAAU,CAAC;AAC/C,8GAA8G;AACjG,QAAA,uBAAuB,GAAG,aAAa,CAAC;AACrD,2FAA2F;AAC9E,QAAA,qBAAqB,GAAG,WAAW,CAAC;AACjD,wFAAwF;AAC3E,QAAA,kBAAkB,GAAG,QAAQ,CAAC;AAE3C;;;;;;;GAOG;AACH,MAAa,UAAU;IACV,IAAI,CAAS;IACtB,oFAAoF;IAC3E,QAAQ,CAAkB;IACnC,yGAAyG;IAChG,QAAQ,CAAS;IACjB,kBAAkB,CAAU;IAErC,YAAY,IAAY,EAAE,QAAyB,EAAE,QAAgB;QACjE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,kBAAkB,GAAG,IAAI,KAAK,4BAAoB,IAAI,IAAI,KAAK,+BAAuB,CAAC;IAChG,CAAC;CACJ;AAdD,gCAcC;AAGM,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IACE;IAA7B,YAA6B,SAA0B;QAA1B,cAAS,GAAT,SAAS,CAAiB;IAAG,CAAC;IAE3D;;;;;;OAMG;IACH,OAAO,CAAC,QA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B;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEG,oCAAe;GAD9C,kBAAkB,CA8B9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * WHICH LOCAL TREE HOLDS THE COMMIT GITHUB JUST SQUASHED — asked as a fact, answered from anywhere.\n *\n * `wp-land-pr` does two things with different scopes: the MERGE belongs to the PR and is reachable from\n * any directory, while the BOOKKEEPING (archive the pre-squash tip, promote merge-info, reap the landed\n * worktree) belongs to the tree that really holds those objects. Until now the second half was resolved\n * from `process.cwd()` — and `pnpm` hoists a bin's cwd to the workspace root, so a command run inside\n * `<primary>/.claude/worktrees/agent-<id>` executed in the PRIMARY CLONE. Every agent worktree is nested\n * like that, so the answer was wrong in exactly the case the mechanism was built for.\n *\n * The fix is to stop asking \"where am I\" and start asking \"where is it\". Both halves of that question are\n * facts nobody has to record:\n *\n * `gh pr view <n> --json headRefName,headRefOid` → the branch, and the exact commit being squashed\n * `git worktree list --porcelain` → every (path, branch, HEAD sha) in this repo\n *\n * The worktree list lives in the COMMON dir, so it reads identically from the primary clone, from any\n * linked worktree, and from a coordinator that never saw the agent that built the branch. That is what\n * makes `wp-land-pr --pr <n>` able to finish a dead agent's work.\n *\n * ─── WHY THE PAIR, AND NEVER THE NAME ALONE ───────────────────────────────────────────────────────\n * A branch NAME does not identify a tree. A second clone, or a worktree somebody has since committed to,\n * holds the same name at a different commit, and archiving `archive/<date>/<branch>` from there tags the\n * wrong objects under the right name. So the selection key is `(headRefName, headRefOid)` together, and a\n * name-only match is never enough to remove or archive anything — in this process or in the child that\n * re-verifies it (see ReapWorktreeCommand).\n *\n * ─── WHY NOT A `.webpieces/**` RECEIPT ────────────────────────────────────────────────────────────\n * The obvious alternative is for `wp-finish-upsert-pr` to write `{ pr, branch, worktreePath, headRefOid }`\n * to a sidecar and for landing to read it back. `decisions/0005-the-pr-description-is-the-merge-body.md`\n * already deleted that pattern once: a recorded claim can only ever be missing, stale, or on the wrong\n * computer — and a worktree PATH is more volatile than the commit body that argument was made about,\n * since the directory is moved, reaped, or recreated under a new agent id between finish and land.\n * `(headRefOid, git worktree list)` is a pair of facts, needs no stored state, and works from a fresh\n * clone. Nothing here reads state.\n */\n\n/** A linked worktree holds the branch AT the squashed commit: archive here, and reap THAT directory. */\nexport const LANDED_TREE_WORKTREE = 'worktree';\n/** No worktree holds it, but the branch ref in this repo IS the squashed commit: archive, nothing to reap. */\nexport const LANDED_TREE_BRANCH_ONLY = 'branch-only';\n/** The name is here, the commit is not. Merge stands; bookkeeping is declined out loud. */\nexport const LANDED_TREE_WRONG_TIP = 'wrong-tip';\n/** The branch is not in this repo at all — landed from a tree that does not hold it. */\nexport const LANDED_TREE_ABSENT = 'absent';\n\n/**\n * Data-only (per CLAUDE.md, classes for data). Where the landed commit lives locally, and therefore\n * whether the bookkeeping half may run at all.\n *\n * `bookkeepingAllowed` is PRECOMPUTED rather than re-derived by the caller, for the same reason\n * `EffectiveTree.redirected` and `WorktreeReapHandoff.canReap` are: a deletion rule spelled out twice is\n * a deletion rule that eventually disagrees with itself.\n */\nexport class LandedTree {\n readonly kind: string;\n /** The linked worktree to reap — non-null ONLY for {@link LANDED_TREE_WORKTREE}. */\n readonly worktree: Worktree | null;\n /** The sha found locally under that branch name, '' when the branch is absent. Printed on a mismatch. */\n readonly localSha: string;\n readonly bookkeepingAllowed: boolean;\n\n constructor(kind: string, worktree: Worktree | null, localSha: string) {\n this.kind = kind;\n this.worktree = worktree;\n this.localSha = localSha;\n this.bookkeepingAllowed = kind === LANDED_TREE_WORKTREE || kind === LANDED_TREE_BRANCH_ONLY;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class LandedTreeResolver {\n constructor(private readonly worktrees: WorktreeService) {}\n\n /**\n * The four-row table this whole design exists to implement, in order of what it can prove.\n *\n * `headRefOid === ''` means `gh` did not tell us which commit it is squashing. That cannot be turned\n * into a mismatch — a fact we do not have is not evidence of disagreement — so the local tip is taken\n * as the landed one, which is exactly what the old `ref.headRefOid !== ''` guard did.\n */\n resolve(repoRoot: string, branch: string, headRefOid: string): LandedTree {\n // Only LINKED worktrees are reapable; the primary clone is the thing reaped FROM, never a target.\n const holder = this.worktrees.linkedWorktrees(repoRoot)\n .find((tree: Worktree): boolean => tree.branch === branch) ?? null;\n const local = holder !== null ? holder.head : this.revParse(repoRoot, branch);\n\n if (local === '') return new LandedTree(LANDED_TREE_ABSENT, null, '');\n if (headRefOid !== '' && local !== headRefOid) {\n return new LandedTree(LANDED_TREE_WRONG_TIP, null, local);\n }\n return holder !== null\n ? new LandedTree(LANDED_TREE_WORKTREE, holder, local)\n : new LandedTree(LANDED_TREE_BRANCH_ONLY, null, local);\n }\n\n // Best-effort sha of a ref — '' when it cannot resolve, which reads as \"the branch is not here\".\n private revParse(repoRoot: string, ref: string): string {\n const result = spawnSync('git', ['rev-parse', ref], { cwd: repoRoot, encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"landed-tree-resolver.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-tree-resolver.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,sEAA0E;AAC1E,yCAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,wGAAwG;AAC3F,QAAA,oBAAoB,GAAG,UAAU,CAAC;AAC/C,8GAA8G;AACjG,QAAA,uBAAuB,GAAG,aAAa,CAAC;AACrD,2FAA2F;AAC9E,QAAA,qBAAqB,GAAG,WAAW,CAAC;AACjD,wFAAwF;AAC3E,QAAA,kBAAkB,GAAG,QAAQ,CAAC;AAE3C;;;;;;;GAOG;AACH,MAAa,UAAU;IACV,IAAI,CAAS;IACtB,oFAAoF;IAC3E,QAAQ,CAAkB;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AC;YACrD,CAAC,CAAC,IAAI,UAAU,CAAC,+BAAuB,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,iGAAiG;IACzF,QAAQ,CAAC,QAAgB,EAAE,GAAW;QAC1C,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QACzF,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,CAAC;CACJ,CAAA;AA9BY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEG,oCAAe;GAD9C,kBAAkB,CA8B9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * WHICH LOCAL TREE HOLDS THE COMMIT GITHUB JUST SQUASHED — asked as a fact, answered from anywhere.\n *\n * `wp-land-pr` does two things with different scopes: the MERGE belongs to the PR and is reachable from\n * any directory, while the BOOKKEEPING (archive the pre-squash tip, promote merge-info, reap the landed\n * worktree) belongs to the tree that really holds those objects. Until now the second half was resolved\n * from `process.cwd()` — and `pnpm` hoists a bin's cwd to the workspace root, so a command run inside\n * `<primary>/.claude/worktrees/agent-<id>` executed in the PRIMARY CLONE. Every agent worktree is nested\n * like that, so the answer was wrong in exactly the case the mechanism was built for.\n *\n * The fix is to stop asking \"where am I\" and start asking \"where is it\". Both halves of that question are\n * facts nobody has to record:\n *\n * `gh pr view <n> --json headRefName,headRefOid` → the branch, and the exact commit being squashed\n * `git worktree list --porcelain` → every (path, branch, HEAD sha) in this repo\n *\n * The worktree list lives in the COMMON dir, so it reads identically from the primary clone, from any\n * linked worktree, and from a coordinator that never saw the agent that built the branch. That is what\n * makes `wp-land-pr --pr <n>` able to finish a dead agent's work.\n *\n * ─── WHY THE PAIR, AND NEVER THE NAME ALONE ───────────────────────────────────────────────────────\n * A branch NAME does not identify a tree. A second clone, or a worktree somebody has since committed to,\n * holds the same name at a different commit, and archiving `archive/<date>/<branch>` from there tags the\n * wrong objects under the right name. So the selection key is `(headRefName, headRefOid)` together, and a\n * name-only match is never enough to remove or archive anything — in this process or in the child that\n * re-verifies it (see ReapWorktreeCommand).\n *\n * ─── WHY NOT A `.webpieces-logs/**` RECEIPT ────────────────────────────────────────────────────────────\n * The obvious alternative is for `wp-finish-upsert-pr` to write `{ pr, branch, worktreePath, headRefOid }`\n * to a sidecar and for landing to read it back. `decisions/0005-the-pr-description-is-the-merge-body.md`\n * already deleted that pattern once: a recorded claim can only ever be missing, stale, or on the wrong\n * computer — and a worktree PATH is more volatile than the commit body that argument was made about,\n * since the directory is moved, reaped, or recreated under a new agent id between finish and land.\n * `(headRefOid, git worktree list)` is a pair of facts, needs no stored state, and works from a fresh\n * clone. Nothing here reads state.\n */\n\n/** A linked worktree holds the branch AT the squashed commit: archive here, and reap THAT directory. */\nexport const LANDED_TREE_WORKTREE = 'worktree';\n/** No worktree holds it, but the branch ref in this repo IS the squashed commit: archive, nothing to reap. */\nexport const LANDED_TREE_BRANCH_ONLY = 'branch-only';\n/** The name is here, the commit is not. Merge stands; bookkeeping is declined out loud. */\nexport const LANDED_TREE_WRONG_TIP = 'wrong-tip';\n/** The branch is not in this repo at all — landed from a tree that does not hold it. */\nexport const LANDED_TREE_ABSENT = 'absent';\n\n/**\n * Data-only (per CLAUDE.md, classes for data). Where the landed commit lives locally, and therefore\n * whether the bookkeeping half may run at all.\n *\n * `bookkeepingAllowed` is PRECOMPUTED rather than re-derived by the caller, for the same reason\n * `EffectiveTree.redirected` and `WorktreeReapHandoff.canReap` are: a deletion rule spelled out twice is\n * a deletion rule that eventually disagrees with itself.\n */\nexport class LandedTree {\n readonly kind: string;\n /** The linked worktree to reap — non-null ONLY for {@link LANDED_TREE_WORKTREE}. */\n readonly worktree: Worktree | null;\n /** The sha found locally under that branch name, '' when the branch is absent. Printed on a mismatch. */\n readonly localSha: string;\n readonly bookkeepingAllowed: boolean;\n\n constructor(kind: string, worktree: Worktree | null, localSha: string) {\n this.kind = kind;\n this.worktree = worktree;\n this.localSha = localSha;\n this.bookkeepingAllowed = kind === LANDED_TREE_WORKTREE || kind === LANDED_TREE_BRANCH_ONLY;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class LandedTreeResolver {\n constructor(private readonly worktrees: WorktreeService) {}\n\n /**\n * The four-row table this whole design exists to implement, in order of what it can prove.\n *\n * `headRefOid === ''` means `gh` did not tell us which commit it is squashing. That cannot be turned\n * into a mismatch — a fact we do not have is not evidence of disagreement — so the local tip is taken\n * as the landed one, which is exactly what the old `ref.headRefOid !== ''` guard did.\n */\n resolve(repoRoot: string, branch: string, headRefOid: string): LandedTree {\n // Only LINKED worktrees are reapable; the primary clone is the thing reaped FROM, never a target.\n const holder = this.worktrees.linkedWorktrees(repoRoot)\n .find((tree: Worktree): boolean => tree.branch === branch) ?? null;\n const local = holder !== null ? holder.head : this.revParse(repoRoot, branch);\n\n if (local === '') return new LandedTree(LANDED_TREE_ABSENT, null, '');\n if (headRefOid !== '' && local !== headRefOid) {\n return new LandedTree(LANDED_TREE_WRONG_TIP, null, local);\n }\n return holder !== null\n ? new LandedTree(LANDED_TREE_WORKTREE, holder, local)\n : new LandedTree(LANDED_TREE_BRANCH_ONLY, null, local);\n }\n\n // Best-effort sha of a ref — '' when it cannot resolve, which reads as \"the branch is not here\".\n private revParse(repoRoot: string, ref: string): string {\n const result = spawnSync('git', ['rev-parse', ref], { cwd: repoRoot, encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n}\n"]}
|
|
@@ -218,7 +218,7 @@ let MergeEnd = class MergeEnd {
|
|
|
218
218
|
: `snapshotted your pre-merge state → ${backupBranch} (auto-removed — clean merge, no undo needed)`;
|
|
219
219
|
const trailer = backupKept
|
|
220
220
|
? ` Pre-merge snapshot trail: git branch --list '${feature}PreMerge*'\n` +
|
|
221
|
-
` Its conflict context lives in the paired merge-<n>/ folder under .webpieces/merge-info/\n` +
|
|
221
|
+
` Its conflict context lives in the paired merge-<n>/ folder under .webpieces-logs/merge-info/\n` +
|
|
222
222
|
` Prune this run's snapshot when safe: git branch -D ${backupBranch}\n\n`
|
|
223
223
|
: '\n';
|
|
224
224
|
process.stdout.write('\n' + SEP + '✅ Sync complete — here is exactly what I did\n' + SEP + '\n' +
|