@webpieces/pr-gate 0.4.836 → 0.4.838

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.
Files changed (85) hide show
  1. package/package.json +6 -4
  2. package/src/scripts/commands/cleanup-command.d.ts +2 -1
  3. package/src/scripts/commands/cleanup-command.js +13 -12
  4. package/src/scripts/commands/cleanup-command.js.map +1 -1
  5. package/src/scripts/commands/finish-upsert-pr-command.js +5 -3
  6. package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
  7. package/src/scripts/commands/human-post-pr-command.d.ts +2 -1
  8. package/src/scripts/commands/human-post-pr-command.js +3 -2
  9. package/src/scripts/commands/human-post-pr-command.js.map +1 -1
  10. package/src/scripts/commands/land-pr-command.d.ts +2 -1
  11. package/src/scripts/commands/land-pr-command.js +12 -9
  12. package/src/scripts/commands/land-pr-command.js.map +1 -1
  13. package/src/scripts/commands/reap-worktree-command.d.ts +2 -1
  14. package/src/scripts/commands/reap-worktree-command.js +4 -2
  15. package/src/scripts/commands/reap-worktree-command.js.map +1 -1
  16. package/src/scripts/commands/sync-main-command.js +2 -1
  17. package/src/scripts/commands/sync-main-command.js.map +1 -1
  18. package/src/scripts/commands/upsert-hotfix-pr-command.d.ts +2 -1
  19. package/src/scripts/commands/upsert-hotfix-pr-command.js +2 -1
  20. package/src/scripts/commands/upsert-hotfix-pr-command.js.map +1 -1
  21. package/src/scripts/commands/worktree-cleanup.d.ts +1 -1
  22. package/src/scripts/commands/worktree-cleanup.js +11 -11
  23. package/src/scripts/commands/worktree-cleanup.js.map +1 -1
  24. package/src/scripts/commands/write-review-command.js +13 -10
  25. package/src/scripts/commands/write-review-command.js.map +1 -1
  26. package/src/scripts/commands/write-review-fixes-command.js +3 -2
  27. package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
  28. package/src/scripts/pr-gate-cli-app.js +2 -1
  29. package/src/scripts/pr-gate-cli-app.js.map +1 -1
  30. package/src/scripts/workflow/build-affected.d.ts +2 -1
  31. package/src/scripts/workflow/build-affected.js +2 -1
  32. package/src/scripts/workflow/build-affected.js.map +1 -1
  33. package/src/scripts/workflow/cleanTmp.d.ts +2 -1
  34. package/src/scripts/workflow/cleanTmp.js +3 -2
  35. package/src/scripts/workflow/cleanTmp.js.map +1 -1
  36. package/src/scripts/workflow/diff-materializer.js +2 -1
  37. package/src/scripts/workflow/diff-materializer.js.map +1 -1
  38. package/src/scripts/workflow/gate-log-file.js +5 -4
  39. package/src/scripts/workflow/gate-log-file.js.map +1 -1
  40. package/src/scripts/workflow/generated-artifact-registry.js +2 -1
  41. package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
  42. package/src/scripts/workflow/hotfix-redirect.d.ts +1 -1
  43. package/src/scripts/workflow/hotfix-redirect.js +2 -1
  44. package/src/scripts/workflow/hotfix-redirect.js.map +1 -1
  45. package/src/scripts/workflow/landed-tree-resolver.d.ts +1 -1
  46. package/src/scripts/workflow/landed-tree-resolver.js +2 -2
  47. package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
  48. package/src/scripts/workflow/landed-worktree-reaper.d.ts +1 -1
  49. package/src/scripts/workflow/landed-worktree-reaper.js +2 -1
  50. package/src/scripts/workflow/landed-worktree-reaper.js.map +1 -1
  51. package/src/scripts/workflow/merge-end.d.ts +1 -1
  52. package/src/scripts/workflow/merge-end.js +6 -5
  53. package/src/scripts/workflow/merge-end.js.map +1 -1
  54. package/src/scripts/workflow/merge-info-index.d.ts +1 -1
  55. package/src/scripts/workflow/merge-info-index.js +5 -4
  56. package/src/scripts/workflow/merge-info-index.js.map +1 -1
  57. package/src/scripts/workflow/merge-start.d.ts +1 -1
  58. package/src/scripts/workflow/merge-start.js +11 -9
  59. package/src/scripts/workflow/merge-start.js.map +1 -1
  60. package/src/scripts/workflow/merge-state.d.ts +1 -1
  61. package/src/scripts/workflow/merge-state.js +3 -2
  62. package/src/scripts/workflow/merge-state.js.map +1 -1
  63. package/src/scripts/workflow/provenance-enforcer.js +5 -4
  64. package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
  65. package/src/scripts/workflow/push-dev-state.d.ts +1 -1
  66. package/src/scripts/workflow/push-dev-state.js +4 -2
  67. package/src/scripts/workflow/push-dev-state.js.map +1 -1
  68. package/src/scripts/workflow/review-round-state.d.ts +2 -1
  69. package/src/scripts/workflow/review-round-state.js +22 -20
  70. package/src/scripts/workflow/review-round-state.js.map +1 -1
  71. package/src/scripts/workflow/review-stage-receipt.js +2 -1
  72. package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
  73. package/src/scripts/workflow/reviewer-briefing-builder.js +2 -1
  74. package/src/scripts/workflow/reviewer-briefing-builder.js.map +1 -1
  75. package/src/scripts/workflow/reviewer-identity.d.ts +1 -1
  76. package/src/scripts/workflow/reviewer-identity.js +8 -7
  77. package/src/scripts/workflow/reviewer-identity.js.map +1 -1
  78. package/src/scripts/workflow/reviewer-verdict-gate.js +2 -1
  79. package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
  80. package/src/scripts/workflow/run-update.d.ts +1 -1
  81. package/src/scripts/workflow/run-update.js +4 -4
  82. package/src/scripts/workflow/run-update.js.map +1 -1
  83. package/src/scripts/workflow/verdict-provenance.d.ts +2 -1
  84. package/src/scripts/workflow/verdict-provenance.js +10 -7
  85. package/src/scripts/workflow/verdict-provenance.js.map +1 -1
