@webpieces/pr-gate 0.4.975 → 0.4.976
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/src/scripts/commands/await-checks-command.d.ts +6 -3
- package/src/scripts/commands/await-checks-command.js +17 -12
- package/src/scripts/commands/await-checks-command.js.map +1 -1
- package/src/scripts/commands/await-reviews-command.d.ts +1 -1
- package/src/scripts/commands/await-reviews-command.js +3 -3
- package/src/scripts/commands/await-reviews-command.js.map +1 -1
- package/src/scripts/commands/check-pr-command.d.ts +3 -1
- package/src/scripts/commands/check-pr-command.js +12 -9
- package/src/scripts/commands/check-pr-command.js.map +1 -1
- package/src/scripts/commands/finish-push-dev-command.js +3 -4
- package/src/scripts/commands/finish-push-dev-command.js.map +1 -1
- package/src/scripts/commands/finish-update-command.js +1 -1
- package/src/scripts/commands/finish-update-command.js.map +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.d.ts +4 -1
- package/src/scripts/commands/finish-upsert-pr-command.js +65 -62
- package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/human-post-pr-command.d.ts +8 -6
- package/src/scripts/commands/human-post-pr-command.js +32 -31
- package/src/scripts/commands/human-post-pr-command.js.map +1 -1
- package/src/scripts/commands/land-pr-command.d.ts +5 -1
- package/src/scripts/commands/land-pr-command.js +36 -22
- package/src/scripts/commands/land-pr-command.js.map +1 -1
- package/src/scripts/commands/main-checkout.d.ts +4 -1
- package/src/scripts/commands/main-checkout.js +22 -22
- package/src/scripts/commands/main-checkout.js.map +1 -1
- package/src/scripts/commands/push-dev-command.js +28 -29
- package/src/scripts/commands/push-dev-command.js.map +1 -1
- package/src/scripts/commands/review-upsert-pr-command.js +9 -9
- package/src/scripts/commands/review-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/start-update-command.d.ts +1 -1
- package/src/scripts/commands/start-update-command.js +3 -3
- package/src/scripts/commands/start-update-command.js.map +1 -1
- package/src/scripts/commands/start-upsert-pr-command.js +4 -4
- package/src/scripts/commands/start-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/sync-main-command.js +2 -2
- package/src/scripts/commands/sync-main-command.js.map +1 -1
- package/src/scripts/commands/upsert-hotfix-pr-command.d.ts +6 -4
- package/src/scripts/commands/upsert-hotfix-pr-command.js +46 -43
- package/src/scripts/commands/upsert-hotfix-pr-command.js.map +1 -1
- package/src/scripts/commands/working-tree-gate.d.ts +4 -1
- package/src/scripts/commands/working-tree-gate.js +14 -11
- package/src/scripts/commands/working-tree-gate.js.map +1 -1
- package/src/scripts/commands/write-review-command.js +4 -6
- package/src/scripts/commands/write-review-command.js.map +1 -1
- package/src/scripts/commands/write-review-fixes-command.js +3 -4
- package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
- package/src/scripts/git-finishUpsertPr.js +2 -2
- package/src/scripts/git-finishUpsertPr.js.map +1 -1
- package/src/scripts/git-gatherInfo.js +6 -7
- package/src/scripts/git-gatherInfo.js.map +1 -1
- package/src/scripts/pr-gate-container.d.ts +9 -0
- package/src/scripts/pr-gate-container.js +19 -0
- package/src/scripts/pr-gate-container.js.map +1 -0
- package/src/scripts/workflow/await-loop.d.ts +1 -1
- package/src/scripts/workflow/await-loop.js +1 -1
- package/src/scripts/workflow/await-loop.js.map +1 -1
- package/src/scripts/workflow/build-affected.js +1 -1
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/build-artifact-gate.d.ts +1 -1
- package/src/scripts/workflow/build-artifact-gate.js +3 -3
- package/src/scripts/workflow/build-artifact-gate.js.map +1 -1
- package/src/scripts/workflow/build-gate-log.d.ts +9 -6
- package/src/scripts/workflow/build-gate-log.js +34 -40
- package/src/scripts/workflow/build-gate-log.js.map +1 -1
- package/src/scripts/workflow/checklist-scanner.d.ts +1 -1
- package/src/scripts/workflow/checklist-scanner.js +8 -8
- package/src/scripts/workflow/checklist-scanner.js.map +1 -1
- package/src/scripts/workflow/checklist-scope-hasher.d.ts +1 -1
- package/src/scripts/workflow/checklist-scope-hasher.js +2 -2
- package/src/scripts/workflow/checklist-scope-hasher.js.map +1 -1
- package/src/scripts/workflow/dev-deploy-refs.d.ts +5 -5
- package/src/scripts/workflow/dev-deploy-refs.js +8 -8
- package/src/scripts/workflow/dev-deploy-refs.js.map +1 -1
- package/src/scripts/workflow/dev-resolve-runner.d.ts +3 -3
- package/src/scripts/workflow/dev-resolve-runner.js +30 -30
- package/src/scripts/workflow/dev-resolve-runner.js.map +1 -1
- package/src/scripts/workflow/diff-basis.d.ts +4 -2
- package/src/scripts/workflow/diff-basis.js +18 -15
- package/src/scripts/workflow/diff-basis.js.map +1 -1
- package/src/scripts/workflow/diff-materializer.d.ts +5 -3
- package/src/scripts/workflow/diff-materializer.js +18 -15
- package/src/scripts/workflow/diff-materializer.js.map +1 -1
- package/src/scripts/workflow/gated-pr-publisher.d.ts +8 -6
- package/src/scripts/workflow/gated-pr-publisher.js +23 -22
- package/src/scripts/workflow/gated-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/generated-artifact-registry.d.ts +4 -2
- package/src/scripts/workflow/generated-artifact-registry.js +11 -8
- package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
- package/src/scripts/workflow/git-exec.d.ts +22 -12
- package/src/scripts/workflow/git-exec.js +45 -29
- package/src/scripts/workflow/git-exec.js.map +1 -1
- package/src/scripts/workflow/git-findForkPoint.d.ts +6 -2
- package/src/scripts/workflow/git-findForkPoint.js +31 -23
- package/src/scripts/workflow/git-findForkPoint.js.map +1 -1
- package/src/scripts/workflow/git-readAiBranchName.d.ts +4 -2
- package/src/scripts/workflow/git-readAiBranchName.js +8 -5
- package/src/scripts/workflow/git-readAiBranchName.js.map +1 -1
- package/src/scripts/workflow/hotfix-pr-publisher.d.ts +4 -3
- package/src/scripts/workflow/hotfix-pr-publisher.js +7 -6
- package/src/scripts/workflow/hotfix-pr-publisher.js.map +1 -1
- package/src/scripts/workflow/landed-tree-resolver.d.ts +4 -2
- package/src/scripts/workflow/landed-tree-resolver.js +11 -8
- package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
- package/src/scripts/workflow/landed-worktree-reaper.d.ts +4 -2
- package/src/scripts/workflow/landed-worktree-reaper.js +12 -9
- package/src/scripts/workflow/landed-worktree-reaper.js.map +1 -1
- package/src/scripts/workflow/merge-end.d.ts +2 -2
- package/src/scripts/workflow/merge-end.js +22 -24
- package/src/scripts/workflow/merge-end.js.map +1 -1
- package/src/scripts/workflow/merge-start.d.ts +5 -1
- package/src/scripts/workflow/merge-start.js +56 -49
- package/src/scripts/workflow/merge-start.js.map +1 -1
- package/src/scripts/workflow/open-pr-check.d.ts +4 -2
- package/src/scripts/workflow/open-pr-check.js +11 -8
- package/src/scripts/workflow/open-pr-check.js.map +1 -1
- package/src/scripts/workflow/pr-comment-upserter.d.ts +5 -3
- package/src/scripts/workflow/pr-comment-upserter.js +15 -14
- package/src/scripts/workflow/pr-comment-upserter.js.map +1 -1
- package/src/scripts/workflow/pr-merger.d.ts +8 -5
- package/src/scripts/workflow/pr-merger.js +32 -27
- package/src/scripts/workflow/pr-merger.js.map +1 -1
- package/src/scripts/workflow/provenance-enforcer.d.ts +4 -2
- package/src/scripts/workflow/provenance-enforcer.js +19 -17
- package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
- package/src/scripts/workflow/review-round-state.d.ts +7 -6
- package/src/scripts/workflow/review-round-state.js +33 -38
- package/src/scripts/workflow/review-round-state.js.map +1 -1
- package/src/scripts/workflow/run-update.js +1 -1
- package/src/scripts/workflow/run-update.js.map +1 -1
- package/src/scripts/workflow/squash-settings-enforcer.d.ts +6 -3
- package/src/scripts/workflow/squash-settings-enforcer.js +19 -14
- package/src/scripts/workflow/squash-settings-enforcer.js.map +1 -1
- package/src/scripts/wp-await-checks.js +2 -2
- package/src/scripts/wp-await-checks.js.map +1 -1
- package/src/scripts/wp-await-reviews.js +2 -2
- package/src/scripts/wp-await-reviews.js.map +1 -1
- package/src/scripts/wp-build.js +2 -2
- package/src/scripts/wp-build.js.map +1 -1
- package/src/scripts/wp-check-pr.js +2 -2
- package/src/scripts/wp-check-pr.js.map +1 -1
- package/src/scripts/wp-cleanup.js +2 -2
- package/src/scripts/wp-cleanup.js.map +1 -1
- package/src/scripts/wp-finish-push-dev.js +2 -2
- package/src/scripts/wp-finish-push-dev.js.map +1 -1
- package/src/scripts/wp-finish-update.js +2 -2
- package/src/scripts/wp-finish-update.js.map +1 -1
- package/src/scripts/wp-human-post-pr.js +2 -2
- package/src/scripts/wp-human-post-pr.js.map +1 -1
- package/src/scripts/wp-land-pr.js +2 -2
- package/src/scripts/wp-land-pr.js.map +1 -1
- package/src/scripts/wp-push-dev.js +2 -2
- package/src/scripts/wp-push-dev.js.map +1 -1
- package/src/scripts/wp-reap-worktree.js +2 -2
- package/src/scripts/wp-reap-worktree.js.map +1 -1
- package/src/scripts/wp-review-upsert-pr.js +2 -2
- package/src/scripts/wp-review-upsert-pr.js.map +1 -1
- package/src/scripts/wp-start-update.js +2 -2
- package/src/scripts/wp-start-update.js.map +1 -1
- package/src/scripts/wp-start-upsert-pr.js +2 -2
- package/src/scripts/wp-start-upsert-pr.js.map +1 -1
- package/src/scripts/wp-sync-main.js +2 -2
- package/src/scripts/wp-sync-main.js.map +1 -1
- package/src/scripts/wp-upsert-hotfix-pr.js +2 -2
- package/src/scripts/wp-upsert-hotfix-pr.js.map +1 -1
- package/src/scripts/wp-write-review-fixes.js +2 -2
- package/src/scripts/wp-write-review-fixes.js.map +1 -1
- package/src/scripts/wp-write-review.js +2 -2
- package/src/scripts/wp-write-review.js.map +1 -1
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.LandedTreeResolver = exports.LandedTree = exports.LANDED_TREE_ABSENT = exports.LANDED_TREE_WRONG_TIP = exports.LANDED_TREE_BRANCH_ONLY = exports.LANDED_TREE_WORKTREE = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
-
const child_process_1 = require("child_process");
|
|
6
5
|
const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
|
|
6
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
7
7
|
const inversify_1 = require("inversify");
|
|
8
8
|
/**
|
|
9
9
|
* WHICH LOCAL TREE HOLDS THE COMMIT GITHUB JUST SQUASHED — asked as a fact, answered from anywhere.
|
|
@@ -74,8 +74,10 @@ class LandedTree {
|
|
|
74
74
|
exports.LandedTree = LandedTree;
|
|
75
75
|
let LandedTreeResolver = class LandedTreeResolver {
|
|
76
76
|
worktrees;
|
|
77
|
-
|
|
77
|
+
git;
|
|
78
|
+
constructor(worktrees, git) {
|
|
78
79
|
this.worktrees = worktrees;
|
|
80
|
+
this.git = git;
|
|
79
81
|
}
|
|
80
82
|
/**
|
|
81
83
|
* The four-row table this whole design exists to implement, in order of what it can prove.
|
|
@@ -84,11 +86,11 @@ let LandedTreeResolver = class LandedTreeResolver {
|
|
|
84
86
|
* into a mismatch — a fact we do not have is not evidence of disagreement — so the local tip is taken
|
|
85
87
|
* as the landed one, which is exactly what the old `ref.headRefOid !== ''` guard did.
|
|
86
88
|
*/
|
|
87
|
-
resolve(repoRoot, branch, headRefOid) {
|
|
89
|
+
async resolve(repoRoot, branch, headRefOid) {
|
|
88
90
|
// Only LINKED worktrees are reapable; the primary clone is the thing reaped FROM, never a target.
|
|
89
91
|
const holder = this.worktrees.linkedWorktrees(repoRoot)
|
|
90
92
|
.find((tree) => tree.branch === branch) ?? null;
|
|
91
|
-
const local = holder !== null ? holder.head : this.revParse(repoRoot, branch);
|
|
93
|
+
const local = holder !== null ? holder.head : await this.revParse(repoRoot, branch);
|
|
92
94
|
if (local === '')
|
|
93
95
|
return new LandedTree(exports.LANDED_TREE_ABSENT, null, '');
|
|
94
96
|
if (headRefOid !== '' && local !== headRefOid) {
|
|
@@ -99,14 +101,15 @@ let LandedTreeResolver = class LandedTreeResolver {
|
|
|
99
101
|
: new LandedTree(exports.LANDED_TREE_BRANCH_ONLY, null, local);
|
|
100
102
|
}
|
|
101
103
|
// Best-effort sha of a ref — '' when it cannot resolve, which reads as "the branch is not here".
|
|
102
|
-
revParse(repoRoot, ref) {
|
|
103
|
-
const result =
|
|
104
|
-
return result.
|
|
104
|
+
async revParse(repoRoot, ref) {
|
|
105
|
+
const result = await this.git.run(['rev-parse', ref], repoRoot);
|
|
106
|
+
return result.ok ? result.stdout.trim() : '';
|
|
105
107
|
}
|
|
106
108
|
};
|
|
107
109
|
exports.LandedTreeResolver = LandedTreeResolver;
|
|
108
110
|
exports.LandedTreeResolver = LandedTreeResolver = tslib_1.__decorate([
|
|
109
111
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
110
|
-
tslib_1.__metadata("design:paramtypes", [repo_workflow_core_1.WorktreeService
|
|
112
|
+
tslib_1.__metadata("design:paramtypes", [repo_workflow_core_1.WorktreeService,
|
|
113
|
+
tooling_common_1.GitProcessApi])
|
|
111
114
|
], LandedTreeResolver);
|
|
112
115
|
//# sourceMappingURL=landed-tree-resolver.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"landed-tree-resolver.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-tree-resolver.ts"],"names":[],"mappings":";;;;AAAA,
|
|
1
|
+
{"version":3,"file":"landed-tree-resolver.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-tree-resolver.ts"],"names":[],"mappings":";;;;AAAA,sEAA0E;AAC1E,8DAA0D;AAC1D,yCAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,wGAAwG;AAC3F,QAAA,oBAAoB,GAAG,UAAU,CAAC;AAC/C,8GAA8G;AACjG,QAAA,uBAAuB,GAAG,aAAa,CAAC;AACrD,2FAA2F;AAC9E,QAAA,qBAAqB,GAAG,WAAW,CAAC;AACjD,wFAAwF;AAC3E,QAAA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AC5C,OAAO,IAAI,UAAU,CAAC,6BAAqB,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;QACD,OAAO,MAAM,KAAK,IAAI;YAClB,CAAC,CAAC,IAAI,UAAU,CAAC,4BAAoB,EAAE,MAAM,EAAE,KAAK,CAAC;YACrD,CAAC,CAAC,IAAI,UAAU,CAAC,+BAAuB,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC/D,CAAC;IAED,iGAAiG;IACzF,KAAK,CAAC,QAAQ,CAAC,QAAgB,EAAE,GAAW;QAChD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;QAChE,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACjD,CAAC;CACJ,CAAA;AAjCY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGL,oCAAe;QACrB,8BAAa;GAH9B,kBAAkB,CAiC9B","sourcesContent":["import { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';\nimport { GitProcessApi } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * WHICH LOCAL TREE HOLDS THE COMMIT GITHUB JUST SQUASHED — asked as a fact, answered from anywhere.\n *\n * `wp-land-pr` does two things with different scopes: the MERGE belongs to the PR and is reachable from\n * any directory, while the BOOKKEEPING (archive the pre-squash tip, promote merge-info, reap the landed\n * worktree) belongs to the tree that really holds those objects. Until now the second half was resolved\n * from `process.cwd()` — and `pnpm` hoists a bin's cwd to the workspace root, so a command run inside\n * `<primary>/.claude/worktrees/agent-<id>` executed in the PRIMARY CLONE. Every agent worktree is nested\n * like that, so the answer was wrong in exactly the case the mechanism was built for.\n *\n * The fix is to stop asking \"where am I\" and start asking \"where is it\". Both halves of that question are\n * facts nobody has to record:\n *\n * `gh pr view <n> --json headRefName,headRefOid` → the branch, and the exact commit being squashed\n * `git worktree list --porcelain` → every (path, branch, HEAD sha) in this repo\n *\n * The worktree list lives in the COMMON dir, so it reads identically from the primary clone, from any\n * linked worktree, and from a coordinator that never saw the agent that built the branch. That is what\n * makes `wp-land-pr --pr <n>` able to finish a dead agent's work.\n *\n * ─── WHY THE PAIR, AND NEVER THE NAME ALONE ───────────────────────────────────────────────────────\n * A branch NAME does not identify a tree. A second clone, or a worktree somebody has since committed to,\n * holds the same name at a different commit, and archiving `archive/<date>/<branch>` from there tags the\n * wrong objects under the right name. So the selection key is `(headRefName, headRefOid)` together, and a\n * name-only match is never enough to remove or archive anything — in this process or in the child that\n * re-verifies it (see ReapWorktreeCommand).\n *\n * ─── WHY NOT A `.webpieces/**` RECEIPT ────────────────────────────────────────────────────────────\n * The obvious alternative is for `wp-finish-upsert-pr` to write `{ pr, branch, worktreePath, headRefOid }`\n * to a sidecar and for landing to read it back. `decisions/0005-the-pr-description-is-the-merge-body.md`\n * already deleted that pattern once: a recorded claim can only ever be missing, stale, or on the wrong\n * computer — and a worktree PATH is more volatile than the commit body that argument was made about,\n * since the directory is moved, reaped, or recreated under a new agent id between finish and land.\n * `(headRefOid, git worktree list)` is a pair of facts, needs no stored state, and works from a fresh\n * clone. Nothing here reads state.\n */\n\n/** A linked worktree holds the branch AT the squashed commit: archive here, and reap THAT directory. */\nexport const LANDED_TREE_WORKTREE = 'worktree';\n/** No worktree holds it, but the branch ref in this repo IS the squashed commit: archive, nothing to reap. */\nexport const LANDED_TREE_BRANCH_ONLY = 'branch-only';\n/** The name is here, the commit is not. Merge stands; bookkeeping is declined out loud. */\nexport const LANDED_TREE_WRONG_TIP = 'wrong-tip';\n/** The branch is not in this repo at all — landed from a tree that does not hold it. */\nexport const LANDED_TREE_ABSENT = 'absent';\n\n/**\n * Data-only (per CLAUDE.md, classes for data). Where the landed commit lives locally, and therefore\n * whether the bookkeeping half may run at all.\n *\n * `bookkeepingAllowed` is PRECOMPUTED rather than re-derived by the caller, for the same reason\n * `EffectiveTree.redirected` and `WorktreeReapHandoff.canReap` are: a deletion rule spelled out twice is\n * a deletion rule that eventually disagrees with itself.\n */\nexport class LandedTree {\n readonly kind: string;\n /** The linked worktree to reap — non-null ONLY for {@link LANDED_TREE_WORKTREE}. */\n readonly worktree: Worktree | null;\n /** The sha found locally under that branch name, '' when the branch is absent. Printed on a mismatch. */\n readonly localSha: string;\n readonly bookkeepingAllowed: boolean;\n\n constructor(kind: string, worktree: Worktree | null, localSha: string) {\n this.kind = kind;\n this.worktree = worktree;\n this.localSha = localSha;\n this.bookkeepingAllowed = kind === LANDED_TREE_WORKTREE || kind === LANDED_TREE_BRANCH_ONLY;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class LandedTreeResolver {\n constructor(\n private readonly worktrees: WorktreeService,\n private readonly git: GitProcessApi,\n ) {}\n\n /**\n * The four-row table this whole design exists to implement, in order of what it can prove.\n *\n * `headRefOid === ''` means `gh` did not tell us which commit it is squashing. That cannot be turned\n * into a mismatch — a fact we do not have is not evidence of disagreement — so the local tip is taken\n * as the landed one, which is exactly what the old `ref.headRefOid !== ''` guard did.\n */\n async resolve(repoRoot: string, branch: string, headRefOid: string): Promise<LandedTree> {\n // Only LINKED worktrees are reapable; the primary clone is the thing reaped FROM, never a target.\n const holder = this.worktrees.linkedWorktrees(repoRoot)\n .find((tree: Worktree): boolean => tree.branch === branch) ?? null;\n const local = holder !== null ? holder.head : await this.revParse(repoRoot, branch);\n\n if (local === '') return new LandedTree(LANDED_TREE_ABSENT, null, '');\n if (headRefOid !== '' && local !== headRefOid) {\n return new LandedTree(LANDED_TREE_WRONG_TIP, null, local);\n }\n return holder !== null\n ? new LandedTree(LANDED_TREE_WORKTREE, holder, local)\n : new LandedTree(LANDED_TREE_BRANCH_ONLY, null, local);\n }\n\n // Best-effort sha of a ref — '' when it cannot resolve, which reads as \"the branch is not here\".\n private async revParse(repoRoot: string, ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', ref], repoRoot);\n return result.ok ? result.stdout.trim() : '';\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';
|
|
2
|
+
import { NativeProcessApi } from '@webpieces/tooling-common';
|
|
2
3
|
import { ReapOutcomeSignal } from './reap-outcome';
|
|
3
4
|
/**
|
|
4
5
|
* Data-only (per CLAUDE.md, classes for data). The decision about the just-landed worktree: which
|
|
@@ -36,7 +37,8 @@ export declare class WorktreeReapHandoff {
|
|
|
36
37
|
export declare class LandedWorktreeReaper {
|
|
37
38
|
private readonly worktrees;
|
|
38
39
|
private readonly signal;
|
|
39
|
-
|
|
40
|
+
private readonly processes;
|
|
41
|
+
constructor(worktrees: WorktreeService, signal: ReapOutcomeSignal, processes: NativeProcessApi);
|
|
40
42
|
/**
|
|
41
43
|
* Is there a worktree to reap at all, and can the hand-off run?
|
|
42
44
|
*
|
|
@@ -73,7 +75,7 @@ export declare class LandedWorktreeReaper {
|
|
|
73
75
|
* only means "the child ran"; whether the DIRECTORY is gone is a separate statement it makes through
|
|
74
76
|
* ReapOutcomeSignal, and that is the one that gates the "your cwd no longer exists" notice.
|
|
75
77
|
*/
|
|
76
|
-
handOff(handoff: WorktreeReapHandoff): string
|
|
78
|
+
handOff(handoff: WorktreeReapHandoff): Promise<string>;
|
|
77
79
|
/**
|
|
78
80
|
* WHY the directory is still there, distinguishing the two cases a single exit code conflated: the
|
|
79
81
|
* child broke (non-zero), versus the child worked perfectly and DECLINED (exit 0, outcome refused).
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.LandedWorktreeReaper = exports.WorktreeReapHandoff = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
-
const child_process_1 = require("child_process");
|
|
6
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
7
6
|
const path = tslib_1.__importStar(require("path"));
|
|
8
7
|
const repo_workflow_core_1 = require("@webpieces/repo-workflow-core");
|
|
9
8
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
9
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
10
10
|
const inversify_1 = require("inversify");
|
|
11
11
|
const reap_outcome_1 = require("./reap-outcome");
|
|
12
12
|
/**
|
|
@@ -87,9 +87,11 @@ exports.WorktreeReapHandoff = WorktreeReapHandoff;
|
|
|
87
87
|
let LandedWorktreeReaper = class LandedWorktreeReaper {
|
|
88
88
|
worktrees;
|
|
89
89
|
signal;
|
|
90
|
-
|
|
90
|
+
processes;
|
|
91
|
+
constructor(worktrees, signal, processes) {
|
|
91
92
|
this.worktrees = worktrees;
|
|
92
93
|
this.signal = signal;
|
|
94
|
+
this.processes = processes;
|
|
93
95
|
}
|
|
94
96
|
/**
|
|
95
97
|
* Is there a worktree to reap at all, and can the hand-off run?
|
|
@@ -145,16 +147,16 @@ let LandedWorktreeReaper = class LandedWorktreeReaper {
|
|
|
145
147
|
* only means "the child ran"; whether the DIRECTORY is gone is a separate statement it makes through
|
|
146
148
|
* ReapOutcomeSignal, and that is the one that gates the "your cwd no longer exists" notice.
|
|
147
149
|
*/
|
|
148
|
-
handOff(handoff) {
|
|
149
|
-
const result =
|
|
150
|
-
const report = this.signal.read(`${result.stdout
|
|
150
|
+
async handOff(handoff) {
|
|
151
|
+
const result = await this.processes.run(process.execPath, [handoff.entryScript, handoff.worktreePath, handoff.branch, handoff.head], handoff.primaryPath);
|
|
152
|
+
const report = this.signal.read(`${result.stdout}${result.stderr}`);
|
|
151
153
|
const output = report.text.trimEnd();
|
|
152
154
|
const head = '\n' + SEP + `🌲 Reaping ${handoff.worktreePath} from ${handoff.primaryPath}\n` + SEP + '\n'
|
|
153
155
|
+ ` The branch just landed, so that directory is dead. The reap runs in a child process\n`
|
|
154
156
|
+ ` whose cwd is the primary clone — nothing deletes the directory it is standing in.\n\n`;
|
|
155
157
|
const body = head + (output !== '' ? output + '\n' : '');
|
|
156
|
-
if (result.
|
|
157
|
-
return body + this.notRemoved(result.
|
|
158
|
+
if (result.code !== 0 || !report.removed) {
|
|
159
|
+
return body + this.notRemoved(result.code, report) + this.manualNotice(handoff);
|
|
158
160
|
}
|
|
159
161
|
return body + this.afterReap(handoff);
|
|
160
162
|
}
|
|
@@ -166,7 +168,7 @@ let LandedWorktreeReaper = class LandedWorktreeReaper {
|
|
|
166
168
|
*/
|
|
167
169
|
notRemoved(status, report) {
|
|
168
170
|
if (status !== 0) {
|
|
169
|
-
return `\n ⚠️ The reap did not complete (exit ${String(status
|
|
171
|
+
return `\n ⚠️ The reap did not complete (exit ${String(status)}). Nothing was forced.\n`;
|
|
170
172
|
}
|
|
171
173
|
const why = report.outcome === reap_outcome_1.REAP_OUTCOME_MISSING
|
|
172
174
|
? 'the child ended without reporting an outcome'
|
|
@@ -222,6 +224,7 @@ exports.LandedWorktreeReaper = LandedWorktreeReaper;
|
|
|
222
224
|
exports.LandedWorktreeReaper = LandedWorktreeReaper = tslib_1.__decorate([
|
|
223
225
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
224
226
|
tslib_1.__metadata("design:paramtypes", [repo_workflow_core_1.WorktreeService,
|
|
225
|
-
reap_outcome_1.ReapOutcomeSignal
|
|
227
|
+
reap_outcome_1.ReapOutcomeSignal,
|
|
228
|
+
tooling_common_1.NativeProcessApi])
|
|
226
229
|
], LandedWorktreeReaper);
|
|
227
230
|
//# 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,sEAA0E;AAC1E,0DAAiD;AACjD,yCAA2D;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AC,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
|
+
{"version":3,"file":"landed-worktree-reaper.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/landed-worktree-reaper.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,sEAA0E;AAC1E,0DAAiD;AACjD,8DAA6D;AAC7D,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,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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;AAtJY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGL,oCAAe;QAClB,gCAAiB;QACd,iCAAgB;GAJvC,oBAAoB,CAsJhC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { Worktree, WorktreeService } from '@webpieces/repo-workflow-core';\nimport { atRoot } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\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 private readonly processes: NativeProcessApi,\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 async handOff(handoff: WorktreeReapHandoff): Promise<string> {\n const result = await this.processes.run(\n process.execPath, [handoff.entryScript, handoff.worktreePath, handoff.branch, handoff.head],\n handoff.primaryPath);\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.code !== 0 || !report.removed) {\n return body + this.notRemoved(result.code, 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, report: ReapOutcomeReport): string {\n if (status !== 0) {\n return `\\n ⚠️ The reap did not complete (exit ${String(status)}). 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"]}
|
|
@@ -33,10 +33,10 @@ export declare class MergeEnd {
|
|
|
33
33
|
*/
|
|
34
34
|
mergeEnd(repoRoot: string, verb: MutationVerb, mergeDir: string, ctx: MergeContext, options: MergeEndOptions): Promise<void>;
|
|
35
35
|
private validateResolution;
|
|
36
|
-
|
|
36
|
+
private localBranchExists;
|
|
37
37
|
private finalizeBranch;
|
|
38
38
|
private explainNoPush;
|
|
39
|
-
|
|
39
|
+
private pushFinalized;
|
|
40
40
|
private remoteRecapLine;
|
|
41
41
|
private printSyncRecap;
|
|
42
42
|
}
|
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MergeEnd = exports.MergeEndOptions = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
-
const child_process_1 = require("child_process");
|
|
6
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
7
6
|
const path = tslib_1.__importStar(require("path"));
|
|
8
7
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
@@ -77,15 +76,15 @@ let MergeEnd = class MergeEnd {
|
|
|
77
76
|
const conflictedFiles = options.conflictedFiles;
|
|
78
77
|
if (conflictedFiles !== null) {
|
|
79
78
|
process.stdout.write('\n' + SEP + '🔎 Validating Merge Resolution\n' + SEP + '\n');
|
|
80
|
-
this.validateResolution(repoRoot, verb, mergeDir, conflictedFiles);
|
|
79
|
+
await this.validateResolution(repoRoot, verb, mergeDir, conflictedFiles);
|
|
81
80
|
// Stage the AI's resolved conflicts, but NEVER sweep untracked files into the squash commit.
|
|
82
81
|
// Fail on untracked so the AI commits or deletes them explicitly; then `git add -u` stages
|
|
83
82
|
// tracked resolutions only.
|
|
84
|
-
this.gitExec.assertNoUntracked(repoRoot);
|
|
85
|
-
this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');
|
|
86
|
-
const nothingStaged = (
|
|
83
|
+
await this.gitExec.assertNoUntracked(repoRoot);
|
|
84
|
+
await this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');
|
|
85
|
+
const nothingStaged = (await this.gitExec.tryGit(['diff-index', '--quiet', '--cached', 'HEAD', '--'], process.cwd())).ok;
|
|
87
86
|
if (!nothingStaged) {
|
|
88
|
-
this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${ctx.currentBranch} (conflicts resolved)`], 'Failed to commit resolved merge');
|
|
87
|
+
await this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${ctx.currentBranch} (conflicts resolved)`], 'Failed to commit resolved merge');
|
|
89
88
|
}
|
|
90
89
|
fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');
|
|
91
90
|
process.stdout.write('\n✅ Merge validated and committed.\n');
|
|
@@ -93,7 +92,7 @@ let MergeEnd = class MergeEnd {
|
|
|
93
92
|
// A marker in THIS run dir means the sync hit conflicts (marker is written only on hand-back).
|
|
94
93
|
// Read it BEFORE clearMergeMarker so finalize knows whether to keep the pre-merge snapshot.
|
|
95
94
|
const hadConflict = this.mergeState.readMergeMarker(mergeDir) !== null;
|
|
96
|
-
this.finalizeBranch(repoRoot, verb, ctx, hadConflict, options.pushRemote);
|
|
95
|
+
await this.finalizeBranch(repoRoot, verb, ctx, hadConflict, options.pushRemote);
|
|
97
96
|
this.mergeState.clearMergeMarker(mergeDir);
|
|
98
97
|
await this.cleanTmpService.cleanTmp();
|
|
99
98
|
}
|
|
@@ -102,7 +101,7 @@ let MergeEnd = class MergeEnd {
|
|
|
102
101
|
// `verb` is the bin the AI actually ran (wp-finish-update or wp-finish-upsert-pr) — every "re-run"
|
|
103
102
|
// instruction below is rendered from it. It used to be hardcoded to wp-finish-upsert-pr, which told
|
|
104
103
|
// someone in the update-only flow to finish with the PR command: a pairing that does not exist.
|
|
105
|
-
validateResolution(repoRoot, verb, mergeDir, conflictedFiles) {
|
|
104
|
+
async validateResolution(repoRoot, verb, mergeDir, conflictedFiles) {
|
|
106
105
|
const reRun = `pnpm ${verb}`;
|
|
107
106
|
// 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).
|
|
108
107
|
const scan = this.mergeState.scanConflictMarkers(repoRoot, conflictedFiles);
|
|
@@ -112,7 +111,7 @@ let MergeEnd = class MergeEnd {
|
|
|
112
111
|
`\n\nResolve them, then re-run: ${reRun}`);
|
|
113
112
|
}
|
|
114
113
|
// 2. Ensure git itself has no remaining unmerged entries.
|
|
115
|
-
const unmerged =
|
|
114
|
+
const unmerged = await this.gitExec.gitQuery(['diff', '--name-only', '--diff-filter=U'], process.cwd(), 'Failed to list unmerged files (git diff --diff-filter=U).');
|
|
116
115
|
if (unmerged !== '') {
|
|
117
116
|
throw new rules_config_1.CliExitError(1, '❌ Git still reports unmerged files:\n' + unmerged +
|
|
118
117
|
'\n\nResolve and `git add` them, then re-run: ' + reRun);
|
|
@@ -132,27 +131,26 @@ let MergeEnd = class MergeEnd {
|
|
|
132
131
|
}
|
|
133
132
|
process.stdout.write('✅ Merge explanations present for all resolved files.\n');
|
|
134
133
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
return (0, child_process_1.spawnSync)('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;
|
|
134
|
+
async localBranchExists(name) {
|
|
135
|
+
return (await this.gitExec.tryGit(['show-ref', '--verify', '--quiet', `refs/heads/${name}`], process.cwd())).ok;
|
|
138
136
|
}
|
|
139
137
|
// Force-push the squash branch to the stable feature branch (where the single PR lives) — unless the
|
|
140
138
|
// caller owns the push (see MergeEndOptions.pushRemote) — then RENAME the local squash branch back to
|
|
141
139
|
// that SAME feature name. On a CLEAN sync the pre-merge snapshot is disposable, so it's deleted at the
|
|
142
140
|
// very end; a CONFLICT sync — or a sync we did not push — keeps it.
|
|
143
141
|
// eslint-disable-next-line @typescript-eslint/max-params
|
|
144
|
-
finalizeBranch(repoRoot, verb, ctx, hadConflict, pushRemote) {
|
|
142
|
+
async finalizeBranch(repoRoot, verb, ctx, hadConflict, pushRemote) {
|
|
145
143
|
process.stdout.write('\n' + SEP + '🗑️ Finalizing\n' + SEP + '\n');
|
|
146
144
|
const base = this.branchNaming.baseBranchName(ctx.currentBranch);
|
|
147
|
-
this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');
|
|
148
|
-
const pushed = pushRemote ? this.pushFinalized(ctx, base) : this.explainNoPush();
|
|
149
|
-
this.gitExec.runGitChecked(['checkout', ctx.squashBranch], 'Failed to checkout squash branch');
|
|
145
|
+
await this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');
|
|
146
|
+
const pushed = pushRemote ? await this.pushFinalized(ctx, base) : this.explainNoPush();
|
|
147
|
+
await this.gitExec.runGitChecked(['checkout', ctx.squashBranch], 'Failed to checkout squash branch');
|
|
150
148
|
// Free the rename target: `base` is normally the branch we just deleted, but a backward-compat
|
|
151
149
|
// sync from a leftover `…wpN` can leave a separate stale `base` lingering — drop it too.
|
|
152
|
-
if (base !== ctx.currentBranch && this.localBranchExists(base)) {
|
|
153
|
-
this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');
|
|
150
|
+
if (base !== ctx.currentBranch && await this.localBranchExists(base)) {
|
|
151
|
+
await this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');
|
|
154
152
|
}
|
|
155
|
-
this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');
|
|
153
|
+
await this.gitExec.runGitChecked(['branch', '-m', base], 'Failed to rename squash branch to the feature name');
|
|
156
154
|
const renameEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'RENAME');
|
|
157
155
|
renameEvent.fromBranch = ctx.currentBranch;
|
|
158
156
|
renameEvent.toBranch = base;
|
|
@@ -165,8 +163,8 @@ let MergeEnd = class MergeEnd {
|
|
|
165
163
|
// deleting the snapshot would leave a history rewrite with no copy anywhere. It is disposable only
|
|
166
164
|
// once origin has the result, and in the PR flow that does not happen until wp-finish-upsert-pr.
|
|
167
165
|
const backupKept = hadConflict || !pushed;
|
|
168
|
-
if (!backupKept && this.localBranchExists(ctx.backupBranch)) {
|
|
169
|
-
this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');
|
|
166
|
+
if (!backupKept && await this.localBranchExists(ctx.backupBranch)) {
|
|
167
|
+
await this.gitExec.runGitChecked(['branch', '-D', ctx.backupBranch], 'Failed to delete clean-merge backup');
|
|
170
168
|
}
|
|
171
169
|
const finalizeEvent = new repo_workflow_core_1.BranchMutationEvent(verb, 'FINALIZE');
|
|
172
170
|
finalizeEvent.fromBranch = ctx.currentBranch;
|
|
@@ -187,14 +185,14 @@ let MergeEnd = class MergeEnd {
|
|
|
187
185
|
// Push the finalized squash branch to the stable feature branch. Returns whether a push actually
|
|
188
186
|
// happened — false when there is no remote branch yet (a brand-new branch is local until something
|
|
189
187
|
// creates it, which in the PR flow is `gh pr create` after GatedPrPublisher's push).
|
|
190
|
-
pushFinalized(ctx, base) {
|
|
191
|
-
const remoteExists = (
|
|
188
|
+
async pushFinalized(ctx, base) {
|
|
189
|
+
const remoteExists = (await this.gitExec.tryGit(['ls-remote', '--exit-code', '--heads', 'origin', base], process.cwd())).ok;
|
|
192
190
|
if (!remoteExists) {
|
|
193
191
|
process.stdout.write('No remote branch — local only.\n');
|
|
194
192
|
return false;
|
|
195
193
|
}
|
|
196
194
|
process.stdout.write(ctx.prNumber ? `Updating PR #${ctx.prNumber} (force-with-lease)...\n` : 'Updating remote branch (force-with-lease)...\n');
|
|
197
|
-
this.gitExec.runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${ctx.squashBranch}:${base}`], 'Failed to push to origin');
|
|
195
|
+
await this.gitExec.runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${ctx.squashBranch}:${base}`], 'Failed to push to origin');
|
|
198
196
|
return true;
|
|
199
197
|
}
|
|
200
198
|
// Where the branch ended up, in the recap's own words. Three distinct outcomes, and "deferred" must
|
|
@@ -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,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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AAC;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
|
+
{"version":3,"file":"merge-end.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-end.ts"],"names":[],"mappings":";;;;AAAA,+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,sG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ION_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 await 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 await this.gitExec.assertNoUntracked(repoRoot);\n await this.gitExec.runGitChecked(['add', '-u'], 'Failed to stage resolved files');\n\n const nothingStaged = (await this.gitExec.tryGit(['diff-index', '--quiet', '--cached', 'HEAD', '--'], process.cwd())).ok;\n if (!nothingStaged) {\n await 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 await 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 async validateResolution(repoRoot: string, verb: MutationVerb, mergeDir: string, conflictedFiles: string[]): Promise<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 = await this.gitExec.gitQuery(['diff', '--name-only', '--diff-filter=U'], process.cwd(), 'Failed to list unmerged files (git diff --diff-filter=U).');\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 private async localBranchExists(name: string): Promise<boolean> {\n return (await this.gitExec.tryGit(['show-ref', '--verify', '--quiet', `refs/heads/${name}`], process.cwd())).ok;\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 async finalizeBranch(repoRoot: string, verb: MutationVerb, ctx: MergeContext, hadConflict: boolean, pushRemote: boolean): Promise<void> {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n const base = this.branchNaming.baseBranchName(ctx.currentBranch);\n await this.gitExec.runGitChecked(['branch', '-D', ctx.currentBranch], 'Failed to delete old feature branch');\n\n const pushed = pushRemote ? await this.pushFinalized(ctx, base) : this.explainNoPush();\n await 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 && await this.localBranchExists(base)) {\n await this.gitExec.runGitChecked(['branch', '-D', base], 'Failed to delete stale base branch');\n }\n await 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 && await this.localBranchExists(ctx.backupBranch)) {\n await 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 private async pushFinalized(ctx: MergeContext, base: string): Promise<boolean> {\n const remoteExists = (await this.gitExec.tryGit(['ls-remote', '--exit-code', '--heads', 'origin', base], process.cwd())).ok;\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 await 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,3 +1,4 @@
|
|
|
1
|
+
import { GitProcessApi, NativeProcessApi } from '@webpieces/tooling-common';
|
|
1
2
|
import { MutationVerb } from '@webpieces/repo-workflow-core';
|
|
2
3
|
import { GatherInfo } from '../git-gatherInfo';
|
|
3
4
|
import { BranchNaming } from './branch-naming';
|
|
@@ -21,10 +22,13 @@ export declare class MergeStart {
|
|
|
21
22
|
private readonly branchNaming;
|
|
22
23
|
private readonly gitExec;
|
|
23
24
|
private readonly mergeState;
|
|
24
|
-
|
|
25
|
+
private readonly git;
|
|
26
|
+
private readonly processes;
|
|
27
|
+
constructor(gatherInfo: GatherInfo, branchNaming: BranchNaming, gitExec: GitExec, mergeState: MergeState, git: GitProcessApi, processes: NativeProcessApi);
|
|
25
28
|
mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult>;
|
|
26
29
|
private detectPr;
|
|
27
30
|
private chooseSyncSlot;
|
|
31
|
+
private branchExists;
|
|
28
32
|
private createBackup;
|
|
29
33
|
private saveConflictContext;
|
|
30
34
|
private mergeProcessDoc;
|