@webpieces/pr-gate 0.4.996 → 0.4.998
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/src/scripts/workflow/generated-artifact-registry.js +2 -0
- package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
- package/src/scripts/workflow/merge-start.d.ts +1 -0
- package/src/scripts/workflow/merge-start.js +8 -1
- package/src/scripts/workflow/merge-start.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/pr-gate",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.998",
|
|
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",
|
|
@@ -16,18 +16,18 @@
|
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@inversifyjs/binding-decorators": "1.1.5",
|
|
19
|
-
"@webpieces/hook-runtime": "0.4.
|
|
20
|
-
"@webpieces/rules-config": "0.4.
|
|
19
|
+
"@webpieces/hook-runtime": "0.4.998",
|
|
20
|
+
"@webpieces/rules-config": "0.4.998",
|
|
21
21
|
"inversify": "7.10.4",
|
|
22
22
|
"reflect-metadata": "0.2.2",
|
|
23
|
-
"@webpieces/tooling-common": "0.4.
|
|
24
|
-
"@webpieces/repo-workflow-core": "0.4.
|
|
23
|
+
"@webpieces/tooling-common": "0.4.998",
|
|
24
|
+
"@webpieces/repo-workflow-core": "0.4.998"
|
|
25
25
|
},
|
|
26
26
|
"publishConfig": {
|
|
27
27
|
"access": "public"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@webpieces/tooling-testkit": "0.4.
|
|
30
|
+
"@webpieces/tooling-testkit": "0.4.998"
|
|
31
31
|
},
|
|
32
32
|
"types": "./src/index.d.ts",
|
|
33
33
|
"bin": {
|
|
@@ -32,6 +32,8 @@ exports.FALLBACK_GENERATED_PATHS = [
|
|
|
32
32
|
'architecture/dependencies.html',
|
|
33
33
|
'architecture/apis',
|
|
34
34
|
'architecture/runtime-dependencies.json',
|
|
35
|
+
'architecture/build-deps.md',
|
|
36
|
+
'architecture/runtime-deps.md',
|
|
35
37
|
];
|
|
36
38
|
/**
|
|
37
39
|
* The set of repo-relative paths/globs that a build is EXPECTED to rewrite, plus where the set came
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generated-artifact-registry.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/generated-artifact-registry.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA0D;AAC1D,8DAA6D;AAC7D,iEAA6D;AAC7D,yCAA2D;AAE3D;;;GAGG;AACU,QAAA,kBAAkB,GAAG,qCAAqC,CAAC;AAC3D,QAAA,wBAAwB,GAAG,kDAAkD,CAAC;AAE3F;;;;;;;;;GASG;AACU,QAAA,wBAAwB,GAAsB;IACvD,gBAAgB;IAChB,cAAc;IACd,gBAAgB;IAChB,gCAAgC;IAChC,gCAAgC;IAChC,mBAAmB;IACnB,wCAAwC;CAC3C,CAAC;AAEF;;;GAGG;AACH,MAAa,kBAAkB;IAC3B,KAAK,CAAW;IAChB,MAAM,CAAS;IAEf,YAAY,KAAe,EAAE,MAAc;QACvC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,gDAQC;AAED;;;;;;;;;;;;;GAaG;AAEI,IAAM,yBAAyB,GAA/B,MAAM,yBAAyB;IAKb;IACA;IALrB,uFAAuF;IAC/E,MAAM,GAA8B,IAAI,CAAC;IAEjD,YACqB,WAA4B,EAC5B,SAA2B;QAD3B,gBAAW,GAAX,WAAW,CAAiB;QAC5B,cAAS,G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pD,IAAI,QAAQ,KAAK,IAAI;wBAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBAC/C,CAAC;YACL,CAAC;QACL,CAAC;QACD,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;IACpC,CAAC;IAED,oGAAoG;IAC5F,MAAM,CAAC,GAAW,EAAE,WAAmB;QAC3C,MAAM,QAAQ,GAAG,GAAG;aACf,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC;aACxC,OAAO,CAAC,sBAAsB,EAAE,EAAE,CAAC;aACnC,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,CAAC;QACxC,IAAI,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QACxC,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACrE,OAAO,UAAU,KAAK,EAAE,IAAI,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;IACvE,CAAC;CACJ,CAAA;AAnFY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMH,8BAAe;QACjB,iCAAgB;GANvC,yBAAyB,CAmFrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RepoScratchDirs } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Where the \"known generated\" answer came from, so a failure message can say whether it is speaking\n * from the workspace's own declarations or from the built-in fallback.\n */\nexport const ARTIFACT_SOURCE_NX = 'nx project graph (target `outputs`)';\nexport const ARTIFACT_SOURCE_FALLBACK = 'built-in fallback (nx project graph unavailable)';\n\n/**\n * The fallback \"known generated\" set, used ONLY when the nx project graph cannot be read (nx not\n * installed, `nx graph` failed, unparseable output). It deliberately mirrors what the webpieces nx\n * plugin declares as `outputs` today — `di-graph-generate` writes design.{json,md,html} per project\n * and the architecture targets write architecture/*.\n *\n * It is a fallback and not the primary source precisely because a hand-maintained list drifts: the\n * moment a repo adds a target that writes a new committed artifact, only the nx `outputs` declaration\n * knows about it. Data (a module-level table), not a list buried inside a function.\n */\nexport const FALLBACK_GENERATED_PATHS: readonly string[] = [\n '**/design.json',\n '**/design.md',\n '**/design.html',\n 'architecture/dependencies.json',\n 'architecture/dependencies.html',\n 'architecture/apis',\n 'architecture/runtime-dependencies.json',\n];\n\n/**\n * The set of repo-relative paths/globs that a build is EXPECTED to rewrite, plus where the set came\n * from. Data-only (per CLAUDE.md) — the resolution logic lives in GeneratedArtifactRegistry.\n */\nexport class GeneratedArtifacts {\n paths: string[];\n source: string;\n\n constructor(paths: string[], source: string) {\n this.paths = paths;\n this.source = source;\n }\n}\n\n/**\n * Answers \"is this path something the build is SUPPOSED to rewrite?\" from the workspace's own nx\n * target `outputs` declarations rather than from a parallel list maintained by hand.\n *\n * Why nx `outputs`: every target that writes a checked-in artifact already has to declare it there or\n * nx caching corrupts the workspace, so the declaration is load-bearing and therefore maintained. A\n * second list in the PR gate would be maintained by nobody and would drift the first time a repo adds\n * a generator. One `nx graph --file=<tmp>` dumps the whole workspace (every project, every target,\n * every `outputs` entry) in one ~2s call, so this costs one subprocess per PR-gate run.\n *\n * Tokens: `{projectRoot}` and `{workspaceRoot}` are expanded; anything still holding a `{...}` token\n * (`{options.outputPath}`, `{options.outputFile}`) is DROPPED — it is only resolvable per-invocation,\n * and such targets write into `dist/`, which is gitignored and therefore invisible to this gate anyway.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GeneratedArtifactRegistry {\n // Resolved once per process: the graph does not change while one PR-gate command runs.\n private cached: GeneratedArtifacts | null = null;\n\n constructor(\n private readonly scratchDirs: RepoScratchDirs,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /** The declared build outputs for this repo, from nx when readable and the fallback table otherwise. */\n async resolve(repoRoot: string): Promise<GeneratedArtifacts> {\n if (this.cached !== null) return this.cached;\n const fromNx = await this.readNxOutputs(repoRoot);\n this.cached = fromNx !== null\n ? new GeneratedArtifacts(fromNx, ARTIFACT_SOURCE_NX)\n : new GeneratedArtifacts(FALLBACK_GENERATED_PATHS.slice(), ARTIFACT_SOURCE_FALLBACK);\n return this.cached;\n }\n\n /** Test seam: pre-seed the resolved set so specs never shell out to nx. */\n seed(artifacts: GeneratedArtifacts): void {\n this.cached = artifacts;\n }\n\n /**\n * Dump the nx project graph to a temp file and collect every target's `outputs`. Returns null (not\n * an empty list) when nx is unavailable or unreadable, so the caller can tell \"no nx\" apart from\n * \"nx says this workspace declares nothing\".\n */\n private async readNxOutputs(repoRoot: string): Promise<string[] | null> {\n const nxBin = path.join(repoRoot, 'node_modules', '.bin', 'nx');\n if (!fs.existsSync(nxBin)) return null;\n const outFile = path.join(this.scratchDirs.make(repoRoot, 'wp-nxgraph-'), 'graph.json');\n const run = await this.processes.run(nxBin, ['graph', '--file', outFile], repoRoot);\n if (!run.ok || !fs.existsSync(outFile)) return null;\n return this.parseGraph(outFile);\n }\n\n /** Read + narrow the dumped graph. Null on anything unreadable, so the caller falls back. */\n private parseGraph(outFile: string): string[] | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable/corrupt graph dump must\n // fall back to the built-in table, never fail a PR flow over a cache artifact we only consult\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque nx JSON, narrowed field by field below\n const parsed = JSON.parse(fs.readFileSync(outFile, 'utf8')) as NxGraphFile;\n const nodes = parsed.graph?.nodes;\n if (nodes === undefined) return null;\n return this.collectOutputs(nodes);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable graph => fall back to the built-in table\n return null;\n }\n }\n\n /** Walk every project → every target → every `outputs` entry, expanding the nx path tokens. */\n private collectOutputs(nodes: Record<string, NxGraphNode>): string[] {\n const found = new Set<string>();\n for (const projectName of Object.keys(nodes)) {\n const data = nodes[projectName].data;\n const targets = data.targets;\n if (targets === undefined) continue;\n for (const targetName of Object.keys(targets)) {\n for (const raw of targets[targetName].outputs ?? []) {\n const expanded = this.expand(raw, data.root ?? '.');\n if (expanded !== null) found.add(expanded);\n }\n }\n }\n return Array.from(found).sort();\n }\n\n /** Expand `{projectRoot}` / `{workspaceRoot}`; drop anything still carrying an unresolved token. */\n private expand(raw: string, projectRoot: string): string | null {\n const replaced = raw\n .replace(/\\{projectRoot\\}/g, projectRoot)\n .replace(/\\{workspaceRoot\\}\\//g, '')\n .replace(/\\{workspaceRoot\\}/g, '.');\n if (replaced.includes('{')) return null;\n const normalized = replaced.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n return normalized === '' || normalized === '.' ? null : normalized;\n }\n}\n\n// Structural views of the `nx graph --file=<json>` payload. Interfaces (not classes) on purpose: these\n// describe a foreign JSON shape we narrow, never something this codebase constructs.\ninterface NxGraphFile {\n graph?: NxGraphBody;\n}\n\ninterface NxGraphBody {\n nodes?: Record<string, NxGraphNode>;\n}\n\ninterface NxGraphNode {\n data: NxProjectData;\n}\n\ninterface NxProjectData {\n root?: string;\n targets?: Record<string, NxTarget>;\n}\n\ninterface NxTarget {\n outputs?: string[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generated-artifact-registry.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/generated-artifact-registry.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAA0D;AAC1D,8DAA6D;AAC7D,iEAA6D;AAC7D,yCAA2D;AAE3D;;;GAGG;AACU,QAAA,kBAAkB,GAAG,qCAAqC,CAAC;AAC3D,QAAA,wBAAwB,GAAG,kDAAkD,CAAC;AAE3F;;;;;;;;;GASG;AACU,QAAA,wBAAwB,GAAsB;IAC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CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;IACvE,CAAC;CACJ,CAAA;AAnFY,8DAAyB;oCAAzB,yBAAyB;IADrC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMH,8BAAe;QACjB,iCAAgB;GANvC,yBAAyB,CAmFrC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RepoScratchDirs } from '@webpieces/rules-config';\nimport { NativeProcessApi } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Where the \"known generated\" answer came from, so a failure message can say whether it is speaking\n * from the workspace's own declarations or from the built-in fallback.\n */\nexport const ARTIFACT_SOURCE_NX = 'nx project graph (target `outputs`)';\nexport const ARTIFACT_SOURCE_FALLBACK = 'built-in fallback (nx project graph unavailable)';\n\n/**\n * The fallback \"known generated\" set, used ONLY when the nx project graph cannot be read (nx not\n * installed, `nx graph` failed, unparseable output). It deliberately mirrors what the webpieces nx\n * plugin declares as `outputs` today — `di-graph-generate` writes design.{json,md,html} per project\n * and the architecture targets write architecture/*.\n *\n * It is a fallback and not the primary source precisely because a hand-maintained list drifts: the\n * moment a repo adds a target that writes a new committed artifact, only the nx `outputs` declaration\n * knows about it. Data (a module-level table), not a list buried inside a function.\n */\nexport const FALLBACK_GENERATED_PATHS: readonly string[] = [\n '**/design.json',\n '**/design.md',\n '**/design.html',\n 'architecture/dependencies.json',\n 'architecture/dependencies.html',\n 'architecture/apis',\n 'architecture/runtime-dependencies.json',\n 'architecture/build-deps.md',\n 'architecture/runtime-deps.md',\n];\n\n/**\n * The set of repo-relative paths/globs that a build is EXPECTED to rewrite, plus where the set came\n * from. Data-only (per CLAUDE.md) — the resolution logic lives in GeneratedArtifactRegistry.\n */\nexport class GeneratedArtifacts {\n paths: string[];\n source: string;\n\n constructor(paths: string[], source: string) {\n this.paths = paths;\n this.source = source;\n }\n}\n\n/**\n * Answers \"is this path something the build is SUPPOSED to rewrite?\" from the workspace's own nx\n * target `outputs` declarations rather than from a parallel list maintained by hand.\n *\n * Why nx `outputs`: every target that writes a checked-in artifact already has to declare it there or\n * nx caching corrupts the workspace, so the declaration is load-bearing and therefore maintained. A\n * second list in the PR gate would be maintained by nobody and would drift the first time a repo adds\n * a generator. One `nx graph --file=<tmp>` dumps the whole workspace (every project, every target,\n * every `outputs` entry) in one ~2s call, so this costs one subprocess per PR-gate run.\n *\n * Tokens: `{projectRoot}` and `{workspaceRoot}` are expanded; anything still holding a `{...}` token\n * (`{options.outputPath}`, `{options.outputFile}`) is DROPPED — it is only resolvable per-invocation,\n * and such targets write into `dist/`, which is gitignored and therefore invisible to this gate anyway.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class GeneratedArtifactRegistry {\n // Resolved once per process: the graph does not change while one PR-gate command runs.\n private cached: GeneratedArtifacts | null = null;\n\n constructor(\n private readonly scratchDirs: RepoScratchDirs,\n private readonly processes: NativeProcessApi,\n ) {}\n\n /** The declared build outputs for this repo, from nx when readable and the fallback table otherwise. */\n async resolve(repoRoot: string): Promise<GeneratedArtifacts> {\n if (this.cached !== null) return this.cached;\n const fromNx = await this.readNxOutputs(repoRoot);\n this.cached = fromNx !== null\n ? new GeneratedArtifacts(fromNx, ARTIFACT_SOURCE_NX)\n : new GeneratedArtifacts(FALLBACK_GENERATED_PATHS.slice(), ARTIFACT_SOURCE_FALLBACK);\n return this.cached;\n }\n\n /** Test seam: pre-seed the resolved set so specs never shell out to nx. */\n seed(artifacts: GeneratedArtifacts): void {\n this.cached = artifacts;\n }\n\n /**\n * Dump the nx project graph to a temp file and collect every target's `outputs`. Returns null (not\n * an empty list) when nx is unavailable or unreadable, so the caller can tell \"no nx\" apart from\n * \"nx says this workspace declares nothing\".\n */\n private async readNxOutputs(repoRoot: string): Promise<string[] | null> {\n const nxBin = path.join(repoRoot, 'node_modules', '.bin', 'nx');\n if (!fs.existsSync(nxBin)) return null;\n const outFile = path.join(this.scratchDirs.make(repoRoot, 'wp-nxgraph-'), 'graph.json');\n const run = await this.processes.run(nxBin, ['graph', '--file', outFile], repoRoot);\n if (!run.ok || !fs.existsSync(outFile)) return null;\n return this.parseGraph(outFile);\n }\n\n /** Read + narrow the dumped graph. Null on anything unreadable, so the caller falls back. */\n private parseGraph(outFile: string): string[] | null {\n // webpieces-disable no-unmanaged-exceptions -- chokepoint: an unreadable/corrupt graph dump must\n // fall back to the built-in table, never fail a PR flow over a cache artifact we only consult\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- opaque nx JSON, narrowed field by field below\n const parsed = JSON.parse(fs.readFileSync(outFile, 'utf8')) as NxGraphFile;\n const nodes = parsed.graph?.nodes;\n if (nodes === undefined) return null;\n return this.collectOutputs(nodes);\n } catch (err: unknown) {\n const error = toError(err);\n void error; // unreadable graph => fall back to the built-in table\n return null;\n }\n }\n\n /** Walk every project → every target → every `outputs` entry, expanding the nx path tokens. */\n private collectOutputs(nodes: Record<string, NxGraphNode>): string[] {\n const found = new Set<string>();\n for (const projectName of Object.keys(nodes)) {\n const data = nodes[projectName].data;\n const targets = data.targets;\n if (targets === undefined) continue;\n for (const targetName of Object.keys(targets)) {\n for (const raw of targets[targetName].outputs ?? []) {\n const expanded = this.expand(raw, data.root ?? '.');\n if (expanded !== null) found.add(expanded);\n }\n }\n }\n return Array.from(found).sort();\n }\n\n /** Expand `{projectRoot}` / `{workspaceRoot}`; drop anything still carrying an unresolved token. */\n private expand(raw: string, projectRoot: string): string | null {\n const replaced = raw\n .replace(/\\{projectRoot\\}/g, projectRoot)\n .replace(/\\{workspaceRoot\\}\\//g, '')\n .replace(/\\{workspaceRoot\\}/g, '.');\n if (replaced.includes('{')) return null;\n const normalized = replaced.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n return normalized === '' || normalized === '.' ? null : normalized;\n }\n}\n\n// Structural views of the `nx graph --file=<json>` payload. Interfaces (not classes) on purpose: these\n// describe a foreign JSON shape we narrow, never something this codebase constructs.\ninterface NxGraphFile {\n graph?: NxGraphBody;\n}\n\ninterface NxGraphBody {\n nodes?: Record<string, NxGraphNode>;\n}\n\ninterface NxGraphNode {\n data: NxProjectData;\n}\n\ninterface NxProjectData {\n root?: string;\n targets?: Record<string, NxTarget>;\n}\n\ninterface NxTarget {\n outputs?: string[];\n}\n"]}
|
|
@@ -4,6 +4,7 @@ import { GatherInfo } from '../git-gatherInfo';
|
|
|
4
4
|
import { BranchNaming } from './branch-naming';
|
|
5
5
|
import { GitExec } from './git-exec';
|
|
6
6
|
import { MergeState } from './merge-state';
|
|
7
|
+
export declare const ARCHITECTURE_CONFLICT_HINT = "architecture/* conflicts: don't hand-merge \u2014 run pnpm nx run architecture:generate, then git add architecture/";
|
|
7
8
|
export declare class MergeContext {
|
|
8
9
|
currentBranch: string;
|
|
9
10
|
squashBranch: string;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MergeStart = exports.MergeStartResult = exports.MergeContext = void 0;
|
|
3
|
+
exports.MergeStart = exports.MergeStartResult = exports.MergeContext = exports.ARCHITECTURE_CONFLICT_HINT = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const path = tslib_1.__importStar(require("path"));
|
|
@@ -12,7 +12,10 @@ const git_gatherInfo_1 = require("../git-gatherInfo");
|
|
|
12
12
|
const branch_naming_1 = require("./branch-naming");
|
|
13
13
|
const git_exec_1 = require("./git-exec");
|
|
14
14
|
const merge_state_1 = require("./merge-state");
|
|
15
|
+
const generated_artifact_registry_1 = require("./generated-artifact-registry");
|
|
15
16
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
17
|
+
// architecture/* is generated (#1429): regenerating is the resolution, a hand merge is a guess.
|
|
18
|
+
exports.ARCHITECTURE_CONFLICT_HINT = "architecture/* conflicts: don't hand-merge — run pnpm nx run architecture:generate, then git add architecture/";
|
|
16
19
|
// The four branch names merge-END needs to finalize a merge (swap squash→feature, push, clean up).
|
|
17
20
|
class MergeContext {
|
|
18
21
|
currentBranch;
|
|
@@ -204,6 +207,10 @@ let MergeStart = class MergeStart {
|
|
|
204
207
|
process.stdout.write('Conflicted files:\n');
|
|
205
208
|
for (const file of conflictedFiles)
|
|
206
209
|
process.stdout.write(` - ${file}\n`);
|
|
210
|
+
// Only the GENERATED architecture files: a hand-written doc under architecture/ is merged by hand.
|
|
211
|
+
const generated = generated_artifact_registry_1.FALLBACK_GENERATED_PATHS.filter((p) => p.startsWith('architecture/'));
|
|
212
|
+
if (conflictedFiles.some((file) => (0, rules_config_1.matchesAnyGlob)(file, generated)))
|
|
213
|
+
process.stdout.write(`\n${exports.ARCHITECTURE_CONFLICT_HINT}\n`);
|
|
207
214
|
process.stdout.write('\n' + SEP);
|
|
208
215
|
}
|
|
209
216
|
// Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAA0F;AAC1F,0DAAsI;AACtI,sEAAqG;AACrG,yCAA2D;AAC3D,sDAA+C;AAC/C,mDAA+C;AAC/C,yCAAqC;AACrC,+CAAwD;AAExD,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,CAA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sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,2BAAU;QACR,4BAAY;QACjB,kBAAO;QACJ,wBAAU;QACjB,8BAAa;QACP,iCAAgB;GAPvC,UAAU,CA4NtB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces, GitProcessApi, NativeProcessApi } from '@webpieces/tooling-common';\nimport { CliExitError, SyncFlowGuidance, MERGE_PROCESS_DOC, MergeProcessText, MergeRun, loadTemplate } from '@webpieces/rules-config';\nimport { MutationVerb, BranchMutationEvent, logBranchMutation } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GatherInfo } from '../git-gatherInfo';\nimport { BranchNaming } from './branch-naming';\nimport { GitExec } from './git-exec';\nimport { MergeState, MergeMarker } from './merge-state';\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// The one number `n` for a sync and the things it names: the pre-merge backup branch, its paired\n// conflict-context run dir, and (via `n`) the `preMerge<n>.hash` record of the tip it snapshotted.\nclass SyncSlot {\n backupBranch: string;\n runDir: string;\n n: number;\n\n constructor(backupBranch: string, runDir: string, n: number) {\n this.backupBranch = backupBranch;\n this.runDir = runDir;\n this.n = n;\n }\n}\n\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 + unvalidated marker + process doc,\n// then hands control back to the AI. On a clean merge it commits the squash and returns the branch\n// context so the caller (RunUpdate) can run merge-END to finalize. NEVER finalizes or posts a PR.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeStart {\n constructor(\n private readonly gatherInfo: GatherInfo,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult> {\n const currentBranch = await this.gitExec.currentBranch(process.cwd());\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 = await this.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 const info = await this.gatherInfo.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 = await this.detectPr(this.branchNaming.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 await this.createBackup(currentBranch, backupBranch);\n // Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash` — every intermediate\n // state, not just the last one. It is what lets the `<feature>PreMerge<n>` snapshot BRANCH be\n // disposable (branches count toward the branch cap; a written-down hash does not), and it is the\n // ref the archive tag is cut from when the PR lands.\n this.mergeState.writePreMergeHash(home, slot.n, await this.fullSha(currentBranch));\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 (await this.branchExists(squashBranch)) {\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. origin/main was already fetched\n // in gatherInfo(), and A/B/C are computed purely from origin/main, so the merge base is identical\n // to the old checkout-main + pull path.\n const originMainSha = await this.shortSha('origin/main');\n await this.gitExec.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 = await this.git.passThrough(['merge', '--squash', currentBranch]);\n if (!merge.ok) {\n await this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);\n await this.logConflict(repoRoot, verb, mergeDir);\n return new MergeStartResult('conflict', null, mergeDir);\n }\n logBranchMutation(repoRoot, new BranchMutationEvent(verb, 'SQUASH'));\n\n const nothingStaged = (await this.git.run(['diff-index', '--quiet', '--cached', 'HEAD', '--'])).ok;\n if (nothingStaged) {\n process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\\n');\n } else {\n // Internal, transient subject for the single squash commit on the feature branch. It NO LONGER\n // reaches main's history: finish-upsert-pr squash-merges the PR with an explicit\n // `gh pr merge --subject <PR title> --body-file <commit summary>`, so main carries the PR title.\n await this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');\n // Clean merge ⇒ hashes only, no conflicts.md. Its ABSENCE is what marks this merge clean.\n this.mergeState.recordCleanMerge(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n }\n return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);\n }\n\n // Detect the PR by its STABLE feature branch (a leftover `…wpN` still resolves to the one name the\n // PR lives on).\n private async detectPr(baseBranch: string): Promise<string> {\n const result = await this.processes.run(\n 'gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n );\n return result.ok ? result.stdout.trim() : '';\n }\n\n // Pick this sync's slot number MONOTONICALLY from the durable audit dirs, then step past any\n // existing `<branch>PreMerge<n>` branch so the same `n` is free for the paired backup branch.\n private async chooseSyncSlot(home: string, currentBranch: string): Promise<SyncSlot> {\n let n = this.mergeState.nextMergeSlotNumber(home);\n while (await this.branchExists(this.branchNaming.preMergeBackupName(currentBranch, n))) n += 1;\n return new SyncSlot(this.branchNaming.preMergeBackupName(currentBranch, n), this.mergeState.mergeRunDirFor(home, n), n);\n }\n\n // Snapshot the pre-merge state onto the caller-chosen `backupBranch`, never overwriting.\n private async branchExists(name: string): Promise<boolean> {\n return (await this.git.run(['show-ref', '--verify', '--quiet', `refs/heads/${name}`])).ok;\n }\n\n private async createBackup(currentBranch: string, backupBranch: string): Promise<void> {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\n');\n await this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n await this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n }\n\n private async saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n ): Promise<void> {\n for (const file of conflictedFiles) {\n const fileDir = this.mergeState.perFileContextDir(mergeDir, file);\n fs.mkdirSync(fileDir, { recursive: true });\n\n const fork = await this.git.run(['show', `${forkPoint}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.ok ? fork.stdout : '(file did not exist)\\n');\n const feature = await this.git.run(['show', `${featureHead}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.ok ? feature.stdout : '(file did not exist)\\n');\n const main = await this.git.run(['show', `${mainHead}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.ok ? main.stdout : '(file did not exist)\\n');\n\n const ba = await this.git.run(['diff', forkPoint, featureHead, '--', file]);\n fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout);\n const ca = await this.git.run(['diff', forkPoint, mainHead, '--', file]);\n fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout);\n }\n }\n\n // The LIVE rendering of the same template `.webpieces/instruct-ai/webpieces.mergeprocess.md` is\n // delivered from — see rules-config/src/merge-process-doc.ts. The text lives there, not here, so\n // the copy every repo receives and the copy a conflicted merge stamps are the same document.\n private mergeProcessDoc(mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const fileList = conflictedFiles.map((f: string): string => `- \\`${f}\\``).join('\\n');\n const run = new MergeRun(\n new SyncFlowGuidance().pairedStart(finishCommand), finishCommand, squashBranch, mergeDir, fileList,\n );\n return new MergeProcessText(loadTemplate(MERGE_PROCESS_DOC)).render(run);\n }\n\n // Returns the absolute path of the written doc.\n private writeMergeProcessDoc(repoRoot: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const docDir = dotWebpieces.localFile(repoRoot, 'instruct-ai');\n fs.mkdirSync(docDir, { recursive: true });\n const docPath = path.join(docDir, MERGE_PROCESS_DOC);\n fs.writeFileSync(docPath, this.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.\n private 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>/), \\`git add\\` it, 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 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.\n private async handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints, finishCommand: string,\n ): Promise<void> {\n const raw = await this.gitExec.gitQuery(['diff', '--name-only', '--diff-filter=U'], process.cwd(), 'Failed to list conflicted files (git diff --diff-filter=U).');\n const conflictedFiles = raw.split('\\n').filter((f: string): boolean => f.trim() !== '');\n fs.mkdirSync(mergeDir, { recursive: true });\n // `conflicts.md` replaces the old `updatemain-conflicted-files.txt` (which nothing read) AND is\n // the 3-point signal itself: this file exists in a run dir if and only if that merge conflicted,\n // which is what lets the index classify each merge without a per-branch directory-name scheme.\n this.mergeState.writeConflicts(mergeDir, conflictedFiles);\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\\n');\n await this.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 this.mergeState.writeMergeMarker(mergeDir, marker);\n const docPath = this.writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles, finishCommand);\n this.printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);\n }\n\n // Short sha of a ref (best-effort — '' if it can't resolve).\n private async shortSha(ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', '--short', ref]);\n return result.ok ? result.stdout.trim() : '';\n }\n\n // FULL sha of a ref (best-effort — '' if it can't resolve). Recorded for the pre-merge tips because\n // those hashes are meant to be used later to restore state, and an abbreviated sha can go ambiguous\n // as the repo grows.\n private async fullSha(ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', ref]);\n return result.ok ? result.stdout.trim() : '';\n }\n\n // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.\n private async logConflict(repoRoot: string, verb: MutationVerb, mergeDir: string): Promise<void> {\n const raw = await this.git.run(['diff', '--name-only', '--diff-filter=U'], repoRoot);\n const files = (raw.ok ? 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 dotWebpieces.localFile(repoRoot, 'instruct-ai', MERGE_PROCESS_DOC),\n ];\n logBranchMutation(repoRoot, event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB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aAAa,EAAE,iBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC;QACrF,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAS,EAAU,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAS,EAAW,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;QACnI,MAAM,KAAK,GAAG,IAAI,wCAAmB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACxD,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;QACtB,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC;QAC5B,KAAK,CAAC,SAAS,GAAG;YACd,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,mBAAmB,CAAC;YACxC,6BAAY,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,EAAE,gCAAiB,CAAC;SACrE,CAAC;QACF,IAAA,sCAAiB,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAhOY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,2BAAU;QACR,4BAAY;QACjB,kBAAO;QACJ,wBAAU;QACjB,8BAAa;QACP,iCAAgB;GAPvC,UAAU,CAgOtB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces, GitProcessApi, NativeProcessApi } from '@webpieces/tooling-common';\nimport { CliExitError, matchesAnyGlob, SyncFlowGuidance, MERGE_PROCESS_DOC, MergeProcessText, MergeRun, loadTemplate } from '@webpieces/rules-config';\nimport { MutationVerb, BranchMutationEvent, logBranchMutation } from '@webpieces/repo-workflow-core';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GatherInfo } from '../git-gatherInfo';\nimport { BranchNaming } from './branch-naming';\nimport { GitExec } from './git-exec';\nimport { MergeState, MergeMarker } from './merge-state';\nimport { FALLBACK_GENERATED_PATHS } from './generated-artifact-registry';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n// architecture/* is generated (#1429): regenerating is the resolution, a hand merge is a guess.\nexport const ARCHITECTURE_CONFLICT_HINT =\n \"architecture/* conflicts: don't hand-merge — run pnpm nx run architecture:generate, then git add architecture/\";\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// The one number `n` for a sync and the things it names: the pre-merge backup branch, its paired\n// conflict-context run dir, and (via `n`) the `preMerge<n>.hash` record of the tip it snapshotted.\nclass SyncSlot {\n backupBranch: string;\n runDir: string;\n n: number;\n\n constructor(backupBranch: string, runDir: string, n: number) {\n this.backupBranch = backupBranch;\n this.runDir = runDir;\n this.n = n;\n }\n}\n\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 + unvalidated marker + process doc,\n// then hands control back to the AI. On a clean merge it commits the squash and returns the branch\n// context so the caller (RunUpdate) can run merge-END to finalize. NEVER finalizes or posts a PR.\n@injectable(bindingScopeValues.Singleton)\nexport class MergeStart {\n constructor(\n private readonly gatherInfo: GatherInfo,\n private readonly branchNaming: BranchNaming,\n private readonly gitExec: GitExec,\n private readonly mergeState: MergeState,\n private readonly git: GitProcessApi,\n private readonly processes: NativeProcessApi,\n ) {}\n\n async mergeStart(repoRoot: string, verb: MutationVerb, home: string, finishCommand: string): Promise<MergeStartResult> {\n const currentBranch = await this.gitExec.currentBranch(process.cwd());\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 = await this.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 const info = await this.gatherInfo.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 = await this.detectPr(this.branchNaming.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 await this.createBackup(currentBranch, backupBranch);\n // Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash` — every intermediate\n // state, not just the last one. It is what lets the `<feature>PreMerge<n>` snapshot BRANCH be\n // disposable (branches count toward the branch cap; a written-down hash does not), and it is the\n // ref the archive tag is cut from when the PR lands.\n this.mergeState.writePreMergeHash(home, slot.n, await this.fullSha(currentBranch));\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 (await this.branchExists(squashBranch)) {\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. origin/main was already fetched\n // in gatherInfo(), and A/B/C are computed purely from origin/main, so the merge base is identical\n // to the old checkout-main + pull path.\n const originMainSha = await this.shortSha('origin/main');\n await this.gitExec.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 = await this.git.passThrough(['merge', '--squash', currentBranch]);\n if (!merge.ok) {\n await this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);\n await this.logConflict(repoRoot, verb, mergeDir);\n return new MergeStartResult('conflict', null, mergeDir);\n }\n logBranchMutation(repoRoot, new BranchMutationEvent(verb, 'SQUASH'));\n\n const nothingStaged = (await this.git.run(['diff-index', '--quiet', '--cached', 'HEAD', '--'])).ok;\n if (nothingStaged) {\n process.stdout.write('ℹ️ Already up-to-date with main (nothing to merge).\\n');\n } else {\n // Internal, transient subject for the single squash commit on the feature branch. It NO LONGER\n // reaches main's history: finish-upsert-pr squash-merges the PR with an explicit\n // `gh pr merge --subject <PR title> --body-file <commit summary>`, so main carries the PR title.\n await this.gitExec.runGitChecked(['commit', '-m', `Squash merge of ${currentBranch}`], 'Failed to commit squash merge');\n // Clean merge ⇒ hashes only, no conflicts.md. Its ABSENCE is what marks this merge clean.\n this.mergeState.recordCleanMerge(mergeDir, hashes.hashForkPoint, hashes.hashFeatureHead, hashes.hashMainHead);\n }\n return new MergeStartResult('clean', new MergeContext(currentBranch, squashBranch, backupBranch, prNumber), mergeDir);\n }\n\n // Detect the PR by its STABLE feature branch (a leftover `…wpN` still resolves to the one name the\n // PR lives on).\n private async detectPr(baseBranch: string): Promise<string> {\n const result = await this.processes.run(\n 'gh', ['pr', 'list', '--head', baseBranch, '--json', 'number', '--jq', '.[0].number'],\n );\n return result.ok ? result.stdout.trim() : '';\n }\n\n // Pick this sync's slot number MONOTONICALLY from the durable audit dirs, then step past any\n // existing `<branch>PreMerge<n>` branch so the same `n` is free for the paired backup branch.\n private async chooseSyncSlot(home: string, currentBranch: string): Promise<SyncSlot> {\n let n = this.mergeState.nextMergeSlotNumber(home);\n while (await this.branchExists(this.branchNaming.preMergeBackupName(currentBranch, n))) n += 1;\n return new SyncSlot(this.branchNaming.preMergeBackupName(currentBranch, n), this.mergeState.mergeRunDirFor(home, n), n);\n }\n\n // Snapshot the pre-merge state onto the caller-chosen `backupBranch`, never overwriting.\n private async branchExists(name: string): Promise<boolean> {\n return (await this.git.run(['show-ref', '--verify', '--quiet', `refs/heads/${name}`])).ok;\n }\n\n private async createBackup(currentBranch: string, backupBranch: string): Promise<void> {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\n');\n await this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n await this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n }\n\n private async saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n ): Promise<void> {\n for (const file of conflictedFiles) {\n const fileDir = this.mergeState.perFileContextDir(mergeDir, file);\n fs.mkdirSync(fileDir, { recursive: true });\n\n const fork = await this.git.run(['show', `${forkPoint}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'A-forkpoint.txt'), fork.ok ? fork.stdout : '(file did not exist)\\n');\n const feature = await this.git.run(['show', `${featureHead}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'B-feature.txt'), feature.ok ? feature.stdout : '(file did not exist)\\n');\n const main = await this.git.run(['show', `${mainHead}:${file}`]);\n fs.writeFileSync(path.join(fileDir, 'C-main.txt'), main.ok ? main.stdout : '(file did not exist)\\n');\n\n const ba = await this.git.run(['diff', forkPoint, featureHead, '--', file]);\n fs.writeFileSync(path.join(fileDir, 'B-A.diff'), ba.stdout);\n const ca = await this.git.run(['diff', forkPoint, mainHead, '--', file]);\n fs.writeFileSync(path.join(fileDir, 'C-A.diff'), ca.stdout);\n }\n }\n\n // The LIVE rendering of the same template `.webpieces/instruct-ai/webpieces.mergeprocess.md` is\n // delivered from — see rules-config/src/merge-process-doc.ts. The text lives there, not here, so\n // the copy every repo receives and the copy a conflicted merge stamps are the same document.\n private mergeProcessDoc(mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const fileList = conflictedFiles.map((f: string): string => `- \\`${f}\\``).join('\\n');\n const run = new MergeRun(\n new SyncFlowGuidance().pairedStart(finishCommand), finishCommand, squashBranch, mergeDir, fileList,\n );\n return new MergeProcessText(loadTemplate(MERGE_PROCESS_DOC)).render(run);\n }\n\n // Returns the absolute path of the written doc.\n private writeMergeProcessDoc(repoRoot: string, mergeDir: string, squashBranch: string, conflictedFiles: string[], finishCommand: string): string {\n const docDir = dotWebpieces.localFile(repoRoot, 'instruct-ai');\n fs.mkdirSync(docDir, { recursive: true });\n const docPath = path.join(docDir, MERGE_PROCESS_DOC);\n fs.writeFileSync(docPath, this.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.\n private 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>/), \\`git add\\` it, 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 commit/push yourself)\\n\\n`);\n process.stdout.write('Conflicted files:\\n');\n for (const file of conflictedFiles) process.stdout.write(` - ${file}\\n`);\n // Only the GENERATED architecture files: a hand-written doc under architecture/ is merged by hand.\n const generated = FALLBACK_GENERATED_PATHS.filter((p: string): boolean => p.startsWith('architecture/'));\n if (conflictedFiles.some((file: string): boolean => matchesAnyGlob(file, generated)))\n process.stdout.write(`\\n${ARCHITECTURE_CONFLICT_HINT}\\n`);\n process.stdout.write('\\n' + SEP);\n }\n\n // Write the conflict context files + the unvalidated marker + the process doc. Does NOT exit.\n private async handleConflictsHandback(\n repoRoot: string, mergeDir: string, currentBranch: string, squashBranch: string,\n backupBranch: string, prNumber: string, hashes: HashPoints, finishCommand: string,\n ): Promise<void> {\n const raw = await this.gitExec.gitQuery(['diff', '--name-only', '--diff-filter=U'], process.cwd(), 'Failed to list conflicted files (git diff --diff-filter=U).');\n const conflictedFiles = raw.split('\\n').filter((f: string): boolean => f.trim() !== '');\n fs.mkdirSync(mergeDir, { recursive: true });\n // `conflicts.md` replaces the old `updatemain-conflicted-files.txt` (which nothing read) AND is\n // the 3-point signal itself: this file exists in a run dir if and only if that merge conflicted,\n // which is what lets the index classify each merge without a per-branch directory-name scheme.\n this.mergeState.writeConflicts(mergeDir, conflictedFiles);\n fs.writeFileSync(path.join(mergeDir, 'updatemain-hashes.json'), JSON.stringify(hashes, null, 2) + '\\n');\n await this.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 this.mergeState.writeMergeMarker(mergeDir, marker);\n const docPath = this.writeMergeProcessDoc(repoRoot, mergeDir, squashBranch, conflictedFiles, finishCommand);\n this.printConflictHandback(docPath, mergeDir, squashBranch, conflictedFiles, finishCommand);\n }\n\n // Short sha of a ref (best-effort — '' if it can't resolve).\n private async shortSha(ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', '--short', ref]);\n return result.ok ? result.stdout.trim() : '';\n }\n\n // FULL sha of a ref (best-effort — '' if it can't resolve). Recorded for the pre-merge tips because\n // those hashes are meant to be used later to restore state, and an abbreviated sha can go ambiguous\n // as the repo grows.\n private async fullSha(ref: string): Promise<string> {\n const result = await this.git.run(['rev-parse', ref]);\n return result.ok ? result.stdout.trim() : '';\n }\n\n // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.\n private async logConflict(repoRoot: string, verb: MutationVerb, mergeDir: string): Promise<void> {\n const raw = await this.git.run(['diff', '--name-only', '--diff-filter=U'], repoRoot);\n const files = (raw.ok ? 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 dotWebpieces.localFile(repoRoot, 'instruct-ai', MERGE_PROCESS_DOC),\n ];\n logBranchMutation(repoRoot, event);\n }\n}\n"]}
|