@webpieces/pr-gate 0.3.309 → 0.3.311
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/workflow/branch-naming.d.ts +0 -4
- package/src/scripts/workflow/branch-naming.js +5 -14
- package/src/scripts/workflow/branch-naming.js.map +1 -1
- package/src/scripts/workflow/cleanTmp.js +8 -6
- package/src/scripts/workflow/cleanTmp.js.map +1 -1
- package/src/scripts/workflow/merge-start.js +14 -8
- package/src/scripts/workflow/merge-start.js.map +1 -1
- package/src/scripts/workflow/merge-state.d.ts +10 -0
- package/src/scripts/workflow/merge-state.js +57 -1
- package/src/scripts/workflow/merge-state.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.311",
|
|
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",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"directory": "packages/tooling/pr-gate"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@webpieces/rules-config": "0.3.
|
|
24
|
+
"@webpieces/rules-config": "0.3.311"
|
|
25
25
|
},
|
|
26
26
|
"publishConfig": {
|
|
27
27
|
"access": "public"
|
|
@@ -6,7 +6,3 @@ export declare function baseBranchName(branch: string): string;
|
|
|
6
6
|
* (`merge-info/<slug>/merge-<n>/`, see merge-state.mergeRunDirFor), so the branch and its context
|
|
7
7
|
* share one number. Clean syncs delete their snapshot at finalize; only conflict syncs leave one. */
|
|
8
8
|
export declare function preMergeBackupName(branch: string, n: number): string;
|
|
9
|
-
/** First free PreMerge slot NUMBER for `branch`, probing 1, 2, 3, … via the `exists` predicate. Pure
|
|
10
|
-
* (the branch-existence check is injected) so it unit-tests without touching git. This integer is the
|
|
11
|
-
* single source of truth for both the backup branch name and its paired `merge-<n>` context folder. */
|
|
12
|
-
export declare function nextFreePreMergeNumber(branch: string, exists: (name: string) => boolean): number;
|
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
// generation number survives a sync — the old scheme numbered the LOCAL branch up (base → basewp2 →
|
|
9
9
|
// basewp3) while the remote/PR stayed on `base`, which read as "the PR moved" when it never did.
|
|
10
10
|
//
|
|
11
|
-
// The pre-merge safety snapshot is a NUMBERED trail
|
|
12
|
-
//
|
|
13
|
-
// the
|
|
14
|
-
//
|
|
11
|
+
// The pre-merge safety snapshot is a NUMBERED trail — `<branch>PreMerge1`, `<branch>PreMerge2`, … —
|
|
12
|
+
// paired with a durable audit folder `merge-<n>/` of the SAME number (see merge-state). The number is
|
|
13
|
+
// chosen MONOTONICALLY from the existing `merge-<n>/` dirs (merge-state.nextMergeSlotNumber), never
|
|
14
|
+
// recycled. A CLEAN sync deletes its snapshot branch at finalize (no undo point needed) but KEEPS its
|
|
15
|
+
// `merge-<n>/` audit record; a CONFLICT sync keeps both the snapshot branch and its `merge-<n>/`.
|
|
15
16
|
//
|
|
16
17
|
// `baseBranchName` still strips a trailing `Squash` (the transient temp-branch suffix) AND a trailing
|
|
17
18
|
// `wp<digits>` — the latter only for BACKWARD COMPATIBILITY, so a consumer sitting on a leftover
|
|
@@ -22,7 +23,6 @@
|
|
|
22
23
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
24
|
exports.baseBranchName = baseBranchName;
|
|
24
25
|
exports.preMergeBackupName = preMergeBackupName;
|
|
25
|
-
exports.nextFreePreMergeNumber = nextFreePreMergeNumber;
|
|
26
26
|
const GENERATION_RE = /^(.*)wp(\d+)$/;
|
|
27
27
|
class Generation {
|
|
28
28
|
base;
|
|
@@ -52,13 +52,4 @@ function baseBranchName(branch) {
|
|
|
52
52
|
function preMergeBackupName(branch, n) {
|
|
53
53
|
return `${branch}PreMerge${n}`;
|
|
54
54
|
}
|
|
55
|
-
/** First free PreMerge slot NUMBER for `branch`, probing 1, 2, 3, … via the `exists` predicate. Pure
|
|
56
|
-
* (the branch-existence check is injected) so it unit-tests without touching git. This integer is the
|
|
57
|
-
* single source of truth for both the backup branch name and its paired `merge-<n>` context folder. */
|
|
58
|
-
function nextFreePreMergeNumber(branch, exists) {
|
|
59
|
-
for (let n = 1;; n++) {
|
|
60
|
-
if (!exists(preMergeBackupName(branch, n)))
|
|
61
|
-
return n;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
55
|
//# sourceMappingURL=branch-naming.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch-naming.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/branch-naming.ts"],"names":[],"mappings":";AAAA,6CAA6C;AAC7C,EAAE;AACF,sGAAsG;AACtG,oGAAoG;AACpG,gGAAgG;AAChG,kGAAkG;AAClG,oGAAoG;AACpG,iGAAiG;AACjG,EAAE;AACF,
|
|
1
|
+
{"version":3,"file":"branch-naming.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/branch-naming.ts"],"names":[],"mappings":";AAAA,6CAA6C;AAC7C,EAAE;AACF,sGAAsG;AACtG,oGAAoG;AACpG,gGAAgG;AAChG,kGAAkG;AAClG,oGAAoG;AACpG,iGAAiG;AACjG,EAAE;AACF,oGAAoG;AACpG,sGAAsG;AACtG,oGAAoG;AACpG,sGAAsG;AACtG,kGAAkG;AAClG,EAAE;AACF,sGAAsG;AACtG,iGAAiG;AACjG,iGAAiG;AACjG,oGAAoG;AACpG,sGAAsG;AACtG,6FAA6F;;AAyB7F,wCAEC;AAMD,gDAEC;AAjCD,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC,MAAM,UAAU;IACZ,IAAI,CAAS;IACb,GAAG,CAAS;IAEZ,YAAY,IAAY,EAAE,GAAW;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACnB,CAAC;CACJ;AAED,SAAS,eAAe,CAAC,MAAc;IACnC,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACpD,MAAM,KAAK,GAAG,aAAa,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjD,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,IAAI,UAAU,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;AAC5C,CAAC;AAED;iGACiG;AACjG,SAAgB,cAAc,CAAC,MAAc;IACzC,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC;AAED;;;sGAGsG;AACtG,SAAgB,kBAAkB,CAAC,MAAc,EAAE,CAAS;IACxD,OAAO,GAAG,MAAM,WAAW,CAAC,EAAE,CAAC;AACnC,CAAC","sourcesContent":["// Branch-naming for the squash-merge scheme.\n//\n// A feature branch has ONE stable name that never changes: it is the local branch, the remote branch,\n// AND the single PR head — all identical, so \"which branch is my PR on?\" is never ambiguous. A sync\n// (re-merge from main) happens on a transient `<branch>Squash` branch and, when it finishes, is\n// force-pushed and RENAMED BACK to the same feature name (see merge-end.finalizeBranch). No `wpN`\n// generation number survives a sync — the old scheme numbered the LOCAL branch up (base → basewp2 →\n// basewp3) while the remote/PR stayed on `base`, which read as \"the PR moved\" when it never did.\n//\n// The pre-merge safety snapshot is a NUMBERED trail — `<branch>PreMerge1`, `<branch>PreMerge2`, … —\n// paired with a durable audit folder `merge-<n>/` of the SAME number (see merge-state). The number is\n// chosen MONOTONICALLY from the existing `merge-<n>/` dirs (merge-state.nextMergeSlotNumber), never\n// recycled. A CLEAN sync deletes its snapshot branch at finalize (no undo point needed) but KEEPS its\n// `merge-<n>/` audit record; a CONFLICT sync keeps both the snapshot branch and its `merge-<n>/`.\n//\n// `baseBranchName` still strips a trailing `Squash` (the transient temp-branch suffix) AND a trailing\n// `wp<digits>` — the latter only for BACKWARD COMPATIBILITY, so a consumer sitting on a leftover\n// `…wp5` branch from the old scheme still resolves to its stable name during the transition. The\n// generation marker `wp<N>` is a literal `wp` prefix (NOT a bare number) so it never mangles branch\n// names that naturally end in digits, e.g. `deanhiller/upgrade-webpieces-0.3.213`. The tool no longer\n// PRODUCES `wpN`; the branch-creation-guard still reserves the suffix during the transition.\n\nconst GENERATION_RE = /^(.*)wp(\\d+)$/;\n\nclass Generation {\n base: string;\n gen: number;\n\n constructor(base: string, gen: number) {\n this.base = base;\n this.gen = gen;\n }\n}\n\nfunction parseGeneration(branch: string): Generation {\n const withoutSquash = branch.replace(/Squash$/, '');\n const match = withoutSquash.match(GENERATION_RE);\n if (match && match[1] !== '') {\n return new Generation(match[1], parseInt(match[2], 10));\n }\n return new Generation(withoutSquash, 1);\n}\n\n/** Stable base identity (remote / PR / feature-name slug source): trailing `Squash` and the\n * generation marker stripped. `base` → `base`, `basewp2` → `base`, `basewp2Squash` → `base`. */\nexport function baseBranchName(branch: string): string {\n return parseGeneration(branch).base;\n}\n\n/** Pre-merge snapshot name for slot `n`, ALWAYS numbered from 1: `<branch>PreMerge1`,\n * `<branch>PreMerge2`, … The same `n` also names the paired conflict-context folder\n * (`merge-info/<slug>/merge-<n>/`, see merge-state.mergeRunDirFor), so the branch and its context\n * share one number. Clean syncs delete their snapshot at finalize; only conflict syncs leave one. */\nexport function preMergeBackupName(branch: string, n: number): string {\n return `${branch}PreMerge${n}`;\n}\n"]}
|
|
@@ -9,9 +9,10 @@ const rules_config_1 = require("@webpieces/rules-config");
|
|
|
9
9
|
const CUTOFF_DAYS = 30;
|
|
10
10
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
11
11
|
// Per-feature workflow dirs now live under `.webpieces/merge-info/<feature>` and
|
|
12
|
-
// `.webpieces/pr-
|
|
12
|
+
// `.webpieces/pr-review/<feature>`; those two homes are permanent (like hooks/ and instruct-ai/) and
|
|
13
13
|
// only their stale subdirs are cleaned. `LEGACY_PREFIXES` sweeps the old flat top-level layout
|
|
14
|
-
// (`merge-<feature>`/`review-<feature>`/`pr-<feature>`) so it self-clears after the move
|
|
14
|
+
// (`merge-<feature>`/`review-<feature>`/`pr-<feature>`) so it self-clears after the move — which also
|
|
15
|
+
// reaps the retired `pr-info/` home (it matches the `pr-` prefix and is no longer the active PR home).
|
|
15
16
|
const LEGACY_PREFIXES = ['merge-', 'review-', 'pr-'];
|
|
16
17
|
async function cleanTmp() {
|
|
17
18
|
const repoRoot = (0, child_process_1.execSync)('git rev-parse --show-toplevel', { encoding: 'utf8' }).trim();
|
|
@@ -32,8 +33,8 @@ async function cleanTmp() {
|
|
|
32
33
|
let deletedCount = 0;
|
|
33
34
|
// Stale per-feature subdirs under each permanent home.
|
|
34
35
|
deletedCount += cleanStaleSubdirs(path.join(tmpBase, rules_config_1.MERGE_INFO_DIR), rules_config_1.MERGE_INFO_DIR, now, cutoffMs);
|
|
35
|
-
deletedCount += cleanStaleSubdirs(path.join(tmpBase, rules_config_1.
|
|
36
|
-
// Legacy flat top-level dirs from before the merge-info/pr-
|
|
36
|
+
deletedCount += cleanStaleSubdirs(path.join(tmpBase, rules_config_1.PR_REVIEW_DIR), rules_config_1.PR_REVIEW_DIR, now, cutoffMs);
|
|
37
|
+
// Legacy flat top-level dirs from before the merge-info/pr-review nesting (also reaps old pr-info/).
|
|
37
38
|
deletedCount += cleanLegacyTopLevel(tmpBase, now, cutoffMs);
|
|
38
39
|
if (deletedCount === 0) {
|
|
39
40
|
process.stdout.write(` ✅ No directories older than ${CUTOFF_DAYS} days found\n`);
|
|
@@ -66,11 +67,12 @@ function cleanStaleSubdirs(parentDir, label, now, cutoffMs) {
|
|
|
66
67
|
return count;
|
|
67
68
|
}
|
|
68
69
|
// Sweep the pre-nesting flat layout (`merge-<feature>` etc.), skipping the current homes (whose
|
|
69
|
-
// names also start with `merge-`/`pr-`) so this never deletes merge-info/ or pr-
|
|
70
|
+
// names also start with `merge-`/`pr-`) so this never deletes merge-info/ or pr-review/ themselves.
|
|
71
|
+
// The retired `pr-info/` home is deliberately NOT skipped — it matches `pr-` and self-clears here.
|
|
70
72
|
function cleanLegacyTopLevel(tmpBase, now, cutoffMs) {
|
|
71
73
|
let count = 0;
|
|
72
74
|
for (const entry of fs.readdirSync(tmpBase)) {
|
|
73
|
-
if (entry === rules_config_1.MERGE_INFO_DIR || entry === rules_config_1.
|
|
75
|
+
if (entry === rules_config_1.MERGE_INFO_DIR || entry === rules_config_1.PR_REVIEW_DIR)
|
|
74
76
|
continue;
|
|
75
77
|
if (!LEGACY_PREFIXES.some((prefix) => entry.startsWith(prefix)))
|
|
76
78
|
continue;
|
|
@@ -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":";;AAeA,4BAqCC;;AApDD,iDAAyC;AACzC,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAoG;AAEpG,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE,iFAAiF;AACjF,qGAAqG;AACrG,+FAA+F;AAC/F,sGAAsG;AACtG,uGAAuG;AACvG,MAAM,eAAe,GAAG,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9C,KAAK,UAAU,QAAQ;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IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,sBAAO,EAAC,QAAQ,CAAC,CAAC","sourcesContent":["import { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { WEBPIECES_TMP_DIR, MERGE_INFO_DIR, PR_REVIEW_DIR, runMain } from '@webpieces/rules-config';\n\nconst CUTOFF_DAYS = 30;\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n// Per-feature workflow dirs now live under `.webpieces/merge-info/<feature>` and\n// `.webpieces/pr-review/<feature>`; those two homes are permanent (like hooks/ and instruct-ai/) and\n// only their stale subdirs are cleaned. `LEGACY_PREFIXES` sweeps the old flat top-level layout\n// (`merge-<feature>`/`review-<feature>`/`pr-<feature>`) so it self-clears after the move — which also\n// reaps the retired `pr-info/` home (it matches the `pr-` prefix and is no longer the active PR home).\nconst LEGACY_PREFIXES = ['merge-', 'review-', 'pr-'];\n\nexport async function cleanTmp(): 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 // Stale per-feature subdirs under each permanent home.\n deletedCount += cleanStaleSubdirs(path.join(tmpBase, MERGE_INFO_DIR), MERGE_INFO_DIR, now, cutoffMs);\n deletedCount += cleanStaleSubdirs(path.join(tmpBase, PR_REVIEW_DIR), PR_REVIEW_DIR, now, cutoffMs);\n // Legacy flat top-level dirs from before the merge-info/pr-review nesting (also reaps old pr-info/).\n deletedCount += cleanLegacyTopLevel(tmpBase, now, cutoffMs);\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\n// Delete immediate subdirs of `parentDir` whose mtime is older than the cutoff. `label` prefixes\n// the printed path so output reads e.g. `merge-info/dean-foo`. No-op if the home doesn't exist.\nfunction cleanStaleSubdirs(parentDir: string, label: string, now: number, cutoffMs: number): number {\n if (!fs.existsSync(parentDir)) return 0;\n let count = 0;\n for (const entry of fs.readdirSync(parentDir)) {\n const fullPath = path.join(parentDir, entry);\n const stat = fs.statSync(fullPath);\n if (!stat.isDirectory()) continue;\n if (now - stat.mtimeMs < cutoffMs) continue;\n process.stdout.write(` 🗑️ Deleting: ${label}/${entry}\\n`);\n fs.rmSync(fullPath, { recursive: true, force: true });\n count += 1;\n }\n return count;\n}\n\n// Sweep the pre-nesting flat layout (`merge-<feature>` etc.), skipping the current homes (whose\n// names also start with `merge-`/`pr-`) so this never deletes merge-info/ or pr-review/ themselves.\n// The retired `pr-info/` home is deliberately NOT skipped — it matches `pr-` and self-clears here.\nfunction cleanLegacyTopLevel(tmpBase: string, now: number, cutoffMs: number): number {\n let count = 0;\n for (const entry of fs.readdirSync(tmpBase)) {\n if (entry === MERGE_INFO_DIR || entry === PR_REVIEW_DIR) continue;\n if (!LEGACY_PREFIXES.some((prefix: string): boolean => entry.startsWith(prefix))) continue;\n const fullPath = path.join(tmpBase, entry);\n const stat = fs.statSync(fullPath);\n if (!stat.isDirectory()) continue;\n if (now - stat.mtimeMs < cutoffMs) continue;\n process.stdout.write(` 🗑️ Deleting: ${entry}\\n`);\n fs.rmSync(fullPath, { recursive: true, force: true });\n count += 1;\n }\n return count;\n}\n\nif (require.main === module) runMain(cleanTmp);\n"]}
|
|
@@ -63,15 +63,18 @@ class SyncSlot {
|
|
|
63
63
|
this.runDir = runDir;
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
-
// Pick
|
|
67
|
-
//
|
|
68
|
-
//
|
|
69
|
-
//
|
|
66
|
+
// Pick this sync's slot number MONOTONICALLY from the durable audit dirs — one past the highest
|
|
67
|
+
// existing `<home>/merge-<n>/`, then stepped past any existing `<branch>PreMerge<n>` branch so the
|
|
68
|
+
// same `n` is also free for the paired backup branch. Unlike the old first-free-branch scheme, the
|
|
69
|
+
// number is never recycled onto a prior merge's context, so we DO NOT (and must not) wipe the run
|
|
70
|
+
// dir: earlier `merge-<k>/` dirs are the audit trail we now deliberately keep. Returns the backup
|
|
71
|
+
// branch name + the (fresh, non-existent) run dir path, both keyed on `n`.
|
|
70
72
|
function chooseSyncSlot(home, currentBranch) {
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
73
|
+
const branchExists = (name) => (0, child_process_1.spawnSync)('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;
|
|
74
|
+
let n = (0, merge_state_1.nextMergeSlotNumber)(home);
|
|
75
|
+
while (branchExists((0, branch_naming_1.preMergeBackupName)(currentBranch, n)))
|
|
76
|
+
n += 1;
|
|
77
|
+
return new SyncSlot((0, branch_naming_1.preMergeBackupName)(currentBranch, n), (0, merge_state_1.mergeRunDirFor)(home, n));
|
|
75
78
|
}
|
|
76
79
|
// Snapshot the pre-merge state onto the caller-chosen `backupBranch` (`<currentBranch>PreMerge<n>`),
|
|
77
80
|
// never overwriting. The slot number `n` is picked once in mergeStart and shared with the paired
|
|
@@ -313,6 +316,9 @@ async function mergeStart(repoRoot, verb, home, finishCommand) {
|
|
|
313
316
|
}
|
|
314
317
|
else {
|
|
315
318
|
(0, git_exec_1.runGitChecked)(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');
|
|
319
|
+
// A real merge happened with no conflicts — leave a durable slot record so EVERY merge (not
|
|
320
|
+
// just conflicted ones) is accounted for under merge-info/<feature>/merge-<n>/.
|
|
321
|
+
(0, merge_state_1.writeCleanMergeMarker)(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);
|
|
316
322
|
}
|
|
317
323
|
return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);
|
|
318
324
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;AA4SA,gCAgEC;;AA5WD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAGiC;AACjC,sDAA+C;AAC/C,mDAA6F;AAC7F,yCAA2C;AAC3C,+CAAiG;AAEjG,qGAAqG;AACrG,oGAAoG;AACpG,qGAAqG;AACrG,+FAA+F;AAC/F,uFAAuF;AACvF,mGAAmG;AACnG,mGAAmG;AACnG,6EAA6E;AAE7E,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAQvE,mGAAmG;AACnG,MAAa,YAAY;IACrB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,YAAY,CAAS;IACrB,QAAQ,CAAS;IAEjB,YAAY,aAAqB,EAAE,YAAoB,EAAE,YAAoB,EAAE,QAAgB;QAC3F,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAZD,oCAYC;AAED,sGAAsG;AACtG,0FAA0F;AAC1F,MAAa,gBAAgB;IACzB,MAAM,CAAuB;IAC7B,OAAO,CAAsB;IAC7B,MAAM,CAAS,CAAC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AAA,wBAAa,EAAC,CAAC,QAAQ,EAAE,IAAI,EAAE,mBAAmB,aAAa,EAAE,CAAC,EAAE,+BAA+B,CAAC,CAAC;IACzG,CAAC;IACD,OAAO,IAAI,gBAAgB,CAAC,OAAO,EAAE,IAAI,YAAY,CAAC,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC1H,CAAC","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n WEBPIECES_TMP_DIR, MERGE_EXPLANATION_FILE, CliExitError,\n MutationVerb, BranchMutationEvent, logBranchMutation,\n} from '@webpieces/rules-config';\nimport { gatherInfo } from '../git-gatherInfo';\nimport { baseBranchName, nextFreePreMergeNumber, preMergeBackupName } from './branch-naming';\nimport { runGitChecked } from './git-exec';\nimport { MergeMarker, perFileContextDir, writeMergeMarker, mergeRunDirFor } from './merge-state';\n\n// merge-START: the first half of the 3-point squash-merge lifecycle. Brings origin/main into a fresh\n// `<branch>Squash`, and on conflict writes the 3-point context files + the unvalidated marker + the\n// process doc, then hands control back to the AI. On a clean merge it commits the squash and returns\n// the branch context so the caller (runUpdateFromMain) can run merge-END to finalize. It NEVER\n// finalizes or posts a PR — that is merge-END's / wp-finish-upsert-pr's job. Shared so\n// runUpdateFromMain (and, via it, wp-start-update + wp-start-upsert-pr) all set up a merge through\n// one code path. `finishCommand` names the command the AI runs to finish after resolving conflicts\n// (standalone update → `wp-finish-update`; PR flow → `wp-finish-upsert-pr`).\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\n// The four branch names merge-END needs to finalize a merge (swap squash→feature, push, clean up).\nexport class MergeContext {\n currentBranch: string;\n squashBranch: string;\n backupBranch: string;\n prNumber: string;\n\n constructor(currentBranch: string, squashBranch: string, backupBranch: string, prNumber: string) {\n this.currentBranch = currentBranch;\n this.squashBranch = squashBranch;\n this.backupBranch = backupBranch;\n this.prNumber = prNumber;\n }\n}\n\n// Outcome of merge-start: 'clean' carries the context for merge-END to finalize; 'conflict' means the\n// marker + context files were written and the caller should hand back to the AI (exit 2).\nexport class MergeStartResult {\n status: 'clean' | 'conflict';\n context: MergeContext | null;\n runDir: string; // this sync's numbered `merge-<n>/` dir — passed to merge-END so it reads THIS marker\n\n constructor(status: 'clean' | 'conflict', context: MergeContext | null, runDir: string) {\n this.status = status;\n this.context = context;\n this.runDir = runDir;\n }\n}\n\n// Detect the PR by its STABLE feature branch — pass baseBranchName(currentBranch) so a leftover\n// `…wpN` from the old scheme still resolves to the one name the PR lives on.\nfunction detectPr(baseBranch: string): string {\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\n// The one number `n` for a sync and the two things it names: the pre-merge backup branch and its\n// paired conflict-context run dir.\nclass SyncSlot {\n backupBranch: string;\n runDir: string;\n\n constructor(backupBranch: string, runDir: string) {\n this.backupBranch = backupBranch;\n this.runDir = runDir;\n }\n}\n\n// Pick the first free `<branch>PreMerge<n>` slot number, then WIPE the paired `<home>/merge-<n>/` run\n// dir — a fresh sync means no merge is in progress, so any leftover `merge-<n>` is stale (its own sync\n// ended, or its branch was deleted) and MUST NOT leak its old per-file merge-explanation.md into this\n// merge's validation. Returns the backup branch name + the (now-empty) run dir path, both keyed on `n`.\nfunction chooseSyncSlot(home: string, currentBranch: string): SyncSlot {\n const n = nextFreePreMergeNumber(\n currentBranch,\n (name: string): boolean => spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0,\n );\n const runDir = mergeRunDirFor(home, n);\n fs.rmSync(runDir, { recursive: true, force: true });\n return new SyncSlot(preMergeBackupName(currentBranch, n), runDir);\n}\n\n// Snapshot the pre-merge state onto the caller-chosen `backupBranch` (`<currentBranch>PreMerge<n>`),\n// never overwriting. The slot number `n` is picked once in mergeStart and shared with the paired\n// `merge-<n>/` context dir. A clean sync deletes this snapshot at finalize; only conflict syncs keep it.\nfunction createBackup(currentBranch: string, backupBranch: string): void {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\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}\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-start-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 {{FINISH_COMMAND}}\\`** — the validation + finish gate. It scans for leftover conflict\n markers, checks each conflicted file has a written merge explanation, validates, and commits the\n merge. (In the PR flow this command is \\`wp-finish-upsert-pr\\`, which additionally runs the\n \\`nx affected\\` build, renders the dashboard, and creates/updates the PR.)\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 (validates the merge AND finalizes it)\n\n\\`\\`\\`\npnpm {{FINISH_COMMAND}}\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- Missing review.json (PR flow only) → write it in the printed format (your PR review), then re-run.\n- On success it commits and finalizes the merge (in the PR flow it also renders the dashboard and\n creates/updates the PR).\n\n## Conflicted files\n\n{{FILE_LIST}}\n\n## If you need to bail out\n\nA numbered backup branch was created (e.g. \\`<feature>PreMerge1\\`). 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[], finishCommand: 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(/\\{\\{FINISH_COMMAND\\}\\}/g, finishCommand)\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[], finishCommand: 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, finishCommand));\n return docPath;\n}\n\n// The AI-facing \"what just happened / what to do next\" recap on the conflict path. Explicit and\n// numbered so an agent (or human) can't miss where the context lives or which command finishes.\nfunction printConflictHandback(\n docPath: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string,\n): 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('Here is exactly what I did and what you need to do:\\n\\n');\n process.stdout.write('What I did:\\n');\n process.stdout.write(' 1. snapshotted your pre-merge state to a PreMerge branch\\n');\n process.stdout.write(' 2. pulled origin/main and squash-merged your work onto it\\n');\n process.stdout.write(` 3. hit conflicts — you are now on the transient branch ${squashBranch}\\n\\n`);\n process.stdout.write('What you need to do:\\n');\n process.stdout.write(` 1. read the merge process doc: ${docPath}\\n`);\n process.stdout.write(` 2. resolve each conflicted file below (its 3-point A/B/C context + diffs are in\\n`);\n process.stdout.write(` ${mergeDir}/updatemain-<file>/), and write that file's merge-explanation.md\\n`);\n process.stdout.write(` 3. run pnpm ${finishCommand} — it validates, commits, and finalizes (do NOT git add/commit/push yourself)\\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\n// Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit — the\n// caller decides (runUpdateFromMain exits 2 to hand back to the AI).\nfunction handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints, finishCommand: string,\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.mkdirSync(mergeDir, { recursive: true }); // run dir was wiped at sync start — create it fresh\n fs.writeFileSync(path.join(mergeDir, 'updatemain-conflicted-files.txt'), raw + '\\n');\n // Copy the A/B/C hashes into THIS run dir so the merge-process doc's `MERGE_DIR/updatemain-hashes.json`\n // pointer is accurate (gatherInfo writes the source copy into the feature home before the slot is known).\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\\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, finishCommand);\n printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);\n}\n\n// Short sha of a ref (best-effort — '' if it can't resolve), for the branch-mutation log's\n// oldMain→newMain annotation.\nfunction shortSha(ref: string): string {\n const result = spawnSync('git', ['rev-parse', '--short', ref], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\n// Log the CONFLICT phase with the conflicted-file list + the artifact paths a resolver needs — the\n// per-file 3-point context dir and the generated merge-process doc — so the branch-mutation log alone\n// tells the next agent where to look (no reflog/log archaeology).\nfunction logConflict(repoRoot: string, verb: MutationVerb, mergeDir: string): void {\n const raw = spawnSync('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: repoRoot, encoding: 'utf8' });\n const files = (raw.status === 0 ? (raw.stdout ?? '') : '').split('\\n').map((f: string): string => f.trim()).filter((f: string): boolean => f !== '');\n const event = new BranchMutationEvent(verb, 'CONFLICT');\n event.conflict = true;\n event.conflictFiles = files;\n event.artifacts = [\n path.join(mergeDir, 'updatemain-<file>'),\n path.join(repoRoot, WEBPIECES_TMP_DIR, 'instruct-ai', 'webpieces.mergeprocess.md'),\n ];\n logBranchMutation(repoRoot, event);\n}\n\nexport async function mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult> {\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n if (currentBranch.endsWith('Squash')) {\n throw new CliExitError(1, `❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}`);\n }\n\n // One number `n` for this sync drives BOTH the backup branch and its `merge-<n>/` context dir.\n const slot = chooseSyncSlot(home, currentBranch);\n const backupBranch = slot.backupBranch;\n const mergeDir = slot.runDir;\n\n process.stdout.write('\\n' + SEP + '🔄 Squash-Merge Update from Main\\n' + SEP + '\\n');\n // gatherInfo RETURNS (never exits): an already-even-with-main branch is NOT special-cased here —\n // we flow straight on. The squash merge below becomes a no-op that the `nothingStaged` path\n // (further down) handles, so the caller still proceeds to push + build. (Previously gatherInfo\n // process.exit(0)'d on this case, silently killing wp-start-upsert-pr before push/build.)\n const info = await gatherInfo();\n const hashes = info.hashes;\n if (info.alreadyUpToDate) {\n process.stdout.write('ℹ️ Branch already even with main; nothing to merge, continuing to push/build.\\n');\n }\n\n const prNumber = detectPr(baseBranchName(currentBranch));\n process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\\n` : 'No existing PR (one can be created later).\\n');\n\n createBackup(currentBranch, backupBranch);\n const backupEvent = new BranchMutationEvent(verb, 'BACKUP');\n backupEvent.fromBranch = currentBranch;\n backupEvent.toBranch = backupBranch;\n logBranchMutation(repoRoot, backupEvent);\n\n const squashBranch = `${currentBranch}Squash`;\n if (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {\n throw new CliExitError(1, `❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}`);\n }\n\n // Branch the squash off origin/main directly — worktree-native. Never checks out or mutates local\n // `main`, which fatals inside a linked worktree (`git checkout main` → \"'main' is already checked\n // out at <primary>\"). origin/main was already fetched in gatherInfo() above, and the fork point +\n // all three hash points (A/B/C) are computed purely from origin/main, so the squash merge base is\n // identical to the old checkout-main + pull path — this is a behavior-preserving change on the\n // primary repo and an unblock inside worktrees.\n const originMainSha = shortSha('origin/main');\n runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');\n const baseEvent = new BranchMutationEvent(verb, 'PULL');\n baseEvent.newMain = originMainSha;\n logBranchMutation(repoRoot, baseEvent);\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, finishCommand);\n logConflict(repoRoot, verb, mergeDir);\n return new MergeStartResult('conflict', null, mergeDir);\n }\n logBranchMutation(repoRoot, new BranchMutationEvent(verb, 'SQUASH'));\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 return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;AA+SA,gCAmEC;;AAlXD,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAGiC;AACj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ATION_FILE, CliExitError,\n MutationVerb, BranchMutationEvent, logBranchMutation,\n} from '@webpieces/rules-config';\nimport { gatherInfo } from '../git-gatherInfo';\nimport { baseBranchName, preMergeBackupName } from './branch-naming';\nimport { runGitChecked } from './git-exec';\nimport {\n MergeMarker, perFileContextDir, writeMergeMarker, mergeRunDirFor,\n nextMergeSlotNumber, writeCleanMergeMarker,\n} from './merge-state';\n\n// merge-START: the first half of the 3-point squash-merge lifecycle. Brings origin/main into a fresh\n// `<branch>Squash`, and on conflict writes the 3-point context files + the unvalidated marker + the\n// process doc, then hands control back to the AI. On a clean merge it commits the squash and returns\n// the branch context so the caller (runUpdateFromMain) can run merge-END to finalize. It NEVER\n// finalizes or posts a PR — that is merge-END's / wp-finish-upsert-pr's job. Shared so\n// runUpdateFromMain (and, via it, wp-start-update + wp-start-upsert-pr) all set up a merge through\n// one code path. `finishCommand` names the command the AI runs to finish after resolving conflicts\n// (standalone update → `wp-finish-update`; PR flow → `wp-finish-upsert-pr`).\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\ninterface HashPoints {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n}\n\n// The four branch names merge-END needs to finalize a merge (swap squash→feature, push, clean up).\nexport class MergeContext {\n currentBranch: string;\n squashBranch: string;\n backupBranch: string;\n prNumber: string;\n\n constructor(currentBranch: string, squashBranch: string, backupBranch: string, prNumber: string) {\n this.currentBranch = currentBranch;\n this.squashBranch = squashBranch;\n this.backupBranch = backupBranch;\n this.prNumber = prNumber;\n }\n}\n\n// Outcome of merge-start: 'clean' carries the context for merge-END to finalize; 'conflict' means the\n// marker + context files were written and the caller should hand back to the AI (exit 2).\nexport class MergeStartResult {\n status: 'clean' | 'conflict';\n context: MergeContext | null;\n runDir: string; // this sync's numbered `merge-<n>/` dir — passed to merge-END so it reads THIS marker\n\n constructor(status: 'clean' | 'conflict', context: MergeContext | null, runDir: string) {\n this.status = status;\n this.context = context;\n this.runDir = runDir;\n }\n}\n\n// Detect the PR by its STABLE feature branch — pass baseBranchName(currentBranch) so a leftover\n// `…wpN` from the old scheme still resolves to the one name the PR lives on.\nfunction detectPr(baseBranch: string): string {\n const result = spawnSync(\n 'gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n { encoding: 'utf8' },\n );\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\n// The one number `n` for a sync and the two things it names: the pre-merge backup branch and its\n// paired conflict-context run dir.\nclass SyncSlot {\n backupBranch: string;\n runDir: string;\n\n constructor(backupBranch: string, runDir: string) {\n this.backupBranch = backupBranch;\n this.runDir = runDir;\n }\n}\n\n// Pick this sync's slot number MONOTONICALLY from the durable audit dirs — one past the highest\n// existing `<home>/merge-<n>/`, then stepped past any existing `<branch>PreMerge<n>` branch so the\n// same `n` is also free for the paired backup branch. Unlike the old first-free-branch scheme, the\n// number is never recycled onto a prior merge's context, so we DO NOT (and must not) wipe the run\n// dir: earlier `merge-<k>/` dirs are the audit trail we now deliberately keep. Returns the backup\n// branch name + the (fresh, non-existent) run dir path, both keyed on `n`.\nfunction chooseSyncSlot(home: string, currentBranch: string): SyncSlot {\n const branchExists = (name: string): boolean =>\n spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${name}`]).status === 0;\n let n = nextMergeSlotNumber(home);\n while (branchExists(preMergeBackupName(currentBranch, n))) n += 1;\n return new SyncSlot(preMergeBackupName(currentBranch, n), mergeRunDirFor(home, n));\n}\n\n// Snapshot the pre-merge state onto the caller-chosen `backupBranch` (`<currentBranch>PreMerge<n>`),\n// never overwriting. The slot number `n` is picked once in mergeStart and shared with the paired\n// `merge-<n>/` context dir. A clean sync deletes this snapshot at finalize; only conflict syncs keep it.\nfunction createBackup(currentBranch: string, backupBranch: string): void {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\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}\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-start-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 {{FINISH_COMMAND}}\\`** — the validation + finish gate. It scans for leftover conflict\n markers, checks each conflicted file has a written merge explanation, validates, and commits the\n merge. (In the PR flow this command is \\`wp-finish-upsert-pr\\`, which additionally runs the\n \\`nx affected\\` build, renders the dashboard, and creates/updates the PR.)\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 (validates the merge AND finalizes it)\n\n\\`\\`\\`\npnpm {{FINISH_COMMAND}}\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- Missing review.json (PR flow only) → write it in the printed format (your PR review), then re-run.\n- On success it commits and finalizes the merge (in the PR flow it also renders the dashboard and\n creates/updates the PR).\n\n## Conflicted files\n\n{{FILE_LIST}}\n\n## If you need to bail out\n\nA numbered backup branch was created (e.g. \\`<feature>PreMerge1\\`). 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[], finishCommand: 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(/\\{\\{FINISH_COMMAND\\}\\}/g, finishCommand)\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[], finishCommand: 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, finishCommand));\n return docPath;\n}\n\n// The AI-facing \"what just happened / what to do next\" recap on the conflict path. Explicit and\n// numbered so an agent (or human) can't miss where the context lives or which command finishes.\nfunction printConflictHandback(\n docPath: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string,\n): 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('Here is exactly what I did and what you need to do:\\n\\n');\n process.stdout.write('What I did:\\n');\n process.stdout.write(' 1. snapshotted your pre-merge state to a PreMerge branch\\n');\n process.stdout.write(' 2. pulled origin/main and squash-merged your work onto it\\n');\n process.stdout.write(` 3. hit conflicts — you are now on the transient branch ${squashBranch}\\n\\n`);\n process.stdout.write('What you need to do:\\n');\n process.stdout.write(` 1. read the merge process doc: ${docPath}\\n`);\n process.stdout.write(` 2. resolve each conflicted file below (its 3-point A/B/C context + diffs are in\\n`);\n process.stdout.write(` ${mergeDir}/updatemain-<file>/), and write that file's merge-explanation.md\\n`);\n process.stdout.write(` 3. run pnpm ${finishCommand} — it validates, commits, and finalizes (do NOT git add/commit/push yourself)\\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\n// Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit — the\n// caller decides (runUpdateFromMain exits 2 to hand back to the AI).\nfunction handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints, finishCommand: string,\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.mkdirSync(mergeDir, { recursive: true }); // run dir was wiped at sync start — create it fresh\n fs.writeFileSync(path.join(mergeDir, 'updatemain-conflicted-files.txt'), raw + '\\n');\n // Copy the A/B/C hashes into THIS run dir so the merge-process doc's `MERGE_DIR/updatemain-hashes.json`\n // pointer is accurate (gatherInfo writes the source copy into the feature home before the slot is known).\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\\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, finishCommand);\n printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);\n}\n\n// Short sha of a ref (best-effort — '' if it can't resolve), for the branch-mutation log's\n// oldMain→newMain annotation.\nfunction shortSha(ref: string): string {\n const result = spawnSync('git', ['rev-parse', '--short', ref], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n}\n\n// Log the CONFLICT phase with the conflicted-file list + the artifact paths a resolver needs — the\n// per-file 3-point context dir and the generated merge-process doc — so the branch-mutation log alone\n// tells the next agent where to look (no reflog/log archaeology).\nfunction logConflict(repoRoot: string, verb: MutationVerb, mergeDir: string): void {\n const raw = spawnSync('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: repoRoot, encoding: 'utf8' });\n const files = (raw.status === 0 ? (raw.stdout ?? '') : '').split('\\n').map((f: string): string => f.trim()).filter((f: string): boolean => f !== '');\n const event = new BranchMutationEvent(verb, 'CONFLICT');\n event.conflict = true;\n event.conflictFiles = files;\n event.artifacts = [\n path.join(mergeDir, 'updatemain-<file>'),\n path.join(repoRoot, WEBPIECES_TMP_DIR, 'instruct-ai', 'webpieces.mergeprocess.md'),\n ];\n logBranchMutation(repoRoot, event);\n}\n\nexport async function mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult> {\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n if (currentBranch.endsWith('Squash')) {\n throw new CliExitError(1, `❌ On a leftover ${currentBranch} branch with no merge marker. Clean up: git branch -D ${currentBranch}`);\n }\n\n // One number `n` for this sync drives BOTH the backup branch and its `merge-<n>/` context dir.\n const slot = chooseSyncSlot(home, currentBranch);\n const backupBranch = slot.backupBranch;\n const mergeDir = slot.runDir;\n\n process.stdout.write('\\n' + SEP + '🔄 Squash-Merge Update from Main\\n' + SEP + '\\n');\n // gatherInfo RETURNS (never exits): an already-even-with-main branch is NOT special-cased here —\n // we flow straight on. The squash merge below becomes a no-op that the `nothingStaged` path\n // (further down) handles, so the caller still proceeds to push + build. (Previously gatherInfo\n // process.exit(0)'d on this case, silently killing wp-start-upsert-pr before push/build.)\n const info = await gatherInfo();\n const hashes = info.hashes;\n if (info.alreadyUpToDate) {\n process.stdout.write('ℹ️ Branch already even with main; nothing to merge, continuing to push/build.\\n');\n }\n\n const prNumber = detectPr(baseBranchName(currentBranch));\n process.stdout.write(prNumber ? `Existing PR #${prNumber} will be updated.\\n` : 'No existing PR (one can be created later).\\n');\n\n createBackup(currentBranch, backupBranch);\n const backupEvent = new BranchMutationEvent(verb, 'BACKUP');\n backupEvent.fromBranch = currentBranch;\n backupEvent.toBranch = backupBranch;\n logBranchMutation(repoRoot, backupEvent);\n\n const squashBranch = `${currentBranch}Squash`;\n if (spawnSync('git', ['show-ref', '--verify', '--quiet', `refs/heads/${squashBranch}`]).status === 0) {\n throw new CliExitError(1, `❌ Stale ${squashBranch} from a previous run. Delete it: git branch -D ${squashBranch}`);\n }\n\n // Branch the squash off origin/main directly — worktree-native. Never checks out or mutates local\n // `main`, which fatals inside a linked worktree (`git checkout main` → \"'main' is already checked\n // out at <primary>\"). origin/main was already fetched in gatherInfo() above, and the fork point +\n // all three hash points (A/B/C) are computed purely from origin/main, so the squash merge base is\n // identical to the old checkout-main + pull path — this is a behavior-preserving change on the\n // primary repo and an unblock inside worktrees.\n const originMainSha = shortSha('origin/main');\n runGitChecked(['checkout', '-b', squashBranch, 'origin/main'], 'Failed to create squash branch off origin/main');\n const baseEvent = new BranchMutationEvent(verb, 'PULL');\n baseEvent.newMain = originMainSha;\n logBranchMutation(repoRoot, baseEvent);\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, finishCommand);\n logConflict(repoRoot, verb, mergeDir);\n return new MergeStartResult('conflict', null, mergeDir);\n }\n logBranchMutation(repoRoot, new BranchMutationEvent(verb, 'SQUASH'));\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 // A real merge happened with no conflicts — leave a durable slot record so EVERY merge (not\n // just conflicted ones) is accounted for under merge-info/<feature>/merge-<n>/.\n writeCleanMergeMarker(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n }\n return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);\n}\n"]}
|
|
@@ -17,6 +17,16 @@ export declare class MarkerScanResult {
|
|
|
17
17
|
}
|
|
18
18
|
export declare function mergeDirFor(repoRoot: string, featureName: string): string;
|
|
19
19
|
export declare function mergeRunDirFor(home: string, n: number): string;
|
|
20
|
+
export declare function nextMergeSlotNumber(home: string): number;
|
|
21
|
+
export declare class MergeHashRecord {
|
|
22
|
+
hashForkPoint: string;
|
|
23
|
+
hashFeatureHead: string;
|
|
24
|
+
hashMainHead: string;
|
|
25
|
+
timestamp: string;
|
|
26
|
+
constructor(hashForkPoint: string, hashFeatureHead: string, hashMainHead: string, timestamp: string);
|
|
27
|
+
}
|
|
28
|
+
export declare const NO_CONFLICT_MARKER_FILE = "no-3point-merge.md";
|
|
29
|
+
export declare function writeCleanMergeMarker(mergeDir: string, forkPoint: string, featureHead: string, mainHead: string): void;
|
|
20
30
|
export declare function findActiveMergeRunDir(home: string): string | null;
|
|
21
31
|
export declare function perFileContextDir(mergeDir: string, file: string): string;
|
|
22
32
|
export declare function markerPath(mergeDir: string): string;
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MarkerScanResult = exports.MergeMarker = void 0;
|
|
3
|
+
exports.NO_CONFLICT_MARKER_FILE = exports.MergeHashRecord = exports.MarkerScanResult = exports.MergeMarker = void 0;
|
|
4
4
|
exports.mergeDirFor = mergeDirFor;
|
|
5
5
|
exports.mergeRunDirFor = mergeRunDirFor;
|
|
6
|
+
exports.nextMergeSlotNumber = nextMergeSlotNumber;
|
|
7
|
+
exports.writeCleanMergeMarker = writeCleanMergeMarker;
|
|
6
8
|
exports.findActiveMergeRunDir = findActiveMergeRunDir;
|
|
7
9
|
exports.perFileContextDir = perFileContextDir;
|
|
8
10
|
exports.markerPath = markerPath;
|
|
@@ -63,6 +65,60 @@ function mergeDirFor(repoRoot, featureName) {
|
|
|
63
65
|
function mergeRunDirFor(home, n) {
|
|
64
66
|
return path.join(home, `merge-${n}`);
|
|
65
67
|
}
|
|
68
|
+
// The next NEVER-REUSED merge slot number for a feature home: one past the highest existing
|
|
69
|
+
// `merge-<n>/` dir (or 1 if none). This is the durable, monotonic source of truth for slot numbers —
|
|
70
|
+
// derived from the audit dirs THEMSELVES, not from which transient `<feature>PreMerge<n>` branch
|
|
71
|
+
// happens to exist. The old branch-existence scheme recycled a number the moment its snapshot was
|
|
72
|
+
// pruned, and the next sync then wiped that slot's `merge-explanation.md`; numbering off the dirs
|
|
73
|
+
// makes every merge keep its own `merge-<n>/` record permanently. Pure fs — unit-testable.
|
|
74
|
+
function nextMergeSlotNumber(home) {
|
|
75
|
+
if (!fs.existsSync(home))
|
|
76
|
+
return 1;
|
|
77
|
+
let max = 0;
|
|
78
|
+
for (const entry of fs.readdirSync(home)) {
|
|
79
|
+
const match = entry.match(/^merge-(\d+)$/);
|
|
80
|
+
if (match === null)
|
|
81
|
+
continue;
|
|
82
|
+
const n = parseInt(match[1], 10);
|
|
83
|
+
if (n > max)
|
|
84
|
+
max = n;
|
|
85
|
+
}
|
|
86
|
+
return max + 1;
|
|
87
|
+
}
|
|
88
|
+
// Data-only: the three commit points of a 3-point merge as persisted in `updatemain-hashes.json`
|
|
89
|
+
// (the exact key shape the conflict path already writes), plus when it was recorded.
|
|
90
|
+
class MergeHashRecord {
|
|
91
|
+
hashForkPoint;
|
|
92
|
+
hashFeatureHead;
|
|
93
|
+
hashMainHead;
|
|
94
|
+
timestamp;
|
|
95
|
+
constructor(hashForkPoint, hashFeatureHead, hashMainHead, timestamp) {
|
|
96
|
+
this.hashForkPoint = hashForkPoint;
|
|
97
|
+
this.hashFeatureHead = hashFeatureHead;
|
|
98
|
+
this.hashMainHead = hashMainHead;
|
|
99
|
+
this.timestamp = timestamp;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
exports.MergeHashRecord = MergeHashRecord;
|
|
103
|
+
// Marker written for a CLEAN (no-conflict) sync so every merge — not just conflicted ones — leaves a
|
|
104
|
+
// durable, self-describing record under `merge-info/<feature>/merge-<n>/`. A clean merge produces no
|
|
105
|
+
// per-file `merge-explanation.md`; this file is the "yes, a merge happened here, and it needed no
|
|
106
|
+
// 3-point resolution" proof, with the A/B/C shas kept so it stays auditable.
|
|
107
|
+
exports.NO_CONFLICT_MARKER_FILE = 'no-3point-merge.md';
|
|
108
|
+
// Write the clean-merge marker + a per-slot `updatemain-hashes.json` copy into the slot's own dir.
|
|
109
|
+
function writeCleanMergeMarker(mergeDir, forkPoint, featureHead, mainHead) {
|
|
110
|
+
fs.mkdirSync(mergeDir, { recursive: true });
|
|
111
|
+
const body = '# Clean squash-merge — no 3-point conflict resolution needed\n\n' +
|
|
112
|
+
'This sync merged main into the feature with no conflicts, so the AI wrote no per-file\n' +
|
|
113
|
+
'merge-explanation.md. The 3-point shas below are kept so the merge is still auditable.\n\n' +
|
|
114
|
+
`3-point shas: A(fork)=${forkPoint} B(feature)=${featureHead} C(main)=${mainHead}\n\n` +
|
|
115
|
+
'Reconstruct what each side changed:\n' +
|
|
116
|
+
` feature (B−A): git diff ${forkPoint} ${featureHead}\n` +
|
|
117
|
+
` main (C−A): git diff ${forkPoint} ${mainHead}\n`;
|
|
118
|
+
fs.writeFileSync(path.join(mergeDir, exports.NO_CONFLICT_MARKER_FILE), body);
|
|
119
|
+
const record = new MergeHashRecord(forkPoint, featureHead, mainHead, new Date().toISOString());
|
|
120
|
+
fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(record, null, 2) + '\n');
|
|
121
|
+
}
|
|
66
122
|
// Locate the in-progress merge's run dir: the `<home>/merge-*/` subdir holding a marker. There is at
|
|
67
123
|
// most one (a fresh sync can't start while a merge is in progress); if more than one somehow exists,
|
|
68
124
|
// prefer an UNVALIDATED marker (the live conflict), else return the first found. Null when none.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-state.ts"],"names":[],"mappings":";;;AA8DA,kCAEC;AAID,wCAEC;AAKD,sDAYC;AAMD,8CAEC;AAED,gCAEC;AAED,0CAeC;AAED,4CAGC;AAED,4CAGC;AAMD,kDASC;AASD,sDAQC;;AA9JD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAKiC;AAEjC,uFAAuF;AACvF,yFAAyF;AACzF,yFAAyF;AACzF,MAAa,WAAW;IACpB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,YAAY,CAAS;IACrB,QAA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E,CAAC,YAAY,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC7C,IAAI,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC;YAAE,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,gBAAgB,CAAC,CAAC;AACjF,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CAAC,QAAgB,EAAE,KAAe;IACnE,MAAM,uBAAuB,GAAa,EAAE,CAAC;IAC7C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,qCAAsB,CAAC,CAAC;QACtF,MAAM,OAAO,GAAG,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC;QAC3F,IAAI,CAAC,OAAO;YAAE,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,IAAI,gBAAgB,CAAC,uBAAuB,CAAC,MAAM,KAAK,CAAC,EAAE,uBAAuB,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n WEBPIECES_TMP_DIR,\n MERGE_INFO_DIR,\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-finish-upsert-pr` 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\n// The per-feature \"home\" dir `.webpieces/merge-info/<slug>/`. It no longer holds the marker/context\n// directly — each sync gets its own numbered `merge-<n>/` run dir underneath (mergeRunDirFor), paired\n// with the sync's `<feature>PreMerge<n>` backup branch. This keeps merge N from ever reusing merge\n// N-1's stale per-file context / merge-explanation.md.\nexport function mergeDirFor(repoRoot: string, featureName: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, MERGE_INFO_DIR, featureName);\n}\n\n// The run dir for sync number `n`: `<home>/merge-<n>/`. Holds this sync's marker + per-file\n// `updatemain-<file>/` context. Numbered to match the sync's `<feature>PreMerge<n>` backup branch.\nexport function mergeRunDirFor(home: string, n: number): string {\n return path.join(home, `merge-${n}`);\n}\n\n// Locate the in-progress merge's run dir: the `<home>/merge-*/` subdir holding a marker. There is at\n// most one (a fresh sync can't start while a merge is in progress); if more than one somehow exists,\n// prefer an UNVALIDATED marker (the live conflict), else return the first found. Null when none.\nexport function findActiveMergeRunDir(home: string): string | null {\n if (!fs.existsSync(home)) return null;\n let fallback: string | null = null;\n for (const entry of fs.readdirSync(home)) {\n if (!entry.startsWith('merge-')) continue;\n const dir = path.join(home, entry);\n const marker = readMergeMarker(dir);\n if (marker === null) continue;\n if (!marker.validated) return dir;\n if (fallback === null) fallback = dir;\n }\n return fallback;\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"]}
|
|
1
|
+
{"version":3,"file":"merge-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-state.ts"],"names":[],"mappings":";;;AA8DA,kCAEC;AAID,wCAEC;AAQD,kDAUC;AAyBD,sDAeC;AAKD,sDAYC;AAMD,8CAEC;AAED,gCAEC;AAED,0CAeC;AAED,4CAGC;AAED,4CAGC;AAMD,kDASC;AASD,sDAQC;;AAxND,+CAAyB;AACzB,mDAA6B;AAC7B,0DAKiC;AAEjC,uFAAuF;AACvF,yFAAyF;AACzF,yFAAyF;AACzF,MAAa,WAAW;IACpB,aAAa,CAAS;IACtB,YAAY,CAAS;IACrB,YAAY,CAAS;IACrB,QAAQ,CAAS;IACjB,eAAe,CAAW;IAC1B,SAAS,CAAS;IAClB,WAAW,CAAS;IACpB,QAAQ,CAAS;IACjB,SAAS,CAAU;IAEnB,YACI,aAAqB,EACrB,YAAoB,EACpB,YAAoB,EACpB,QAAgB,EAChB,eAAyB,EACzB,SAAiB,EACjB,WAAmB,EACnB,QAAgB,EAChB,SAAkB;QAElB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,YAAY,GAAG,YAA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AAuB,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n WEBPIECES_TMP_DIR,\n MERGE_INFO_DIR,\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-finish-upsert-pr` 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\n// The per-feature \"home\" dir `.webpieces/merge-info/<slug>/`. It no longer holds the marker/context\n// directly — each sync gets its own numbered `merge-<n>/` run dir underneath (mergeRunDirFor), paired\n// with the sync's `<feature>PreMerge<n>` backup branch. This keeps merge N from ever reusing merge\n// N-1's stale per-file context / merge-explanation.md.\nexport function mergeDirFor(repoRoot: string, featureName: string): string {\n return path.join(repoRoot, WEBPIECES_TMP_DIR, MERGE_INFO_DIR, featureName);\n}\n\n// The run dir for sync number `n`: `<home>/merge-<n>/`. Holds this sync's marker + per-file\n// `updatemain-<file>/` context. Numbered to match the sync's `<feature>PreMerge<n>` backup branch.\nexport function mergeRunDirFor(home: string, n: number): string {\n return path.join(home, `merge-${n}`);\n}\n\n// The next NEVER-REUSED merge slot number for a feature home: one past the highest existing\n// `merge-<n>/` dir (or 1 if none). This is the durable, monotonic source of truth for slot numbers —\n// derived from the audit dirs THEMSELVES, not from which transient `<feature>PreMerge<n>` branch\n// happens to exist. The old branch-existence scheme recycled a number the moment its snapshot was\n// pruned, and the next sync then wiped that slot's `merge-explanation.md`; numbering off the dirs\n// makes every merge keep its own `merge-<n>/` record permanently. Pure fs — unit-testable.\nexport function nextMergeSlotNumber(home: string): number {\n if (!fs.existsSync(home)) return 1;\n let max = 0;\n for (const entry of fs.readdirSync(home)) {\n const match = entry.match(/^merge-(\\d+)$/);\n if (match === null) continue;\n const n = parseInt(match[1], 10);\n if (n > max) max = n;\n }\n return max + 1;\n}\n\n// Data-only: the three commit points of a 3-point merge as persisted in `updatemain-hashes.json`\n// (the exact key shape the conflict path already writes), plus when it was recorded.\nexport class MergeHashRecord {\n hashForkPoint: string;\n hashFeatureHead: string;\n hashMainHead: string;\n timestamp: string;\n\n constructor(hashForkPoint: string, hashFeatureHead: string, hashMainHead: string, timestamp: string) {\n this.hashForkPoint = hashForkPoint;\n this.hashFeatureHead = hashFeatureHead;\n this.hashMainHead = hashMainHead;\n this.timestamp = timestamp;\n }\n}\n\n// Marker written for a CLEAN (no-conflict) sync so every merge — not just conflicted ones — leaves a\n// durable, self-describing record under `merge-info/<feature>/merge-<n>/`. A clean merge produces no\n// per-file `merge-explanation.md`; this file is the \"yes, a merge happened here, and it needed no\n// 3-point resolution\" proof, with the A/B/C shas kept so it stays auditable.\nexport const NO_CONFLICT_MARKER_FILE = 'no-3point-merge.md';\n\n// Write the clean-merge marker + a per-slot `updatemain-hashes.json` copy into the slot's own dir.\nexport function writeCleanMergeMarker(\n mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n): void {\n fs.mkdirSync(mergeDir, { recursive: true });\n const body =\n '# Clean squash-merge — no 3-point conflict resolution needed\\n\\n' +\n 'This sync merged main into the feature with no conflicts, so the AI wrote no per-file\\n' +\n 'merge-explanation.md. The 3-point shas below are kept so the merge is still auditable.\\n\\n' +\n `3-point shas: A(fork)=${forkPoint} B(feature)=${featureHead} C(main)=${mainHead}\\n\\n` +\n 'Reconstruct what each side changed:\\n' +\n ` feature (B−A): git diff ${forkPoint} ${featureHead}\\n` +\n ` main (C−A): git diff ${forkPoint} ${mainHead}\\n`;\n fs.writeFileSync(path.join(mergeDir, NO_CONFLICT_MARKER_FILE), body);\n const record = new MergeHashRecord(forkPoint, featureHead, mainHead, new Date().toISOString());\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(record, null, 2) + '\\n');\n}\n\n// Locate the in-progress merge's run dir: the `<home>/merge-*/` subdir holding a marker. There is at\n// most one (a fresh sync can't start while a merge is in progress); if more than one somehow exists,\n// prefer an UNVALIDATED marker (the live conflict), else return the first found. Null when none.\nexport function findActiveMergeRunDir(home: string): string | null {\n if (!fs.existsSync(home)) return null;\n let fallback: string | null = null;\n for (const entry of fs.readdirSync(home)) {\n if (!entry.startsWith('merge-')) continue;\n const dir = path.join(home, entry);\n const marker = readMergeMarker(dir);\n if (marker === null) continue;\n if (!marker.validated) return dir;\n if (fallback === null) fallback = dir;\n }\n return fallback;\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"]}
|