@webpieces/pr-gate 0.3.187 → 0.3.189
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 +2 -2
- package/src/scripts/git-gatherInfo.js +2 -1
- package/src/scripts/git-gatherInfo.js.map +1 -1
- package/src/scripts/git-mergeComplete.js +47 -24
- package/src/scripts/git-mergeComplete.js.map +1 -1
- package/src/scripts/git-updateFromMain.js +120 -17
- package/src/scripts/git-updateFromMain.js.map +1 -1
- package/src/scripts/workflow/build-affected.d.ts +13 -0
- package/src/scripts/workflow/build-affected.js +21 -0
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/cleanTmp.js +8 -1
- package/src/scripts/workflow/cleanTmp.js.map +1 -1
- package/src/scripts/workflow/git-findForkPoint.js +2 -1
- package/src/scripts/workflow/git-findForkPoint.js.map +1 -1
- package/src/scripts/workflow/merge-state.d.ts +9 -0
- package/src/scripts/workflow/merge-state.js +26 -0
- package/src/scripts/workflow/merge-state.js.map +1 -1
- package/src/scripts/wp-upsert-pr.js +8 -3
- package/src/scripts/wp-upsert-pr.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/pr-gate",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.189",
|
|
4
4
|
"description": "Gated PR system: 3-point squash-merge, merge validation gate, and red/yellow/green PR dashboard. Standalone scripts, no Nx dependency required.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"directory": "packages/tooling/pr-gate"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@webpieces/rules-config": "0.3.
|
|
25
|
+
"@webpieces/rules-config": "0.3.189"
|
|
26
26
|
},
|
|
27
27
|
"publishConfig": {
|
|
28
28
|
"access": "public"
|
|
@@ -6,6 +6,7 @@ const tslib_1 = require("tslib");
|
|
|
6
6
|
const child_process_1 = require("child_process");
|
|
7
7
|
const fs = tslib_1.__importStar(require("fs"));
|
|
8
8
|
const path = tslib_1.__importStar(require("path"));
|
|
9
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
9
10
|
const git_readAiBranchName_1 = require("./workflow/git-readAiBranchName");
|
|
10
11
|
const git_findForkPoint_1 = require("./workflow/git-findForkPoint");
|
|
11
12
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
@@ -58,7 +59,7 @@ async function main() {
|
|
|
58
59
|
const currentBranch = (0, child_process_1.execSync)('git branch --show-current', { encoding: 'utf8' }).trim();
|
|
59
60
|
const featureName = (0, git_readAiBranchName_1.getFeatureName)();
|
|
60
61
|
const repoRoot = (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
61
|
-
const mergeDir = path.join(repoRoot,
|
|
62
|
+
const mergeDir = path.join(repoRoot, rules_config_1.WEBPIECES_TMP_DIR, `merge-${featureName}`);
|
|
62
63
|
fs.mkdirSync(mergeDir, { recursive: true });
|
|
63
64
|
validateCleanTree(currentBranch);
|
|
64
65
|
process.stderr.write('\n');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git-gatherInfo.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/git-gatherInfo.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"git-gatherInfo.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/git-gatherInfo.ts"],"names":[],"mappings":";;;AAiEA,oBAwCC;;AAxGD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4D;AAC5D,0EAAiE;AACjE,oEAA6D;AAE7D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAQvE,SAAS,iBAAiB,CAAC,aAAqB;IAC5C,IAAI,aAA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AAC/B,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;QACjB,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\nimport { getFeatureName } from './workflow/git-readAiBranchName';\nimport { findForkPoint } from './workflow/git-findForkPoint';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\nfunction validateCleanTree(currentBranch: string): void {\n if (currentBranch === 'main') {\n process.stderr.write('❌ Error: Already on main branch. No need to update from main.\\n');\n process.exit(1);\n }\n\n process.stderr.write(`Current branch: ${currentBranch}\\n`);\n\n const hasDirtyFiles = spawnSync('git', ['diff-index', '--quiet', 'HEAD', '--']).status !== 0;\n if (!hasDirtyFiles) return;\n\n const changedFiles = execSync('git diff --name-only HEAD', { encoding: 'utf8' }).trim();\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('❌ ERROR: You have uncommitted changes\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n process.stderr.write('Please commit or stash your changes before updating from main.\\n');\n process.stderr.write('\\n');\n process.stderr.write('Files with changes:\\n');\n process.stderr.write(changedFiles + '\\n');\n process.stderr.write('\\n');\n process.stderr.write('\\x1b[1;31mTo commit your changes, run:\\n');\n process.stderr.write(' git add -A && git commit -m \"your message\"\\x1b[0m\\n');\n process.stderr.write('\\n');\n process.stderr.write('Or to stash them temporarily:\\n');\n process.stderr.write(' git stash\\n');\n process.stderr.write(' pnpm wp-git-update\\n');\n process.stderr.write(' git stash pop\\n');\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.exit(1);\n}\n\nfunction printHashPoints(hashes: HashPoints, currentBranch: string, mergeDir: string): void {\n process.stderr.write('📍 The 3 Hash Points:\\n');\n process.stderr.write(` 1. Fork point (A): ${hashes.hashForkPoint}\\n`);\n process.stderr.write(` (where ${currentBranch} diverged from main)\\n`);\n process.stderr.write('\\n');\n process.stderr.write(` 2. Feature HEAD (B): ${hashes.hashFeatureHead}\\n`);\n process.stderr.write(` (tip of ${currentBranch})\\n`);\n process.stderr.write('\\n');\n process.stderr.write(` 3. Main HEAD (C): ${hashes.hashMainHead}\\n`);\n process.stderr.write(' (current origin/main)\\n');\n process.stderr.write('\\n');\n process.stderr.write(`Merge directory: ${mergeDir}\\n`);\n process.stderr.write('\\n');\n}\n\nexport async function main(): Promise<void> {\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const featureName = getFeatureName();\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n const mergeDir = path.join(repoRoot, WEBPIECES_TMP_DIR, `merge-${featureName}`);\n fs.mkdirSync(mergeDir, { recursive: true });\n\n validateCleanTree(currentBranch);\n\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('📍 Gathering Merge Context\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n process.stderr.write('Fetching latest changes from origin/main...\\n');\n spawnSync('git', ['fetch', 'origin', 'main'], { stdio: 'inherit' });\n\n await findForkPoint('merge');\n\n const hashesFile = path.join(mergeDir, 'updatemain-hashes.json');\n const hashes = JSON.parse(fs.readFileSync(hashesFile, 'utf8')) as HashPoints;\n\n printHashPoints(hashes, currentBranch, mergeDir);\n\n if (hashes.hashForkPoint === hashes.hashMainHead) {\n process.stderr.write(SEP);\n process.stderr.write('✅ Already up to date with main!\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n process.stderr.write('Your branch has not diverged from main.\\n');\n process.stderr.write('There are no new changes from main to merge.\\n');\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.exit(0);\n }\n\n process.stderr.write('Main has advanced. Merge will be needed.\\n');\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n}\n\nif (require.main === module) {\n main().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
@@ -6,36 +6,24 @@ const tslib_1 = require("tslib");
|
|
|
6
6
|
const child_process_1 = require("child_process");
|
|
7
7
|
const fs = tslib_1.__importStar(require("fs"));
|
|
8
8
|
const path = tslib_1.__importStar(require("path"));
|
|
9
|
-
const rules_config_1 = require("@webpieces/rules-config");
|
|
10
9
|
const git_readAiBranchName_1 = require("./workflow/git-readAiBranchName");
|
|
11
10
|
const git_exec_1 = require("./workflow/git-exec");
|
|
12
11
|
const build_affected_1 = require("./workflow/build-affected");
|
|
12
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
13
13
|
const merge_state_1 = require("./workflow/merge-state");
|
|
14
14
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const marker = (0, merge_state_1.readMergeMarker)(mergeDir);
|
|
20
|
-
if (!marker) {
|
|
21
|
-
process.stderr.write('❌ No merge in progress (no marker found). Nothing to complete.\n');
|
|
22
|
-
process.exit(1);
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
if (marker.validated) {
|
|
26
|
-
process.stdout.write('✅ Merge already validated. Run pnpm wp-git-update (or wp-upsert-pr) to finalize.\n');
|
|
27
|
-
return;
|
|
28
|
-
}
|
|
29
|
-
process.stdout.write('\n' + SEP + '🔎 Validating Merge Resolution\n' + SEP + '\n');
|
|
15
|
+
// Validate the AI's resolution of the conflicted files — the part of the process the AI owns
|
|
16
|
+
// (branch creation/finalization is the script's job, so it is not re-checked here). Exits the
|
|
17
|
+
// process with a fix instruction on any failure; returns only when all three checks pass.
|
|
18
|
+
function validateResolution(repoRoot, mergeDir, conflictedFiles) {
|
|
30
19
|
// 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).
|
|
31
|
-
const scan = (0, merge_state_1.scanConflictMarkers)(repoRoot,
|
|
20
|
+
const scan = (0, merge_state_1.scanConflictMarkers)(repoRoot, conflictedFiles);
|
|
32
21
|
if (!scan.clean) {
|
|
33
22
|
process.stderr.write('❌ Unresolved conflict markers (<<<<<<< / ======= / >>>>>>>) remain in:\n');
|
|
34
23
|
for (const file of scan.filesWithMarkers)
|
|
35
24
|
process.stderr.write(` - ${file}\n`);
|
|
36
25
|
process.stderr.write('\nResolve them, then re-run: pnpm wp-git-merge-complete\n');
|
|
37
26
|
process.exit(1);
|
|
38
|
-
return;
|
|
39
27
|
}
|
|
40
28
|
// 2. Ensure git itself has no remaining unmerged entries.
|
|
41
29
|
const unmerged = (0, child_process_1.execSync)('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();
|
|
@@ -43,24 +31,59 @@ async function main() {
|
|
|
43
31
|
process.stderr.write('❌ Git still reports unmerged files:\n' + unmerged + '\n');
|
|
44
32
|
process.stderr.write('\nResolve and `git add` them, then re-run: pnpm wp-git-merge-complete\n');
|
|
45
33
|
process.exit(1);
|
|
46
|
-
return;
|
|
47
34
|
}
|
|
48
35
|
process.stdout.write('✅ No conflict markers in resolved files.\n');
|
|
36
|
+
// 3. Explanation check — every conflicted file must have a non-empty merge-explanation.md in
|
|
37
|
+
// its per-file context dir, proving the AI deliberately 3-point merged it (and recording how)
|
|
38
|
+
// rather than blindly taking one side. A sidecar file works for any type, incl. JSON/deletes.
|
|
39
|
+
const explanations = (0, merge_state_1.scanMergeExplanations)(mergeDir, conflictedFiles);
|
|
40
|
+
if (!explanations.clean) {
|
|
41
|
+
process.stderr.write(`❌ Missing/empty merge explanation (${rules_config_1.MERGE_EXPLANATION_FILE}) for:\n`);
|
|
42
|
+
for (const file of explanations.filesWithMarkers) {
|
|
43
|
+
process.stderr.write(` - ${file}\n → ${path.join((0, merge_state_1.perFileContextDir)(mergeDir, file), rules_config_1.MERGE_EXPLANATION_FILE)}\n`);
|
|
44
|
+
}
|
|
45
|
+
process.stderr.write('\nWrite a few sentences on how you resolved each (which side, what you combined, why),\n' +
|
|
46
|
+
'then re-run: pnpm wp-git-merge-complete\n');
|
|
47
|
+
process.exit(1);
|
|
48
|
+
}
|
|
49
|
+
process.stdout.write('✅ Merge explanations present for all resolved files.\n');
|
|
50
|
+
}
|
|
51
|
+
async function main() {
|
|
52
|
+
const repoRoot = (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
53
|
+
const featureName = (0, git_readAiBranchName_1.getFeatureName)();
|
|
54
|
+
const mergeDir = (0, merge_state_1.mergeDirFor)(repoRoot, featureName);
|
|
55
|
+
const marker = (0, merge_state_1.readMergeMarker)(mergeDir);
|
|
56
|
+
if (!marker) {
|
|
57
|
+
process.stderr.write('❌ No merge in progress (no marker found). Nothing to complete.\n');
|
|
58
|
+
process.exit(1);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (marker.validated) {
|
|
62
|
+
process.stdout.write('✅ Merge already validated. Run pnpm wp-git-update (or wp-upsert-pr) to finalize.\n');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
process.stdout.write('\n' + SEP + '🔎 Validating Merge Resolution\n' + SEP + '\n');
|
|
66
|
+
validateResolution(repoRoot, mergeDir, marker.conflictedFiles);
|
|
49
67
|
(0, git_exec_1.runGitChecked)(['add', '-A'], 'Failed to stage resolved files');
|
|
50
|
-
//
|
|
51
|
-
const
|
|
68
|
+
// Build gate (authoritative). Same configured command wp-upsert-pr uses — fast on a big monorepo.
|
|
69
|
+
const buildCommand = (0, build_affected_1.resolveBuildCommand)(repoRoot);
|
|
70
|
+
process.stdout.write(`\nRunning the build gate. To get it passing, run the SAME command yourself and fix everything it reports:\n\n` +
|
|
71
|
+
` ${buildCommand}\n\n`);
|
|
72
|
+
const buildCode = (0, build_affected_1.runConfiguredBuildGate)(repoRoot);
|
|
52
73
|
if (buildCode !== 0) {
|
|
53
|
-
process.stderr.write(
|
|
74
|
+
process.stderr.write(`\n❌ Build failed.\n\n` +
|
|
75
|
+
`Run THIS exact command to reproduce and fix all errors, then re-run pnpm wp-git-merge-complete:\n\n` +
|
|
76
|
+
` ${buildCommand}\n\n`);
|
|
54
77
|
process.exit(buildCode);
|
|
55
78
|
return;
|
|
56
79
|
}
|
|
57
80
|
process.stdout.write('\n✅ Build passed.\n');
|
|
58
|
-
//
|
|
81
|
+
// Commit the resolved squash merge.
|
|
59
82
|
const nothingStaged = (0, child_process_1.spawnSync)('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;
|
|
60
83
|
if (!nothingStaged) {
|
|
61
84
|
(0, git_exec_1.runGitChecked)(['commit', '-m', `Squash merge of ${marker.currentBranch} (conflicts resolved)`], 'Failed to commit resolved merge');
|
|
62
85
|
}
|
|
63
|
-
//
|
|
86
|
+
// Flip the marker to validated + drop the proof file → unblocks the guard.
|
|
64
87
|
marker.validated = true;
|
|
65
88
|
(0, merge_state_1.writeMergeMarker)(mergeDir, marker);
|
|
66
89
|
fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git-mergeComplete.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/git-mergeComplete.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"git-mergeComplete.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CACpC,CAAC;IACN,CAAC;IAED,2EAA2E;IAC3E,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;IACxB,IAAA,8BAAgB,EAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACnC,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,oBAAoB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEhE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,GAAG,GAAG,mCAAmC,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;IACpF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,6EAA6E,CAAC,CAAC;AACxG,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAU,EAAE,EAAE;QACxB,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getFeatureName } from './workflow/git-readAiBranchName';\nimport { runGitChecked } from './workflow/git-exec';\nimport { runConfiguredBuildGate, resolveBuildCommand } from './workflow/build-affected';\nimport { MERGE_EXPLANATION_FILE } from '@webpieces/rules-config';\nimport {\n mergeDirFor,\n perFileContextDir,\n readMergeMarker,\n writeMergeMarker,\n scanConflictMarkers,\n scanMergeExplanations,\n} from './workflow/merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// Validate the AI's resolution of the conflicted files — the part of the process the AI owns\n// (branch creation/finalization is the script's job, so it is not re-checked here). Exits the\n// process with a fix instruction on any failure; returns only when all three checks pass.\nfunction validateResolution(repoRoot: string, mergeDir: string, conflictedFiles: string[]): void {\n // 1. Scoped conflict-marker scan (only the conflicted files — O(conflicts), not O(repo)).\n const scan = scanConflictMarkers(repoRoot, conflictedFiles);\n if (!scan.clean) {\n process.stderr.write('❌ Unresolved conflict markers (<<<<<<< / ======= / >>>>>>>) remain in:\\n');\n for (const file of scan.filesWithMarkers) process.stderr.write(` - ${file}\\n`);\n process.stderr.write('\\nResolve them, then re-run: pnpm wp-git-merge-complete\\n');\n process.exit(1);\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 process.stderr.write('❌ Git still reports unmerged files:\\n' + unmerged + '\\n');\n process.stderr.write('\\nResolve and `git add` them, then re-run: pnpm wp-git-merge-complete\\n');\n process.exit(1);\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\n // its per-file context dir, proving the AI deliberately 3-point merged it (and recording how)\n // rather than blindly taking one side. A sidecar file works for any type, incl. JSON/deletes.\n const explanations = scanMergeExplanations(mergeDir, conflictedFiles);\n if (!explanations.clean) {\n process.stderr.write(`❌ Missing/empty merge explanation (${MERGE_EXPLANATION_FILE}) for:\\n`);\n for (const file of explanations.filesWithMarkers) {\n process.stderr.write(` - ${file}\\n → ${path.join(perFileContextDir(mergeDir, file), MERGE_EXPLANATION_FILE)}\\n`);\n }\n process.stderr.write(\n '\\nWrite a few sentences on how you resolved each (which side, what you combined, why),\\n' +\n 'then re-run: pnpm wp-git-merge-complete\\n',\n );\n process.exit(1);\n }\n process.stdout.write('✅ Merge explanations present for all resolved files.\\n');\n}\n\nexport async function main(): Promise<void> {\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n const featureName = getFeatureName();\n const mergeDir = mergeDirFor(repoRoot, featureName);\n\n const marker = readMergeMarker(mergeDir);\n if (!marker) {\n process.stderr.write('❌ No merge in progress (no marker found). Nothing to complete.\\n');\n process.exit(1);\n return;\n }\n if (marker.validated) {\n process.stdout.write('✅ Merge already validated. Run pnpm wp-git-update (or wp-upsert-pr) to finalize.\\n');\n return;\n }\n\n process.stdout.write('\\n' + SEP + '🔎 Validating Merge Resolution\\n' + SEP + '\\n');\n\n validateResolution(repoRoot, mergeDir, marker.conflictedFiles);\n runGitChecked(['add', '-A'], 'Failed to stage resolved files');\n\n // Build gate (authoritative). Same configured command wp-upsert-pr uses — fast on a big monorepo.\n const buildCommand = resolveBuildCommand(repoRoot);\n process.stdout.write(\n `\\nRunning the build gate. To get it passing, run the SAME command yourself and fix everything it reports:\\n\\n` +\n ` ${buildCommand}\\n\\n`,\n );\n const buildCode = runConfiguredBuildGate(repoRoot);\n if (buildCode !== 0) {\n process.stderr.write(\n `\\n❌ Build failed.\\n\\n` +\n `Run THIS exact command to reproduce and fix all errors, then re-run pnpm wp-git-merge-complete:\\n\\n` +\n ` ${buildCommand}\\n\\n`,\n );\n process.exit(buildCode);\n return;\n }\n process.stdout.write('\\n✅ Build passed.\\n');\n\n // Commit the resolved squash merge.\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (!nothingStaged) {\n runGitChecked(\n ['commit', '-m', `Squash merge of ${marker.currentBranch} (conflicts resolved)`],\n 'Failed to commit resolved merge',\n );\n }\n\n // Flip the marker to validated + drop the proof file → unblocks the guard.\n marker.validated = true;\n writeMergeMarker(mergeDir, marker);\n fs.writeFileSync(path.join(mergeDir, 'conflicts-resolved'), '');\n\n process.stdout.write('\\n' + SEP + '✅ Merge validated and committed\\n' + SEP + '\\n');\n process.stdout.write('Finalize & push by running: pnpm wp-upsert-pr (or pnpm wp-git-update)\\n\\n');\n}\n\nif (require.main === module) {\n main().catch((err: Error) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
@@ -6,6 +6,7 @@ const tslib_1 = require("tslib");
|
|
|
6
6
|
const child_process_1 = require("child_process");
|
|
7
7
|
const fs = tslib_1.__importStar(require("fs"));
|
|
8
8
|
const path = tslib_1.__importStar(require("path"));
|
|
9
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
9
10
|
const git_readAiBranchName_1 = require("./workflow/git-readAiBranchName");
|
|
10
11
|
const git_gatherInfo_1 = require("./git-gatherInfo");
|
|
11
12
|
const cleanTmp_1 = require("./workflow/cleanTmp");
|
|
@@ -30,8 +31,7 @@ function createBackup(currentBranch) {
|
|
|
30
31
|
}
|
|
31
32
|
function saveConflictContext(conflictedFiles, mergeDir, forkPoint, featureHead, mainHead) {
|
|
32
33
|
for (const file of conflictedFiles) {
|
|
33
|
-
const
|
|
34
|
-
const fileDir = path.join(mergeDir, `updatemain-${safePath}`);
|
|
34
|
+
const fileDir = (0, merge_state_1.perFileContextDir)(mergeDir, file);
|
|
35
35
|
fs.mkdirSync(fileDir, { recursive: true });
|
|
36
36
|
const fork = (0, child_process_1.spawnSync)('git', ['show', `${forkPoint}:${file}`], { encoding: 'utf8' });
|
|
37
37
|
fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.status === 0 ? (fork.stdout ?? '') : '(file did not exist)\n');
|
|
@@ -45,30 +45,133 @@ function saveConflictContext(conflictedFiles, mergeDir, forkPoint, featureHead,
|
|
|
45
45
|
fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout ?? '');
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
|
-
|
|
48
|
+
// Single source of truth for the merge process. The script WRITES it at conflict time (rather
|
|
49
|
+
// than the AI relying on a separate hand-maintained doc), parameterized with the live MERGE_DIR
|
|
50
|
+
// and conflicted-file list, so the instructions can never drift from the actual layout. The body
|
|
51
|
+
// is a template constant with {{...}} placeholders so this stays a small filler function.
|
|
52
|
+
const MERGE_PROCESS_TEMPLATE = `# AI-Assisted Squash-Merge Conflict Resolution (generated)
|
|
53
|
+
|
|
54
|
+
This file was generated by \`pnpm wp-git-update\` when the 3-point squash-merge hit conflicts.
|
|
55
|
+
It is the single source of truth for the merge process — follow it exactly.
|
|
56
|
+
|
|
57
|
+
You are on branch \`{{SQUASH_BRANCH}}\` with conflict markers in the working tree.
|
|
58
|
+
\`MERGE_DIR = {{MERGE_DIR}}\`
|
|
59
|
+
|
|
60
|
+
## How the gate works
|
|
61
|
+
|
|
62
|
+
- Resolve every conflicted file in the working tree.
|
|
63
|
+
- Run **\`pnpm wp-git-merge-complete\`** — the validation gate. It scans for leftover conflict
|
|
64
|
+
markers, checks each conflicted file has a written merge explanation, runs the \`nx affected\`
|
|
65
|
+
build, and — only if all pass — stages, commits, and unblocks the workflow.
|
|
66
|
+
- **Do NOT run \`git add\` / \`git commit\` / \`git push\` / \`gh pr\` yourself.** They are blocked by
|
|
67
|
+
the \`merge-in-progress-guard\` hook until the gate validates. The gate does the commit.
|
|
68
|
+
|
|
69
|
+
## STEP 1 — Load the merge context
|
|
70
|
+
|
|
71
|
+
Per conflicted file, \`MERGE_DIR/updatemain-<safe_path>/\` holds (\`<safe_path>\` = path with \`/\`→\`__\`):
|
|
72
|
+
|
|
73
|
+
\`\`\`
|
|
74
|
+
A-forkpoint.txt # file at fork point (base)
|
|
75
|
+
B-feature.txt # file on your feature branch
|
|
76
|
+
C-main.txt # file on main
|
|
77
|
+
B-A.diff # what your feature changed (B−A)
|
|
78
|
+
C-A.diff # what main changed (C−A)
|
|
79
|
+
\`\`\`
|
|
80
|
+
|
|
81
|
+
\`updatemain-hashes.json\` holds A/B/C commit hashes. To see why main changed:
|
|
82
|
+
\`git log <A>..<C> --oneline\`.
|
|
83
|
+
|
|
84
|
+
## STEP 2 — Resolve each conflicted file
|
|
85
|
+
|
|
86
|
+
For each file: read the working-tree file (the markers) and its \`B-A.diff\` / \`C-A.diff\` (intent),
|
|
87
|
+
then Edit to the resolved version, removing ALL conflict markers.
|
|
88
|
+
|
|
89
|
+
Strategies: goals align & non-overlapping → merge both · one side removes what the other modifies
|
|
90
|
+
→ prefer the removal · same lines, simple (imports/format) → merge both · same lines, complex or
|
|
91
|
+
conflicting goals → ask the user · feature re-implements what main already squashed → prefer
|
|
92
|
+
main's, then re-apply only the genuinely new feature work.
|
|
93
|
+
|
|
94
|
+
**Then write a merge explanation** for each conflicted file — NOT a comment in the source (that
|
|
95
|
+
breaks for JSON and deleted files). Write it next to that file's diffs, at:
|
|
96
|
+
|
|
97
|
+
\`\`\`
|
|
98
|
+
MERGE_DIR/updatemain-<safe_path>/{{EXPLANATION_FILE}}
|
|
99
|
+
\`\`\`
|
|
100
|
+
|
|
101
|
+
(\`<safe_path>\` = the conflict file path with \`/\` → \`__\`, the same dir that holds its
|
|
102
|
+
\`A-forkpoint.txt\` / \`B-A.diff\` / \`C-A.diff\`.) In it, explain in a few sentences how you resolved
|
|
103
|
+
this file: which side you took where, what you combined from B-A.diff vs C-A.diff, and why. The
|
|
104
|
+
gate fails if any conflicted file's explanation is missing or empty. Do not paste A/B/C context
|
|
105
|
+
blocks into the source code.
|
|
106
|
+
|
|
107
|
+
## STEP 3 — Run the gate
|
|
108
|
+
|
|
109
|
+
\`\`\`
|
|
110
|
+
pnpm wp-git-merge-complete
|
|
111
|
+
\`\`\`
|
|
112
|
+
|
|
113
|
+
- Leftover conflict markers → fix those files and re-run.
|
|
114
|
+
- Missing merge explanation → write it (see STEP 2) and re-run.
|
|
115
|
+
- Build failure → fix the TypeScript/lint errors and re-run (the gate re-stages for you).
|
|
116
|
+
- On success it commits and prints the finalize instruction.
|
|
117
|
+
|
|
118
|
+
## STEP 4 — Finalize
|
|
119
|
+
|
|
120
|
+
\`\`\`
|
|
121
|
+
pnpm wp-upsert-pr # (or pnpm wp-git-update)
|
|
122
|
+
\`\`\`
|
|
123
|
+
|
|
124
|
+
Force-pushes the resolved squash branch over your feature branch and updates/creates the PR.
|
|
125
|
+
|
|
126
|
+
## Conflicted files
|
|
127
|
+
|
|
128
|
+
{{FILE_LIST}}
|
|
129
|
+
|
|
130
|
+
## If you need to bail out
|
|
131
|
+
|
|
132
|
+
A backup branch was created (e.g. \`<feature>Backup1\`). To abandon:
|
|
133
|
+
|
|
134
|
+
\`\`\`
|
|
135
|
+
git merge --abort 2>/dev/null; git checkout <feature> ; git branch -D {{SQUASH_BRANCH}}
|
|
136
|
+
\`\`\`
|
|
137
|
+
|
|
138
|
+
Then delete \`{{MERGE_DIR}}/\` for a clean slate.
|
|
139
|
+
`;
|
|
140
|
+
function mergeProcessDoc(mergeDir, squashBranch, conflictedFiles) {
|
|
141
|
+
const fileList = conflictedFiles.map((f) => `- \`${f}\``).join('\n');
|
|
142
|
+
return MERGE_PROCESS_TEMPLATE
|
|
143
|
+
.replace(/\{\{SQUASH_BRANCH\}\}/g, squashBranch)
|
|
144
|
+
.replace(/\{\{MERGE_DIR\}\}/g, mergeDir)
|
|
145
|
+
.replace(/\{\{EXPLANATION_FILE\}\}/g, rules_config_1.MERGE_EXPLANATION_FILE)
|
|
146
|
+
.replace(/\{\{FILE_LIST\}\}/g, fileList);
|
|
147
|
+
}
|
|
148
|
+
// Returns the absolute path of the written doc.
|
|
149
|
+
function writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles) {
|
|
150
|
+
const docDir = path.join(repoRoot, rules_config_1.WEBPIECES_TMP_DIR, 'instruct-ai');
|
|
151
|
+
fs.mkdirSync(docDir, { recursive: true });
|
|
152
|
+
const docPath = path.join(docDir, 'webpieces.mergeprocess.md');
|
|
153
|
+
fs.writeFileSync(docPath, mergeProcessDoc(mergeDir, squashBranch, conflictedFiles));
|
|
154
|
+
return docPath;
|
|
155
|
+
}
|
|
156
|
+
function printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles) {
|
|
49
157
|
process.stdout.write('\n' + SEP + `⚠️ Conflicts in ${conflictedFiles.length} file(s) — handing control back to you\n` + SEP + '\n');
|
|
50
|
-
process.stdout.write(`You are on branch ${squashBranch} with conflicts in the working tree.\n`);
|
|
51
|
-
process.stdout.write(`
|
|
52
|
-
process.stdout.write(
|
|
53
|
-
process.stdout.write('RESOLVE NOW (in the working tree):\n');
|
|
54
|
-
process.stdout.write(' 1. Edit each conflicted file, combining your changes (B−A) with main\'s (C−A).\n');
|
|
55
|
-
process.stdout.write(' 2. Do NOT git commit / git push / gh pr — these are blocked until validated.\n');
|
|
56
|
-
process.stdout.write(' 3. When every file is resolved, run: pnpm wp-git-merge-complete\n');
|
|
57
|
-
process.stdout.write(' (runs the conflict-marker scan + build; commits only if green)\n');
|
|
58
|
-
process.stdout.write(' 4. Then re-run pnpm wp-upsert-pr (or pnpm wp-git-update) to finalize & push.\n\n');
|
|
158
|
+
process.stdout.write(`You are on branch ${squashBranch} with conflicts in the working tree.\n\n`);
|
|
159
|
+
process.stdout.write(`FOLLOW THE MERGE PROCESS: ${docPath}\n`);
|
|
160
|
+
process.stdout.write(`3-point context per file in: ${mergeDir}/updatemain-<file>/\n\n`);
|
|
59
161
|
process.stdout.write('Conflicted files:\n');
|
|
60
162
|
for (const file of conflictedFiles)
|
|
61
163
|
process.stdout.write(` - ${file}\n`);
|
|
62
164
|
process.stdout.write('\n' + SEP);
|
|
63
165
|
}
|
|
64
|
-
function handleConflictsHandback(mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes) {
|
|
166
|
+
function handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes) {
|
|
65
167
|
const raw = (0, child_process_1.execSync)('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();
|
|
66
168
|
const conflictedFiles = raw.split('\n').filter((f) => f.trim() !== '');
|
|
67
169
|
fs.writeFileSync(path.join(mergeDir, 'updatemain-conflicted-files.txt'), raw + '\n');
|
|
68
170
|
saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);
|
|
69
171
|
const marker = new merge_state_1.MergeMarker(currentBranch, squashBranch, backupBranch, prNumber, conflictedFiles, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead, false);
|
|
70
172
|
(0, merge_state_1.writeMergeMarker)(mergeDir, marker);
|
|
71
|
-
|
|
173
|
+
const docPath = writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles);
|
|
174
|
+
printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles);
|
|
72
175
|
process.exit(2);
|
|
73
176
|
}
|
|
74
177
|
function finalizeBranch(currentBranch, squashBranch, backupBranch, prNumber) {
|
|
@@ -99,7 +202,7 @@ async function handleResume(mergeDir, marker) {
|
|
|
99
202
|
(0, merge_state_1.clearMergeMarker)(mergeDir);
|
|
100
203
|
await (0, cleanTmp_1.main)();
|
|
101
204
|
}
|
|
102
|
-
async function runFreshUpdate(mergeDir) {
|
|
205
|
+
async function runFreshUpdate(repoRoot, mergeDir) {
|
|
103
206
|
const currentBranch = (0, child_process_1.execSync)('git branch --show-current', { encoding: 'utf8' }).trim();
|
|
104
207
|
if (currentBranch.endsWith('Squash')) {
|
|
105
208
|
process.stderr.write(`❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}\n`);
|
|
@@ -122,7 +225,7 @@ async function runFreshUpdate(mergeDir) {
|
|
|
122
225
|
process.stdout.write('\n' + SEP + `🔀 Squash merging ${currentBranch}\n` + SEP + '\n');
|
|
123
226
|
const merge = (0, child_process_1.spawnSync)('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });
|
|
124
227
|
if (merge.status !== 0) {
|
|
125
|
-
handleConflictsHandback(mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes);
|
|
228
|
+
handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes);
|
|
126
229
|
return;
|
|
127
230
|
}
|
|
128
231
|
const nothingStaged = (0, child_process_1.spawnSync)('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;
|
|
@@ -145,7 +248,7 @@ async function main() {
|
|
|
145
248
|
await handleResume(mergeDir, existing);
|
|
146
249
|
return;
|
|
147
250
|
}
|
|
148
|
-
await runFreshUpdate(mergeDir);
|
|
251
|
+
await runFreshUpdate(repoRoot, mergeDir);
|
|
149
252
|
}
|
|
150
253
|
if (require.main === module) {
|
|
151
254
|
main().catch((err) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git-updateFromMain.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/git-updateFromMain.ts"],"names":[],"mappings":";;;AAgLA,oBAYC;;AA3LD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0EAAiE;AACjE,qDAAsD;AACtD,kDAAuD;AACvD,kDAAoD;AACpD,wDAMgC;AAEhC,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAQvE,SAAS,QAAQ,CAAC,aAAqB;IACnC,MAAM,MAAM,GAAG,IAAA,yBAAS,EACpB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EACxF,EAAE,QAAQ,EAAE,MAAM,EAAE,CACvB,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACnE,CAAC;AAED,SAAS,YAAY,CAAC,aAAqB;IACvC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,GAAG,GAAG,kCAAkC,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;IACnF,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,OAAO,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,UAAU,EAAE,UAAU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CAAC,CAAC;QACjE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getFeatureName } from './workflow/git-readAiBranchName';\nimport { main as gatherInfo } from './git-gatherInfo';\nimport { main as cleanTmp } from './workflow/cleanTmp';\nimport { runGitChecked } from './workflow/git-exec';\nimport {\n MergeMarker,\n mergeDirFor,\n readMergeMarker,\n writeMergeMarker,\n clearMergeMarker,\n} from './workflow/merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\nfunction detectPr(currentBranch: string): string {\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', currentBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\nfunction createBackup(currentBranch: string): string {\n process.stdout.write('\\n' + SEP + '💾 Creating Incremental Backup\\n' + SEP + '\\n');\n let n = 1;\n while (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${currentBranch}Backup${n}`]).status === 0) {\n n += 1;\n }\n const backupBranch = `${currentBranch}Backup${n}`;\n runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n return backupBranch;\n}\n\nfunction saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n): void {\n for (const file of conflictedFiles) {\n const safePath = file.replace(/\\//g, '__');\n const fileDir = path.join(mergeDir, `updatemain-${safePath}`);\n fs.mkdirSync(fileDir, { recursive: true });\n\n const fork = spawnSync('git', ['show', `${forkPoint}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.status === 0 ? (fork.stdout ?? '') : '(file did not exist)\\n');\n const feature = spawnSync('git', ['show', `${featureHead}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.status === 0 ? (feature.stdout ?? '') : '(file did not exist)\\n');\n const main = spawnSync('git', ['show', `${mainHead}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.status === 0 ? (main.stdout ?? '') : '(file did not exist)\\n');\n\n const ba = spawnSync('git', ['diff', forkPoint, featureHead, '--', file], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout ?? '');\n const ca = spawnSync('git', ['diff', forkPoint, mainHead, '--', file], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout ?? '');\n }\n}\n\nfunction printConflictHandback(mergeDir: string, squashBranch: string, conflictedFiles: string[]): void {\n process.stdout.write('\\n' + SEP + `⚠️ Conflicts in ${conflictedFiles.length} file(s) — handing control back to you\\n` + SEP + '\\n');\n process.stdout.write(`You are on branch ${squashBranch} with conflicts in the working tree.\\n`);\n process.stdout.write(`3-point context per file in: ${mergeDir}/updatemain-<file>/\\n`);\n process.stdout.write(' A-forkpoint.txt (base) · B-feature.txt (yours) · C-main.txt (main) · B-A.diff · C-A.diff\\n\\n');\n process.stdout.write('RESOLVE NOW (in the working tree):\\n');\n process.stdout.write(' 1. Edit each conflicted file, combining your changes (B−A) with main\\'s (C−A).\\n');\n process.stdout.write(' 2. Do NOT git commit / git push / gh pr — these are blocked until validated.\\n');\n process.stdout.write(' 3. When every file is resolved, run: pnpm wp-git-merge-complete\\n');\n process.stdout.write(' (runs the conflict-marker scan + build; commits only if green)\\n');\n process.stdout.write(' 4. Then re-run pnpm wp-upsert-pr (or pnpm wp-git-update) to finalize & push.\\n\\n');\n process.stdout.write('Conflicted files:\\n');\n for (const file of conflictedFiles) process.stdout.write(` - ${file}\\n`);\n process.stdout.write('\\n' + SEP);\n}\n\nfunction handleConflictsHandback(\n mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints,\n): void {\n const raw = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n const conflictedFiles = raw.split('\\n').filter((f: string): boolean => f.trim() !== '');\n fs.writeFileSync(path.join(mergeDir, 'updatemain-conflicted-files.txt'), raw + '\\n');\n saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n\n const marker = new MergeMarker(\n currentBranch, squashBranch, backupBranch, prNumber, conflictedFiles,\n hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead, false,\n );\n writeMergeMarker(mergeDir, marker);\n printConflictHandback(mergeDir, squashBranch, conflictedFiles);\n process.exit(2);\n}\n\nfunction finalizeBranch(\n currentBranch: string, squashBranch: string, backupBranch: string, prNumber: string,\n): void {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n runGitChecked(['branch', '-D', currentBranch], 'Failed to delete old feature branch');\n\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n process.stdout.write(prNumber ? `Updating PR #${prNumber} (force-with-lease)...\\n` : 'Updating remote branch (force-with-lease)...\\n');\n runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${squashBranch}:${currentBranch}`], 'Failed to push to origin');\n } else {\n process.stdout.write('No remote branch — local only.\\n');\n }\n runGitChecked(['checkout', squashBranch], 'Failed to checkout squash branch');\n runGitChecked(['branch', '-m', currentBranch], 'Failed to rename squash branch');\n\n process.stdout.write(`\\n✅ Branch ${currentBranch} updated from main. Backup: ${backupBranch}\\n`);\n process.stdout.write(` Delete backup when safe: git branch -D ${backupBranch}\\n\\n`);\n}\n\nasync function handleResume(mergeDir: string, marker: MergeMarker): Promise<void> {\n if (!marker.validated) {\n process.stdout.write('\\n' + SEP + '⏸️ Merge in progress — not yet validated\\n' + SEP + '\\n');\n process.stdout.write('Resolve the remaining conflicts in the working tree, then run:\\n');\n process.stdout.write(' pnpm wp-git-merge-complete\\n\\n');\n process.exit(1);\n }\n process.stdout.write('Resuming: merge validated — finalizing.\\n');\n finalizeBranch(marker.currentBranch, marker.squashBranch, marker.backupBranch, marker.prNumber);\n clearMergeMarker(mergeDir);\n await cleanTmp();\n}\n\nasync function runFreshUpdate(mergeDir: string): Promise<void> {\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n if (currentBranch.endsWith('Squash')) {\n process.stderr.write(`❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}\\n`);\n process.exit(1);\n }\n\n process.stdout.write('\\n' + SEP + '🔄 Squash-Merge Update from Main\\n' + SEP + '\\n');\n await gatherInfo();\n const hashes = JSON.parse(fs.readFileSync(path.join(mergeDir, 'updatemain-hashes.json'), 'utf8')) as HashPoints;\n\n const prNumber = detectPr(currentBranch);\n process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\\n` : 'No existing PR (one can be created later).\\n');\n\n const backupBranch = createBackup(currentBranch);\n const squashBranch = `${currentBranch}Squash`;\n if (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {\n process.stderr.write(`❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}\\n`);\n process.exit(1);\n }\n\n runGitChecked(['checkout', 'main'], 'Failed to checkout main');\n runGitChecked(['pull', 'origin', 'main'], 'Failed to pull origin/main');\n runGitChecked(['checkout', '-b', squashBranch], 'Failed to create squash branch');\n\n process.stdout.write('\\n' + SEP + `🔀 Squash merging ${currentBranch}\\n` + SEP + '\\n');\n const merge = spawnSync('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });\n if (merge.status !== 0) {\n handleConflictsHandback(mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes);\n return;\n }\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (nothingStaged) {\n process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\\n');\n } else {\n runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');\n }\n finalizeBranch(currentBranch, squashBranch, backupBranch, prNumber);\n await cleanTmp();\n}\n\nexport async function main(): Promise<void> {\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n const featureName = getFeatureName();\n const mergeDir = mergeDirFor(repoRoot, featureName);\n fs.mkdirSync(mergeDir, { recursive: true });\n\n const existing = readMergeMarker(mergeDir);\n if (existing) {\n await handleResume(mergeDir, existing);\n return;\n }\n await runFreshUpdate(mergeDir);\n}\n\nif (require.main === module) {\n main().catch((err: Error) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"git-updateFromMain.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/git-updateFromMain.ts"],"names":[],"mappings":";;;AA2RA,oBAYC;;AAtSD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAoF;AACpF,0EAAiE;AACjE,qDAAsD;AACtD,kDAAuD;AACvD,kDAAoD;AACpD,wDAOgC;AAEhC,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAQvE,SAAS,QAAQ,CAAC,aAAqB;IACnC,MAAM,MAAM,GAAG,IAAA,yBAAS,EACpB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EACxF,EAAE,QAA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C,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { WEBPIECES_TMP_DIR, MERGE_EXPLANATION_FILE } from '@webpieces/rules-config';\nimport { getFeatureName } from './workflow/git-readAiBranchName';\nimport { main as gatherInfo } from './git-gatherInfo';\nimport { main as cleanTmp } from './workflow/cleanTmp';\nimport { runGitChecked } from './workflow/git-exec';\nimport {\n MergeMarker,\n mergeDirFor,\n perFileContextDir,\n readMergeMarker,\n writeMergeMarker,\n clearMergeMarker,\n} from './workflow/merge-state';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\nfunction detectPr(currentBranch: string): string {\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', currentBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\nfunction createBackup(currentBranch: string): string {\n process.stdout.write('\\n' + SEP + '💾 Creating Incremental Backup\\n' + SEP + '\\n');\n let n = 1;\n while (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${currentBranch}Backup${n}`]).status === 0) {\n n += 1;\n }\n const backupBranch = `${currentBranch}Backup${n}`;\n runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n return backupBranch;\n}\n\nfunction saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n): void {\n for (const file of conflictedFiles) {\n const fileDir = perFileContextDir(mergeDir, file);\n fs.mkdirSync(fileDir, { recursive: true });\n\n const fork = spawnSync('git', ['show', `${forkPoint}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.status === 0 ? (fork.stdout ?? '') : '(file did not exist)\\n');\n const feature = spawnSync('git', ['show', `${featureHead}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.status === 0 ? (feature.stdout ?? '') : '(file did not exist)\\n');\n const main = spawnSync('git', ['show', `${mainHead}:${file}`], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.status === 0 ? (main.stdout ?? '') : '(file did not exist)\\n');\n\n const ba = spawnSync('git', ['diff', forkPoint, featureHead, '--', file], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout ?? '');\n const ca = spawnSync('git', ['diff', forkPoint, mainHead, '--', file], { encoding: 'utf8' });\n fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout ?? '');\n }\n}\n\n// Single source of truth for the merge process. The script WRITES it at conflict time (rather\n// than the AI relying on a separate hand-maintained doc), parameterized with the live MERGE_DIR\n// and conflicted-file list, so the instructions can never drift from the actual layout. The body\n// is a template constant with {{...}} placeholders so this stays a small filler function.\nconst MERGE_PROCESS_TEMPLATE = `# AI-Assisted Squash-Merge Conflict Resolution (generated)\n\nThis file was generated by \\`pnpm wp-git-update\\` when the 3-point squash-merge hit conflicts.\nIt is the single source of truth for the merge process — follow it exactly.\n\nYou are on branch \\`{{SQUASH_BRANCH}}\\` with conflict markers in the working tree.\n\\`MERGE_DIR = {{MERGE_DIR}}\\`\n\n## How the gate works\n\n- Resolve every conflicted file in the working tree.\n- Run **\\`pnpm wp-git-merge-complete\\`** — the validation gate. It scans for leftover conflict\n markers, checks each conflicted file has a written merge explanation, runs the \\`nx affected\\`\n build, and — only if all pass — stages, commits, and unblocks the workflow.\n- **Do NOT run \\`git add\\` / \\`git commit\\` / \\`git push\\` / \\`gh pr\\` yourself.** They are blocked by\n the \\`merge-in-progress-guard\\` hook until the gate validates. The gate does the commit.\n\n## STEP 1 — Load the merge context\n\nPer conflicted file, \\`MERGE_DIR/updatemain-<safe_path>/\\` holds (\\`<safe_path>\\` = path with \\`/\\`→\\`__\\`):\n\n\\`\\`\\`\nA-forkpoint.txt # file at fork point (base)\nB-feature.txt # file on your feature branch\nC-main.txt # file on main\nB-A.diff # what your feature changed (B−A)\nC-A.diff # what main changed (C−A)\n\\`\\`\\`\n\n\\`updatemain-hashes.json\\` holds A/B/C commit hashes. To see why main changed:\n\\`git log <A>..<C> --oneline\\`.\n\n## STEP 2 — Resolve each conflicted file\n\nFor each file: read the working-tree file (the markers) and its \\`B-A.diff\\` / \\`C-A.diff\\` (intent),\nthen Edit to the resolved version, removing ALL conflict markers.\n\nStrategies: goals align & non-overlapping → merge both · one side removes what the other modifies\n→ prefer the removal · same lines, simple (imports/format) → merge both · same lines, complex or\nconflicting goals → ask the user · feature re-implements what main already squashed → prefer\nmain's, then re-apply only the genuinely new feature work.\n\n**Then write a merge explanation** for each conflicted file — NOT a comment in the source (that\nbreaks for JSON and deleted files). Write it next to that file's diffs, at:\n\n\\`\\`\\`\nMERGE_DIR/updatemain-<safe_path>/{{EXPLANATION_FILE}}\n\\`\\`\\`\n\n(\\`<safe_path>\\` = the conflict file path with \\`/\\` → \\`__\\`, the same dir that holds its\n\\`A-forkpoint.txt\\` / \\`B-A.diff\\` / \\`C-A.diff\\`.) In it, explain in a few sentences how you resolved\nthis file: which side you took where, what you combined from B-A.diff vs C-A.diff, and why. The\ngate fails if any conflicted file's explanation is missing or empty. Do not paste A/B/C context\nblocks into the source code.\n\n## STEP 3 — Run the gate\n\n\\`\\`\\`\npnpm wp-git-merge-complete\n\\`\\`\\`\n\n- Leftover conflict markers → fix those files and re-run.\n- Missing merge explanation → write it (see STEP 2) and re-run.\n- Build failure → fix the TypeScript/lint errors and re-run (the gate re-stages for you).\n- On success it commits and prints the finalize instruction.\n\n## STEP 4 — Finalize\n\n\\`\\`\\`\npnpm wp-upsert-pr # (or pnpm wp-git-update)\n\\`\\`\\`\n\nForce-pushes the resolved squash branch over your feature branch and updates/creates the PR.\n\n## Conflicted files\n\n{{FILE_LIST}}\n\n## If you need to bail out\n\nA backup branch was created (e.g. \\`<feature>Backup1\\`). To abandon:\n\n\\`\\`\\`\ngit merge --abort 2>/dev/null; git checkout <feature> ; git branch -D {{SQUASH_BRANCH}}\n\\`\\`\\`\n\nThen delete \\`{{MERGE_DIR}}/\\` for a clean slate.\n`;\n\nfunction mergeProcessDoc(mergeDir: string, squashBranch: string, conflictedFiles: string[]): string {\n const fileList = conflictedFiles.map((f: string): string => `- \\`${f}\\``).join('\\n');\n return MERGE_PROCESS_TEMPLATE\n .replace(/\\{\\{SQUASH_BRANCH\\}\\}/g, squashBranch)\n .replace(/\\{\\{MERGE_DIR\\}\\}/g, mergeDir)\n .replace(/\\{\\{EXPLANATION_FILE\\}\\}/g, MERGE_EXPLANATION_FILE)\n .replace(/\\{\\{FILE_LIST\\}\\}/g, fileList);\n}\n\n// Returns the absolute path of the written doc.\nfunction writeMergeProcessDoc(repoRoot: string, mergeDir: string, squashBranch: string, conflictedFiles: string[]): string {\n const docDir = path.join(repoRoot, WEBPIECES_TMP_DIR, 'instruct-ai');\n fs.mkdirSync(docDir, { recursive: true });\n const docPath = path.join(docDir, 'webpieces.mergeprocess.md');\n fs.writeFileSync(docPath, mergeProcessDoc(mergeDir, squashBranch, conflictedFiles));\n return docPath;\n}\n\nfunction printConflictHandback(docPath: string, mergeDir: string, squashBranch: string, conflictedFiles: string[]): void {\n process.stdout.write('\\n' + SEP + `⚠️ Conflicts in ${conflictedFiles.length} file(s) — handing control back to you\\n` + SEP + '\\n');\n process.stdout.write(`You are on branch ${squashBranch} with conflicts in the working tree.\\n\\n`);\n process.stdout.write(`FOLLOW THE MERGE PROCESS: ${docPath}\\n`);\n process.stdout.write(`3-point context per file in: ${mergeDir}/updatemain-<file>/\\n\\n`);\n process.stdout.write('Conflicted files:\\n');\n for (const file of conflictedFiles) process.stdout.write(` - ${file}\\n`);\n process.stdout.write('\\n' + SEP);\n}\n\nfunction handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints,\n): void {\n const raw = execSync('git diff --name-only --diff-filter=U', { encoding: 'utf8' }).trim();\n const conflictedFiles = raw.split('\\n').filter((f: string): boolean => f.trim() !== '');\n fs.writeFileSync(path.join(mergeDir, 'updatemain-conflicted-files.txt'), raw + '\\n');\n saveConflictContext(conflictedFiles, mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n\n const marker = new MergeMarker(\n currentBranch, squashBranch, backupBranch, prNumber, conflictedFiles,\n hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead, false,\n );\n writeMergeMarker(mergeDir, marker);\n const docPath = writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles);\n printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles);\n process.exit(2);\n}\n\nfunction finalizeBranch(\n currentBranch: string, squashBranch: string, backupBranch: string, prNumber: string,\n): void {\n process.stdout.write('\\n' + SEP + '🗑️ Finalizing\\n' + SEP + '\\n');\n runGitChecked(['branch', '-D', currentBranch], 'Failed to delete old feature branch');\n\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n process.stdout.write(prNumber ? `Updating PR #${prNumber} (force-with-lease)...\\n` : 'Updating remote branch (force-with-lease)...\\n');\n runGitChecked(['push', '-u', '--force-with-lease', 'origin', `${squashBranch}:${currentBranch}`], 'Failed to push to origin');\n } else {\n process.stdout.write('No remote branch — local only.\\n');\n }\n runGitChecked(['checkout', squashBranch], 'Failed to checkout squash branch');\n runGitChecked(['branch', '-m', currentBranch], 'Failed to rename squash branch');\n\n process.stdout.write(`\\n✅ Branch ${currentBranch} updated from main. Backup: ${backupBranch}\\n`);\n process.stdout.write(` Delete backup when safe: git branch -D ${backupBranch}\\n\\n`);\n}\n\nasync function handleResume(mergeDir: string, marker: MergeMarker): Promise<void> {\n if (!marker.validated) {\n process.stdout.write('\\n' + SEP + '⏸️ Merge in progress — not yet validated\\n' + SEP + '\\n');\n process.stdout.write('Resolve the remaining conflicts in the working tree, then run:\\n');\n process.stdout.write(' pnpm wp-git-merge-complete\\n\\n');\n process.exit(1);\n }\n process.stdout.write('Resuming: merge validated — finalizing.\\n');\n finalizeBranch(marker.currentBranch, marker.squashBranch, marker.backupBranch, marker.prNumber);\n clearMergeMarker(mergeDir);\n await cleanTmp();\n}\n\nasync function runFreshUpdate(repoRoot: string, mergeDir: string): Promise<void> {\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n if (currentBranch.endsWith('Squash')) {\n process.stderr.write(`❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}\\n`);\n process.exit(1);\n }\n\n process.stdout.write('\\n' + SEP + '🔄 Squash-Merge Update from Main\\n' + SEP + '\\n');\n await gatherInfo();\n const hashes = JSON.parse(fs.readFileSync(path.join(mergeDir, 'updatemain-hashes.json'), 'utf8')) as HashPoints;\n\n const prNumber = detectPr(currentBranch);\n process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\\n` : 'No existing PR (one can be created later).\\n');\n\n const backupBranch = createBackup(currentBranch);\n const squashBranch = `${currentBranch}Squash`;\n if (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {\n process.stderr.write(`❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}\\n`);\n process.exit(1);\n }\n\n runGitChecked(['checkout', 'main'], 'Failed to checkout main');\n runGitChecked(['pull', 'origin', 'main'], 'Failed to pull origin/main');\n runGitChecked(['checkout', '-b', squashBranch], 'Failed to create squash branch');\n\n process.stdout.write('\\n' + SEP + `🔀 Squash merging ${currentBranch}\\n` + SEP + '\\n');\n const merge = spawnSync('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });\n if (merge.status !== 0) {\n handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes);\n return;\n }\n\n const nothingStaged = spawnSync('git', ['diff-index', '--quiet', '--cached', 'HEAD', '--']).status === 0;\n if (nothingStaged) {\n process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\\n');\n } else {\n runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');\n }\n finalizeBranch(currentBranch, squashBranch, backupBranch, prNumber);\n await cleanTmp();\n}\n\nexport async function main(): Promise<void> {\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n const featureName = getFeatureName();\n const mergeDir = mergeDirFor(repoRoot, featureName);\n fs.mkdirSync(mergeDir, { recursive: true });\n\n const existing = readMergeMarker(mergeDir);\n if (existing) {\n await handleResume(mergeDir, existing);\n return;\n }\n await runFreshUpdate(repoRoot, mergeDir);\n}\n\nif (require.main === module) {\n main().catch((err: Error) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
export declare const DEFAULT_BUILD_COMMAND = "pnpm nx affected --target=ci --base=origin/main";
|
|
2
|
+
/**
|
|
3
|
+
* Resolve the exact build command this gate will run for a repo: the project's configured
|
|
4
|
+
* PrGateConfig.buildCommand, or the default affected-ci command when none is set. Callers
|
|
5
|
+
* print this so the AI knows precisely which command to run locally to get the gate passing.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveBuildCommand(repoRoot: string): string;
|
|
2
8
|
/**
|
|
3
9
|
* Run the build gate. Returns the process exit code (0 = pass). `buildCommand` overrides
|
|
4
10
|
* the default (sourced from PrGateConfig.buildCommand by callers); empty/undefined uses the
|
|
5
11
|
* default affected-ci command.
|
|
6
12
|
*/
|
|
7
13
|
export declare function runBuildAffected(repoRoot: string, buildCommand?: string): number;
|
|
14
|
+
/**
|
|
15
|
+
* Run the build gate using the project's configured command (PrGateConfig.buildCommand). The
|
|
16
|
+
* merge-complete gate and wp-upsert-pr both call THIS so they provably build with the same
|
|
17
|
+
* command — the resolution the AI validates is built exactly as the PR command builds it.
|
|
18
|
+
* Returns the exit code; callers print their own re-run hint.
|
|
19
|
+
*/
|
|
20
|
+
export declare function runConfiguredBuildGate(repoRoot: string): number;
|
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.DEFAULT_BUILD_COMMAND = void 0;
|
|
4
|
+
exports.resolveBuildCommand = resolveBuildCommand;
|
|
4
5
|
exports.runBuildAffected = runBuildAffected;
|
|
6
|
+
exports.runConfiguredBuildGate = runConfiguredBuildGate;
|
|
5
7
|
const child_process_1 = require("child_process");
|
|
8
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
6
9
|
// Single source of truth for the build gate. Both `wp-build-affected` (CI + local) and the
|
|
7
10
|
// merge validation gate (`wp-git-merge-complete`) run THIS, so "what CI runs" and "what the
|
|
8
11
|
// PR command runs" can never drift. nx `affected` only rebuilds changed projects, so this
|
|
9
12
|
// stays fast on a large monorepo.
|
|
10
13
|
exports.DEFAULT_BUILD_COMMAND = 'pnpm nx affected --target=ci --base=origin/main';
|
|
14
|
+
/**
|
|
15
|
+
* Resolve the exact build command this gate will run for a repo: the project's configured
|
|
16
|
+
* PrGateConfig.buildCommand, or the default affected-ci command when none is set. Callers
|
|
17
|
+
* print this so the AI knows precisely which command to run locally to get the gate passing.
|
|
18
|
+
*/
|
|
19
|
+
function resolveBuildCommand(repoRoot) {
|
|
20
|
+
const configured = (0, rules_config_1.loadPrGateConfig)(repoRoot).buildCommand;
|
|
21
|
+
return configured !== undefined && configured.trim() !== '' ? configured : exports.DEFAULT_BUILD_COMMAND;
|
|
22
|
+
}
|
|
11
23
|
/**
|
|
12
24
|
* Run the build gate. Returns the process exit code (0 = pass). `buildCommand` overrides
|
|
13
25
|
* the default (sourced from PrGateConfig.buildCommand by callers); empty/undefined uses the
|
|
@@ -19,4 +31,13 @@ function runBuildAffected(repoRoot, buildCommand) {
|
|
|
19
31
|
const result = (0, child_process_1.spawnSync)(cmd, { stdio: 'inherit', cwd: repoRoot, shell: true });
|
|
20
32
|
return result.status ?? 1;
|
|
21
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Run the build gate using the project's configured command (PrGateConfig.buildCommand). The
|
|
36
|
+
* merge-complete gate and wp-upsert-pr both call THIS so they provably build with the same
|
|
37
|
+
* command — the resolution the AI validates is built exactly as the PR command builds it.
|
|
38
|
+
* Returns the exit code; callers print their own re-run hint.
|
|
39
|
+
*/
|
|
40
|
+
function runConfiguredBuildGate(repoRoot) {
|
|
41
|
+
return runBuildAffected(repoRoot, (0, rules_config_1.loadPrGateConfig)(repoRoot).buildCommand);
|
|
42
|
+
}
|
|
22
43
|
//# sourceMappingURL=build-affected.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-affected.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-affected.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"build-affected.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/build-affected.ts"],"names":[],"mappings":";;;AAcA,kDAGC;AAOD,4CAKC;AAQD,wDAEC;AAvCD,iDAA0C;AAC1C,0DAA2D;AAE3D,2FAA2F;AAC3F,4FAA4F;AAC5F,0FAA0F;AAC1F,kCAAkC;AACrB,QAAA,qBAAqB,GAAG,iDAAiD,CAAC;AAEvF;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,QAAgB;IAChD,MAAM,UAAU,GAAG,IAAA,+BAAgB,EAAC,QAAQ,CAAC,CAAC,YAAY,CAAC;IAC3D,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,6BAAqB,CAAC;AACrG,CAAC;AAED;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,QAAgB,EAAE,YAAqB;IACpE,MAAM,GAAG,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,6BAAqB,CAAC;IAC5G,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,CAAC,CAAC;IACnD,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAChF,OAAO,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,SAAgB,sBAAsB,CAAC,QAAgB;IACnD,OAAO,gBAAgB,CAAC,QAAQ,EAAE,IAAA,+BAAgB,EAAC,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport { loadPrGateConfig } from '@webpieces/rules-config';\n\n// Single source of truth for the build gate. Both `wp-build-affected` (CI + local) and the\n// merge validation gate (`wp-git-merge-complete`) run THIS, so \"what CI runs\" and \"what the\n// PR command runs\" can never drift. nx `affected` only rebuilds changed projects, so this\n// stays fast on a large monorepo.\nexport const DEFAULT_BUILD_COMMAND = 'pnpm nx affected --target=ci --base=origin/main';\n\n/**\n * Resolve the exact build command this gate will run for a repo: the project's configured\n * PrGateConfig.buildCommand, or the default affected-ci command when none is set. Callers\n * print this so the AI knows precisely which command to run locally to get the gate passing.\n */\nexport function resolveBuildCommand(repoRoot: string): string {\n const configured = loadPrGateConfig(repoRoot).buildCommand;\n return configured !== undefined && configured.trim() !== '' ? configured : DEFAULT_BUILD_COMMAND;\n}\n\n/**\n * Run the build gate. Returns the process exit code (0 = pass). `buildCommand` overrides\n * the default (sourced from PrGateConfig.buildCommand by callers); empty/undefined uses the\n * default affected-ci command.\n */\nexport function runBuildAffected(repoRoot: string, buildCommand?: string): number {\n const cmd = buildCommand !== undefined && buildCommand.trim() !== '' ? buildCommand : DEFAULT_BUILD_COMMAND;\n process.stdout.write(`\\n▶ Build gate: ${cmd}\\n\\n`);\n const result = spawnSync(cmd, { stdio: 'inherit', cwd: repoRoot, shell: true });\n return result.status ?? 1;\n}\n\n/**\n * Run the build gate using the project's configured command (PrGateConfig.buildCommand). The\n * merge-complete gate and wp-upsert-pr both call THIS so they provably build with the same\n * command — the resolution the AI validates is built exactly as the PR command builds it.\n * Returns the exit code; callers print their own re-run hint.\n */\nexport function runConfiguredBuildGate(repoRoot: string): number {\n return runBuildAffected(repoRoot, loadPrGateConfig(repoRoot).buildCommand);\n}\n"]}
|
|
@@ -5,11 +5,16 @@ const tslib_1 = require("tslib");
|
|
|
5
5
|
const child_process_1 = require("child_process");
|
|
6
6
|
const fs = tslib_1.__importStar(require("fs"));
|
|
7
7
|
const path = tslib_1.__importStar(require("path"));
|
|
8
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
8
9
|
const CUTOFF_DAYS = 30;
|
|
9
10
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
11
|
+
// Only workflow-generated working dirs are eligible for 30-day cleanup. `.webpieces/` is shared
|
|
12
|
+
// with the ai-hook-rules bootstrap/cache and the instruct-ai docs — those must never be deleted,
|
|
13
|
+
// so we scope to the per-feature prefixes the pr-gate scripts create.
|
|
14
|
+
const CLEANABLE_PREFIXES = ['merge-', 'review-', 'pr-'];
|
|
10
15
|
async function main() {
|
|
11
16
|
const repoRoot = (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
12
|
-
const tmpBase = path.join(repoRoot,
|
|
17
|
+
const tmpBase = path.join(repoRoot, rules_config_1.WEBPIECES_TMP_DIR);
|
|
13
18
|
if (!fs.existsSync(tmpBase)) {
|
|
14
19
|
return;
|
|
15
20
|
}
|
|
@@ -30,6 +35,8 @@ async function main() {
|
|
|
30
35
|
const stat = fs.statSync(fullPath);
|
|
31
36
|
if (!stat.isDirectory())
|
|
32
37
|
continue;
|
|
38
|
+
if (!CLEANABLE_PREFIXES.some((prefix) => entry.startsWith(prefix)))
|
|
39
|
+
continue;
|
|
33
40
|
if (now - stat.mtimeMs < cutoffMs)
|
|
34
41
|
continue;
|
|
35
42
|
process.stdout.write(` 🗑️ Deleting: ${entry}\n`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanTmp.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/cleanTmp.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"cleanTmp.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/cleanTmp.ts"],"names":[],"mappings":";;AAaA,oBA4CC;;AAzDD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4D;AAE5D,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,gGAAgG;AAChG,iGAAiG;AACjG,sEAAsE;AACtE,MAAM,kBAAkB,GAAG,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAEjD,KAAK,UAAU,IAAI;IACtB,MAAM,QAAQ,GAAG,IAAA,wBAAQ,EAAC,+BAA+B,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACxF,MAAM,OAAO,GAAG,IAAI,CAAC,I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C,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\n\nconst CUTOFF_DAYS = 30;\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// Only workflow-generated working dirs are eligible for 30-day cleanup. `.webpieces/` is shared\n// with the ai-hook-rules bootstrap/cache and the instruct-ai docs — those must never be deleted,\n// so we scope to the per-feature prefixes the pr-gate scripts create.\nconst CLEANABLE_PREFIXES = ['merge-', 'review-', 'pr-'];\n\nexport async function main(): Promise<void> {\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n const tmpBase = path.join(repoRoot, WEBPIECES_TMP_DIR);\n\n if (!fs.existsSync(tmpBase)) {\n return;\n }\n\n process.stdout.write('\\n');\n process.stdout.write(SEP);\n process.stdout.write('🧹 Cleaning Old Temporary Directories\\n');\n process.stdout.write(SEP);\n process.stdout.write('\\n');\n process.stdout.write(`Location: ${tmpBase}\\n`);\n process.stdout.write(`Retention: ${CUTOFF_DAYS} days\\n`);\n process.stdout.write('\\n');\n\n const cutoffMs = CUTOFF_DAYS * 24 * 60 * 60 * 1000;\n const now = Date.now();\n let deletedCount = 0;\n\n const entries = fs.readdirSync(tmpBase);\n for (const entry of entries) {\n const fullPath = path.join(tmpBase, entry);\n const stat = fs.statSync(fullPath);\n if (!stat.isDirectory()) continue;\n if (!CLEANABLE_PREFIXES.some((prefix: string) => entry.startsWith(prefix))) continue;\n if (now - stat.mtimeMs < cutoffMs) continue;\n\n process.stdout.write(` 🗑️ Deleting: ${entry}\\n`);\n fs.rmSync(fullPath, { recursive: true, force: true });\n deletedCount += 1;\n }\n\n if (deletedCount === 0) {\n process.stdout.write(` ✅ No directories older than ${CUTOFF_DAYS} days found\\n`);\n } else {\n process.stdout.write('\\n');\n process.stdout.write(` ✅ Deleted ${deletedCount} old director${deletedCount === 1 ? 'y' : 'ies'}\\n`);\n }\n\n process.stdout.write('\\n');\n process.stdout.write(SEP);\n process.stdout.write('\\n');\n}\n\nif (require.main === module) {\n main().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
@@ -6,6 +6,7 @@ const tslib_1 = require("tslib");
|
|
|
6
6
|
const child_process_1 = require("child_process");
|
|
7
7
|
const fs = tslib_1.__importStar(require("fs"));
|
|
8
8
|
const path = tslib_1.__importStar(require("path"));
|
|
9
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
9
10
|
const git_readAiBranchName_1 = require("./git-readAiBranchName");
|
|
10
11
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
11
12
|
function printMergeFromMainError(commit, parent, featureName, currentBranch) {
|
|
@@ -74,7 +75,7 @@ async function findForkPoint(workflow) {
|
|
|
74
75
|
const featureName = (0, git_readAiBranchName_1.getFeatureName)();
|
|
75
76
|
const currentBranch = (0, child_process_1.execSync)('git branch --show-current', { encoding: 'utf8' }).trim();
|
|
76
77
|
const repoRoot = (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
77
|
-
const outputDir = path.join(repoRoot,
|
|
78
|
+
const outputDir = path.join(repoRoot, rules_config_1.WEBPIECES_TMP_DIR, `${workflow}-${featureName}`);
|
|
78
79
|
const prefix = workflow === 'review' ? 'review-' : 'updatemain-';
|
|
79
80
|
fs.mkdirSync(outputDir, { recursive: true });
|
|
80
81
|
(0, child_process_1.spawnSync)('git', ['fetch', 'origin', 'main'], { stdio: 'ignore' });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"git-findForkPoint.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/git-findForkPoint.ts"],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fs';\nimport * as path from 'path';\nimport { getFeatureName } from './git-readAiBranchName';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\nfunction printMergeFromMainError(commit: string, parent: string, featureName: string, currentBranch: string): void {\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('❌ This branch merged main without pnpm wp-git-update\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n process.stderr.write(`Merge commit detected: ${commit}\\n`);\n process.stderr.write(`Parent from main: ${parent}\\n`);\n process.stderr.write('\\n');\n process.stderr.write('This prevents clean squash-merge. To recover, follow these steps:\\n');\n process.stderr.write('\\n');\n process.stderr.write('1. Switch to main branch:\\n');\n process.stderr.write(' git checkout main\\n');\n process.stderr.write('\\n');\n process.stderr.write('2. Pull latest changes:\\n');\n process.stderr.write(' git pull\\n');\n process.stderr.write('\\n');\n process.stderr.write('3. Create new branch with a new name:\\n');\n process.stderr.write(` git checkout -b ${featureName}-v2\\n`);\n process.stderr.write('\\n');\n process.stderr.write('4. Squash merge your old branch:\\n');\n process.stderr.write(` git merge --squash ${currentBranch}\\n`);\n process.stderr.write('\\n');\n process.stderr.write('5. Commit the squashed changes:\\n');\n process.stderr.write(` git add -A && git commit -m \"Squashed from ${currentBranch}\"\\n`);\n process.stderr.write('\\n');\n process.stderr.write('6. If you have an existing PR:\\n');\n process.stderr.write(` - Create a NEW PR for ${featureName}-v2\\n`);\n process.stderr.write(` - Close the old PR for ${currentBranch}\\n`);\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n}\n\nfunction checkMergeCommits(mergeCommits: string[], outputDir: string, prefix: string, featureName: string, currentBranch: string): void {\n process.stderr.write(`Found ${mergeCommits.length} merge commit(s) to check...\\n`);\n\n for (const commit of mergeCommits) {\n const parentsResult = spawnSync('git', ['rev-list', '--parents', '-n', '1', commit], { encoding: 'utf8' });\n const parents = (parentsResult.stdout ?? '').trim().split(' ').slice(1);\n\n for (const parent of parents) {\n const ancestorCheck = spawnSync('git', ['merge-base', '--is-ancestor', parent, 'origin/main']);\n const reverseCheck = spawnSync('git', ['merge-base', '--is-ancestor', 'origin/main', parent]);\n\n if (ancestorCheck.status === 0 && reverseCheck.status === 0) {\n const errorJson = JSON.stringify({\n error: 'Merge from main detected',\n mergeCommit: commit,\n parentFromMain: parent,\n timestamp: new Date().toISOString(),\n }, null, 2);\n\n fs.writeFileSync(path.join(outputDir, `${prefix}forkpoint-error.json`), errorJson + '\\n');\n printMergeFromMainError(commit, parent, featureName, currentBranch);\n process.exit(1);\n }\n }\n }\n process.stderr.write('✅ No improper merges from main detected\\n');\n}\n\nexport async function findForkPoint(workflow: string): Promise<void> {\n if (workflow !== 'review' && workflow !== 'merge') {\n process.stderr.write('ERROR: Workflow argument required\\n');\n process.stderr.write('Usage: git-findForkPoint <workflow>\\n');\n process.stderr.write(\" workflow: 'review' or 'merge'\\n\");\n process.exit(1);\n }\n\n const featureName = getFeatureName();\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n\n const outputDir = path.join(repoRoot, 'webpiecesTmp', `${workflow}-${featureName}`);\n const prefix = workflow === 'review' ? 'review-' : 'updatemain-';\n fs.mkdirSync(outputDir, { recursive: true });\n\n spawnSync('git', ['fetch', 'origin', 'main'], { stdio: 'ignore' });\n\n const featureHead = execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();\n const originMain = execSync('git rev-parse origin/main', { encoding: 'utf8' }).trim();\n\n process.stderr.write('Finding fork point using git merge-base...\\n');\n\n const forkPointResult = spawnSync('git', ['merge-base', 'origin/main', 'HEAD'], { encoding: 'utf8' });\n const forkPoint = (forkPointResult.stdout ?? '').trim();\n\n if (!forkPoint || forkPointResult.status !== 0) {\n process.stderr.write('ERROR: Could not find common ancestor with origin/main\\n');\n process.exit(1);\n }\n\n process.stderr.write(`✅ Fork point found: ${forkPoint.slice(0, 7)}\\n`);\n process.stderr.write('Checking for improper merges from main...\\n');\n\n const mergeCommitsResult = spawnSync('git', ['log', `${forkPoint}..HEAD`, '--merges', '--format=%H'], { encoding: 'utf8' });\n const mergeCommitsRaw = (mergeCommitsResult.stdout ?? '').trim();\n const mergeCommits = mergeCommitsRaw ? mergeCommitsRaw.split('\\n') : [];\n\n if (mergeCommits.length > 0) {\n checkMergeCommits(mergeCommits, outputDir, prefix, featureName, currentBranch);\n } else {\n process.stderr.write('✅ No merge commits found (clean history)\\n');\n }\n\n const hashesJson = JSON.stringify({\n hashForkPoint: forkPoint,\n hashFeatureHead: featureHead,\n hashMainHead: originMain,\n timestamp: new Date().toISOString(),\n }, null, 2);\n\n fs.writeFileSync(path.join(outputDir, `${prefix}hashes.json`), hashesJson + '\\n');\n process.stderr.write(`✅ Hash points written to: ${outputDir}/${prefix}hashes.json\\n`);\n}\n\nexport async function main(): Promise<void> {\n await findForkPoint(process.argv[2] ?? '');\n}\n\nif (require.main === module) {\n main().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"git-findForkPoint.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/git-findForkPoint.ts"],"names":[],"mappings":";;AAsEA,sCAqDC;AAED,oBAEC;;AA/HD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA4D;AAC5D,iEAAwD;AAExD,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,SAAS,uBAAuB,CAAC,MAAc,EAAE,MAAc,EAAE,WAAmB,EAAE,aAAqB;IACvG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC3B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,wDAAwD,CAAC,C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,EAAE;KACtC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAEZ,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,MAAM,aAAa,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC,CAAC;IAClF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,6BAA6B,SAAS,IAAI,MAAM,eAAe,CAAC,CAAC;AAC1F,CAAC;AAEM,KAAK,UAAU,IAAI;IACtB,MAAM,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAC/C,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;QACjB,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\nimport { getFeatureName } from './git-readAiBranchName';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\nfunction printMergeFromMainError(commit: string, parent: string, featureName: string, currentBranch: string): void {\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('❌ This branch merged main without pnpm wp-git-update\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n process.stderr.write(`Merge commit detected: ${commit}\\n`);\n process.stderr.write(`Parent from main: ${parent}\\n`);\n process.stderr.write('\\n');\n process.stderr.write('This prevents clean squash-merge. To recover, follow these steps:\\n');\n process.stderr.write('\\n');\n process.stderr.write('1. Switch to main branch:\\n');\n process.stderr.write(' git checkout main\\n');\n process.stderr.write('\\n');\n process.stderr.write('2. Pull latest changes:\\n');\n process.stderr.write(' git pull\\n');\n process.stderr.write('\\n');\n process.stderr.write('3. Create new branch with a new name:\\n');\n process.stderr.write(` git checkout -b ${featureName}-v2\\n`);\n process.stderr.write('\\n');\n process.stderr.write('4. Squash merge your old branch:\\n');\n process.stderr.write(` git merge --squash ${currentBranch}\\n`);\n process.stderr.write('\\n');\n process.stderr.write('5. Commit the squashed changes:\\n');\n process.stderr.write(` git add -A && git commit -m \"Squashed from ${currentBranch}\"\\n`);\n process.stderr.write('\\n');\n process.stderr.write('6. If you have an existing PR:\\n');\n process.stderr.write(` - Create a NEW PR for ${featureName}-v2\\n`);\n process.stderr.write(` - Close the old PR for ${currentBranch}\\n`);\n process.stderr.write('\\n');\n process.stderr.write(SEP);\n process.stderr.write('\\n');\n}\n\nfunction checkMergeCommits(mergeCommits: string[], outputDir: string, prefix: string, featureName: string, currentBranch: string): void {\n process.stderr.write(`Found ${mergeCommits.length} merge commit(s) to check...\\n`);\n\n for (const commit of mergeCommits) {\n const parentsResult = spawnSync('git', ['rev-list', '--parents', '-n', '1', commit], { encoding: 'utf8' });\n const parents = (parentsResult.stdout ?? '').trim().split(' ').slice(1);\n\n for (const parent of parents) {\n const ancestorCheck = spawnSync('git', ['merge-base', '--is-ancestor', parent, 'origin/main']);\n const reverseCheck = spawnSync('git', ['merge-base', '--is-ancestor', 'origin/main', parent]);\n\n if (ancestorCheck.status === 0 && reverseCheck.status === 0) {\n const errorJson = JSON.stringify({\n error: 'Merge from main detected',\n mergeCommit: commit,\n parentFromMain: parent,\n timestamp: new Date().toISOString(),\n }, null, 2);\n\n fs.writeFileSync(path.join(outputDir, `${prefix}forkpoint-error.json`), errorJson + '\\n');\n printMergeFromMainError(commit, parent, featureName, currentBranch);\n process.exit(1);\n }\n }\n }\n process.stderr.write('✅ No improper merges from main detected\\n');\n}\n\nexport async function findForkPoint(workflow: string): Promise<void> {\n if (workflow !== 'review' && workflow !== 'merge') {\n process.stderr.write('ERROR: Workflow argument required\\n');\n process.stderr.write('Usage: git-findForkPoint <workflow>\\n');\n process.stderr.write(\" workflow: 'review' or 'merge'\\n\");\n process.exit(1);\n }\n\n const featureName = getFeatureName();\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n\n const outputDir = path.join(repoRoot, WEBPIECES_TMP_DIR, `${workflow}-${featureName}`);\n const prefix = workflow === 'review' ? 'review-' : 'updatemain-';\n fs.mkdirSync(outputDir, { recursive: true });\n\n spawnSync('git', ['fetch', 'origin', 'main'], { stdio: 'ignore' });\n\n const featureHead = execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();\n const originMain = execSync('git rev-parse origin/main', { encoding: 'utf8' }).trim();\n\n process.stderr.write('Finding fork point using git merge-base...\\n');\n\n const forkPointResult = spawnSync('git', ['merge-base', 'origin/main', 'HEAD'], { encoding: 'utf8' });\n const forkPoint = (forkPointResult.stdout ?? '').trim();\n\n if (!forkPoint || forkPointResult.status !== 0) {\n process.stderr.write('ERROR: Could not find common ancestor with origin/main\\n');\n process.exit(1);\n }\n\n process.stderr.write(`✅ Fork point found: ${forkPoint.slice(0, 7)}\\n`);\n process.stderr.write('Checking for improper merges from main...\\n');\n\n const mergeCommitsResult = spawnSync('git', ['log', `${forkPoint}..HEAD`, '--merges', '--format=%H'], { encoding: 'utf8' });\n const mergeCommitsRaw = (mergeCommitsResult.stdout ?? '').trim();\n const mergeCommits = mergeCommitsRaw ? mergeCommitsRaw.split('\\n') : [];\n\n if (mergeCommits.length > 0) {\n checkMergeCommits(mergeCommits, outputDir, prefix, featureName, currentBranch);\n } else {\n process.stderr.write('✅ No merge commits found (clean history)\\n');\n }\n\n const hashesJson = JSON.stringify({\n hashForkPoint: forkPoint,\n hashFeatureHead: featureHead,\n hashMainHead: originMain,\n timestamp: new Date().toISOString(),\n }, null, 2);\n\n fs.writeFileSync(path.join(outputDir, `${prefix}hashes.json`), hashesJson + '\\n');\n process.stderr.write(`✅ Hash points written to: ${outputDir}/${prefix}hashes.json\\n`);\n}\n\nexport async function main(): Promise<void> {\n await findForkPoint(process.argv[2] ?? '');\n}\n\nif (require.main === module) {\n main().catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
|
|
@@ -16,6 +16,7 @@ export declare class MarkerScanResult {
|
|
|
16
16
|
constructor(clean: boolean, filesWithMarkers: string[]);
|
|
17
17
|
}
|
|
18
18
|
export declare function mergeDirFor(repoRoot: string, featureName: string): string;
|
|
19
|
+
export declare function perFileContextDir(mergeDir: string, file: string): string;
|
|
19
20
|
export declare function markerPath(mergeDir: string): string;
|
|
20
21
|
export declare function readMergeMarker(mergeDir: string): MergeMarker | null;
|
|
21
22
|
export declare function writeMergeMarker(mergeDir: string, marker: MergeMarker): void;
|
|
@@ -25,3 +26,11 @@ export declare function clearMergeMarker(mergeDir: string): void;
|
|
|
25
26
|
* root), never the whole repo — stays O(conflicts) regardless of monorepo size.
|
|
26
27
|
*/
|
|
27
28
|
export declare function scanConflictMarkers(repoRoot: string, files: string[]): MarkerScanResult;
|
|
29
|
+
/**
|
|
30
|
+
* Explanation scan: every conflicted file the AI resolved must have a non-empty
|
|
31
|
+
* MERGE_EXPLANATION_FILE sitting in its per-file context dir (next to the diffs), proving the AI
|
|
32
|
+
* deliberately 3-point merged it and recording HOW. Returns the files whose explanation is
|
|
33
|
+
* missing or empty. Works for every conflicted file regardless of type — including comment-less
|
|
34
|
+
* files (JSON) and files resolved by deletion (no working-tree file to inspect).
|
|
35
|
+
*/
|
|
36
|
+
export declare function scanMergeExplanations(mergeDir: string, files: string[]): MarkerScanResult;
|
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MarkerScanResult = exports.MergeMarker = void 0;
|
|
4
4
|
exports.mergeDirFor = mergeDirFor;
|
|
5
|
+
exports.perFileContextDir = perFileContextDir;
|
|
5
6
|
exports.markerPath = markerPath;
|
|
6
7
|
exports.readMergeMarker = readMergeMarker;
|
|
7
8
|
exports.writeMergeMarker = writeMergeMarker;
|
|
8
9
|
exports.clearMergeMarker = clearMergeMarker;
|
|
9
10
|
exports.scanConflictMarkers = scanConflictMarkers;
|
|
11
|
+
exports.scanMergeExplanations = scanMergeExplanations;
|
|
10
12
|
const tslib_1 = require("tslib");
|
|
11
13
|
const fs = tslib_1.__importStar(require("fs"));
|
|
12
14
|
const path = tslib_1.__importStar(require("path"));
|
|
@@ -50,6 +52,13 @@ const CONFLICT_MARKER_RE = /^(<{7}|={7}|>{7})/m;
|
|
|
50
52
|
function mergeDirFor(repoRoot, featureName) {
|
|
51
53
|
return path.join(repoRoot, rules_config_1.WEBPIECES_TMP_DIR, `${rules_config_1.MERGE_DIR_PREFIX}${featureName}`);
|
|
52
54
|
}
|
|
55
|
+
// Per-conflicted-file context dir holding A-forkpoint.txt / B-feature.txt / C-main.txt /
|
|
56
|
+
// B-A.diff / C-A.diff (and the AI's merge-explanation.md). Shared so the writer
|
|
57
|
+
// (saveConflictContext) and the reader (the explanation gate) agree on the layout: the conflict
|
|
58
|
+
// file path with `/` → `__`, prefixed `updatemain-`.
|
|
59
|
+
function perFileContextDir(mergeDir, file) {
|
|
60
|
+
return path.join(mergeDir, `updatemain-${file.replace(/\//g, '__')}`);
|
|
61
|
+
}
|
|
53
62
|
function markerPath(mergeDir) {
|
|
54
63
|
return path.join(mergeDir, rules_config_1.MERGE_IN_PROGRESS_FILE);
|
|
55
64
|
}
|
|
@@ -85,4 +94,21 @@ function scanConflictMarkers(repoRoot, files) {
|
|
|
85
94
|
}
|
|
86
95
|
return new MarkerScanResult(filesWithMarkers.length === 0, filesWithMarkers);
|
|
87
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* Explanation scan: every conflicted file the AI resolved must have a non-empty
|
|
99
|
+
* MERGE_EXPLANATION_FILE sitting in its per-file context dir (next to the diffs), proving the AI
|
|
100
|
+
* deliberately 3-point merged it and recording HOW. Returns the files whose explanation is
|
|
101
|
+
* missing or empty. Works for every conflicted file regardless of type — including comment-less
|
|
102
|
+
* files (JSON) and files resolved by deletion (no working-tree file to inspect).
|
|
103
|
+
*/
|
|
104
|
+
function scanMergeExplanations(mergeDir, files) {
|
|
105
|
+
const filesMissingExplanation = [];
|
|
106
|
+
for (const file of files) {
|
|
107
|
+
const explPath = path.join(perFileContextDir(mergeDir, file), rules_config_1.MERGE_EXPLANATION_FILE);
|
|
108
|
+
const present = fs.existsSync(explPath) && fs.readFileSync(explPath, 'utf8').trim() !== '';
|
|
109
|
+
if (!present)
|
|
110
|
+
filesMissingExplanation.push(file);
|
|
111
|
+
}
|
|
112
|
+
return new MarkerScanResult(filesMissingExplanation.length === 0, filesMissingExplanation);
|
|
113
|
+
}
|
|
88
114
|
//# sourceMappingURL=merge-state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-state.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"merge-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-state.ts"],"names":[],"mappings":";;;AA0DA,kCAEC;AAMD,8CAEC;AAED,gCAEC;AAED,0CAeC;AAED,4CAGC;AAED,4CAGC;AAMD,kDASC;AASD,sDAQC;;AAnID,+CAAyB;AACzB,mDAA6B;AAC7B,0DAKiC;AAEjC,uFAAuF;AACvF,yFAAyF;AACzF,2FAA2F;AAC3F,MAAa,WAAW;IACpB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,YAAY,CAAS;IACrB,QAAQ,CA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import * as path from 'path';\nimport {\n WEBPIECES_TMP_DIR,\n MERGE_DIR_PREFIX,\n MERGE_IN_PROGRESS_FILE,\n MERGE_EXPLANATION_FILE,\n} from '@webpieces/rules-config';\n\n// Proof-obligation marker written when a 3-point squash-merge hits conflicts. Its mere\n// presence (with validated=false) is what the merge-in-progress-guard hook uses to block\n// commit/push/PR until `wp-git-merge-complete` validates the resolution and flips it true.\nexport class MergeMarker {\n currentBranch: string;\n squashBranch: string;\n backupBranch: string;\n prNumber: string;\n conflictedFiles: string[];\n forkPoint: string;\n featureHead: string;\n mainHead: string;\n validated: boolean;\n\n constructor(\n currentBranch: string,\n squashBranch: string,\n backupBranch: string,\n prNumber: string,\n conflictedFiles: string[],\n forkPoint: string,\n featureHead: string,\n mainHead: string,\n validated: boolean,\n ) {\n this.currentBranch = currentBranch;\n this.squashBranch = squashBranch;\n this.backupBranch = backupBranch;\n this.prNumber = prNumber;\n this.conflictedFiles = conflictedFiles;\n this.forkPoint = forkPoint;\n this.featureHead = featureHead;\n this.mainHead = mainHead;\n this.validated = validated;\n }\n}\n\nexport class MarkerScanResult {\n clean: boolean;\n filesWithMarkers: string[];\n\n constructor(clean: boolean, filesWithMarkers: string[]) {\n this.clean = clean;\n this.filesWithMarkers = filesWithMarkers;\n }\n}\n\nconst CONFLICT_MARKER_RE = /^(<{7}|={7}|>{7})/m;\n\nexport function mergeDirFor(repoRoot: string, featureName: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, `${MERGE_DIR_PREFIX}${featureName}`);\n}\n\n// Per-conflicted-file context dir holding A-forkpoint.txt / B-feature.txt / C-main.txt /\n// B-A.diff / C-A.diff (and the AI's merge-explanation.md). Shared so the writer\n// (saveConflictContext) and the reader (the explanation gate) agree on the layout: the conflict\n// file path with `/` → `__`, prefixed `updatemain-`.\nexport function perFileContextDir(mergeDir: string, file: string): string {\n return path.join(mergeDir, `updatemain-${file.replace(/\\//g, '__')}`);\n}\n\nexport function markerPath(mergeDir: string): string {\n return path.join(mergeDir, MERGE_IN_PROGRESS_FILE);\n}\n\nexport function readMergeMarker(mergeDir: string): MergeMarker | null {\n const filePath = markerPath(mergeDir);\n if (!fs.existsSync(filePath)) return null;\n const raw = JSON.parse(fs.readFileSync(filePath, 'utf8')) as MergeMarker;\n return new MergeMarker(\n raw.currentBranch,\n raw.squashBranch,\n raw.backupBranch,\n raw.prNumber,\n raw.conflictedFiles ?? [],\n raw.forkPoint,\n raw.featureHead,\n raw.mainHead,\n raw.validated === true,\n );\n}\n\nexport function writeMergeMarker(mergeDir: string, marker: MergeMarker): void {\n fs.mkdirSync(mergeDir, { recursive: true });\n fs.writeFileSync(markerPath(mergeDir), JSON.stringify(marker, null, 2) + '\\n');\n}\n\nexport function clearMergeMarker(mergeDir: string): void {\n const filePath = markerPath(mergeDir);\n if (fs.existsSync(filePath)) fs.rmSync(filePath);\n}\n\n/**\n * Scoped conflict-marker scan: reads ONLY the given conflicted files (relative to repo\n * root), never the whole repo — stays O(conflicts) regardless of monorepo size.\n */\nexport function scanConflictMarkers(repoRoot: string, files: string[]): MarkerScanResult {\n const filesWithMarkers: string[] = [];\n for (const file of files) {\n const abs = path.join(repoRoot, file);\n if (!fs.existsSync(abs)) continue;\n const content = fs.readFileSync(abs, 'utf8');\n if (CONFLICT_MARKER_RE.test(content)) filesWithMarkers.push(file);\n }\n return new MarkerScanResult(filesWithMarkers.length === 0, filesWithMarkers);\n}\n\n/**\n * Explanation scan: every conflicted file the AI resolved must have a non-empty\n * MERGE_EXPLANATION_FILE sitting in its per-file context dir (next to the diffs), proving the AI\n * deliberately 3-point merged it and recording HOW. Returns the files whose explanation is\n * missing or empty. Works for every conflicted file regardless of type — including comment-less\n * files (JSON) and files resolved by deletion (no working-tree file to inspect).\n */\nexport function scanMergeExplanations(mergeDir: string, files: string[]): MarkerScanResult {\n const filesMissingExplanation: string[] = [];\n for (const file of files) {\n const explPath = path.join(perFileContextDir(mergeDir, file), MERGE_EXPLANATION_FILE);\n const present = fs.existsSync(explPath) && fs.readFileSync(explPath, 'utf8').trim() !== '';\n if (!present) filesMissingExplanation.push(file);\n }\n return new MarkerScanResult(filesMissingExplanation.length === 0, filesMissingExplanation);\n}\n"]}
|
|
@@ -79,11 +79,16 @@ function main() {
|
|
|
79
79
|
const repoRoot = (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
80
80
|
runUpdateFromMain();
|
|
81
81
|
ensurePushed((0, child_process_1.execSync)('git branch --show-current', { encoding: 'utf8' }).trim());
|
|
82
|
+
const buildCommand = (0, build_affected_1.resolveBuildCommand)(repoRoot);
|
|
82
83
|
process.stdout.write('\n' + SEP + '② Build gate (nx affected)\n' + SEP + '\n');
|
|
83
|
-
|
|
84
|
-
|
|
84
|
+
process.stdout.write(`This gate runs the build command below. To get it passing BEFORE this command runs it,\n` +
|
|
85
|
+
`run the SAME command yourself first and fix everything it reports:\n\n` +
|
|
86
|
+
` ${buildCommand}\n\n`);
|
|
87
|
+
const buildCode = (0, build_affected_1.runConfiguredBuildGate)(repoRoot);
|
|
85
88
|
if (buildCode !== 0) {
|
|
86
|
-
process.stderr.write(
|
|
89
|
+
process.stderr.write(`\n❌ Build failed — no PR created/updated.\n\n` +
|
|
90
|
+
`Run THIS exact command to reproduce and fix all errors, then re-run pnpm wp-upsert-pr:\n\n` +
|
|
91
|
+
` ${buildCommand}\n\n`);
|
|
87
92
|
process.exit(buildCode);
|
|
88
93
|
}
|
|
89
94
|
process.stdout.write('\n' + SEP + '③ Dashboard + PR\n' + SEP + '\n');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wp-upsert-pr.js","sourceRoot":"","sources":["../../../../../../packages/tooling/pr-gate/src/scripts/wp-upsert-pr.ts"],"names":[],"mappings":";;;AAyFA,oBAmBC;;AA3GD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA8E;AAC9E,0EAAiE;AACjE,8DAA6D;AAC7D,kDAAoD;AACpD,sDAKgC;AAE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G,IAAA,+BAAgB,EAAC,QAAQ,CAAC,CAAC;IAC1C,MAAM,SAAS,GAAG,IAAA,iCAAgB,EAAC,QAAQ,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;IAClE,IAAI,SAAS,KAAK,CAAC,EAAE,CAAC;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,+EAA+E,CAAC,CAAC;QACtG,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5B,CAAC;IAED,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,GAAG,GAAG,oBAAoB,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC;IACrE,MAAM,aAAa,GAAG,IAAA,wBAAQ,EAAC,2BAA2B,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACzF,MAAM,IAAI,GAAG,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC5C,QAAQ,CAAC,QAAQ,EAAE,aAAa,EAAE,IAAI,CAAC,CAAC;IACxC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;AACxC,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,IAAI,EAAE,CAAC;AACX,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { loadPrGateConfig, WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\nimport { getFeatureName } from './workflow/git-readAiBranchName';\nimport { runBuildAffected } from './workflow/build-affected';\nimport { runGitChecked } from './workflow/git-exec';\nimport {\n computeGateResults,\n countAddedDisables,\n renderDashboard,\n DashboardInput,\n} from '../dashboard/dashboard';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\nfunction gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\n// Step A — bring the branch up to date with main via the 3-point engine (child process, so\n// its conflict handback / guard interplay is unaffected by this command's hook context).\nfunction runUpdateFromMain(): void {\n process.stdout.write('\\n' + SEP + '① Updating branch from main\\n' + SEP + '\\n');\n const result = spawnSync('pnpm', ['wp-git-update'], { stdio: 'inherit' });\n if (result.status === 2) {\n process.stdout.write('\\n⏸️ Conflicts — resolve them, run pnpm wp-git-merge-complete, then re-run pnpm wp-upsert-pr.\\n');\n process.exit(2);\n }\n if (result.status !== 0) {\n process.stderr.write('\\n❌ Branch update failed — see output above.\\n');\n process.exit(result.status ?? 1);\n }\n}\n\nfunction ensurePushed(currentBranch: string): void {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');\n } else {\n runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');\n }\n}\n\nfunction buildDashboard(repoRoot: string, buildPassed: boolean): string {\n const config = loadPrGateConfig(repoRoot);\n const forkPoint = gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = gitOut(['rev-parse', 'HEAD']);\n const mainHead = gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = gitOut(['diff', range, '--name-only']).split('\\n').filter((f: string): boolean => f.trim() !== '');\n const patch = gitOut(['diff', range]);\n const title = gitOut(['log', '-1', '--format=%s']);\n\n const gateResults = computeGateResults(config.gates, changedFiles);\n const disables = countAddedDisables(patch);\n const input = new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, '');\n return renderDashboard(input);\n}\n\nfunction upsertPr(repoRoot: string, currentBranch: string, body: string): void {\n const prDir = path.join(repoRoot, WEBPIECES_TMP_DIR, `pr-${getFeatureName()}`);\n fs.mkdirSync(prDir, { recursive: true });\n const bodyFile = path.join(prDir, 'pr-body.md');\n fs.writeFileSync(bodyFile, body + '\\n');\n\n const existing = gitOut(['log', '-1', '--format=%s']); // title fallback\n const prNumber = spawnSync(\n 'gh', ['pr', 'list', '--head', currentBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n const num = prNumber.status === 0 ? (prNumber.stdout ?? '').trim() : '';\n\n if (num === '') {\n process.stdout.write('Creating PR...\\n');\n const create = spawnSync('gh', ['pr', 'create', '--head', currentBranch, '--base', 'main', '--title', existing, '--body-file', bodyFile], { stdio: 'inherit' });\n if (create.status !== 0) {\n process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\\n ' + bodyFile + '\\n');\n return;\n }\n } else {\n process.stdout.write(`Updating PR #${num}...\\n`);\n spawnSync('gh', ['pr', 'edit', num, '--body-file', bodyFile], { stdio: 'inherit' });\n }\n spawnSync('gh', ['pr', 'merge', currentBranch, '--auto', '--squash'], { stdio: 'inherit' });\n}\n\nexport function main(): void {\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n\n runUpdateFromMain();\n ensurePushed(execSync('git branch --show-current', { encoding: 'utf8' }).trim());\n\n process.stdout.write('\\n' + SEP + '② Build gate (nx affected)\\n' + SEP + '\\n');\n const config = loadPrGateConfig(repoRoot);\n const buildCode = runBuildAffected(repoRoot, config.buildCommand);\n if (buildCode !== 0) {\n process.stderr.write('\\n❌ Build failed — no PR created/updated. Fix and re-run pnpm wp-upsert-pr.\\n');\n process.exit(buildCode);\n }\n\n process.stdout.write('\\n' + SEP + '③ Dashboard + PR\\n' + SEP + '\\n');\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const body = buildDashboard(repoRoot, true);\n upsertPr(repoRoot, currentBranch, body);\n process.stdout.write('\\n✅ Done.\\n');\n}\n\nif (require.main === module) {\n main();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"wp-upsert-pr.js","sourceRoot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{ loadPrGateConfig, WEBPIECES_TMP_DIR } from '@webpieces/rules-config';\nimport { getFeatureName } from './workflow/git-readAiBranchName';\nimport { runConfiguredBuildGate, resolveBuildCommand } from './workflow/build-affected';\nimport { runGitChecked } from './workflow/git-exec';\nimport {\n computeGateResults,\n countAddedDisables,\n renderDashboard,\n DashboardInput,\n} from '../dashboard/dashboard';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\nfunction gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\n// Step A — bring the branch up to date with main via the 3-point engine (child process, so\n// its conflict handback / guard interplay is unaffected by this command's hook context).\nfunction runUpdateFromMain(): void {\n process.stdout.write('\\n' + SEP + '① Updating branch from main\\n' + SEP + '\\n');\n const result = spawnSync('pnpm', ['wp-git-update'], { stdio: 'inherit' });\n if (result.status === 2) {\n process.stdout.write('\\n⏸️ Conflicts — resolve them, run pnpm wp-git-merge-complete, then re-run pnpm wp-upsert-pr.\\n');\n process.exit(2);\n }\n if (result.status !== 0) {\n process.stderr.write('\\n❌ Branch update failed — see output above.\\n');\n process.exit(result.status ?? 1);\n }\n}\n\nfunction ensurePushed(currentBranch: string): void {\n const remoteExists = spawnSync('git', ['ls-remote', '--exit-code', '--heads', 'origin', currentBranch]).status === 0;\n if (remoteExists) {\n runGitChecked(['push', '--force-with-lease', 'origin', `HEAD:${currentBranch}`], 'Failed to push branch');\n } else {\n runGitChecked(['push', '-u', 'origin', `HEAD:${currentBranch}`], 'Failed to push new branch');\n }\n}\n\nfunction buildDashboard(repoRoot: string, buildPassed: boolean): string {\n const config = loadPrGateConfig(repoRoot);\n const forkPoint = gitOut(['merge-base', 'origin/main', 'HEAD']);\n const featureHead = gitOut(['rev-parse', 'HEAD']);\n const mainHead = gitOut(['rev-parse', 'origin/main']);\n const range = `${forkPoint}..${featureHead}`;\n const changedFiles = gitOut(['diff', range, '--name-only']).split('\\n').filter((f: string): boolean => f.trim() !== '');\n const patch = gitOut(['diff', range]);\n const title = gitOut(['log', '-1', '--format=%s']);\n\n const gateResults = computeGateResults(config.gates, changedFiles);\n const disables = countAddedDisables(patch);\n const input = new DashboardInput(title, gateResults, disables, buildPassed, forkPoint, featureHead, mainHead, '');\n return renderDashboard(input);\n}\n\nfunction upsertPr(repoRoot: string, currentBranch: string, body: string): void {\n const prDir = path.join(repoRoot, WEBPIECES_TMP_DIR, `pr-${getFeatureName()}`);\n fs.mkdirSync(prDir, { recursive: true });\n const bodyFile = path.join(prDir, 'pr-body.md');\n fs.writeFileSync(bodyFile, body + '\\n');\n\n const existing = gitOut(['log', '-1', '--format=%s']); // title fallback\n const prNumber = spawnSync(\n 'gh', ['pr', 'list', '--head', currentBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n const num = prNumber.status === 0 ? (prNumber.stdout ?? '').trim() : '';\n\n if (num === '') {\n process.stdout.write('Creating PR...\\n');\n const create = spawnSync('gh', ['pr', 'create', '--head', currentBranch, '--base', 'main', '--title', existing, '--body-file', bodyFile], { stdio: 'inherit' });\n if (create.status !== 0) {\n process.stderr.write('⚠️ gh pr create failed — create the PR manually with the body in:\\n ' + bodyFile + '\\n');\n return;\n }\n } else {\n process.stdout.write(`Updating PR #${num}...\\n`);\n spawnSync('gh', ['pr', 'edit', num, '--body-file', bodyFile], { stdio: 'inherit' });\n }\n spawnSync('gh', ['pr', 'merge', currentBranch, '--auto', '--squash'], { stdio: 'inherit' });\n}\n\nexport function main(): void {\n const repoRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();\n\n runUpdateFromMain();\n ensurePushed(execSync('git branch --show-current', { encoding: 'utf8' }).trim());\n\n const buildCommand = resolveBuildCommand(repoRoot);\n process.stdout.write('\\n' + SEP + '② Build gate (nx affected)\\n' + SEP + '\\n');\n process.stdout.write(\n `This gate runs the build command below. To get it passing BEFORE this command runs it,\\n` +\n `run the SAME command yourself first and fix everything it reports:\\n\\n` +\n ` ${buildCommand}\\n\\n`,\n );\n const buildCode = runConfiguredBuildGate(repoRoot);\n if (buildCode !== 0) {\n process.stderr.write(\n `\\n❌ Build failed — no PR created/updated.\\n\\n` +\n `Run THIS exact command to reproduce and fix all errors, then re-run pnpm wp-upsert-pr:\\n\\n` +\n ` ${buildCommand}\\n\\n`,\n );\n process.exit(buildCode);\n }\n\n process.stdout.write('\\n' + SEP + '③ Dashboard + PR\\n' + SEP + '\\n');\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n const body = buildDashboard(repoRoot, true);\n upsertPr(repoRoot, currentBranch, body);\n process.stdout.write('\\n✅ Done.\\n');\n}\n\nif (require.main === module) {\n main();\n}\n"]}
|