@@ -5,6 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const child_process_1 = require("child_process");
6
6
  const fs = tslib_1.__importStar(require("fs"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
8
9
  const rules_config_1 = require("@webpieces/rules-config");
9
10
  const inversify_1 = require("inversify");
10
11
  const reap_outcome_1 = require("./reap-outcome");
@@ -220,7 +221,7 @@ let LandedWorktreeReaper = class LandedWorktreeReaper {
220
221
  exports.LandedWorktreeReaper = LandedWorktreeReaper;
221
222
  exports.LandedWorktreeReaper = LandedWorktreeReaper = tslib_1.__decorate([
222
223
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
223
- tslib_1.__metadata("design:paramtypes", [rules_config_1.WorktreeService,
224
+ tslib_1.__metadata("design:paramtypes", [repo_workflow_core_1.WorktreeService,
224
225
  reap_outcome_1.ReapOutcomeSignal])
225
226
  ], LandedWorktreeReaper);
226
227
  //# sourceMappingURL=landed-worktree-reaper.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"landed-worktree-reaper.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-worktree-reaper.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4E;AAC5E,yCAA2D;AAE3D,iDAA4F;AAE5F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;GAGG;AACH,MAAa,mBAAmB;IAC5B,mEAAmE;IAC1D,YAAY,CAAS;IACrB,MAAM,CAAS;IACxB;;;;OAIG;IACM,IAAI,CAAS;IACtB,gGAAgG;IACvF,WAAW,CAAS;IAC7B,kFAAkF;IACzE,WAAW,CAAS;IAC7B,kGAAkG;IACzF,cAAc,CAAS;IAChC;;;;;;;OAOG;IACM,YAAY,CAAU;IAC/B,8FAA8F;IACrF,OAAO,CAAU;IAE1B,yDAAyD;IACzD,YACI,YAAoB,EACpB,MAAc,EACd,IAAY,EACZ,WAAmB,EACnB,WAAmB,EACnB,cAAsB,EACtB,YAAqB;QAErB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,YAAY,GAAG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AC,OAAO,CAAC,YAAY,EAAE,CAAC;YACxB,OAAO,QAAQ,OAAO,CAAC,YAAY,iDAAiD,CAAC;QACzF,CAAC;QACD,OAAO,YAAY,OAAO,CAAC,YAAY,2DAA2D;cAC5F,2EAA2E;YAC7E,yFAAyF;YACzF,0FAA0F;cACxF,kBAAkB,OAAO,CAAC,WAAW,KAAK,CAAC;IACrD,CAAC;IAED;;;;;;;;;OASG;IACO,eAAe;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,qBAAqB,CAAC,CAAC;QAChE,OAAO,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IAC7C,CAAC;CACJ,CAAA;AArJY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGL,8BAAe;QAClB,gCAAiB;GAHrC,oBAAoB,CAqJhC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Worktree, WorktreeService, atRoot } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { ReapOutcomeReport, ReapOutcomeSignal, REAP_OUTCOME_MISSING } from './reap-outcome';\n\n/**\n * The RE-EXEC half of `wp-land-pr`: reap the worktree the command is standing in, from a process that\n * is NOT standing in it.\n *\n * THE PROBLEM. `wp-land-pr` squash-merges the branch checked out in the worktree it runs in. The\n * moment that lands, both the branch and the directory are dead — but removing them from in here means\n * deleting the files underneath the running process, which is exactly what every rail in WorktreeReaper\n * refuses. #512 took this to an honest halfway point: print `cd <primary> && pnpm wp-cleanup` and stop.\n * Correct, and the single most-skipped step in the whole flow, because the PR is already landed and the\n * work FEELS done. Every skipped one leaves a corpse, and corpses are what trip branch-creation-guard.\n *\n * THE FIX. Do not reap in this process at all — hand the reap to a CHILD process whose `cwd` is the\n * PRIMARY CLONE. The child's cwd is a directory nobody is deleting, so `git worktree remove` is an\n * ordinary removal of somebody else's directory, and every existing rail still holds inside the child\n * (it refuses its own cwd, which is now the primary clone, and it refuses the primary clone by name).\n *\n * WHY `WorktreeService` AND NOT `EffectiveTreeResolver`. EffectiveTreeResolver (ai-hook-rules) answers\n * \"which tree does this BASH COMMAND STRING act on\" — it takes a command, resolves its leading `cd`\n * run, and classifies foreign/outside repos for the PreToolUse guards. There is no command string\n * here, pr-gate does not (and must not) depend on ai-hook-rules, and the only question being asked is\n * \"which of git's worktrees is the primary clone, and which one holds this branch\". That is\n * WorktreeService's whole job, and it is already the authority WorktreeReaper itself uses to decide\n * what is protected — using a second resolver would risk the two disagreeing about which tree we are\n * in, which for a directory deletion is the one disagreement nobody survives.\n *\n * WHY A CHILD AND NOT AN IN-PROCESS `chdir`. `process.chdir(primary)` would leave this node process's\n * own module graph rooted in a directory that is about to be deleted, and its lazily-resolved requires\n * with it. The child is spawned from THIS package's own files (same version — no skew with whatever\n * the primary clone has installed), and it finishes loading them before it removes anything.\n */\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * Data-only (per CLAUDE.md, classes for data). The decision about the just-landed worktree: which\n * directory, which branch, where the reap must run FROM, and — when it cannot run — why not.\n */\nexport class WorktreeReapHandoff {\n /** The linked worktree holding the branch that was just landed. */\n readonly worktreePath: string;\n readonly branch: string;\n /**\n * That worktree's HEAD — which is, by construction, the exact commit GitHub squashed (see\n * LandedTreeResolver). Carried so the child can re-verify the SELECTION rather than take a path on\n * trust: a branch name is not an identity, and this is the half that makes it one.\n */\n readonly head: string;\n /** The primary clone — the child's `cwd`, and the directory a human must `cd` to afterwards. */\n readonly primaryPath: string;\n /** The compiled entry the child runs. '' when it could not be located on disk. */\n readonly entryScript: string;\n /** '' when the hand-off can run; otherwise the reason it cannot, in one human-readable clause. */\n readonly blockedBecause: string;\n /**\n * Is the OPERATOR'S OWN shell inside the directory about to be removed?\n *\n * True is the `/full-cycle` case (the agent lands its own PR from its own worktree) and it is the\n * only case where \"your cwd no longer exists\" is a true sentence worth shouting. False is the\n * coordinator case — `wp-land-pr --pr <n>` from the primary clone — where saying it would send a\n * reader chasing a directory move they do not need to make.\n */\n readonly standingHere: boolean;\n /** Precomputed (as EffectiveTree does with `redirected`) so no caller re-derives the rule. */\n readonly canReap: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n worktreePath: string,\n branch: string,\n head: string,\n primaryPath: string,\n entryScript: string,\n blockedBecause: string,\n standingHere: boolean,\n ) {\n this.worktreePath = worktreePath;\n this.branch = branch;\n this.head = head;\n this.primaryPath = primaryPath;\n this.entryScript = entryScript;\n this.blockedBecause = blockedBecause;\n this.standingHere = standingHere;\n this.canReap = blockedBecause === '';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class LandedWorktreeReaper {\n constructor(\n private readonly worktrees: WorktreeService,\n private readonly signal: ReapOutcomeSignal,\n ) {}\n\n /**\n * Is there a worktree to reap at all, and can the hand-off run?\n *\n * IT IS TOLD WHICH TREE, AND NO LONGER LOOKS. This used to call `currentWorktree(repoRoot)` and reap\n * only when the tree it was STANDING IN held the landed branch — which made the whole #512 mechanism\n * dead code in the one case it was built for, because `pnpm` hoists a bin's cwd out of a nested\n * `.claude/worktrees/**` worktree and into the primary clone, where `isMain` is true and this\n * returned null. Worse, \"the tree I am in\" was never the right question: a coordinator landing a dead\n * agent's PR is standing somewhere else entirely. LandedTreeResolver answers the right one — which\n * tree's HEAD is the commit GitHub squashed — and hands the answer here.\n *\n * `null` means there is genuinely no worktree to reap: the branch lived only in the primary clone, or\n * nowhere the sha agrees with. That is the ordinary `pnpm wp-cleanup` case and needs no special\n * sentence. A non-null handoff with `canReap === false` means there IS a corpse but the re-exec is\n * not safely achievable, which is the case that must keep the manual notice.\n */\n plan(repoRoot: string, landed: Worktree | null, invocationCwd: string): WorktreeReapHandoff | null {\n if (landed === null || landed.isMain) return null;\n const standingHere = this.isInside(invocationCwd, landed.path);\n\n const primary = this.worktrees.listWorktrees(repoRoot)\n .find((tree: Worktree): boolean => tree.isMain);\n if (primary === undefined) {\n return new WorktreeReapHandoff(\n landed.path, landed.branch, landed.head, '<the primary clone>', '',\n 'git did not report a primary clone, so there is no safe directory to reap from',\n standingHere);\n }\n\n const entry = this.reapEntryScript();\n if (entry === '') {\n return new WorktreeReapHandoff(\n landed.path, landed.branch, landed.head, primary.path, '',\n 'the reap entry point is not on disk (this package is running unbuilt)', standingHere);\n }\n return new WorktreeReapHandoff(\n landed.path, landed.branch, landed.head, primary.path, entry, '', standingHere);\n }\n\n /**\n * Is `cwd` the worktree itself or somewhere beneath it? A path COMPARISON, not a git question:\n * the operator may have been in a subdirectory when they ran the command, and that shell is just as\n * dead once the tree goes. Both sides are resolved first so `.`/`..` and a trailing slash cannot\n * turn a match into a miss.\n */\n private isInside(cwd: string, worktreePath: string): boolean {\n const from = path.resolve(cwd);\n const tree = path.resolve(worktreePath);\n return from === tree || from.startsWith(tree + path.sep);\n }\n\n /**\n * Run the reap in a child process rooted in the primary clone, and render what happened.\n *\n * stdin is `ignore` deliberately: the child must never be able to ask a question. A prompt printed\n * into a landing recap nobody is watching is not consent, and this reap is authorised by the merge\n * that just succeeded, not by an answer.\n *\n * THE EXIT CODE IS NOT THE ANSWER. The child refuses by PRINTING and exiting 0 on purpose — a\n * non-zero exit after a successful merge would report a landed PR as a failed command. So `exit 0`\n * only means \"the child ran\"; whether the DIRECTORY is gone is a separate statement it makes through\n * ReapOutcomeSignal, and that is the one that gates the \"your cwd no longer exists\" notice.\n */\n handOff(handoff: WorktreeReapHandoff): string {\n const result = spawnSync(\n process.execPath, [handoff.entryScript, handoff.worktreePath, handoff.branch, handoff.head],\n { cwd: handoff.primaryPath, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });\n\n const report = this.signal.read(`${result.stdout ?? ''}${result.stderr ?? ''}`);\n const output = report.text.trimEnd();\n const head = '\\n' + SEP + `🌲 Reaping ${handoff.worktreePath} from ${handoff.primaryPath}\\n` + SEP + '\\n'\n + ` The branch just landed, so that directory is dead. The reap runs in a child process\\n`\n + ` whose cwd is the primary clone — nothing deletes the directory it is standing in.\\n\\n`;\n const body = head + (output !== '' ? output + '\\n' : '');\n\n if (result.status !== 0 || !report.removed) {\n return body + this.notRemoved(result.status, report) + this.manualNotice(handoff);\n }\n return body + this.afterReap(handoff);\n }\n\n /**\n * WHY the directory is still there, distinguishing the two cases a single exit code conflated: the\n * child broke (non-zero), versus the child worked perfectly and DECLINED (exit 0, outcome refused).\n * `--force` is absent from both, and from every path below them: git refusing to remove a worktree\n * holding untracked files is work no archive tag captured.\n */\n private notRemoved(status: number | null, report: ReapOutcomeReport): string {\n if (status !== 0) {\n return `\\n ⚠️ The reap did not complete (exit ${String(status ?? -1)}). Nothing was forced.\\n`;\n }\n const why = report.outcome === REAP_OUTCOME_MISSING\n ? 'the child ended without reporting an outcome'\n : `the child reported '${report.outcome}'`;\n return `\\n ⚠️ The worktree was NOT removed — ${why}. It is still on disk.\\n`\n + ' Nothing was forced.\\n';\n }\n\n /**\n * The #512 notice, kept verbatim in spirit for every case the re-exec cannot cover. An honest\n * limitation beats a command that deletes its own working directory mid-run.\n */\n manualNotice(handoff: WorktreeReapHandoff): string {\n const why = handoff.blockedBecause !== '' ? ` (${handoff.blockedBecause})\\n` : '';\n return ` Next: this branch is checked out in ${handoff.worktreePath}, so neither it nor that\\n`\n + ' worktree can be removed from here. Run cleanup from the primary clone instead:\\n'\n + ` ${atRoot(handoff.primaryPath, 'pnpm wp-cleanup')}\\n`\n + why\n + ` It archives ${handoff.branch} as a tag, removes ${handoff.worktreePath}, then deletes the branch.\\n`;\n }\n\n /**\n * The one thing a human or agent MUST be told after a successful reap — but only when it is TRUE of\n * them. Landing from inside the tree that just went (the `/full-cycle` case) leaves the shell in a\n * deleted directory and every following relative path is a mystery ENOENT until they move. Landing a\n * dead agent's PR from the primary clone removes somebody ELSE's directory, and telling that operator\n * to `cd` somewhere sends them chasing a move they do not need to make.\n */\n private afterReap(handoff: WorktreeReapHandoff): string {\n if (!handoff.standingHere) {\n return `\\n ${handoff.worktreePath} is gone. Your own shell was never inside it.\\n`;\n }\n return `\\n ⚠️ ${handoff.worktreePath} NO LONGER EXISTS — your shell is standing in a deleted\\n`\n + ' directory, and every following command will fail until you move:\\n'\n // Single-quoted for the same reason atRoot() quotes: a primary clone under a path with a\n // space (`/Users/dean hiller/…`, \"Google Drive\", iCloud) makes a bare `cd` two arguments.\n + ` cd '${handoff.primaryPath}'\\n`;\n }\n\n /**\n * WHERE the child's entry point lives — a seam, overridden in the spec, because under vitest this\n * package runs from `.ts` sources and the compiled sibling does not exist.\n *\n * Resolved from `__dirname`, i.e. from THIS package's own installed files, NOT by remapping a path\n * into the primary clone. The primary clone may have a different @webpieces/pr-gate version\n * installed, and re-exec'ing a build that predates this feature would silently do something else.\n * The files are read into the child before it removes anything, so the directory going away\n * underneath them afterwards is harmless.\n */\n protected reapEntryScript(): string {\n const entry = path.join(__dirname, '..', 'wp-reap-worktree.js');\n return fs.existsSync(entry) ? entry : '';\n }\n}\n"]}
1
+ {"version":3,"file":"landed-worktree-reaper.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-worktree-reaper.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,sEAA0E;AAC1E,0DAAiD;AACjD,yCAA2D;AAE3D,iDAA4F;AAE5F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;GAGG;AACH,MAAa,mBAAmB;IAC5B,mEAAmE;IAC1D,YAAY,CAAS;IACrB,MAAM,CAAS;IACxB;;;;OAIG;IACM,IAAI,CAAS;IACtB,gGAAgG;IACvF,WAAW,CAAS;IAC7B,kFAAkF;IACzE,WAAW,CAAS;IAC7B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,8BAA8B,CAAC;IACzC,CAAC;IAED;;;OAGG;IACH,YAAY,CAAC,OAA4B;QACrC,MAAM,GAAG,GAAG,OAAO,CAAC,cAAc,KAAK,EAAE,CAAC,CAAC,CAAC,aAAa,OAAO,CAAC,cAAc,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1F,OAAO,0CAA0C,OAAO,CAAC,YAAY,4BAA4B;cAC3F,2FAA2F;cAC3F,cAAc,IAAA,qBAAM,EAAC,OAAO,CAAC,WAAW,EAAE,iBAAiB,CAAC,IAAI;cAChE,GAAG;cACH,wBAAwB,OAAO,CAAC,MAAM,sBAAsB,OAAO,CAAC,YAAY,8BAA8B,CAAC;IACzH,CAAC;IAED;;;;;;OAMG;IACK,SAAS,CAAC,OAA4B;QAC1C,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC;YACxB,OAAO,QAAQ,OAAO,CAAC,YAAY,iDAAiD,CAAC;QACzF,CAAC;QACD,OAAO,YAAY,OAAO,CAAC,YAAY,2DAA2D;cAC5F,2EAA2E;YAC7E,yFAAyF;YACzF,0FAA0F;cACxF,kBAAkB,OAAO,CAAC,WAAW,KAAK,CAAC;IACrD,CAAC;IAED;;;;;;;;;OASG;IACO,eAAe;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,qBAAqB,CAAC,CAAC;QAChE,OAAO,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IAC7C,CAAC;CACJ,CAAA;AArJY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGL,oCAAe;QAClB,gCAAiB;GAHrC,oBAAoB,CAqJhC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';\nimport { atRoot } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { ReapOutcomeReport, ReapOutcomeSignal, REAP_OUTCOME_MISSING } from './reap-outcome';\n\n/**\n * The RE-EXEC half of `wp-land-pr`: reap the worktree the command is standing in, from a process that\n * is NOT standing in it.\n *\n * THE PROBLEM. `wp-land-pr` squash-merges the branch checked out in the worktree it runs in. The\n * moment that lands, both the branch and the directory are dead — but removing them from in here means\n * deleting the files underneath the running process, which is exactly what every rail in WorktreeReaper\n * refuses. #512 took this to an honest halfway point: print `cd <primary> && pnpm wp-cleanup` and stop.\n * Correct, and the single most-skipped step in the whole flow, because the PR is already landed and the\n * work FEELS done. Every skipped one leaves a corpse, and corpses are what trip branch-creation-guard.\n *\n * THE FIX. Do not reap in this process at all — hand the reap to a CHILD process whose `cwd` is the\n * PRIMARY CLONE. The child's cwd is a directory nobody is deleting, so `git worktree remove` is an\n * ordinary removal of somebody else's directory, and every existing rail still holds inside the child\n * (it refuses its own cwd, which is now the primary clone, and it refuses the primary clone by name).\n *\n * WHY `WorktreeService` AND NOT `EffectiveTreeResolver`. EffectiveTreeResolver (ai-hook-rules) answers\n * \"which tree does this BASH COMMAND STRING act on\" — it takes a command, resolves its leading `cd`\n * run, and classifies foreign/outside repos for the PreToolUse guards. There is no command string\n * here, pr-gate does not (and must not) depend on ai-hook-rules, and the only question being asked is\n * \"which of git's worktrees is the primary clone, and which one holds this branch\". That is\n * WorktreeService's whole job, and it is already the authority WorktreeReaper itself uses to decide\n * what is protected — using a second resolver would risk the two disagreeing about which tree we are\n * in, which for a directory deletion is the one disagreement nobody survives.\n *\n * WHY A CHILD AND NOT AN IN-PROCESS `chdir`. `process.chdir(primary)` would leave this node process's\n * own module graph rooted in a directory that is about to be deleted, and its lazily-resolved requires\n * with it. The child is spawned from THIS package's own files (same version — no skew with whatever\n * the primary clone has installed), and it finishes loading them before it removes anything.\n */\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * Data-only (per CLAUDE.md, classes for data). The decision about the just-landed worktree: which\n * directory, which branch, where the reap must run FROM, and — when it cannot run — why not.\n */\nexport class WorktreeReapHandoff {\n /** The linked worktree holding the branch that was just landed. */\n readonly worktreePath: string;\n readonly branch: string;\n /**\n * That worktree's HEAD — which is, by construction, the exact commit GitHub squashed (see\n * LandedTreeResolver). Carried so the child can re-verify the SELECTION rather than take a path on\n * trust: a branch name is not an identity, and this is the half that makes it one.\n */\n readonly head: string;\n /** The primary clone — the child's `cwd`, and the directory a human must `cd` to afterwards. */\n readonly primaryPath: string;\n /** The compiled entry the child runs. '' when it could not be located on disk. */\n readonly entryScript: string;\n /** '' when the hand-off can run; otherwise the reason it cannot, in one human-readable clause. */\n readonly blockedBecause: string;\n /**\n * Is the OPERATOR'S OWN shell inside the directory about to be removed?\n *\n * True is the `/full-cycle` case (the agent lands its own PR from its own worktree) and it is the\n * only case where \"your cwd no longer exists\" is a true sentence worth shouting. False is the\n * coordinator case — `wp-land-pr --pr <n>` from the primary clone — where saying it would send a\n * reader chasing a directory move they do not need to make.\n */\n readonly standingHere: boolean;\n /** Precomputed (as EffectiveTree does with `redirected`) so no caller re-derives the rule. */\n readonly canReap: boolean;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n worktreePath: string,\n branch: string,\n head: string,\n primaryPath: string,\n entryScript: string,\n blockedBecause: string,\n standingHere: boolean,\n ) {\n this.worktreePath = worktreePath;\n this.branch = branch;\n this.head = head;\n this.primaryPath = primaryPath;\n this.entryScript = entryScript;\n this.blockedBecause = blockedBecause;\n this.standingHere = standingHere;\n this.canReap = blockedBecause === '';\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class LandedWorktreeReaper {\n constructor(\n private readonly worktrees: WorktreeService,\n private readonly signal: ReapOutcomeSignal,\n ) {}\n\n /**\n * Is there a worktree to reap at all, and can the hand-off run?\n *\n * IT IS TOLD WHICH TREE, AND NO LONGER LOOKS. This used to call `currentWorktree(repoRoot)` and reap\n * only when the tree it was STANDING IN held the landed branch — which made the whole #512 mechanism\n * dead code in the one case it was built for, because `pnpm` hoists a bin's cwd out of a nested\n * `.claude/worktrees/**` worktree and into the primary clone, where `isMain` is true and this\n * returned null. Worse, \"the tree I am in\" was never the right question: a coordinator landing a dead\n * agent's PR is standing somewhere else entirely. LandedTreeResolver answers the right one — which\n * tree's HEAD is the commit GitHub squashed — and hands the answer here.\n *\n * `null` means there is genuinely no worktree to reap: the branch lived only in the primary clone, or\n * nowhere the sha agrees with. That is the ordinary `pnpm wp-cleanup` case and needs no special\n * sentence. A non-null handoff with `canReap === false` means there IS a corpse but the re-exec is\n * not safely achievable, which is the case that must keep the manual notice.\n */\n plan(repoRoot: string, landed: Worktree | null, invocationCwd: string): WorktreeReapHandoff | null {\n if (landed === null || landed.isMain) return null;\n const standingHere = this.isInside(invocationCwd, landed.path);\n\n const primary = this.worktrees.listWorktrees(repoRoot)\n .find((tree: Worktree): boolean => tree.isMain);\n if (primary === undefined) {\n return new WorktreeReapHandoff(\n landed.path, landed.branch, landed.head, '<the primary clone>', '',\n 'git did not report a primary clone, so there is no safe directory to reap from',\n standingHere);\n }\n\n const entry = this.reapEntryScript();\n if (entry === '') {\n return new WorktreeReapHandoff(\n landed.path, landed.branch, landed.head, primary.path, '',\n 'the reap entry point is not on disk (this package is running unbuilt)', standingHere);\n }\n return new WorktreeReapHandoff(\n landed.path, landed.branch, landed.head, primary.path, entry, '', standingHere);\n }\n\n /**\n * Is `cwd` the worktree itself or somewhere beneath it? A path COMPARISON, not a git question:\n * the operator may have been in a subdirectory when they ran the command, and that shell is just as\n * dead once the tree goes. Both sides are resolved first so `.`/`..` and a trailing slash cannot\n * turn a match into a miss.\n */\n private isInside(cwd: string, worktreePath: string): boolean {\n const from = path.resolve(cwd);\n const tree = path.resolve(worktreePath);\n return from === tree || from.startsWith(tree + path.sep);\n }\n\n /**\n * Run the reap in a child process rooted in the primary clone, and render what happened.\n *\n * stdin is `ignore` deliberately: the child must never be able to ask a question. A prompt printed\n * into a landing recap nobody is watching is not consent, and this reap is authorised by the merge\n * that just succeeded, not by an answer.\n *\n * THE EXIT CODE IS NOT THE ANSWER. The child refuses by PRINTING and exiting 0 on purpose — a\n * non-zero exit after a successful merge would report a landed PR as a failed command. So `exit 0`\n * only means \"the child ran\"; whether the DIRECTORY is gone is a separate statement it makes through\n * ReapOutcomeSignal, and that is the one that gates the \"your cwd no longer exists\" notice.\n */\n handOff(handoff: WorktreeReapHandoff): string {\n const result = spawnSync(\n process.execPath, [handoff.entryScript, handoff.worktreePath, handoff.branch, handoff.head],\n { cwd: handoff.primaryPath, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });\n\n const report = this.signal.read(`${result.stdout ?? ''}${result.stderr ?? ''}`);\n const output = report.text.trimEnd();\n const head = '\\n' + SEP + `🌲 Reaping ${handoff.worktreePath} from ${handoff.primaryPath}\\n` + SEP + '\\n'\n + ` The branch just landed, so that directory is dead. The reap runs in a child process\\n`\n + ` whose cwd is the primary clone — nothing deletes the directory it is standing in.\\n\\n`;\n const body = head + (output !== '' ? output + '\\n' : '');\n\n if (result.status !== 0 || !report.removed) {\n return body + this.notRemoved(result.status, report) + this.manualNotice(handoff);\n }\n return body + this.afterReap(handoff);\n }\n\n /**\n * WHY the directory is still there, distinguishing the two cases a single exit code conflated: the\n * child broke (non-zero), versus the child worked perfectly and DECLINED (exit 0, outcome refused).\n * `--force` is absent from both, and from every path below them: git refusing to remove a worktree\n * holding untracked files is work no archive tag captured.\n */\n private notRemoved(status: number | null, report: ReapOutcomeReport): string {\n if (status !== 0) {\n return `\\n ⚠️ The reap did not complete (exit ${String(status ?? -1)}). Nothing was forced.\\n`;\n }\n const why = report.outcome === REAP_OUTCOME_MISSING\n ? 'the child ended without reporting an outcome'\n : `the child reported '${report.outcome}'`;\n return `\\n ⚠️ The worktree was NOT removed — ${why}. It is still on disk.\\n`\n + ' Nothing was forced.\\n';\n }\n\n /**\n * The #512 notice, kept verbatim in spirit for every case the re-exec cannot cover. An honest\n * limitation beats a command that deletes its own working directory mid-run.\n */\n manualNotice(handoff: WorktreeReapHandoff): string {\n const why = handoff.blockedBecause !== '' ? ` (${handoff.blockedBecause})\\n` : '';\n return ` Next: this branch is checked out in ${handoff.worktreePath}, so neither it nor that\\n`\n + ' worktree can be removed from here. Run cleanup from the primary clone instead:\\n'\n + ` ${atRoot(handoff.primaryPath, 'pnpm wp-cleanup')}\\n`\n + why\n + ` It archives ${handoff.branch} as a tag, removes ${handoff.worktreePath}, then deletes the branch.\\n`;\n }\n\n /**\n * The one thing a human or agent MUST be told after a successful reap — but only when it is TRUE of\n * them. Landing from inside the tree that just went (the `/full-cycle` case) leaves the shell in a\n * deleted directory and every following relative path is a mystery ENOENT until they move. Landing a\n * dead agent's PR from the primary clone removes somebody ELSE's directory, and telling that operator\n * to `cd` somewhere sends them chasing a move they do not need to make.\n */\n private afterReap(handoff: WorktreeReapHandoff): string {\n if (!handoff.standingHere) {\n return `\\n ${handoff.worktreePath} is gone. Your own shell was never inside it.\\n`;\n }\n return `\\n ⚠️ ${handoff.worktreePath} NO LONGER EXISTS — your shell is standing in a deleted\\n`\n + ' directory, and every following command will fail until you move:\\n'\n // Single-quoted for the same reason atRoot() quotes: a primary clone under a path with a\n // space (`/Users/dean hiller/…`, \"Google Drive\", iCloud) makes a bare `cd` two arguments.\n + ` cd '${handoff.primaryPath}'\\n`;\n }\n\n /**\n * WHERE the child's entry point lives — a seam, overridden in the spec, because under vitest this\n * package runs from `.ts` sources and the compiled sibling does not exist.\n *\n * Resolved from `__dirname`, i.e. from THIS package's own installed files, NOT by remapping a path\n * into the primary clone. The primary clone may have a different @webpieces/pr-gate version\n * installed, and re-exec'ing a build that predates this feature would silently do something else.\n * The files are read into the child before it removes anything, so the directory going away\n * underneath them afterwards is harmless.\n */\n protected reapEntryScript(): string {\n const entry = path.join(__dirname, '..', 'wp-reap-worktree.js');\n return fs.existsSync(entry) ? entry : '';\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { MutationVerb } from '@webpieces/rules-config';
1
+ import { MutationVerb } from '@webpieces/repo-workflow-core';
2
2
  import { BranchNaming } from './branch-naming';
3
3
  import { CleanTmp } from './cleanTmp';
4
4
  import { GitExec } from './git-exec';
@@ -6,6 +6,7 @@ const child_process_1 = require("child_process");
6
6
  const fs = tslib_1.__importStar(require("fs"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
8
  const rules_config_1 = require("@webpieces/rules-config");
9
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
9
10
  const inversify_1 = require("inversify");
10
11
  const branch_naming_1 = require("./branch-naming");
11
12
  const cleanTmp_1 = require("./cleanTmp");
@@ -152,13 +153,13 @@ let MergeEnd = class MergeEnd {
152
153
  this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');
153
154
  }
154
155
  this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');
155
- const renameEvent = new rules_config_1.BranchMutationEvent(verb, 'RENAME');
156
+ const renameEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'RENAME');
156
157
  renameEvent.fromBranch = ctx.currentBranch;
157
158
  renameEvent.toBranch = base;
158
- (0, rules_config_1.logBranchMutation)(repoRoot, renameEvent);
159
+ (0, repo_workflow_core_1.logBranchMutation)(repoRoot, renameEvent);
159
160
  // Branch now contains origin/main — stamp a clean main-sync status so the feature-branch-guard
160
161
  // unblocks edits immediately (no wait for the async refresher).
161
- (0, rules_config_1.stampCleanMainSyncStatus)(repoRoot);
162
+ (0, repo_workflow_core_1.stampCleanMainSyncStatus)(repoRoot);
162
163
  // Clean sync → the pre-merge snapshot was never needed; delete it LAST. Conflict sync → keep it.
163
164
  // ALSO keep it when we did not push: the squash rewrite then exists ONLY in this working copy, so
164
165
  // deleting the snapshot would leave a history rewrite with no copy anywhere. It is disposable only
@@ -167,12 +168,12 @@ let MergeEnd = class MergeEnd {
167
168
  if (!backupKept && this.localBranchExists(ctx.backupBranch)) {
168
169
  this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');
169
170
  }
170
- const finalizeEvent = new rules_config_1.BranchMutationEvent(verb, 'FINALIZE');
171
+ const finalizeEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'FINALIZE');
171
172
  finalizeEvent.fromBranch = ctx.currentBranch;
172
173
  finalizeEvent.toBranch = base;
173
174
  finalizeEvent.outcome = 'finalized';
174
175
  finalizeEvent.artifacts = [backupKept ? `backup=${ctx.backupBranch}` : `backupDeleted=${ctx.backupBranch}`, `remotePR=${base}`];
175
- (0, rules_config_1.logBranchMutation)(repoRoot, finalizeEvent);
176
+ (0, repo_workflow_core_1.logBranchMutation)(repoRoot, finalizeEvent);
176
177
  this.printSyncRecap(base, ctx.backupBranch, ctx.prNumber, new SyncRecap(pushed, !pushRemote, hadConflict, backupKept));
177
178
  }
178
179
  // Say WHY nothing was pushed, so an unpushed branch never looks like a failure. Always returns false
@@ -1 +1 @@
1
- {"version":3,"file":"merge-end.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-end.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAGiC;AACjC,yCAA2D;AAC3D,mDAA+C;AAC/C,yCAAsC;AACtC,yCAAqC;AAErC,+CAA2C;AAE3C,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,sGAAsG;AACtG,kGAAkG;AAClG,MAAM,SAAS;IACX,MAAM,CAAU;IAChB,YAAY,CAAU;IACtB,WAAW,CAAU;IACrB,UAAU,CAAU;IAEpB,YAAY,MAAe,EAAE,YAAqB,EAAE,WAAoB,EAAE,UAAmB;QACzF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,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AAO;QACJ,wBAAU;GALlC,QAAQ,CAsMpB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n MERGE_EXPLANATION_FILE, stampCleanMainSyncStatus, CliExitError,\n MutationVerb, BranchMutationEvent, logBranchMutation,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\nimport { CleanTmp } from './cleanTmp';\nimport { GitExec } from './git-exec';\nimport { MergeContext } from './merge-start';\nimport { MergeState } from './merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// What finalizing actually did, for the recap. Data-only. `pushed` and `pushDeferred` are distinct on\n// purpose: \"we chose not to push yet\" must not be reported like \"there was no remote to push to\".\nclass SyncRecap {\n pushed: boolean;\n pushDeferred: boolean;\n hadConflict: boolean;\n backupKept: boolean;\n\n constructor(pushed: boolean, pushDeferred: boolean, hadConflict: boolean, backupKept: boolean) {\n this.pushed = pushed;\n this.pushDeferred = pushDeferred;\n this.hadConflict = hadConflict;\n this.backupKept = backupKept;\n }\n}\n\n// How a merge should be finalized. Data-only (per CLAUDE.md, classes for data) — bundled rather than\n// added as more positional params, which mergeEnd already has enough of.\nexport class MergeEndOptions {\n // Non-null means the AI resolved a conflict and it must be validated + committed before finalizing.\n // Null means merge-START already committed a clean merge, so finalize only.\n conflictedFiles: string[] | null;\n\n /**\n * Whether finalizing may push the squashed branch to origin.\n *\n * FALSE for the PR flow (`wp-start-upsert-pr` / `wp-finish-upsert-pr`), which pushes EXACTLY ONCE,\n * from GatedPrPublisher, after summary.json + every BLOCK checklist + the authoritative build gate\n * have passed and the gated PR body is already up. Code must not reach the remote ahead of its\n * review, and an early push here is also what fires `pull_request:synchronize` against a PR body\n * still carrying the previous run's gate token — the flap the whole gate redesign is removing.\n *\n * TRUE for the update-only flow (`wp-start-update` / `wp-finish-update`), which has no later push;\n * finalizing IS the end of that flow, so not pushing would silently strand the rewrite locally.\n */\n pushRemote: boolean;\n\n constructor(conflictedFiles: string[] | null, pushRemote: boolean) {\n this.conflictedFiles = conflictedFiles;\n this.pushRemote = pushRemote;\n }\n}\n\n// merge-END: the second half of the 3-point squash-merge lifecycle, symmetric with merge-START. Given\n// the branch context, it (optionally) validates + commits the AI's conflict resolution, then ALWAYS\n// finalizes — force-pushes `<branch>Squash` to the stable feature branch and renames it BACK to that\n// same feature name (local == remote == PR head), stamps a clean main-sync status, clears the marker,\n// and sweeps stale tmp. RunUpdate (clean path / validated resume), wp-finish-update, and\n// wp-finish-upsert-pr (conflict resolution) all call THIS, so finalization happens in exactly one place.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeEnd {\n constructor(\n private readonly branchNaming: BranchNaming,\n private readonly cleanTmpService: CleanTmp,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n ) {}\n\n /**\n * Complete a 3-point squash merge. See {@link MergeEndOptions} for what `conflictedFiles` and\n * `pushRemote` mean. Either way the merge ends fully finalized on the feature branch.\n */\n async mergeEnd(\n repoRoot: string, verb: MutationVerb, mergeDir: string, ctx: MergeContext, options: MergeEndOptions,\n ): Promise<void> {\n const conflictedFiles = options.conflictedFiles;\n if (conflictedFiles !== null) {\n process.stdout.write('\\n' + SEP + '🔎 Validating Merge Resolution\\n' + SEP + '\\n');\n this.validateResolution(repoRoot, verb, mergeDir, conflictedFiles);\n // Stage the AI's resolved conflicts, but NEVER sweep untracked files into the squash commit.\n // Fail on untracked so the AI commits or deletes them explicitly; then `git add -u` stages\n // tracked resolutions only.\n this.gitExec.assertNoUntracked(repoRoot);\n this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (!nothingStaged) {\n this.gitExec.runGitChecked(\n ['commit', '-m', `Squash merge of ${ctx.currentBranch} (conflicts resolved)`],\n 'Failed to commit resolved merge',\n );\n }\n fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');\n process.stdout.write('\\n✅ Merge validated and committed.\\n');\n }\n\n // A marker in THIS run dir means the sync hit conflicts (marker is written only on hand-back).\n // Read it BEFORE clearMergeMarker so finalize knows whether to keep the pre-merge snapshot.\n const hadConflict = this.mergeState.readMergeMarker(mergeDir) !== null;\n this.finalizeBranch(repoRoot, verb, ctx, hadConflict, options.pushRemote);\n this.mergeState.clearMergeMarker(mergeDir);\n await this.cleanTmpService.cleanTmp();\n }\n\n // Validate the AI's resolution of the conflicted files. Throws CliExitError with a fix instruction\n // on any failure; returns only when all three checks pass.\n // `verb` is the bin the AI actually ran (wp-finish-update or wp-finish-upsert-pr) — every \"re-run\"\n // instruction below is rendered from it. It used to be hardcoded to wp-finish-upsert-pr, which told\n // someone in the update-only flow to finish with the PR command: a pairing that does not exist.\n private validateResolution(repoRoot: string, verb: MutationVerb, mergeDir: string, conflictedFiles: string[]): void {\n const reRun = `pnpm ${verb}`;\n // 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).\n const scan = this.mergeState.scanConflictMarkers(repoRoot, conflictedFiles);\n if (!scan.clean) {\n throw new CliExitError(1,\n '❌ Unresolved conflict markers (<<<<<<< / ======= / >>>>>>>) remain in:\\n' +\n scan.filesWithMarkers.map((file: string): string => ` - ${file}`).join('\\n') +\n `\\n\\nResolve them, then re-run: ${reRun}`,\n );\n }\n\n // 2. Ensure git itself has no remaining unmerged entries.\n const unmerged = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n if (unmerged !== '') {\n throw new CliExitError(1,\n '❌ Git still reports unmerged files:\\n' + unmerged +\n '\\n\\nResolve and `git add` them, then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ No conflict markers in resolved files.\\n');\n\n // 3. Explanation check — every conflicted file must have a non-empty merge-explanation.md in its\n // per-file context dir, proving the AI deliberately 3-point merged it (and recording how).\n const explanations = this.mergeState.scanMergeExplanations(mergeDir, conflictedFiles);\n if (!explanations.clean) {\n const missing = explanations.filesWithMarkers\n .map((file: string): string => ` - ${file}\\n → ${path.join(this.mergeState.perFileContextDir(mergeDir, file), MERGE_EXPLANATION_FILE)}`)\n .join('\\n');\n throw new CliExitError(1,\n `❌ Missing/empty merge explanation (${MERGE_EXPLANATION_FILE}) for:\\n` +\n missing +\n '\\n\\nWrite a few sentences on how you resolved each (which side, what you combined, why),\\n' +\n 'then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ Merge explanations present for all resolved files.\\n');\n }\n\n // Seam: overridden in the spec so the push/backup decisions are testable with no git and no repo.\n protected localBranchExists(name: string): boolean {\n return spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;\n }\n\n // Force-push the squash branch to the stable feature branch (where the single PR lives) — unless the\n // caller owns the push (see MergeEndOptions.pushRemote) — then RENAME the local squash branch back to\n // that SAME feature name. On a CLEAN sync the pre-merge snapshot is disposable, so it's deleted at the\n // very end; a CONFLICT sync — or a sync we did not push — keeps it.\n // eslint-disable-next-line @typescript-eslint/max-params\n private finalizeBranch(repoRoot: string, verb: MutationVerb, ctx: MergeContext, hadConflict: boolean, pushRemote: boolean): void {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n const base = this.branchNaming.baseBranchName(ctx.currentBranch);\n this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');\n\n const pushed = pushRemote ? this.pushFinalized(ctx, base) : this.explainNoPush();\n this.gitExec.runGitChecked(['checkout', ctx.squashBranch], 'Failed to checkout squash branch');\n // Free the rename target: `base` is normally the branch we just deleted, but a backward-compat\n // sync from a leftover `…wpN` can leave a separate stale `base` lingering — drop it too.\n if (base !== ctx.currentBranch && this.localBranchExists(base)) {\n this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');\n }\n this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');\n const renameEvent = new BranchMutationEvent(verb, 'RENAME');\n renameEvent.fromBranch = ctx.currentBranch;\n renameEvent.toBranch = base;\n logBranchMutation(repoRoot, renameEvent);\n\n // Branch now contains origin/main — stamp a clean main-sync status so the feature-branch-guard\n // unblocks edits immediately (no wait for the async refresher).\n stampCleanMainSyncStatus(repoRoot);\n\n // Clean sync → the pre-merge snapshot was never needed; delete it LAST. Conflict sync → keep it.\n // ALSO keep it when we did not push: the squash rewrite then exists ONLY in this working copy, so\n // deleting the snapshot would leave a history rewrite with no copy anywhere. It is disposable only\n // once origin has the result, and in the PR flow that does not happen until wp-finish-upsert-pr.\n const backupKept = hadConflict || !pushed;\n if (!backupKept && this.localBranchExists(ctx.backupBranch)) {\n this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');\n }\n\n const finalizeEvent = new BranchMutationEvent(verb, 'FINALIZE');\n finalizeEvent.fromBranch = ctx.currentBranch;\n finalizeEvent.toBranch = base;\n finalizeEvent.outcome = 'finalized';\n finalizeEvent.artifacts = [backupKept ? `backup=${ctx.backupBranch}` : `backupDeleted=${ctx.backupBranch}`, `remotePR=${base}`];\n logBranchMutation(repoRoot, finalizeEvent);\n\n this.printSyncRecap(base, ctx.backupBranch, ctx.prNumber, new SyncRecap(pushed, !pushRemote, hadConflict, backupKept));\n }\n\n // Say WHY nothing was pushed, so an unpushed branch never looks like a failure. Always returns false\n // (nothing was pushed), which also keeps the pre-merge snapshot alive — see the backupKept comment.\n private explainNoPush(): boolean {\n process.stdout.write(\n 'Not pushing — the PR flow pushes exactly ONCE, from pnpm wp-finish-upsert-pr, after summary.json\\n' +\n 'and the build gate pass and the gated PR body is written. Your work stays local until then\\n' +\n '(the pre-merge snapshot below is kept as well, so nothing is only in one place).\\n',\n );\n return false;\n }\n\n // Push the finalized squash branch to the stable feature branch. Returns whether a push actually\n // happened — false when there is no remote branch yet (a brand-new branch is local until something\n // creates it, which in the PR flow is `gh pr create` after GatedPrPublisher's push).\n protected pushFinalized(ctx: MergeContext, base: string): boolean {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', base]).status === 0;\n if (!remoteExists) {\n process.stdout.write('No remote branch — local only.\\n');\n return false;\n }\n process.stdout.write(ctx.prNumber ? `Updating PR #${ctx.prNumber} (force-with-lease)...\\n` : 'Updating remote branch (force-with-lease)...\\n');\n this.gitExec.runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${ctx.squashBranch}:${base}`], 'Failed to push to origin');\n return true;\n }\n\n // Where the branch ended up, in the recap's own words. Three distinct outcomes, and \"deferred\" must\n // never read like the failure the other two could be mistaken for.\n private remoteRecapLine(feature: string, prNumber: string, recap: SyncRecap): string {\n if (recap.pushed) {\n return `landed back on ${feature} (== origin/${feature}${prNumber ? ` == PR #${prNumber}` : ''} — names match)`;\n }\n if (recap.pushDeferred) {\n return `landed back on ${feature} (local — by design; pnpm wp-finish-upsert-pr does the one push)`;\n }\n return `landed back on ${feature} (local only — no remote branch yet)`;\n }\n\n // The explicit, numbered \"here is exactly what I did\" recap the AI (and human) reads after a sync.\n private printSyncRecap(feature: string, backupBranch: string, prNumber: string, recap: SyncRecap): void {\n const backupKept = recap.backupKept;\n const remoteLine = this.remoteRecapLine(feature, prNumber, recap);\n const keptReason = recap.hadConflict ? 'this merge had conflicts' : 'not pushed yet — wp-finish-upsert-pr will push';\n const step1 = backupKept\n ? `snapshotted your pre-merge state → ${backupBranch} (kept — ${keptReason})`\n : `snapshotted your pre-merge state → ${backupBranch} (auto-removed — clean merge, no undo needed)`;\n const trailer = backupKept\n ? ` Pre-merge snapshot trail: git branch --list '${feature}PreMerge*'\\n` +\n ` Its conflict context lives in the paired merge-<n>/ folder under .webpieces/merge-info/\\n` +\n ` Prune this run's snapshot when safe: git branch -D ${backupBranch}\\n\\n`\n : '\\n';\n process.stdout.write(\n '\\n' + SEP + '✅ Sync complete — here is exactly what I did\\n' + SEP + '\\n' +\n ` 1. ${step1}\\n` +\n ` 2. pulled origin/main\\n` +\n ` 3. squash-merged your work onto main\\n` +\n ` 4. ${remoteLine}\\n\\n` +\n trailer,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"merge-end.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-end.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA+E;AAC/E,sEAA+H;AAC/H,yCAA2D;AAC3D,mDAA+C;AAC/C,yCAAsC;AACtC,yCAAqC;AAErC,+CAA2C;AAE3C,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,sGAAsG;AACtG,kGAAkG;AAClG,MAAM,SAAS;IACX,MAAM,CAAU;IAChB,YAAY,CAAU;IACtB,WAAW,CAAU;IACrB,UAAU,CAAU;IAEpB,YAAY,MAAe,EAAE,YAAqB,EAAE,WAAoB,EAAE,UAAmB;QACzF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAED,qGAAqG;AACrG,yEAAyE;AACzE,MAAa,eAAe;IACxB,oGAAoG;IACpG,4EAA4E;IAC5E,eAAe,CAAkB;IAEjC;;;;;;;;;;;OAWG;IACH,UAAU,CAAU;IAEpB,YAAY,eAAgC,EAAE,UAAmB;QAC7D,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;CACJ;AAvBD,0CAuBC;AAED,sGAAsG;AACtG,oGAAoG;AACpG,qGAAqG;AACrG,sGAAsG;AACtG,yFAAyF;AACzF,yGAAyG;AAElG,IAAM,QAAQ,GAAd,MAAM,QAAQ;IAEI;IACA;IACA;IACA;IAJrB,YACqB,YAA0B,EAC1B,eAAyB,EACzB,OAAgB,EACh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,UAAU,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,gDAAgD,CAAC;QACrH,MAAM,KAAK,GAAG,UAAU;YACpB,CAAC,CAAC,sCAAsC,YAAY,YAAY,UAAU,GAAG;YAC7E,CAAC,CAAC,sCAAsC,YAAY,+CAA+C,CAAC;QACxG,MAAM,OAAO,GAAG,UAAU;YACtB,CAAC,CAAC,oDAAoD,OAAO,cAAc;gBACzE,gGAAgG;gBAChG,0DAA0D,YAAY,MAAM;YAC9E,CAAC,CAAC,IAAI,CAAC;QACX,OAAO,CAAC,MAAM,CAAC,KAAK,CAChB,IAAI,GAAG,GAAG,GAAG,gDAAgD,GAAG,GAAG,GAAG,IAAI;YAC1E,SAAS,KAAK,IAAI;YAClB,4BAA4B;YAC5B,2CAA2C;YAC3C,SAAS,UAAU,MAAM;YACzB,OAAO,CACV,CAAC;IACN,CAAC;CACJ,CAAA;AAtMY,4BAAQ;mBAAR,QAAQ;IADpB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGF,4BAAY;QACT,mBAAQ;QAChB,kBAAO;QACJ,wBAAU;GALlC,QAAQ,CAsMpB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { MERGE_EXPLANATION_FILE, CliExitError } from '@webpieces/rules-config';\nimport { stampCleanMainSyncStatus, MutationVerb, BranchMutationEvent, logBranchMutation } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { BranchNaming } from './branch-naming';\nimport { CleanTmp } from './cleanTmp';\nimport { GitExec } from './git-exec';\nimport { MergeContext } from './merge-start';\nimport { MergeState } from './merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// What finalizing actually did, for the recap. Data-only. `pushed` and `pushDeferred` are distinct on\n// purpose: \"we chose not to push yet\" must not be reported like \"there was no remote to push to\".\nclass SyncRecap {\n pushed: boolean;\n pushDeferred: boolean;\n hadConflict: boolean;\n backupKept: boolean;\n\n constructor(pushed: boolean, pushDeferred: boolean, hadConflict: boolean, backupKept: boolean) {\n this.pushed = pushed;\n this.pushDeferred = pushDeferred;\n this.hadConflict = hadConflict;\n this.backupKept = backupKept;\n }\n}\n\n// How a merge should be finalized. Data-only (per CLAUDE.md, classes for data) — bundled rather than\n// added as more positional params, which mergeEnd already has enough of.\nexport class MergeEndOptions {\n // Non-null means the AI resolved a conflict and it must be validated + committed before finalizing.\n // Null means merge-START already committed a clean merge, so finalize only.\n conflictedFiles: string[] | null;\n\n /**\n * Whether finalizing may push the squashed branch to origin.\n *\n * FALSE for the PR flow (`wp-start-upsert-pr` / `wp-finish-upsert-pr`), which pushes EXACTLY ONCE,\n * from GatedPrPublisher, after summary.json + every BLOCK checklist + the authoritative build gate\n * have passed and the gated PR body is already up. Code must not reach the remote ahead of its\n * review, and an early push here is also what fires `pull_request:synchronize` against a PR body\n * still carrying the previous run's gate token — the flap the whole gate redesign is removing.\n *\n * TRUE for the update-only flow (`wp-start-update` / `wp-finish-update`), which has no later push;\n * finalizing IS the end of that flow, so not pushing would silently strand the rewrite locally.\n */\n pushRemote: boolean;\n\n constructor(conflictedFiles: string[] | null, pushRemote: boolean) {\n this.conflictedFiles = conflictedFiles;\n this.pushRemote = pushRemote;\n }\n}\n\n// merge-END: the second half of the 3-point squash-merge lifecycle, symmetric with merge-START. Given\n// the branch context, it (optionally) validates + commits the AI's conflict resolution, then ALWAYS\n// finalizes — force-pushes `<branch>Squash` to the stable feature branch and renames it BACK to that\n// same feature name (local == remote == PR head), stamps a clean main-sync status, clears the marker,\n// and sweeps stale tmp. RunUpdate (clean path / validated resume), wp-finish-update, and\n// wp-finish-upsert-pr (conflict resolution) all call THIS, so finalization happens in exactly one place.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeEnd {\n constructor(\n private readonly branchNaming: BranchNaming,\n private readonly cleanTmpService: CleanTmp,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n ) {}\n\n /**\n * Complete a 3-point squash merge. See {@link MergeEndOptions} for what `conflictedFiles` and\n * `pushRemote` mean. Either way the merge ends fully finalized on the feature branch.\n */\n async mergeEnd(\n repoRoot: string, verb: MutationVerb, mergeDir: string, ctx: MergeContext, options: MergeEndOptions,\n ): Promise<void> {\n const conflictedFiles = options.conflictedFiles;\n if (conflictedFiles !== null) {\n process.stdout.write('\\n' + SEP + '🔎 Validating Merge Resolution\\n' + SEP + '\\n');\n this.validateResolution(repoRoot, verb, mergeDir, conflictedFiles);\n // Stage the AI's resolved conflicts, but NEVER sweep untracked files into the squash commit.\n // Fail on untracked so the AI commits or deletes them explicitly; then `git add -u` stages\n // tracked resolutions only.\n this.gitExec.assertNoUntracked(repoRoot);\n this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (!nothingStaged) {\n this.gitExec.runGitChecked(\n ['commit', '-m', `Squash merge of ${ctx.currentBranch} (conflicts resolved)`],\n 'Failed to commit resolved merge',\n );\n }\n fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');\n process.stdout.write('\\n✅ Merge validated and committed.\\n');\n }\n\n // A marker in THIS run dir means the sync hit conflicts (marker is written only on hand-back).\n // Read it BEFORE clearMergeMarker so finalize knows whether to keep the pre-merge snapshot.\n const hadConflict = this.mergeState.readMergeMarker(mergeDir) !== null;\n this.finalizeBranch(repoRoot, verb, ctx, hadConflict, options.pushRemote);\n this.mergeState.clearMergeMarker(mergeDir);\n await this.cleanTmpService.cleanTmp();\n }\n\n // Validate the AI's resolution of the conflicted files. Throws CliExitError with a fix instruction\n // on any failure; returns only when all three checks pass.\n // `verb` is the bin the AI actually ran (wp-finish-update or wp-finish-upsert-pr) — every \"re-run\"\n // instruction below is rendered from it. It used to be hardcoded to wp-finish-upsert-pr, which told\n // someone in the update-only flow to finish with the PR command: a pairing that does not exist.\n private validateResolution(repoRoot: string, verb: MutationVerb, mergeDir: string, conflictedFiles: string[]): void {\n const reRun = `pnpm ${verb}`;\n // 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).\n const scan = this.mergeState.scanConflictMarkers(repoRoot, conflictedFiles);\n if (!scan.clean) {\n throw new CliExitError(1,\n '❌ Unresolved conflict markers (<<<<<<< / ======= / >>>>>>>) remain in:\\n' +\n scan.filesWithMarkers.map((file: string): string => ` - ${file}`).join('\\n') +\n `\\n\\nResolve them, then re-run: ${reRun}`,\n );\n }\n\n // 2. Ensure git itself has no remaining unmerged entries.\n const unmerged = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n if (unmerged !== '') {\n throw new CliExitError(1,\n '❌ Git still reports unmerged files:\\n' + unmerged +\n '\\n\\nResolve and `git add` them, then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ No conflict markers in resolved files.\\n');\n\n // 3. Explanation check — every conflicted file must have a non-empty merge-explanation.md in its\n // per-file context dir, proving the AI deliberately 3-point merged it (and recording how).\n const explanations = this.mergeState.scanMergeExplanations(mergeDir, conflictedFiles);\n if (!explanations.clean) {\n const missing = explanations.filesWithMarkers\n .map((file: string): string => ` - ${file}\\n → ${path.join(this.mergeState.perFileContextDir(mergeDir, file), MERGE_EXPLANATION_FILE)}`)\n .join('\\n');\n throw new CliExitError(1,\n `❌ Missing/empty merge explanation (${MERGE_EXPLANATION_FILE}) for:\\n` +\n missing +\n '\\n\\nWrite a few sentences on how you resolved each (which side, what you combined, why),\\n' +\n 'then re-run: ' + reRun,\n );\n }\n process.stdout.write('✅ Merge explanations present for all resolved files.\\n');\n }\n\n // Seam: overridden in the spec so the push/backup decisions are testable with no git and no repo.\n protected localBranchExists(name: string): boolean {\n return spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;\n }\n\n // Force-push the squash branch to the stable feature branch (where the single PR lives) — unless the\n // caller owns the push (see MergeEndOptions.pushRemote) — then RENAME the local squash branch back to\n // that SAME feature name. On a CLEAN sync the pre-merge snapshot is disposable, so it's deleted at the\n // very end; a CONFLICT sync — or a sync we did not push — keeps it.\n // eslint-disable-next-line @typescript-eslint/max-params\n private finalizeBranch(repoRoot: string, verb: MutationVerb, ctx: MergeContext, hadConflict: boolean, pushRemote: boolean): void {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n const base = this.branchNaming.baseBranchName(ctx.currentBranch);\n this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');\n\n const pushed = pushRemote ? this.pushFinalized(ctx, base) : this.explainNoPush();\n this.gitExec.runGitChecked(['checkout', ctx.squashBranch], 'Failed to checkout squash branch');\n // Free the rename target: `base` is normally the branch we just deleted, but a backward-compat\n // sync from a leftover `…wpN` can leave a separate stale `base` lingering — drop it too.\n if (base !== ctx.currentBranch && this.localBranchExists(base)) {\n this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');\n }\n this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');\n const renameEvent = new BranchMutationEvent(verb, 'RENAME');\n renameEvent.fromBranch = ctx.currentBranch;\n renameEvent.toBranch = base;\n logBranchMutation(repoRoot, renameEvent);\n\n // Branch now contains origin/main — stamp a clean main-sync status so the feature-branch-guard\n // unblocks edits immediately (no wait for the async refresher).\n stampCleanMainSyncStatus(repoRoot);\n\n // Clean sync → the pre-merge snapshot was never needed; delete it LAST. Conflict sync → keep it.\n // ALSO keep it when we did not push: the squash rewrite then exists ONLY in this working copy, so\n // deleting the snapshot would leave a history rewrite with no copy anywhere. It is disposable only\n // once origin has the result, and in the PR flow that does not happen until wp-finish-upsert-pr.\n const backupKept = hadConflict || !pushed;\n if (!backupKept && this.localBranchExists(ctx.backupBranch)) {\n this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');\n }\n\n const finalizeEvent = new BranchMutationEvent(verb, 'FINALIZE');\n finalizeEvent.fromBranch = ctx.currentBranch;\n finalizeEvent.toBranch = base;\n finalizeEvent.outcome = 'finalized';\n finalizeEvent.artifacts = [backupKept ? `backup=${ctx.backupBranch}` : `backupDeleted=${ctx.backupBranch}`, `remotePR=${base}`];\n logBranchMutation(repoRoot, finalizeEvent);\n\n this.printSyncRecap(base, ctx.backupBranch, ctx.prNumber, new SyncRecap(pushed, !pushRemote, hadConflict, backupKept));\n }\n\n // Say WHY nothing was pushed, so an unpushed branch never looks like a failure. Always returns false\n // (nothing was pushed), which also keeps the pre-merge snapshot alive — see the backupKept comment.\n private explainNoPush(): boolean {\n process.stdout.write(\n 'Not pushing — the PR flow pushes exactly ONCE, from pnpm wp-finish-upsert-pr, after summary.json\\n' +\n 'and the build gate pass and the gated PR body is written. Your work stays local until then\\n' +\n '(the pre-merge snapshot below is kept as well, so nothing is only in one place).\\n',\n );\n return false;\n }\n\n // Push the finalized squash branch to the stable feature branch. Returns whether a push actually\n // happened — false when there is no remote branch yet (a brand-new branch is local until something\n // creates it, which in the PR flow is `gh pr create` after GatedPrPublisher's push).\n protected pushFinalized(ctx: MergeContext, base: string): boolean {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', base]).status === 0;\n if (!remoteExists) {\n process.stdout.write('No remote branch — local only.\\n');\n return false;\n }\n process.stdout.write(ctx.prNumber ? `Updating PR #${ctx.prNumber} (force-with-lease)...\\n` : 'Updating remote branch (force-with-lease)...\\n');\n this.gitExec.runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${ctx.squashBranch}:${base}`], 'Failed to push to origin');\n return true;\n }\n\n // Where the branch ended up, in the recap's own words. Three distinct outcomes, and \"deferred\" must\n // never read like the failure the other two could be mistaken for.\n private remoteRecapLine(feature: string, prNumber: string, recap: SyncRecap): string {\n if (recap.pushed) {\n return `landed back on ${feature} (== origin/${feature}${prNumber ? ` == PR #${prNumber}` : ''} — names match)`;\n }\n if (recap.pushDeferred) {\n return `landed back on ${feature} (local — by design; pnpm wp-finish-upsert-pr does the one push)`;\n }\n return `landed back on ${feature} (local only — no remote branch yet)`;\n }\n\n // The explicit, numbered \"here is exactly what I did\" recap the AI (and human) reads after a sync.\n private printSyncRecap(feature: string, backupBranch: string, prNumber: string, recap: SyncRecap): void {\n const backupKept = recap.backupKept;\n const remoteLine = this.remoteRecapLine(feature, prNumber, recap);\n const keptReason = recap.hadConflict ? 'this merge had conflicts' : 'not pushed yet — wp-finish-upsert-pr will push';\n const step1 = backupKept\n ? `snapshotted your pre-merge state → ${backupBranch} (kept — ${keptReason})`\n : `snapshotted your pre-merge state → ${backupBranch} (auto-removed — clean merge, no undo needed)`;\n const trailer = backupKept\n ? ` Pre-merge snapshot trail: git branch --list '${feature}PreMerge*'\\n` +\n ` Its conflict context lives in the paired merge-<n>/ folder under .webpieces/merge-info/\\n` +\n ` Prune this run's snapshot when safe: git branch -D ${backupBranch}\\n\\n`\n : '\\n';\n process.stdout.write(\n '\\n' + SEP + '✅ Sync complete — here is exactly what I did\\n' + SEP + '\\n' +\n ` 1. ${step1}\\n` +\n ` 2. pulled origin/main\\n` +\n ` 3. squash-merged your work onto main\\n` +\n ` 4. ${remoteLine}\\n\\n` +\n trailer,\n );\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AtomicFile } from '@webpieces/rules-config';
1
+ import { AtomicFile } from '@webpieces/tooling-common';
2
2
  import { MergeState } from './merge-state';
3
3
  /**
4
4
  * `.webpieces/merge-info/index.json` — the one answer to "which merges, across ALL branches, were
@@ -4,7 +4,8 @@ exports.MergeInfoIndex = exports.MergeInfoIndexFile = exports.MergedBranchEntry
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
- const rules_config_1 = require("@webpieces/rules-config");
7
+ const tooling_common_1 = require("@webpieces/tooling-common");
8
+ const to_error_1 = require("@webpieces/tooling-common/to-error");
8
9
  const inversify_1 = require("inversify");
9
10
  const merge_state_1 = require("./merge-state");
10
11
  /**
@@ -78,7 +79,7 @@ exports.MergeInfoIndexFile = MergeInfoIndexFile;
78
79
  let MergeInfoIndex = class MergeInfoIndex {
79
80
  mergeState;
80
81
  atomicFile;
81
- constructor(mergeState, atomicFile = new rules_config_1.AtomicFile()) {
82
+ constructor(mergeState, atomicFile = new tooling_common_1.AtomicFile()) {
82
83
  this.mergeState = mergeState;
83
84
  this.atomicFile = atomicFile;
84
85
  }
@@ -155,7 +156,7 @@ let MergeInfoIndex = class MergeInfoIndex {
155
156
  return new ArchiveRecord(raw.archiveTag ?? '', raw.tipSha ?? '', raw.baseSha ?? '', raw.pr ?? 0, raw.mergedAt ?? '');
156
157
  }
157
158
  catch (err) {
158
- const error = (0, rules_config_1.toError)(err);
159
+ const error = (0, to_error_1.toError)(err);
159
160
  void error;
160
161
  return new ArchiveRecord('', '', '', 0, '');
161
162
  }
@@ -165,6 +166,6 @@ exports.MergeInfoIndex = MergeInfoIndex;
165
166
  exports.MergeInfoIndex = MergeInfoIndex = tslib_1.__decorate([
166
167
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
167
168
  tslib_1.__metadata("design:paramtypes", [merge_state_1.MergeState,
168
- rules_config_1.AtomicFile])
169
+ tooling_common_1.AtomicFile])
169
170
  ], MergeInfoIndex);
170
171
  //# sourceMappingURL=merge-info-index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"merge-info-index.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-info-index.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA8D;AAC9D,yCAA2D;AAE3D,+CAA8F;AAE9F;;;;;;;;;;;;;;;;GAgBG;AAEH,+EAA+E;AAC/E,MAAa,WAAW;IACpB,CAAC,CAAS;IACV,QAAQ,CAAU;IAClB,2EAA2E;IAC3E,SAAS,CAAW;IAEpB,YAAY,CA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AE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAChD,CAAC;IACL,CAAC;CACJ,CAAA;AArFY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACV,yBAAU;GAHlC,cAAc,CAqF1B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { AtomicFile, toError } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { ARCHIVE_RECORD_FILE, MERGED_DIR, MERGE_INDEX_FILE, MergeState } from './merge-state';\n\n/**\n * `.webpieces/merge-info/index.json` — the one answer to \"which merges, across ALL branches, were\n * 3-point?\", which is the actual review question.\n *\n * WHY AN INDEX IS REQUIRED and a directory name will not do: a single branch can alternate\n * clean → 3-point → clean → 3-point across its syncs. So the clean/3-point axis belongs to the MERGE,\n * not the branch, and cannot be encoded in `merged/<branch>/`. With the index, one jq lists every\n * 3-point merge in the repo and stays correct for alternating branches:\n *\n * jq -r '.merged | to_entries[] | .key as $b | .value.merges[] |\n * select(.threeWay) | \"\\($b) merge-\\(.n)\"' .webpieces/merge-info/index.json\n *\n * WHY IT IS DERIVED, NOT INCREMENTALLY WRITTEN: every fact in it already exists on disk — `threeWay`\n * is the presence of `conflicts.md` in the run dir, `conflicts` is that file's list, and the archive\n * fields come from `archive.json`. Rebuilding by scanning `merged/` makes the index a pure projection\n * that cannot drift from the directories, and makes a lost or corrupt index self-healing.\n */\n\n// One merge slot within a branch. Data-only (per CLAUDE.md, classes for data).\nexport class MergeRecord {\n n: number;\n threeWay: boolean;\n // Only non-empty when threeWay — the files the AI actually had to resolve.\n conflicts: string[];\n\n constructor(n: number, threeWay: boolean, conflicts: string[]) {\n this.n = n;\n this.threeWay = threeWay;\n this.conflicts = conflicts;\n }\n}\n\n// `{ archiveTag, tipSha, baseSha, pr, mergedAt }` — the landed branch's archive record, written into\n// `merged/<feature>/archive.json` and mirrored into the index so one file answers everything.\nexport class ArchiveRecord {\n archiveTag: string;\n tipSha: string;\n baseSha: string;\n pr: number;\n mergedAt: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(archiveTag: string, tipSha: string, baseSha: string, pr: number, mergedAt: string) {\n this.archiveTag = archiveTag;\n this.tipSha = tipSha;\n this.baseSha = baseSha;\n this.pr = pr;\n this.mergedAt = mergedAt;\n }\n}\n\n// One landed branch's whole story: which PR, where its history is archived, and every merge it took.\nexport class MergedBranchEntry {\n pr: number;\n archiveTag: string;\n merges: MergeRecord[];\n\n constructor(pr: number, archiveTag: string, merges: MergeRecord[]) {\n this.pr = pr;\n this.archiveTag = archiveTag;\n this.merges = merges;\n }\n}\n\n// The whole file. `merged` is keyed by feature slug, matching the `merged/<feature>/` dir names.\nexport class MergeInfoIndexFile {\n merged: Record<string, MergedBranchEntry>;\n\n constructor(merged: Record<string, MergedBranchEntry>) {\n this.merged = merged;\n }\n}\n\n// Raw JSON shape for the cast at the parse boundary.\ninterface RawArchiveRecord {\n archiveTag?: string;\n tipSha?: string;\n baseSha?: string;\n pr?: number;\n mergedAt?: string;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MergeInfoIndex {\n constructor(\n private readonly mergeState: MergeState,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n ) {}\n\n indexPath(repoRoot: string): string {\n return path.join(this.mergeState.mergeInfoRoot(repoRoot), MERGE_INDEX_FILE);\n }\n\n /**\n * MOVE a landed feature's whole `staged/<feature>/` tree to `merged/<feature>/`, drop its\n * `archive.json` in, and rebuild the index. This is what makes `staged/` self-cleaning: it holds\n * only branches still in flight, instead of growing for the life of the repo.\n *\n * Returns false when there was nothing staged to promote (a branch that landed without ever syncing\n * from main), which is a normal outcome and not an error.\n */\n promoteToMerged(repoRoot: string, featureName: string, archive: ArchiveRecord): boolean {\n const staged = this.mergeState.stagedDirFor(repoRoot, featureName);\n const merged = this.mergeState.mergedDirFor(repoRoot, featureName);\n if (!fs.existsSync(staged)) {\n this.rebuildIndex(repoRoot);\n return false;\n }\n fs.mkdirSync(path.dirname(merged), { recursive: true });\n // An existing merged/<feature> means the same branch name landed before. Keep BOTH — the older\n // record moves aside rather than being overwritten, since it is the audit trail of a real PR.\n if (fs.existsSync(merged)) fs.renameSync(merged, `${merged}-prev-${String(Date.now())}`);\n fs.renameSync(staged, merged);\n fs.writeFileSync(path.join(merged, ARCHIVE_RECORD_FILE), JSON.stringify(archive, null, 2) + '\\n');\n this.rebuildIndex(repoRoot);\n return true;\n }\n\n /** Rebuild `index.json` by scanning `merged/` from scratch. Pure projection of what is on disk. */\n rebuildIndex(repoRoot: string): MergeInfoIndexFile {\n const mergedRoot = path.join(this.mergeState.mergeInfoRoot(repoRoot), MERGED_DIR);\n const entries: Record<string, MergedBranchEntry> = {};\n if (fs.existsSync(mergedRoot)) {\n for (const feature of fs.readdirSync(mergedRoot)) {\n const home = path.join(mergedRoot, feature);\n if (!fs.statSync(home).isDirectory()) continue;\n entries[feature] = this.entryFor(home);\n }\n }\n const index = new MergeInfoIndexFile(entries);\n // ATOMIC write. index.json is the one file under merge-info/ that is shared BETWEEN the\n // features of a worktree rather than owned by one of them, so two commands promoting different\n // branches at once can overlap here. Temp + rename means a reader never sees it torn. (It is a\n // pure projection of `merged/` on disk, so a lost update self-heals on the next rebuild — this\n // is not, and must not be assumed to be, a transaction.)\n this.atomicFile.writeJsonAtomic(this.indexPath(repoRoot), index);\n return index;\n }\n\n // One landed branch, derived entirely from its own directory: the archive record it was promoted\n // with, plus one MergeRecord per `merge-<n>/` whose threeWay is the presence of conflicts.md.\n private entryFor(home: string): MergedBranchEntry {\n const archive = this.readArchive(home);\n const merges: MergeRecord[] = [];\n for (const n of this.mergeState.listMergeRunDirs(home)) {\n const runDir = path.join(home, `merge-${String(n)}`);\n const threeWay = this.mergeState.wasThreeWay(runDir);\n merges.push(new MergeRecord(n, threeWay, threeWay ? this.mergeState.readConflictedFiles(runDir) : []));\n }\n return new MergedBranchEntry(archive.pr, archive.archiveTag, merges);\n }\n\n // Missing/corrupt archive.json degrades to empty fields rather than failing the whole index — the\n // merge records are still worth publishing, and a lost archive tag is not worth losing them over.\n private readArchive(home: string): ArchiveRecord {\n const filePath = path.join(home, ARCHIVE_RECORD_FILE);\n if (!fs.existsSync(filePath)) return new ArchiveRecord('', '', '', 0, '');\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as RawArchiveRecord;\n return new ArchiveRecord(\n raw.archiveTag ?? '', raw.tipSha ?? '', raw.baseSha ?? '', raw.pr ?? 0, raw.mergedAt ?? '');\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return new ArchiveRecord('', '', '', 0, '');\n }\n }\n}\n"]}
1
+ {"version":3,"file":"merge-info-index.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-info-index.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAuD;AACvD,iEAA6D;AAC7D,yCAA2D;AAE3D,+CAA8F;AAE9F;;;;;;;;;;;;;;;;GAgBG;AAEH,+EAA+E;AAC/E,MAAa,WAAW;IACpB,CAAC,CAAS;IACV,QAAQ,CAAU;IAClB,2EAA2E;IAC3E,SAAS,CAAW;IAEpB,YAAY,CAAS,EAAE,QAAiB,EAAE,SAAmB;QACzD,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QACX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;CACJ;AAXD,kCAWC;AAED,qGAAqG;AACrG,8FAA8F;AAC9F,MAAa,aAAa;IACtB,UAAU,CAAS;IACnB,MAAM,CAAS;IACf,OAAO,CAAS;IAChB,EAAE,CAAS;IACX,QAAQ,CAAS;IAEjB,yDAAyD;IACzD,YAAY,UAAkB,EAAE,MAAc,EAAE,OAAe,EAAE,EAAU,EAAE,QAAgB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GAAkG;IAClG,kGAAkG;IAC1F,WAAW,CAAC,IAAY;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,iCAAmB,CAAC,CAAC;QACtD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,aAAa,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAC1E,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAqB,CAAC;YAC9E,OAAO,IAAI,aAAa,CACpB,GAAG,CAAC,UAAU,IAAI,EAAE,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE,EAAE,GAAG,CAAC,OAAO,IAAI,EAAE,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,EAAE,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;QACpG,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,KAAK,KAAK,CAAC;YACX,OAAO,IAAI,aAAa,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAChD,CAAC;IACL,CAAC;CACJ,CAAA;AArFY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACV,2BAAU;GAHlC,cAAc,CAqF1B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { AtomicFile } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { ARCHIVE_RECORD_FILE, MERGED_DIR, MERGE_INDEX_FILE, MergeState } from './merge-state';\n\n/**\n * `.webpieces/merge-info/index.json` — the one answer to \"which merges, across ALL branches, were\n * 3-point?\", which is the actual review question.\n *\n * WHY AN INDEX IS REQUIRED and a directory name will not do: a single branch can alternate\n * clean → 3-point → clean → 3-point across its syncs. So the clean/3-point axis belongs to the MERGE,\n * not the branch, and cannot be encoded in `merged/<branch>/`. With the index, one jq lists every\n * 3-point merge in the repo and stays correct for alternating branches:\n *\n * jq -r '.merged | to_entries[] | .key as $b | .value.merges[] |\n * select(.threeWay) | \"\\($b) merge-\\(.n)\"' .webpieces/merge-info/index.json\n *\n * WHY IT IS DERIVED, NOT INCREMENTALLY WRITTEN: every fact in it already exists on disk — `threeWay`\n * is the presence of `conflicts.md` in the run dir, `conflicts` is that file's list, and the archive\n * fields come from `archive.json`. Rebuilding by scanning `merged/` makes the index a pure projection\n * that cannot drift from the directories, and makes a lost or corrupt index self-healing.\n */\n\n// One merge slot within a branch. Data-only (per CLAUDE.md, classes for data).\nexport class MergeRecord {\n n: number;\n threeWay: boolean;\n // Only non-empty when threeWay — the files the AI actually had to resolve.\n conflicts: string[];\n\n constructor(n: number, threeWay: boolean, conflicts: string[]) {\n this.n = n;\n this.threeWay = threeWay;\n this.conflicts = conflicts;\n }\n}\n\n// `{ archiveTag, tipSha, baseSha, pr, mergedAt }` — the landed branch's archive record, written into\n// `merged/<feature>/archive.json` and mirrored into the index so one file answers everything.\nexport class ArchiveRecord {\n archiveTag: string;\n tipSha: string;\n baseSha: string;\n pr: number;\n mergedAt: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(archiveTag: string, tipSha: string, baseSha: string, pr: number, mergedAt: string) {\n this.archiveTag = archiveTag;\n this.tipSha = tipSha;\n this.baseSha = baseSha;\n this.pr = pr;\n this.mergedAt = mergedAt;\n }\n}\n\n// One landed branch's whole story: which PR, where its history is archived, and every merge it took.\nexport class MergedBranchEntry {\n pr: number;\n archiveTag: string;\n merges: MergeRecord[];\n\n constructor(pr: number, archiveTag: string, merges: MergeRecord[]) {\n this.pr = pr;\n this.archiveTag = archiveTag;\n this.merges = merges;\n }\n}\n\n// The whole file. `merged` is keyed by feature slug, matching the `merged/<feature>/` dir names.\nexport class MergeInfoIndexFile {\n merged: Record<string, MergedBranchEntry>;\n\n constructor(merged: Record<string, MergedBranchEntry>) {\n this.merged = merged;\n }\n}\n\n// Raw JSON shape for the cast at the parse boundary.\ninterface RawArchiveRecord {\n archiveTag?: string;\n tipSha?: string;\n baseSha?: string;\n pr?: number;\n mergedAt?: string;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MergeInfoIndex {\n constructor(\n private readonly mergeState: MergeState,\n private readonly atomicFile: AtomicFile = new AtomicFile(),\n ) {}\n\n indexPath(repoRoot: string): string {\n return path.join(this.mergeState.mergeInfoRoot(repoRoot), MERGE_INDEX_FILE);\n }\n\n /**\n * MOVE a landed feature's whole `staged/<feature>/` tree to `merged/<feature>/`, drop its\n * `archive.json` in, and rebuild the index. This is what makes `staged/` self-cleaning: it holds\n * only branches still in flight, instead of growing for the life of the repo.\n *\n * Returns false when there was nothing staged to promote (a branch that landed without ever syncing\n * from main), which is a normal outcome and not an error.\n */\n promoteToMerged(repoRoot: string, featureName: string, archive: ArchiveRecord): boolean {\n const staged = this.mergeState.stagedDirFor(repoRoot, featureName);\n const merged = this.mergeState.mergedDirFor(repoRoot, featureName);\n if (!fs.existsSync(staged)) {\n this.rebuildIndex(repoRoot);\n return false;\n }\n fs.mkdirSync(path.dirname(merged), { recursive: true });\n // An existing merged/<feature> means the same branch name landed before. Keep BOTH — the older\n // record moves aside rather than being overwritten, since it is the audit trail of a real PR.\n if (fs.existsSync(merged)) fs.renameSync(merged, `${merged}-prev-${String(Date.now())}`);\n fs.renameSync(staged, merged);\n fs.writeFileSync(path.join(merged, ARCHIVE_RECORD_FILE), JSON.stringify(archive, null, 2) + '\\n');\n this.rebuildIndex(repoRoot);\n return true;\n }\n\n /** Rebuild `index.json` by scanning `merged/` from scratch. Pure projection of what is on disk. */\n rebuildIndex(repoRoot: string): MergeInfoIndexFile {\n const mergedRoot = path.join(this.mergeState.mergeInfoRoot(repoRoot), MERGED_DIR);\n const entries: Record<string, MergedBranchEntry> = {};\n if (fs.existsSync(mergedRoot)) {\n for (const feature of fs.readdirSync(mergedRoot)) {\n const home = path.join(mergedRoot, feature);\n if (!fs.statSync(home).isDirectory()) continue;\n entries[feature] = this.entryFor(home);\n }\n }\n const index = new MergeInfoIndexFile(entries);\n // ATOMIC write. index.json is the one file under merge-info/ that is shared BETWEEN the\n // features of a worktree rather than owned by one of them, so two commands promoting different\n // branches at once can overlap here. Temp + rename means a reader never sees it torn. (It is a\n // pure projection of `merged/` on disk, so a lost update self-heals on the next rebuild — this\n // is not, and must not be assumed to be, a transaction.)\n this.atomicFile.writeJsonAtomic(this.indexPath(repoRoot), index);\n return index;\n }\n\n // One landed branch, derived entirely from its own directory: the archive record it was promoted\n // with, plus one MergeRecord per `merge-<n>/` whose threeWay is the presence of conflicts.md.\n private entryFor(home: string): MergedBranchEntry {\n const archive = this.readArchive(home);\n const merges: MergeRecord[] = [];\n for (const n of this.mergeState.listMergeRunDirs(home)) {\n const runDir = path.join(home, `merge-${String(n)}`);\n const threeWay = this.mergeState.wasThreeWay(runDir);\n merges.push(new MergeRecord(n, threeWay, threeWay ? this.mergeState.readConflictedFiles(runDir) : []));\n }\n return new MergedBranchEntry(archive.pr, archive.archiveTag, merges);\n }\n\n // Missing/corrupt archive.json degrades to empty fields rather than failing the whole index — the\n // merge records are still worth publishing, and a lost archive tag is not worth losing them over.\n private readArchive(home: string): ArchiveRecord {\n const filePath = path.join(home, ARCHIVE_RECORD_FILE);\n if (!fs.existsSync(filePath)) return new ArchiveRecord('', '', '', 0, '');\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as RawArchiveRecord;\n return new ArchiveRecord(\n raw.archiveTag ?? '', raw.tipSha ?? '', raw.baseSha ?? '', raw.pr ?? 0, raw.mergedAt ?? '');\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return new ArchiveRecord('', '', '', 0, '');\n }\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { MutationVerb } from '@webpieces/rules-config';
1
+ import { MutationVerb } from '@webpieces/repo-workflow-core';
2
2
  import { GatherInfo } from '../git-gatherInfo';
3
3
  import { BranchNaming } from './branch-naming';
4
4
  import { GitExec } from './git-exec';
@@ -5,7 +5,9 @@ const tslib_1 = require("tslib");
5
5
  const child_process_1 = require("child_process");
6
6
  const fs = tslib_1.__importStar(require("fs"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
+ const tooling_common_1 = require("@webpieces/tooling-common");
8
9
  const rules_config_1 = require("@webpieces/rules-config");
10
+ const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
9
11
  const inversify_1 = require("inversify");
10
12
  const git_gatherInfo_1 = require("../git-gatherInfo");
11
13
  const branch_naming_1 = require("./branch-naming");
@@ -89,10 +91,10 @@ let MergeStart = class MergeStart {
89
91
  // disposable (branches count toward the branch cap; a written-down hash does not), and it is the
90
92
  // ref the archive tag is cut from when the PR lands.
91
93
  this.mergeState.writePreMergeHash(home, slot.n, this.fullSha(currentBranch));
92
- const backupEvent = new rules_config_1.BranchMutationEvent(verb, 'BACKUP');
94
+ const backupEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'BACKUP');
93
95
  backupEvent.fromBranch = currentBranch;
94
96
  backupEvent.toBranch = backupBranch;
95
- (0, rules_config_1.logBranchMutation)(repoRoot, backupEvent);
97
+ (0, repo_workflow_core_1.logBranchMutation)(repoRoot, backupEvent);
96
98
  const squashBranch = `${currentBranch}Squash`;
97
99
  if ((0, child_process_1.spawnSync)('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {
98
100
  throw new rules_config_1.CliExitError(1, `❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}`);
@@ -102,9 +104,9 @@ let MergeStart = class MergeStart {
102
104
  // to the old checkout-main + pull path.
103
105
  const originMainSha = this.shortSha('origin/main');
104
106
  this.gitExec.runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');
105
- const baseEvent = new rules_config_1.BranchMutationEvent(verb, 'PULL');
107
+ const baseEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'PULL');
106
108
  baseEvent.newMain = originMainSha;
107
- (0, rules_config_1.logBranchMutation)(repoRoot, baseEvent);
109
+ (0, repo_workflow_core_1.logBranchMutation)(repoRoot, baseEvent);
108
110
  process.stdout.write('\n' + SEP + `🔀 Squash merging ${currentBranch}\n` + SEP + '\n');
109
111
  const merge = (0, child_process_1.spawnSync)('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });
110
112
  if (merge.status !== 0) {
@@ -112,7 +114,7 @@ let MergeStart = class MergeStart {
112
114
  this.logConflict(repoRoot, verb, mergeDir);
113
115
  return new MergeStartResult('conflict', null, mergeDir);
114
116
  }
115
- (0, rules_config_1.logBranchMutation)(repoRoot, new rules_config_1.BranchMutationEvent(verb, 'SQUASH'));
117
+ (0, repo_workflow_core_1.logBranchMutation)(repoRoot, new repo_workflow_core_1.BranchMutationEvent(verb, 'SQUASH'));
116
118
  const nothingStaged = (0, child_process_1.spawnSync)('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;
117
119
  if (nothingStaged) {
118
120
  process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\n');
@@ -175,7 +177,7 @@ let MergeStart = class MergeStart {
175
177
  }
176
178
  // Returns the absolute path of the written doc.
177
179
  writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles, finishCommand) {
178
- const docDir = rules_config_1.dotWebpieces.localFile(repoRoot, 'instruct-ai');
180
+ const docDir = tooling_common_1.dotWebpieces.localFile(repoRoot, 'instruct-ai');
179
181
  fs.mkdirSync(docDir, { recursive: true });
180
182
  const docPath = path.join(docDir, rules_config_1.MERGE_PROCESS_DOC);
181
183
  fs.writeFileSync(docPath, this.mergeProcessDoc(mergeDir, squashBranch, conflictedFiles, finishCommand));
@@ -231,14 +233,14 @@ let MergeStart = class MergeStart {
231
233
  logConflict(repoRoot, verb, mergeDir) {
232
234
  const raw = (0, child_process_1.spawnSync)('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: repoRoot, encoding: 'utf8' });
233
235
  const files = (raw.status === 0 ? (raw.stdout ?? '') : '').split('\n').map((f) => f.trim()).filter((f) => f !== '');
234
- const event = new rules_config_1.BranchMutationEvent(verb, 'CONFLICT');
236
+ const event = new repo_workflow_core_1.BranchMutationEvent(verb, 'CONFLICT');
235
237
  event.conflict = true;
236
238
  event.conflictFiles = files;
237
239
  event.artifacts = [
238
240
  path.join(mergeDir, 'updatemain-<file>'),
239
- rules_config_1.dotWebpieces.localFile(repoRoot, 'instruct-ai', rules_config_1.MERGE_PROCESS_DOC),
241
+ tooling_common_1.dotWebpieces.localFile(repoRoot, 'instruct-ai', rules_config_1.MERGE_PROCESS_DOC),
240
242
  ];
241
- (0, rules_config_1.logBranchMutation)(repoRoot, event);
243
+ (0, repo_workflow_core_1.logBranchMutation)(repoRoot, event);
242
244
  }
243
245
  };
244
246
  exports.MergeStart = MergeStart;