@webpieces/pr-gate 0.4.836 → 0.4.838
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -4
- package/src/scripts/commands/cleanup-command.d.ts +2 -1
- package/src/scripts/commands/cleanup-command.js +13 -12
- package/src/scripts/commands/cleanup-command.js.map +1 -1
- package/src/scripts/commands/finish-upsert-pr-command.js +5 -3
- package/src/scripts/commands/finish-upsert-pr-command.js.map +1 -1
- package/src/scripts/commands/human-post-pr-command.d.ts +2 -1
- package/src/scripts/commands/human-post-pr-command.js +3 -2
- package/src/scripts/commands/human-post-pr-command.js.map +1 -1
- package/src/scripts/commands/land-pr-command.d.ts +2 -1
- package/src/scripts/commands/land-pr-command.js +12 -9
- package/src/scripts/commands/land-pr-command.js.map +1 -1
- package/src/scripts/commands/reap-worktree-command.d.ts +2 -1
- package/src/scripts/commands/reap-worktree-command.js +4 -2
- package/src/scripts/commands/reap-worktree-command.js.map +1 -1
- package/src/scripts/commands/sync-main-command.js +2 -1
- package/src/scripts/commands/sync-main-command.js.map +1 -1
- package/src/scripts/commands/upsert-hotfix-pr-command.d.ts +2 -1
- package/src/scripts/commands/upsert-hotfix-pr-command.js +2 -1
- package/src/scripts/commands/upsert-hotfix-pr-command.js.map +1 -1
- package/src/scripts/commands/worktree-cleanup.d.ts +1 -1
- package/src/scripts/commands/worktree-cleanup.js +11 -11
- package/src/scripts/commands/worktree-cleanup.js.map +1 -1
- package/src/scripts/commands/write-review-command.js +13 -10
- package/src/scripts/commands/write-review-command.js.map +1 -1
- package/src/scripts/commands/write-review-fixes-command.js +3 -2
- package/src/scripts/commands/write-review-fixes-command.js.map +1 -1
- package/src/scripts/pr-gate-cli-app.js +2 -1
- package/src/scripts/pr-gate-cli-app.js.map +1 -1
- package/src/scripts/workflow/build-affected.d.ts +2 -1
- package/src/scripts/workflow/build-affected.js +2 -1
- package/src/scripts/workflow/build-affected.js.map +1 -1
- package/src/scripts/workflow/cleanTmp.d.ts +2 -1
- package/src/scripts/workflow/cleanTmp.js +3 -2
- package/src/scripts/workflow/cleanTmp.js.map +1 -1
- package/src/scripts/workflow/diff-materializer.js +2 -1
- package/src/scripts/workflow/diff-materializer.js.map +1 -1
- package/src/scripts/workflow/gate-log-file.js +5 -4
- package/src/scripts/workflow/gate-log-file.js.map +1 -1
- package/src/scripts/workflow/generated-artifact-registry.js +2 -1
- package/src/scripts/workflow/generated-artifact-registry.js.map +1 -1
- package/src/scripts/workflow/hotfix-redirect.d.ts +1 -1
- package/src/scripts/workflow/hotfix-redirect.js +2 -1
- package/src/scripts/workflow/hotfix-redirect.js.map +1 -1
- package/src/scripts/workflow/landed-tree-resolver.d.ts +1 -1
- package/src/scripts/workflow/landed-tree-resolver.js +2 -2
- package/src/scripts/workflow/landed-tree-resolver.js.map +1 -1
- package/src/scripts/workflow/landed-worktree-reaper.d.ts +1 -1
- package/src/scripts/workflow/landed-worktree-reaper.js +2 -1
- package/src/scripts/workflow/landed-worktree-reaper.js.map +1 -1
- package/src/scripts/workflow/merge-end.d.ts +1 -1
- package/src/scripts/workflow/merge-end.js +6 -5
- package/src/scripts/workflow/merge-end.js.map +1 -1
- package/src/scripts/workflow/merge-info-index.d.ts +1 -1
- package/src/scripts/workflow/merge-info-index.js +5 -4
- package/src/scripts/workflow/merge-info-index.js.map +1 -1
- package/src/scripts/workflow/merge-start.d.ts +1 -1
- package/src/scripts/workflow/merge-start.js +11 -9
- package/src/scripts/workflow/merge-start.js.map +1 -1
- package/src/scripts/workflow/merge-state.d.ts +1 -1
- package/src/scripts/workflow/merge-state.js +3 -2
- package/src/scripts/workflow/merge-state.js.map +1 -1
- package/src/scripts/workflow/provenance-enforcer.js +5 -4
- package/src/scripts/workflow/provenance-enforcer.js.map +1 -1
- package/src/scripts/workflow/push-dev-state.d.ts +1 -1
- package/src/scripts/workflow/push-dev-state.js +4 -2
- package/src/scripts/workflow/push-dev-state.js.map +1 -1
- package/src/scripts/workflow/review-round-state.d.ts +2 -1
- package/src/scripts/workflow/review-round-state.js +22 -20
- package/src/scripts/workflow/review-round-state.js.map +1 -1
- package/src/scripts/workflow/review-stage-receipt.js +2 -1
- package/src/scripts/workflow/review-stage-receipt.js.map +1 -1
- package/src/scripts/workflow/reviewer-briefing-builder.js +2 -1
- package/src/scripts/workflow/reviewer-briefing-builder.js.map +1 -1
- package/src/scripts/workflow/reviewer-identity.d.ts +1 -1
- package/src/scripts/workflow/reviewer-identity.js +8 -7
- package/src/scripts/workflow/reviewer-identity.js.map +1 -1
- package/src/scripts/workflow/reviewer-verdict-gate.js +2 -1
- package/src/scripts/workflow/reviewer-verdict-gate.js.map +1 -1
- package/src/scripts/workflow/run-update.d.ts +1 -1
- package/src/scripts/workflow/run-update.js +4 -4
- package/src/scripts/workflow/run-update.js.map +1 -1
- package/src/scripts/workflow/verdict-provenance.d.ts +2 -1
- package/src/scripts/workflow/verdict-provenance.js +10 -7
- package/src/scripts/workflow/verdict-provenance.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-start.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-start.ts"],"names":[],"mappings":";;;;AAAA,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,0DAIiC;AACjC,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,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QA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,CAAC;YACxC,2BAAY,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,EAAE,gCAAiB,CAAC;SACrE,CAAC;QACF,IAAA,gCAAiB,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAzNY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,2BAAU;QACR,4BAAY;QACjB,kBAAO;QACJ,wBAAU;GALlC,UAAU,CAyNtB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n dotWebpieces, CliExitError,\n MutationVerb, BranchMutationEvent, logBranchMutation, SyncFlowGuidance,\n MERGE_PROCESS_DOC, MergeProcessText, MergeRun, loadTemplate,\n} from '@webpieces/rules-config';\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 ) {}\n\n async 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 = 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 = 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 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, 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 (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. 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 = this.shortSha('origin/main');\n 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 = spawnSync('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });\n if (merge.status !== 0) {\n this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);\n this.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 // 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 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 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 // 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 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 = this.mergeState.nextMergeSlotNumber(home);\n while (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 createBackup(currentBranch: string, backupBranch: string): void {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\n');\n this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n }\n\n private saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n ): 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 = 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 // 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 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 });\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 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 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 // 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 fullSha(ref: string): string {\n const result = spawnSync('git', ['rev-parse', ref], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.\n private 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 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,iDAAoD;AACpD,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAyD;AACzD,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,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,sFAAsF;IAEtG,YAAY,MAA4B,EAAE,OAA4B,EAAE,MAAc;QAClF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAVD,4CAUC;AAED,iGAAiG;AACjG,mGAAmG;AACnG,MAAM,QAAQ;IACV,YAAY,CAAS;IACrB,M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AE,IAAkB,EAAE,QAAgB;QACtE,MAAM,GAAG,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,iBAAiB,CAAC,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAC9G,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,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;QACrJ,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;AAzNY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,2BAAU;QACR,4BAAY;QACjB,kBAAO;QACJ,wBAAU;GALlC,UAAU,CAyNtB","sourcesContent":["import { execSync, spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { dotWebpieces } 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 ) {}\n\n async 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 = 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 = 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 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, 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 (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. 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 = this.shortSha('origin/main');\n 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 = spawnSync('git', ['merge', '--squash', currentBranch], { stdio: 'inherit' });\n if (merge.status !== 0) {\n this.handleConflictsHandback(repoRoot, mergeDir, currentBranch, squashBranch, backupBranch, prNumber, hashes, finishCommand);\n this.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 // 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 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 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 // 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 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 = this.mergeState.nextMergeSlotNumber(home);\n while (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 createBackup(currentBranch: string, backupBranch: string): void {\n process.stdout.write('\\n' + SEP + '💾 Creating Pre-Merge Backup\\n' + SEP + '\\n');\n this.gitExec.runGitChecked(['checkout', '-b', backupBranch], 'Failed to create backup branch');\n this.gitExec.runGitChecked(['checkout', currentBranch], 'Failed to return to feature branch');\n process.stdout.write(`✅ Backup created: ${backupBranch}\\n\\n`);\n }\n\n private saveConflictContext(\n conflictedFiles: string[], mergeDir: string, forkPoint: string, featureHead: string, mainHead: string,\n ): 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 = 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 // 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 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 });\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 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 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 // 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 fullSha(ref: string): string {\n const result = spawnSync('git', ['rev-parse', ref], { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Log the CONFLICT phase with the conflicted-file list + artifact paths a resolver needs.\n private 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 dotWebpieces.localFile(repoRoot, 'instruct-ai', MERGE_PROCESS_DOC),\n ];\n logBranchMutation(repoRoot, event);\n }\n}\n"]}
|
|
@@ -4,6 +4,7 @@ exports.MergeState = exports.MERGE_INDEX_FILE = exports.ARCHIVE_RECORD_FILE = ex
|
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const path = tslib_1.__importStar(require("path"));
|
|
7
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
7
8
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
8
9
|
const inversify_1 = require("inversify");
|
|
9
10
|
// Proof-obligation marker written when a 3-point squash-merge hits conflicts. Its mere
|
|
@@ -86,7 +87,7 @@ exports.MERGE_INDEX_FILE = 'index.json';
|
|
|
86
87
|
/** Filesystem layout + read/write of the per-feature merge run dirs and their conflict markers. */
|
|
87
88
|
let MergeState = class MergeState {
|
|
88
89
|
dotDir;
|
|
89
|
-
constructor(dotDir =
|
|
90
|
+
constructor(dotDir = tooling_common_1.dotWebpieces) {
|
|
90
91
|
this.dotDir = dotDir;
|
|
91
92
|
}
|
|
92
93
|
// The per-feature "home" dir `.webpieces/merge-info/<slug>/`. It no longer holds the marker/context
|
|
@@ -329,6 +330,6 @@ let MergeState = class MergeState {
|
|
|
329
330
|
exports.MergeState = MergeState;
|
|
330
331
|
exports.MergeState = MergeState = tslib_1.__decorate([
|
|
331
332
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
332
|
-
tslib_1.__metadata("design:paramtypes", [
|
|
333
|
+
tslib_1.__metadata("design:paramtypes", [tooling_common_1.DotWebpieces])
|
|
333
334
|
], MergeState);
|
|
334
335
|
//# sourceMappingURL=merge-state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"merge-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAMiC;AACjC,yCAA2D;AAE3D,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,EACz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AAK,EAAE,CAAC;YACvB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,qCAAsB,CAAC,CAAC;YAC3F,MAAM,OAAO,GAAG,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC;YAC3F,IAAI,CAAC,OAAO;gBAAE,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC;QACD,OAAO,IAAI,gBAAgB,CAAC,uBAAuB,CAAC,MAAM,KAAK,CAAC,EAAE,uBAAuB,CAAC,CAAC;IAC/F,CAAC;CACJ,CAAA;AA5PY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,2BAAY;GADxC,UAAU,CA4PtB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n DotWebpieces,\n dotWebpieces,\n MERGE_INFO_DIR,\n MERGE_IN_PROGRESS_FILE,\n MERGE_EXPLANATION_FILE,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\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\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\nconst CONFLICT_MARKER_RE = /^(<{7}|={7}|>{7})/m;\n\n/**\n * The two halves of `.webpieces/merge-info/`.\n *\n * `staged/` mirrors branches that STILL EXIST — it answers \"what am I working on right now\", and it\n * self-cleans when a PR lands (the whole dir is MOVED to `merged/`) instead of growing forever.\n * `merged/` is the post-mortem record, and is where the archive-tag reference lives.\n *\n * Both are reserved names: a feature branch slugifies `/`→`-`, so no feature can ever be called\n * `staged` or `merged` and collide with them.\n */\nexport const STAGED_DIR = 'staged';\nexport const MERGED_DIR = 'merged';\n\n/**\n * The 3-point conflict record. PRESENT ONLY WHEN THE MERGE ACTUALLY CONFLICTED.\n *\n * This replaces the old `no-3point-merge.md`, which was written into EVERY clean merge dir and whose\n * entire content was \"nothing interesting happened here\" plus the same A/B/C shas that\n * `updatemain-hashes.json` already carries, one line below, in machine-readable form. Nothing read it.\n * So ABSENCE is now the signal: \"does this directory contain conflicts.md?\" is the whole question, and\n * the shas a human might have wanted from the marker are still on disk in updatemain-hashes.json.\n */\nexport const CONFLICTS_FILE = 'conflicts.md';\n\n// `{ archiveTag, tipSha, baseSha, pr, mergedAt }` written into `merged/<feature>/` when the PR lands.\nexport const ARCHIVE_RECORD_FILE = 'archive.json';\n\n// The one index that answers \"which merges across ALL branches were 3-point?\" — see MergeInfoIndex.\nexport const MERGE_INDEX_FILE = 'index.json';\n\n/** Filesystem layout + read/write of the per-feature merge run dirs and their conflict markers. */\n@injectable(bindingScopeValues.Singleton)\nexport class MergeState {\n constructor(private readonly dotDir: DotWebpieces = dotWebpieces) {}\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),\n // paired with the sync's `<feature>PreMerge<n>` backup branch. This keeps merge N from ever reusing\n // merge N-1's stale per-file context / merge-explanation.md.\n mergeDirFor(repoRoot: string, featureName: string): string {\n const staged = this.stagedDirFor(repoRoot, featureName);\n this.migrateLegacyHome(repoRoot, featureName, staged);\n return staged;\n }\n\n /**\n * `<local .webpieces>/merge-info/staged/<feature>/` — the in-flight home.\n *\n * LOCAL scope throughout this class: a 3-point merge belongs to the worktree performing it, and\n * two worktrees are on two different branches, so these paths are disjoint by construction and need\n * no locking. In a linked worktree they now resolve under\n * `<primary>/.webpieces/worktrees/<name>/merge-info/…`, which also means an in-flight merge is not\n * destroyed by removing the worktree directory.\n */\n stagedDirFor(repoRoot: string, featureName: string): string {\n return this.dotDir.localFile(repoRoot, MERGE_INFO_DIR, STAGED_DIR, featureName);\n }\n\n /** `<local .webpieces>/merge-info/merged/<feature>/` — the landed home. */\n mergedDirFor(repoRoot: string, featureName: string): string {\n return this.dotDir.localFile(repoRoot, MERGE_INFO_DIR, MERGED_DIR, featureName);\n }\n\n /** `<local .webpieces>/merge-info/` itself — holds `staged/`, `merged/` and `index.json`. */\n mergeInfoRoot(repoRoot: string): string {\n return this.dotDir.localFile(repoRoot, MERGE_INFO_DIR);\n }\n\n /**\n * MIGRATION for the pre-`staged/` layout, done IN PLACE and lazily.\n *\n * Old layout put the feature home directly at `merge-info/<feature>/`. That dir is real, live state\n * (it can hold an UNVALIDATED merge marker for a merge that is in progress RIGHT NOW), so leaving\n * legacy dirs alone was not an option: the in-flight merge would become invisible to the finish\n * gate, which now looks under `staged/`. Tolerating both layouts on read was the other candidate and\n * was rejected — two homes means every reader, the guard included, needs two lookups forever.\n *\n * So: the first time anything asks for a feature's home, an existing legacy dir is MOVED to\n * `staged/<feature>/`. `fs.renameSync` is atomic within a filesystem and moves the whole tree with no\n * copying, so no merge record can be half-migrated. If `staged/<feature>` already exists the legacy\n * dir is left untouched — never merged, never deleted — because two homes for one feature is exactly\n * the ambiguity a human must resolve. `.webpieces/` is gitignored local state, so nothing here is\n * ever part of a commit.\n */\n private migrateLegacyHome(repoRoot: string, featureName: string, staged: string): void {\n const legacy = this.dotDir.localFile(repoRoot, MERGE_INFO_DIR, featureName);\n if (featureName === STAGED_DIR || featureName === MERGED_DIR) return;\n if (!fs.existsSync(legacy) || fs.existsSync(staged)) return;\n fs.mkdirSync(path.dirname(staged), { recursive: true });\n fs.renameSync(legacy, staged);\n }\n\n /**\n * Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash`.\n *\n * Every intermediate state, not just the last: a branch updated from main five times has five\n * genuinely different pre-merge tips, and the fifth tells you nothing about what the second looked\n * like. The hashes are what make the `<feature>PreMerge<n>` snapshot BRANCHES disposable — once the\n * tip is written down (and, at land time, tagged), the branch itself is pure branch-cap pressure.\n */\n writePreMergeHash(home: string, n: number, sha: string): void {\n fs.mkdirSync(home, { recursive: true });\n fs.writeFileSync(path.join(home, `preMerge${String(n)}.hash`), sha + '\\n');\n }\n\n /** Every recorded pre-merge tip for a feature, in slot order. [] when none were recorded. */\n readPreMergeHashes(home: string): string[] {\n if (!fs.existsSync(home)) return [];\n const found = new Map<number, string>();\n for (const entry of fs.readdirSync(home)) {\n const match = entry.match(/^preMerge(\\d+)\\.hash$/);\n if (match === null) continue;\n found.set(parseInt(match[1], 10), fs.readFileSync(path.join(home, entry), 'utf8').trim());\n }\n return [...found.keys()].sort((a: number, b: number): number => a - b)\n .map((n: number): string => found.get(n) ?? '');\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.\n 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). Durable, monotonic source of truth for slot numbers — derived\n // from the audit dirs THEMSELVES, not from which transient `<feature>PreMerge<n>` branch exists.\n 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 /**\n * Record a CLEAN (no-conflict) sync: the A/B/C shas in `updatemain-hashes.json`, and NOTHING ELSE.\n *\n * The `no-3point-merge.md` placeholder this used to also write is gone. Its whole content was a\n * sentence saying nothing interesting happened plus the same three shas being written on the very\n * next line in machine-readable form — a file that appeared in every clean directory a human opens,\n * carried no information the JSON did not, and had no consumer anywhere in the codebase. Absence is\n * now the signal instead: a run dir with no {@link CONFLICTS_FILE} was a clean merge.\n */\n recordCleanMerge(mergeDir: string, forkPoint: string, featureHead: string, mainHead: string): void {\n fs.mkdirSync(mergeDir, { recursive: true });\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 /** Path of a run dir's conflict record. Its EXISTENCE is what makes the merge \"3-point\". */\n conflictsPath(mergeDir: string): string {\n return path.join(mergeDir, CONFLICTS_FILE);\n }\n\n /** True when this run dir records a 3-point merge — i.e. `conflicts.md` is there. */\n wasThreeWay(mergeDir: string): boolean {\n return fs.existsSync(this.conflictsPath(mergeDir));\n }\n\n /** Write the 3-point conflict record. Only ever called on the conflict path. */\n writeConflicts(mergeDir: string, files: string[]): void {\n fs.mkdirSync(mergeDir, { recursive: true });\n const body =\n '# 3-point squash-merge — conflicts\\n\\n' +\n 'This sync needed a 3-point resolution. Each file below has its A/B/C context and the AI\\'s\\n' +\n `${MERGE_EXPLANATION_FILE} under \\`updatemain-<path with / → __>/\\`, and the A/B/C commit shas\\n` +\n 'are in `updatemain-hashes.json` next to this file.\\n\\n' +\n files.map((file: string): string => `- ${file}`).join('\\n') + '\\n';\n fs.writeFileSync(this.conflictsPath(mergeDir), body);\n }\n\n /** The conflicted-file list back out of `conflicts.md`. [] when the merge was clean. */\n readConflictedFiles(mergeDir: string): string[] {\n const filePath = this.conflictsPath(mergeDir);\n if (!fs.existsSync(filePath)) return [];\n return fs.readFileSync(filePath, 'utf8')\n .split('\\n')\n .filter((line: string): boolean => line.startsWith('- '))\n .map((line: string): string => line.slice(2).trim())\n .filter((line: string): boolean => line !== '');\n }\n\n /** Every `merge-<n>/` run dir under a feature home, in slot order. [] when the home does not exist. */\n listMergeRunDirs(home: string): number[] {\n if (!fs.existsSync(home)) return [];\n const slots: number[] = [];\n for (const entry of fs.readdirSync(home)) {\n const match = entry.match(/^merge-(\\d+)$/);\n if (match !== null) slots.push(parseInt(match[1], 10));\n }\n return slots.sort((a: number, b: number): number => a - b);\n }\n\n // Locate the in-progress merge's run dir: the `<home>/merge-*/` subdir holding a marker. There is\n // at most one; if more than one somehow exists, prefer an UNVALIDATED marker (the live conflict),\n // else return the first found. Null when none.\n 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 = this.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 writer and reader agree on the\n // layout: the conflict file path with `/` → `__`, prefixed `updatemain-`.\n perFileContextDir(mergeDir: string, file: string): string {\n return path.join(mergeDir, `updatemain-${file.replace(/\\//g, '__')}`);\n }\n\n markerPath(mergeDir: string): string {\n return path.join(mergeDir, MERGE_IN_PROGRESS_FILE);\n }\n\n readMergeMarker(mergeDir: string): MergeMarker | null {\n const filePath = this.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\n writeMergeMarker(mergeDir: string, marker: MergeMarker): void {\n fs.mkdirSync(mergeDir, { recursive: true });\n fs.writeFileSync(this.markerPath(mergeDir), JSON.stringify(marker, null, 2) + '\\n');\n }\n\n clearMergeMarker(mergeDir: string): void {\n const filePath = this.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 root),\n * never the whole repo — stays O(conflicts) regardless of monorepo size.\n */\n 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 in its per-file context dir (next to the diffs), proving the AI\n * deliberately 3-point merged it and recording HOW. Returns files whose explanation is missing or\n * empty. Works for every conflicted file type — including comment-less files (JSON) and files\n * resolved by deletion (no working-tree file to inspect).\n */\n scanMergeExplanations(mergeDir: string, files: string[]): MarkerScanResult {\n const filesMissingExplanation: string[] = [];\n for (const file of files) {\n const explPath = path.join(this.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}\n"]}
|
|
1
|
+
{"version":3,"file":"merge-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/merge-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,8DAAuE;AACvE,0DAAyG;AACzG,yCAA2D;AAE3D,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,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;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AM,KAAK,CAAC,EAAE,uBAAuB,CAAC,CAAC;IAC/F,CAAC;CACJ,CAAA;AA5PY,gCAAU;qBAAV,UAAU;IADtB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEA,6BAAY;GADxC,UAAU,CA4PtB","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { DotWebpieces, dotWebpieces } from '@webpieces/tooling-common';\nimport { MERGE_INFO_DIR, MERGE_IN_PROGRESS_FILE, MERGE_EXPLANATION_FILE } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\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\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\nconst CONFLICT_MARKER_RE = /^(<{7}|={7}|>{7})/m;\n\n/**\n * The two halves of `.webpieces/merge-info/`.\n *\n * `staged/` mirrors branches that STILL EXIST — it answers \"what am I working on right now\", and it\n * self-cleans when a PR lands (the whole dir is MOVED to `merged/`) instead of growing forever.\n * `merged/` is the post-mortem record, and is where the archive-tag reference lives.\n *\n * Both are reserved names: a feature branch slugifies `/`→`-`, so no feature can ever be called\n * `staged` or `merged` and collide with them.\n */\nexport const STAGED_DIR = 'staged';\nexport const MERGED_DIR = 'merged';\n\n/**\n * The 3-point conflict record. PRESENT ONLY WHEN THE MERGE ACTUALLY CONFLICTED.\n *\n * This replaces the old `no-3point-merge.md`, which was written into EVERY clean merge dir and whose\n * entire content was \"nothing interesting happened here\" plus the same A/B/C shas that\n * `updatemain-hashes.json` already carries, one line below, in machine-readable form. Nothing read it.\n * So ABSENCE is now the signal: \"does this directory contain conflicts.md?\" is the whole question, and\n * the shas a human might have wanted from the marker are still on disk in updatemain-hashes.json.\n */\nexport const CONFLICTS_FILE = 'conflicts.md';\n\n// `{ archiveTag, tipSha, baseSha, pr, mergedAt }` written into `merged/<feature>/` when the PR lands.\nexport const ARCHIVE_RECORD_FILE = 'archive.json';\n\n// The one index that answers \"which merges across ALL branches were 3-point?\" — see MergeInfoIndex.\nexport const MERGE_INDEX_FILE = 'index.json';\n\n/** Filesystem layout + read/write of the per-feature merge run dirs and their conflict markers. */\n@injectable(bindingScopeValues.Singleton)\nexport class MergeState {\n constructor(private readonly dotDir: DotWebpieces = dotWebpieces) {}\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),\n // paired with the sync's `<feature>PreMerge<n>` backup branch. This keeps merge N from ever reusing\n // merge N-1's stale per-file context / merge-explanation.md.\n mergeDirFor(repoRoot: string, featureName: string): string {\n const staged = this.stagedDirFor(repoRoot, featureName);\n this.migrateLegacyHome(repoRoot, featureName, staged);\n return staged;\n }\n\n /**\n * `<local .webpieces>/merge-info/staged/<feature>/` — the in-flight home.\n *\n * LOCAL scope throughout this class: a 3-point merge belongs to the worktree performing it, and\n * two worktrees are on two different branches, so these paths are disjoint by construction and need\n * no locking. In a linked worktree they now resolve under\n * `<primary>/.webpieces/worktrees/<name>/merge-info/…`, which also means an in-flight merge is not\n * destroyed by removing the worktree directory.\n */\n stagedDirFor(repoRoot: string, featureName: string): string {\n return this.dotDir.localFile(repoRoot, MERGE_INFO_DIR, STAGED_DIR, featureName);\n }\n\n /** `<local .webpieces>/merge-info/merged/<feature>/` — the landed home. */\n mergedDirFor(repoRoot: string, featureName: string): string {\n return this.dotDir.localFile(repoRoot, MERGE_INFO_DIR, MERGED_DIR, featureName);\n }\n\n /** `<local .webpieces>/merge-info/` itself — holds `staged/`, `merged/` and `index.json`. */\n mergeInfoRoot(repoRoot: string): string {\n return this.dotDir.localFile(repoRoot, MERGE_INFO_DIR);\n }\n\n /**\n * MIGRATION for the pre-`staged/` layout, done IN PLACE and lazily.\n *\n * Old layout put the feature home directly at `merge-info/<feature>/`. That dir is real, live state\n * (it can hold an UNVALIDATED merge marker for a merge that is in progress RIGHT NOW), so leaving\n * legacy dirs alone was not an option: the in-flight merge would become invisible to the finish\n * gate, which now looks under `staged/`. Tolerating both layouts on read was the other candidate and\n * was rejected — two homes means every reader, the guard included, needs two lookups forever.\n *\n * So: the first time anything asks for a feature's home, an existing legacy dir is MOVED to\n * `staged/<feature>/`. `fs.renameSync` is atomic within a filesystem and moves the whole tree with no\n * copying, so no merge record can be half-migrated. If `staged/<feature>` already exists the legacy\n * dir is left untouched — never merged, never deleted — because two homes for one feature is exactly\n * the ambiguity a human must resolve. `.webpieces/` is gitignored local state, so nothing here is\n * ever part of a commit.\n */\n private migrateLegacyHome(repoRoot: string, featureName: string, staged: string): void {\n const legacy = this.dotDir.localFile(repoRoot, MERGE_INFO_DIR, featureName);\n if (featureName === STAGED_DIR || featureName === MERGED_DIR) return;\n if (!fs.existsSync(legacy) || fs.existsSync(staged)) return;\n fs.mkdirSync(path.dirname(staged), { recursive: true });\n fs.renameSync(legacy, staged);\n }\n\n /**\n * Record THIS sync's pre-merge tip as `staged/<feature>/preMerge<n>.hash`.\n *\n * Every intermediate state, not just the last: a branch updated from main five times has five\n * genuinely different pre-merge tips, and the fifth tells you nothing about what the second looked\n * like. The hashes are what make the `<feature>PreMerge<n>` snapshot BRANCHES disposable — once the\n * tip is written down (and, at land time, tagged), the branch itself is pure branch-cap pressure.\n */\n writePreMergeHash(home: string, n: number, sha: string): void {\n fs.mkdirSync(home, { recursive: true });\n fs.writeFileSync(path.join(home, `preMerge${String(n)}.hash`), sha + '\\n');\n }\n\n /** Every recorded pre-merge tip for a feature, in slot order. [] when none were recorded. */\n readPreMergeHashes(home: string): string[] {\n if (!fs.existsSync(home)) return [];\n const found = new Map<number, string>();\n for (const entry of fs.readdirSync(home)) {\n const match = entry.match(/^preMerge(\\d+)\\.hash$/);\n if (match === null) continue;\n found.set(parseInt(match[1], 10), fs.readFileSync(path.join(home, entry), 'utf8').trim());\n }\n return [...found.keys()].sort((a: number, b: number): number => a - b)\n .map((n: number): string => found.get(n) ?? '');\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.\n 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). Durable, monotonic source of truth for slot numbers — derived\n // from the audit dirs THEMSELVES, not from which transient `<feature>PreMerge<n>` branch exists.\n 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 /**\n * Record a CLEAN (no-conflict) sync: the A/B/C shas in `updatemain-hashes.json`, and NOTHING ELSE.\n *\n * The `no-3point-merge.md` placeholder this used to also write is gone. Its whole content was a\n * sentence saying nothing interesting happened plus the same three shas being written on the very\n * next line in machine-readable form — a file that appeared in every clean directory a human opens,\n * carried no information the JSON did not, and had no consumer anywhere in the codebase. Absence is\n * now the signal instead: a run dir with no {@link CONFLICTS_FILE} was a clean merge.\n */\n recordCleanMerge(mergeDir: string, forkPoint: string, featureHead: string, mainHead: string): void {\n fs.mkdirSync(mergeDir, { recursive: true });\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 /** Path of a run dir's conflict record. Its EXISTENCE is what makes the merge \"3-point\". */\n conflictsPath(mergeDir: string): string {\n return path.join(mergeDir, CONFLICTS_FILE);\n }\n\n /** True when this run dir records a 3-point merge — i.e. `conflicts.md` is there. */\n wasThreeWay(mergeDir: string): boolean {\n return fs.existsSync(this.conflictsPath(mergeDir));\n }\n\n /** Write the 3-point conflict record. Only ever called on the conflict path. */\n writeConflicts(mergeDir: string, files: string[]): void {\n fs.mkdirSync(mergeDir, { recursive: true });\n const body =\n '# 3-point squash-merge — conflicts\\n\\n' +\n 'This sync needed a 3-point resolution. Each file below has its A/B/C context and the AI\\'s\\n' +\n `${MERGE_EXPLANATION_FILE} under \\`updatemain-<path with / → __>/\\`, and the A/B/C commit shas\\n` +\n 'are in `updatemain-hashes.json` next to this file.\\n\\n' +\n files.map((file: string): string => `- ${file}`).join('\\n') + '\\n';\n fs.writeFileSync(this.conflictsPath(mergeDir), body);\n }\n\n /** The conflicted-file list back out of `conflicts.md`. [] when the merge was clean. */\n readConflictedFiles(mergeDir: string): string[] {\n const filePath = this.conflictsPath(mergeDir);\n if (!fs.existsSync(filePath)) return [];\n return fs.readFileSync(filePath, 'utf8')\n .split('\\n')\n .filter((line: string): boolean => line.startsWith('- '))\n .map((line: string): string => line.slice(2).trim())\n .filter((line: string): boolean => line !== '');\n }\n\n /** Every `merge-<n>/` run dir under a feature home, in slot order. [] when the home does not exist. */\n listMergeRunDirs(home: string): number[] {\n if (!fs.existsSync(home)) return [];\n const slots: number[] = [];\n for (const entry of fs.readdirSync(home)) {\n const match = entry.match(/^merge-(\\d+)$/);\n if (match !== null) slots.push(parseInt(match[1], 10));\n }\n return slots.sort((a: number, b: number): number => a - b);\n }\n\n // Locate the in-progress merge's run dir: the `<home>/merge-*/` subdir holding a marker. There is\n // at most one; if more than one somehow exists, prefer an UNVALIDATED marker (the live conflict),\n // else return the first found. Null when none.\n 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 = this.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 writer and reader agree on the\n // layout: the conflict file path with `/` → `__`, prefixed `updatemain-`.\n perFileContextDir(mergeDir: string, file: string): string {\n return path.join(mergeDir, `updatemain-${file.replace(/\\//g, '__')}`);\n }\n\n markerPath(mergeDir: string): string {\n return path.join(mergeDir, MERGE_IN_PROGRESS_FILE);\n }\n\n readMergeMarker(mergeDir: string): MergeMarker | null {\n const filePath = this.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\n writeMergeMarker(mergeDir: string, marker: MergeMarker): void {\n fs.mkdirSync(mergeDir, { recursive: true });\n fs.writeFileSync(this.markerPath(mergeDir), JSON.stringify(marker, null, 2) + '\\n');\n }\n\n clearMergeMarker(mergeDir: string): void {\n const filePath = this.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 root),\n * never the whole repo — stays O(conflicts) regardless of monorepo size.\n */\n 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 in its per-file context dir (next to the diffs), proving the AI\n * deliberately 3-point merged it and recording HOW. Returns files whose explanation is missing or\n * empty. Works for every conflicted file type — including comment-less files (JSON) and files\n * resolved by deletion (no working-tree file to inspect).\n */\n scanMergeExplanations(mergeDir: string, files: string[]): MarkerScanResult {\n const filesMissingExplanation: string[] = [];\n for (const file of files) {\n const explPath = path.join(this.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}\n"]}
|
|
@@ -6,6 +6,7 @@ const child_process_1 = require("child_process");
|
|
|
6
6
|
const fs = tslib_1.__importStar(require("fs"));
|
|
7
7
|
const path = tslib_1.__importStar(require("path"));
|
|
8
8
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
9
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
9
10
|
const inversify_1 = require("inversify");
|
|
10
11
|
const git_readAiBranchName_1 = require("./git-readAiBranchName");
|
|
11
12
|
const verdict_provenance_1 = require("./verdict-provenance");
|
|
@@ -157,7 +158,7 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
157
158
|
// is what printed "1 checklist(s) require …" above a list of seven names. Floored at 1 so the
|
|
158
159
|
// nameless-MISSING case above cannot announce "0 checklist(s) failed" and then refuse.
|
|
159
160
|
const atFault = Math.max(new Set([...missing, ...blind]).size, 1);
|
|
160
|
-
throw new
|
|
161
|
+
throw new tooling_common_1.InformAiError(`${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\n\n` +
|
|
161
162
|
paragraphs.map((e) => ` • ${e}`).join('\n\n'));
|
|
162
163
|
}
|
|
163
164
|
/**
|
|
@@ -205,10 +206,10 @@ let ProvenanceEnforcer = class ProvenanceEnforcer {
|
|
|
205
206
|
const session = this.provenanceRecord.sessionId();
|
|
206
207
|
if (session === '' || this.provenanceRecord.mainTranscript() !== '')
|
|
207
208
|
return '';
|
|
208
|
-
const configured =
|
|
209
|
+
const configured = tooling_common_1.claudeConfigDir.configuredDir();
|
|
209
210
|
return ` Provenance found NO transcripts at all for session ${session} — not even the main agent's own — under:\n` +
|
|
210
|
-
|
|
211
|
-
` $${
|
|
211
|
+
tooling_common_1.claudeConfigDir.projectsRoots().map((root) => ` ${root}\n`).join('') +
|
|
212
|
+
` $${tooling_common_1.CLAUDE_CONFIG_DIR_ENV}=${configured === '' ? '<unset>' : configured}. This is a transcript-LOCATION problem, not a\n` +
|
|
212
213
|
` reviewer problem — your reviewers' verdicts are intact and must not be re-run. Point this command at the\n` +
|
|
213
214
|
` config dir that session wrote to.`;
|
|
214
215
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provenance-enforcer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/provenance-enforcer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAOiC;AACjC,yCAA2D;AAC3D,iEAAsD;AACtD,6DAAgE;AAEhE;;;GAGG;AACH,MAAa,gBAAgB;IACzB,QAAQ,CAAU;IAClB,QAAQ,CAAqB;IAE7B,YAAY,QAAiB,EAAE,QAA4B;QACvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AARD,4CAQC;AAED;;;;;;;;;;GAUG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAGN;IACA;IACA;IACA;IACA;IACA;IAPrB,yDAAyD;IACzD,YACqB,YAA0B,EAC1B,UAAqC,EACrC,gBAAyC,EACzC,oBAAiD,EACjD,iBAAoC,EACpC,iBAA2C;QAL3C,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA2B;QACrC,qBAAgB,GAAhB,gBAAgB,CAAyB;QACzC,yBAAoB,GAApB,oBAAoB,CAA6B;QACjD,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,sBAAiB,GAAjB,iBAAiB,CAA0B;IAC7D,CAAC;IAEJ;;;;;;;OAOG;IACH,aAAa,CAAC,KAAa;QACvB,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IAED,mGAAmG;IACnG,mGAAmG;IAC3F,MAAM,CAAC,IAAc;QACzB,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QAC5D,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,EA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AA2B;QAC9B,gCAAiB;QACjB,6CAAwB;GARvD,kBAAkB,CAkQ9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n prDirFor, summaryJsonPath, RequiredChecklist, PrGateConfig, ReviewJsonService,\n SubagentProvenanceService, PROVENANCE_OK, PROVENANCE_MISSING, PROVENANCE_SKIPPED,\n ProvenanceResult, ReviewerEvidence, ReviewerContext, ExpectedReviewer,\n ReviewProvenanceService, ProvenanceWriteRequest, ReviewerTranscript, ReviewerPaths, OfferedContext,\n ReviewerInstructionsService, InformAiError,\n claudeConfigDir, CLAUDE_CONFIG_DIR_ENV,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from './git-readAiBranchName';\nimport { VerdictProvenanceService } from './verdict-provenance';\n\n/**\n * The provenance outcome: whether each reviewer was VERIFIED to have run (the integrity check, which\n * blocks) plus what each one actually read (the quality signal, which is published). Data-only.\n */\nexport class ProvenanceReport {\n verified: boolean;\n evidence: ReviewerEvidence[];\n\n constructor(verified: boolean, evidence: ReviewerEvidence[]) {\n this.verified = verified;\n this.evidence = evidence;\n }\n}\n\n/**\n * Proves each checklist verdict came from an independently-run reviewer subagent, and records what\n * each one read.\n *\n * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam\n * twice over: this is a self-contained integrity check with its own spec\n * (`finish-provenance-record.spec.ts`), and that spec previously had to reach through\n * `command as unknown as { enforceProvenance(...) }` to get at it. Now `enforce` is simply public.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProvenanceEnforcer {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly aiBranchName: AiBranchName,\n private readonly provenance: SubagentProvenanceService,\n private readonly provenanceRecord: ReviewProvenanceService,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly verdictProvenance: VerdictProvenanceService,\n ) {}\n\n /**\n * Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps\n * the transcript links belonging to the round that produced it — a record overwritten by the NEXT\n * round audits nothing.\n *\n * Here rather than in the command because this class owns the record; the command only knows WHEN to\n * archive, not what the record is.\n */\n archiveRecord(prDir: string): void {\n this.provenanceRecord.archive(prDir);\n }\n\n // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades\n // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Enforce that EACH matched checklist was reviewed by a real reviewer SUBAGENT — the coding agent may\n // not self-certify. Not by one of a particular NAME: see SubagentProvenanceService.isReviewerRun. One run may cover several checklists, because `reviewerAgents` is a\n // required CAP and grouping under it is what the repo configured. A verified set passes silently; any\n // missing reviewer throws so the PR does not open.\n //\n // No Claude session id (Codex, a plain terminal) is NOT a pass on integrity any more (issue #863): by\n // the time this runs the checklist scan has already REJECTED every verdict that `wp-write-review` did\n // not write for a reviewer subagent. What is skipped is only the transcript evidence, and the audit\n // record is filled from the bin's provenance instead — so a Codex reviewer's identity is recorded too.\n // eslint-disable-next-line @typescript-eslint/max-params\n enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport {\n const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified\n // Defense in depth: the scanner normally hands finish an empty set under this project policy, but\n // provenance must never resurrect a reviewer requirement if a caller still passes matched checklists.\n const enforced = config.reviewer.maxAgents === 0 ? [] : required;\n const expected = enforced\n .filter((r: RequiredChecklist): boolean => r.reviewer.agentName.trim() !== '')\n .map((r: RequiredChecklist): ExpectedReviewer => new ExpectedReviewer(r.id, r.reviewer.agentName.trim()));\n const context = this.contextFor(repoRoot, enforced, branch);\n // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no\n // checklists still gets a provenance record naming the session and the main agent's own transcript.\n const result = this.provenance.verifyReviewers(expected, context);\n report.verified = result.status === PROVENANCE_OK;\n if (result.status === PROVENANCE_SKIPPED) process.stderr.write(`⚠️ ${result.detail}\\n`);\n const skipped = result.status === PROVENANCE_SKIPPED;\n report.evidence = skipped\n ? this.binEvidence(repoRoot, expected)\n : this.provenance.evidenceFor(context, expected, result.agentIds);\n // Bin evidence says WHO submitted, not what they read, so it cannot be judged blind.\n const blind = skipped ? [] : this.blindReviewers(report.evidence, config);\n // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record\n // that only ever appeared on success could not answer what the reviewers did the time it was refused.\n this.writeProvenanceRecord(repoRoot, enforced, result, report.evidence);\n this.refuse(result, blind, context);\n return report;\n }\n\n /**\n * Evidence from `review-round<N>-<id>.provenance.json` when there are no Claude transcripts to read: the harness,\n * session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.\n */\n private binEvidence(repoRoot: string, expected: readonly ExpectedReviewer[]): ReviewerEvidence[] {\n const summaryPath = summaryJsonPath(repoRoot, this.aiBranchName.getFeatureName());\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const record = this.verdictProvenance.read(summaryPath, want.checklistId, this.reviewJsonService.latestVerdictRound(summaryPath, want.checklistId));\n if (record === null) continue;\n out.push(new ReviewerEvidence(\n want.checklistId, record.agentType === '' ? want.agentType : record.agentType, record.agentId));\n }\n return out;\n }\n\n /**\n * Refuse — with an instruction that matches WHICH failure this is.\n *\n * The count is the number of CHECKLISTS at fault, not the number of message paragraphs. It used to be\n * `errors.length`, which printed \"1 checklist(s) require …\" above a list of seven names.\n *\n * The split matters more than the count. A checklist with no verdict file needs a reviewer spawned. A\n * checklist WITH one needs the opposite: the reviewer already ran, the verdict is on disk, and only the\n * attribution failed — so telling an agent to \"spawn each as its OWN subagent\" makes it overwrite seven\n * verdicts with runs that are stamped identically and refused identically. That is a loop that destroys\n * evidence on every iteration, and it is what the previous single message guaranteed.\n *\n * The BLOCK decision is the STATUS, not the length of `missing`. Those agree today — but a\n * `PROVENANCE_MISSING` that arrived carrying no names would otherwise be a silent pass: reported\n * unverified and refused by nothing. Refusing on the status makes the unverified verdict block whatever\n * else is true, and `detail` carries the wording when there are no names to word it from.\n */\n private refuse(result: ProvenanceResult, blind: readonly string[], context: ReviewerContext): void {\n const missing = result.missing;\n const neverRan = missing.filter((t: string): boolean => !fs.existsSync(context.verdictPaths[t] ?? ''));\n const unattributed = missing.filter((t: string): boolean => fs.existsSync(context.verdictPaths[t] ?? ''));\n const paragraphs: string[] = [];\n if (result.status === PROVENANCE_MISSING && missing.length === 0) paragraphs.push(result.detail);\n if (neverRan.length > 0) {\n paragraphs.push(\n 'no reviewer subagent ran on this branch for these checklists (spawn the reviewer agent that ' +\n `pnpm wp-review-upsert-pr names — do not self-certify): ${neverRan.join(', ')}`);\n }\n if (unattributed.length > 0) paragraphs.push(this.unattributedMessage(unattributed, context));\n if (blind.length > 0) {\n paragraphs.push(`these reviewers wrote a verdict without opening the diff (pr-gate.requireDiffEvidence is on): ${blind.join(', ')}`);\n }\n if (paragraphs.length === 0) return;\n // The UNION, because one checklist can be both unattributed and blind, and counting the paragraphs\n // is what printed \"1 checklist(s) require …\" above a list of seven names. Floored at 1 so the\n // nameless-MISSING case above cannot announce \"0 checklist(s) failed\" and then refuse.\n const atFault = Math.max(new Set([...missing, ...blind]).size, 1);\n throw new InformAiError(\n `${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n paragraphs.map((e: string): string => ` • ${e}`).join('\\n\\n'));\n }\n\n /**\n * The verdict exists but nothing can prove WHICH branch its reviewer looked at — or, in the one case\n * below, provenance never found the session's transcripts AT ALL and this is not about reviewers.\n *\n * The cwd paragraph is reachable when a session rooted in the PRIMARY CLONE spawns reviewers for a\n * branch that lives in a linked worktree: the harness stamps record 0 from the spawning session's cwd\n * (the Agent tool has no cwd parameter), so every respawn is stamped identically and re-spawning\n * cannot change the outcome. Saying so is the whole point of that message — the remedy is a session\n * rooted in the worktree, or a reviewer that names this branch's own files.\n *\n * It is GATED on having found the session, because it was printed for a completely different fault\n * and sent two debugging rounds in the wrong direction: see {@link transcriptRootProblem}.\n */\n private unattributedMessage(unattributed: readonly string[], context: ReviewerContext): string {\n const head = `these reviewers WROTE a verdict for this branch that provenance cannot attribute to them: ${unattributed.join(', ')}\\n` +\n ` Do NOT re-spawn them. A re-spawn overwrites the verdict file it already wrote, so that loop destroys\\n` +\n ` the verdicts and cannot change the outcome.\\n`;\n const rootProblem = this.transcriptRootProblem();\n if (rootProblem !== '') return head + rootProblem;\n return head +\n ` A reviewer is attributed when it names this branch's own files: its verdict\\n` +\n ` (${context.verdictPaths[unattributed[0]] ?? '<verdict path>'}) or the extracted diff (${context.diffDir}).\\n` +\n ` It is stamped with the cwd of the session that spawned it, so if the reviewers ran before\\n` +\n ` pnpm wp-review-upsert-pr materialized that diff, re-run this from a Claude Code session whose\\n` +\n ` cwd IS the worktree holding ${context.branch} — that is the only cwd the harness will stamp on them.`;\n }\n\n /**\n * The transcript ROOT is wrong — said so, instead of blaming the reviewers. '' when it is not.\n *\n * The test is exact rather than heuristic: the main agent's transcript is located by SESSION ID alone,\n * with no cwd, branch or stamping involved, so a known session id with no transcript anywhere can only\n * mean nothing was searched in the right place. That is a transcript-location problem, and it is not\n * something a reviewer did.\n *\n * It happened, and the cost was the whole point of gating the other message: on a machine with\n * `$CLAUDE_CONFIG_DIR` relocated, provenance searched a hardcoded `~/.claude`, found neither the\n * reviewers' transcripts nor the main agent's, and refused every PR with advice about cwd stamping,\n * worktrees and primary clones — none of which was involved. Two debugging rounds went into that\n * before `provenance.json`'s empty `mainTranscript` settled it.\n */\n private transcriptRootProblem(): string {\n const session = this.provenanceRecord.sessionId();\n if (session === '' || this.provenanceRecord.mainTranscript() !== '') return '';\n const configured = claudeConfigDir.configuredDir();\n return ` Provenance found NO transcripts at all for session ${session} — not even the main agent's own — under:\\n` +\n claudeConfigDir.projectsRoots().map((root: string): string => ` ${root}\\n`).join('') +\n ` $${CLAUDE_CONFIG_DIR_ENV}=${configured === '' ? '<unset>' : configured}. This is a transcript-LOCATION problem, not a\\n` +\n ` reviewer problem — your reviewers' verdicts are intact and must not be re-run. Point this command at the\\n` +\n ` config dir that session wrote to.`;\n }\n\n /**\n * WHERE this branch's review materials live — the paths BOTH provenance passes compare against.\n *\n * One object for crediting and for evidence: they ask different questions of the same files, and\n * building the paths twice is how the two could drift apart.\n */\n private contextFor(repoRoot: string, required: readonly RequiredChecklist[], branch: string): ReviewerContext {\n const featureName = this.aiBranchName.getFeatureName();\n const docPaths: Record<string, string> = {};\n const verdictPaths: Record<string, string> = {};\n for (const req of required) {\n docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n verdictPaths[req.id] = this.reviewJsonService.latestChecklistResultPath(summaryJsonPath(repoRoot, featureName), req.id);\n }\n return new ReviewerContext(branch, path.join(prDirFor(repoRoot, featureName), 'diff'), docPaths, verdictPaths);\n }\n\n /**\n * Write this round's audit record: `.webpieces/pr-review/<featureSlug>/provenance.json`, linking each\n * verdict to the transcript of the subagent that produced it.\n *\n * `<featureSlug>`, not `<branch>`: the dir is named by `AiBranchName.getFeatureName()`, which\n * dash-sanitizes the branch. Calling it `<branch>` is what led a bug reporter to conclude the gate\n * must be comparing a dash-form name against a slash-form git branch — see\n * ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.\n *\n * A SEPARATE file rather than a field inside summary.json / review-round<N>-<id>.json, for two reasons. The\n * reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no\n * agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files\n * byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about\n * itself. Every path here is derived by the tooling from the harness's own artifacts.\n *\n * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeProvenanceRecord(repoRoot: string, required: readonly RequiredChecklist[], result: ProvenanceResult, evidence: readonly ReviewerEvidence[]): void {\n const featureName = this.aiBranchName.getFeatureName();\n const prDir = prDirFor(repoRoot, featureName);\n const request = new ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);\n request.offered = new OfferedContext(\n path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));\n request.reviewers = evidence.map((e: ReviewerEvidence): ReviewerTranscript =>\n new ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));\n const written = this.provenanceRecord.write(request);\n if (written !== '') process.stdout.write(` transcript provenance → ${written}\\n`);\n }\n\n // Where ONE checklist's verdict, instructions and doc live — keyed by the checklist id, never by the\n // agent type, which every checklist now shares.\n // eslint-disable-next-line @typescript-eslint/max-params\n private reviewerPathsFor(repoRoot: string, featureName: string, required: readonly RequiredChecklist[], checklistId: string): ReviewerPaths {\n const req = required.find((r: RequiredChecklist): boolean => r.id === checklistId);\n const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';\n return new ReviewerPaths(\n this.reviewJsonService.latestChecklistResultPath(summaryJsonPath(repoRoot, featureName), checklistId),\n this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId),\n doc,\n );\n }\n\n /**\n * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for\n * {@link refuse} to block on (opt-in).\n *\n * Default-warn because the signal is derived from undocumented Claude Code transcript internals: if the\n * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.\n * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.\n *\n * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —\n * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.\n */\n private blindReviewers(evidence: readonly ReviewerEvidence[], config: PrGateConfig): string[] {\n const blind = evidence.filter((e: ReviewerEvidence): boolean => !e.readDiff);\n if (blind.length === 0) return [];\n const names = blind.map((e: ReviewerEvidence): string => e.checklistId);\n if (config.requireDiffEvidence) return names;\n process.stderr.write(\n `\\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\\n` +\n ' Published on the PR as a note. Not blocking — set pr-gate.requireDiffEvidence:true to make it one.\\n');\n return [];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provenance-enforcer.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/provenance-enforcer.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAkZ;AAClZ,8DAAkG;AAClG,yCAA2D;AAC3D,iEAAsD;AACtD,6DAAgE;AAEhE;;;GAGG;AACH,MAAa,gBAAgB;IACzB,QAAQ,CAAU;IAClB,QAAQ,CAAqB;IAE7B,YAAY,QAAiB,EAAE,QAA4B;QACvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AARD,4CAQC;AAED;;;;;;;;;;GAUG;AAEI,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAGN;IACA;IACA;IACA;IACA;IACA;IAPrB,yDAAyD;IACzD,YACqB,YAA0B,EAC1B,UAAqC,EACrC,gBAAyC,EACzC,oBAAiD,EACjD,iBAAoC,EACpC,iBAA2C;QAL3C,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA2B;QACrC,qBAAgB,GAAhB,gBAAgB,CAAyB;QACzC,yBAAoB,GAApB,oBAAoB,CAA6B;QACjD,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,sBAAiB,GAAjB,iBAAiB,CAA0B;IAC7D,CAAC;IAEJ;;;;;;;OAOG;IACH,aAAa,CAAC,KAAa;QACvB,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IAED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,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;YACvH,yGAAyG,CAAC,CAAC;QAC/G,OAAO,EAAE,CAAC;IACd,CAAC;CACJ,CAAA;AAlQY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIF,mCAAY;QACd,wCAAyB;QACnB,sCAAuB;QACnB,0CAA2B;QAC9B,gCAAiB;QACjB,6CAAwB;GARvD,kBAAkB,CAkQ9B","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { prDirFor, summaryJsonPath, RequiredChecklist, PrGateConfig, ReviewJsonService, SubagentProvenanceService, PROVENANCE_OK, PROVENANCE_MISSING, PROVENANCE_SKIPPED, ProvenanceResult, ReviewerEvidence, ReviewerContext, ExpectedReviewer, ReviewProvenanceService, ProvenanceWriteRequest, ReviewerTranscript, ReviewerPaths, OfferedContext, ReviewerInstructionsService } from '@webpieces/rules-config';\nimport { InformAiError, claudeConfigDir, CLAUDE_CONFIG_DIR_ENV } from '@webpieces/tooling-common';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { AiBranchName } from './git-readAiBranchName';\nimport { VerdictProvenanceService } from './verdict-provenance';\n\n/**\n * The provenance outcome: whether each reviewer was VERIFIED to have run (the integrity check, which\n * blocks) plus what each one actually read (the quality signal, which is published). Data-only.\n */\nexport class ProvenanceReport {\n verified: boolean;\n evidence: ReviewerEvidence[];\n\n constructor(verified: boolean, evidence: ReviewerEvidence[]) {\n this.verified = verified;\n this.evidence = evidence;\n }\n}\n\n/**\n * Proves each checklist verdict came from an independently-run reviewer subagent, and records what\n * each one read.\n *\n * Split out of FinishUpsertPrCommand when that file crossed the 700-line cap, and it is the right seam\n * twice over: this is a self-contained integrity check with its own spec\n * (`finish-provenance-record.spec.ts`), and that spec previously had to reach through\n * `command as unknown as { enforceProvenance(...) }` to get at it. Now `enforce` is simply public.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it is drawn in the DI design and injected by type.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ProvenanceEnforcer {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n private readonly aiBranchName: AiBranchName,\n private readonly provenance: SubagentProvenanceService,\n private readonly provenanceRecord: ReviewProvenanceService,\n private readonly reviewerInstructions: ReviewerInstructionsService,\n private readonly reviewJsonService: ReviewJsonService,\n private readonly verdictProvenance: VerdictProvenanceService,\n ) {}\n\n /**\n * Archive this round's provenance.json alongside the archived summary.json, so an archived review keeps\n * the transcript links belonging to the round that produced it — a record overwritten by the NEXT\n * round audits nothing.\n *\n * Here rather than in the command because this class owns the record; the command only knows WHEN to\n * archive, not what the record is.\n */\n archiveRecord(prDir: string): void {\n this.provenanceRecord.archive(prDir);\n }\n\n // HEAD sha for the audit record. Failure-tolerant ('' rather than a throw): a missing sha degrades\n // the audit trail, and refusing a PR over it would be the wrong trade — see writeProvenanceRecord.\n private gitOut(args: string[]): string {\n const result = spawnSync('git', args, { encoding: 'utf8' });\n return result.status === 0 ? (result.stdout ?? '').trim() : '';\n }\n\n // Enforce that EACH matched checklist was reviewed by a real reviewer SUBAGENT — the coding agent may\n // not self-certify. Not by one of a particular NAME: see SubagentProvenanceService.isReviewerRun. One run may cover several checklists, because `reviewerAgents` is a\n // required CAP and grouping under it is what the repo configured. A verified set passes silently; any\n // missing reviewer throws so the PR does not open.\n //\n // No Claude session id (Codex, a plain terminal) is NOT a pass on integrity any more (issue #863): by\n // the time this runs the checklist scan has already REJECTED every verdict that `wp-write-review` did\n // not write for a reviewer subagent. What is skipped is only the transcript evidence, and the audit\n // record is filled from the bin's provenance instead — so a Codex reviewer's identity is recorded too.\n // eslint-disable-next-line @typescript-eslint/max-params\n enforce(required: readonly RequiredChecklist[], branch: string, repoRoot: string, config: PrGateConfig): ProvenanceReport {\n const report = new ProvenanceReport(true, []); // no reviewers to verify ⇒ vacuously verified\n // Defense in depth: the scanner normally hands finish an empty set under this project policy, but\n // provenance must never resurrect a reviewer requirement if a caller still passes matched checklists.\n const enforced = config.reviewer.maxAgents === 0 ? [] : required;\n const expected = enforced\n .filter((r: RequiredChecklist): boolean => r.reviewer.agentName.trim() !== '')\n .map((r: RequiredChecklist): ExpectedReviewer => new ExpectedReviewer(r.id, r.reviewer.agentName.trim()));\n const context = this.contextFor(repoRoot, enforced, branch);\n // verifyReviewers short-circuits to OK on an empty set, so this runs unconditionally: a repo with no\n // checklists still gets a provenance record naming the session and the main agent's own transcript.\n const result = this.provenance.verifyReviewers(expected, context);\n report.verified = result.status === PROVENANCE_OK;\n if (result.status === PROVENANCE_SKIPPED) process.stderr.write(`⚠️ ${result.detail}\\n`);\n const skipped = result.status === PROVENANCE_SKIPPED;\n report.evidence = skipped\n ? this.binEvidence(repoRoot, expected)\n : this.provenance.evidenceFor(context, expected, result.agentIds);\n // Bin evidence says WHO submitted, not what they read, so it cannot be judged blind.\n const blind = skipped ? [] : this.blindReviewers(report.evidence, config);\n // BEFORE the throw below, deliberately. A refused round is the one most worth auditing, and a record\n // that only ever appeared on success could not answer what the reviewers did the time it was refused.\n this.writeProvenanceRecord(repoRoot, enforced, result, report.evidence);\n this.refuse(result, blind, context);\n return report;\n }\n\n /**\n * Evidence from `review-round<N>-<id>.provenance.json` when there are no Claude transcripts to read: the harness,\n * session and agent `wp-write-review` recorded. Read-counters stay at zero — the bin cannot know them.\n */\n private binEvidence(repoRoot: string, expected: readonly ExpectedReviewer[]): ReviewerEvidence[] {\n const summaryPath = summaryJsonPath(repoRoot, this.aiBranchName.getFeatureName());\n const out: ReviewerEvidence[] = [];\n for (const want of expected) {\n const record = this.verdictProvenance.read(summaryPath, want.checklistId, this.reviewJsonService.latestVerdictRound(summaryPath, want.checklistId));\n if (record === null) continue;\n out.push(new ReviewerEvidence(\n want.checklistId, record.agentType === '' ? want.agentType : record.agentType, record.agentId));\n }\n return out;\n }\n\n /**\n * Refuse — with an instruction that matches WHICH failure this is.\n *\n * The count is the number of CHECKLISTS at fault, not the number of message paragraphs. It used to be\n * `errors.length`, which printed \"1 checklist(s) require …\" above a list of seven names.\n *\n * The split matters more than the count. A checklist with no verdict file needs a reviewer spawned. A\n * checklist WITH one needs the opposite: the reviewer already ran, the verdict is on disk, and only the\n * attribution failed — so telling an agent to \"spawn each as its OWN subagent\" makes it overwrite seven\n * verdicts with runs that are stamped identically and refused identically. That is a loop that destroys\n * evidence on every iteration, and it is what the previous single message guaranteed.\n *\n * The BLOCK decision is the STATUS, not the length of `missing`. Those agree today — but a\n * `PROVENANCE_MISSING` that arrived carrying no names would otherwise be a silent pass: reported\n * unverified and refused by nothing. Refusing on the status makes the unverified verdict block whatever\n * else is true, and `detail` carries the wording when there are no names to word it from.\n */\n private refuse(result: ProvenanceResult, blind: readonly string[], context: ReviewerContext): void {\n const missing = result.missing;\n const neverRan = missing.filter((t: string): boolean => !fs.existsSync(context.verdictPaths[t] ?? ''));\n const unattributed = missing.filter((t: string): boolean => fs.existsSync(context.verdictPaths[t] ?? ''));\n const paragraphs: string[] = [];\n if (result.status === PROVENANCE_MISSING && missing.length === 0) paragraphs.push(result.detail);\n if (neverRan.length > 0) {\n paragraphs.push(\n 'no reviewer subagent ran on this branch for these checklists (spawn the reviewer agent that ' +\n `pnpm wp-review-upsert-pr names — do not self-certify): ${neverRan.join(', ')}`);\n }\n if (unattributed.length > 0) paragraphs.push(this.unattributedMessage(unattributed, context));\n if (blind.length > 0) {\n paragraphs.push(`these reviewers wrote a verdict without opening the diff (pr-gate.requireDiffEvidence is on): ${blind.join(', ')}`);\n }\n if (paragraphs.length === 0) return;\n // The UNION, because one checklist can be both unattributed and blind, and counting the paragraphs\n // is what printed \"1 checklist(s) require …\" above a list of seven names. Floored at 1 so the\n // nameless-MISSING case above cannot announce \"0 checklist(s) failed\" and then refuse.\n const atFault = Math.max(new Set([...missing, ...blind]).size, 1);\n throw new InformAiError(\n `${atFault} checklist(s) failed the reviewer-provenance check — fix, then re-run pnpm wp-finish-upsert-pr:\\n\\n` +\n paragraphs.map((e: string): string => ` • ${e}`).join('\\n\\n'));\n }\n\n /**\n * The verdict exists but nothing can prove WHICH branch its reviewer looked at — or, in the one case\n * below, provenance never found the session's transcripts AT ALL and this is not about reviewers.\n *\n * The cwd paragraph is reachable when a session rooted in the PRIMARY CLONE spawns reviewers for a\n * branch that lives in a linked worktree: the harness stamps record 0 from the spawning session's cwd\n * (the Agent tool has no cwd parameter), so every respawn is stamped identically and re-spawning\n * cannot change the outcome. Saying so is the whole point of that message — the remedy is a session\n * rooted in the worktree, or a reviewer that names this branch's own files.\n *\n * It is GATED on having found the session, because it was printed for a completely different fault\n * and sent two debugging rounds in the wrong direction: see {@link transcriptRootProblem}.\n */\n private unattributedMessage(unattributed: readonly string[], context: ReviewerContext): string {\n const head = `these reviewers WROTE a verdict for this branch that provenance cannot attribute to them: ${unattributed.join(', ')}\\n` +\n ` Do NOT re-spawn them. A re-spawn overwrites the verdict file it already wrote, so that loop destroys\\n` +\n ` the verdicts and cannot change the outcome.\\n`;\n const rootProblem = this.transcriptRootProblem();\n if (rootProblem !== '') return head + rootProblem;\n return head +\n ` A reviewer is attributed when it names this branch's own files: its verdict\\n` +\n ` (${context.verdictPaths[unattributed[0]] ?? '<verdict path>'}) or the extracted diff (${context.diffDir}).\\n` +\n ` It is stamped with the cwd of the session that spawned it, so if the reviewers ran before\\n` +\n ` pnpm wp-review-upsert-pr materialized that diff, re-run this from a Claude Code session whose\\n` +\n ` cwd IS the worktree holding ${context.branch} — that is the only cwd the harness will stamp on them.`;\n }\n\n /**\n * The transcript ROOT is wrong — said so, instead of blaming the reviewers. '' when it is not.\n *\n * The test is exact rather than heuristic: the main agent's transcript is located by SESSION ID alone,\n * with no cwd, branch or stamping involved, so a known session id with no transcript anywhere can only\n * mean nothing was searched in the right place. That is a transcript-location problem, and it is not\n * something a reviewer did.\n *\n * It happened, and the cost was the whole point of gating the other message: on a machine with\n * `$CLAUDE_CONFIG_DIR` relocated, provenance searched a hardcoded `~/.claude`, found neither the\n * reviewers' transcripts nor the main agent's, and refused every PR with advice about cwd stamping,\n * worktrees and primary clones — none of which was involved. Two debugging rounds went into that\n * before `provenance.json`'s empty `mainTranscript` settled it.\n */\n private transcriptRootProblem(): string {\n const session = this.provenanceRecord.sessionId();\n if (session === '' || this.provenanceRecord.mainTranscript() !== '') return '';\n const configured = claudeConfigDir.configuredDir();\n return ` Provenance found NO transcripts at all for session ${session} — not even the main agent's own — under:\\n` +\n claudeConfigDir.projectsRoots().map((root: string): string => ` ${root}\\n`).join('') +\n ` $${CLAUDE_CONFIG_DIR_ENV}=${configured === '' ? '<unset>' : configured}. This is a transcript-LOCATION problem, not a\\n` +\n ` reviewer problem — your reviewers' verdicts are intact and must not be re-run. Point this command at the\\n` +\n ` config dir that session wrote to.`;\n }\n\n /**\n * WHERE this branch's review materials live — the paths BOTH provenance passes compare against.\n *\n * One object for crediting and for evidence: they ask different questions of the same files, and\n * building the paths twice is how the two could drift apart.\n */\n private contextFor(repoRoot: string, required: readonly RequiredChecklist[], branch: string): ReviewerContext {\n const featureName = this.aiBranchName.getFeatureName();\n const docPaths: Record<string, string> = {};\n const verdictPaths: Record<string, string> = {};\n for (const req of required) {\n docPaths[req.id] = req.doc.trim() === '' ? '' : path.resolve(repoRoot, req.doc);\n verdictPaths[req.id] = this.reviewJsonService.latestChecklistResultPath(summaryJsonPath(repoRoot, featureName), req.id);\n }\n return new ReviewerContext(branch, path.join(prDirFor(repoRoot, featureName), 'diff'), docPaths, verdictPaths);\n }\n\n /**\n * Write this round's audit record: `.webpieces/pr-review/<featureSlug>/provenance.json`, linking each\n * verdict to the transcript of the subagent that produced it.\n *\n * `<featureSlug>`, not `<branch>`: the dir is named by `AiBranchName.getFeatureName()`, which\n * dash-sanitizes the branch. Calling it `<branch>` is what led a bug reporter to conclude the gate\n * must be comparing a dash-form name against a slash-form git branch — see\n * ProvenanceWriteRequest.featureSlug, whose field carried the same mislabel.\n *\n * A SEPARATE file rather than a field inside summary.json / review-round<N>-<id>.json, for two reasons. The\n * reviewer cannot supply this itself — a subagent's environment exposes the PARENT session id and no\n * agent id, so a self-reported transcript link would be invented — and keeping the AI-authored files\n * byte-untouched means nothing in the record can be mistaken for something a reviewer claimed about\n * itself. Every path here is derived by the tooling from the harness's own artifacts.\n *\n * Never fatal: an unwritable record is a lost audit trail, not a reason to refuse a PR.\n */\n // eslint-disable-next-line @typescript-eslint/max-params\n private writeProvenanceRecord(repoRoot: string, required: readonly RequiredChecklist[], result: ProvenanceResult, evidence: readonly ReviewerEvidence[]): void {\n const featureName = this.aiBranchName.getFeatureName();\n const prDir = prDirFor(repoRoot, featureName);\n const request = new ProvenanceWriteRequest(prDir, featureName, this.gitOut(['rev-parse', 'HEAD']), result.status);\n request.offered = new OfferedContext(\n path.join(prDir, 'diff'), this.reviewerInstructions.instructionsDirFor(repoRoot, featureName));\n request.reviewers = evidence.map((e: ReviewerEvidence): ReviewerTranscript =>\n new ReviewerTranscript(e, this.reviewerPathsFor(repoRoot, featureName, required, e.checklistId)));\n const written = this.provenanceRecord.write(request);\n if (written !== '') process.stdout.write(` transcript provenance → ${written}\\n`);\n }\n\n // Where ONE checklist's verdict, instructions and doc live — keyed by the checklist id, never by the\n // agent type, which every checklist now shares.\n // eslint-disable-next-line @typescript-eslint/max-params\n private reviewerPathsFor(repoRoot: string, featureName: string, required: readonly RequiredChecklist[], checklistId: string): ReviewerPaths {\n const req = required.find((r: RequiredChecklist): boolean => r.id === checklistId);\n const doc = req !== undefined && req.doc.trim() !== '' ? path.resolve(repoRoot, req.doc) : '';\n return new ReviewerPaths(\n this.reviewJsonService.latestChecklistResultPath(summaryJsonPath(repoRoot, featureName), checklistId),\n this.reviewerInstructions.pathFor(repoRoot, featureName, checklistId),\n doc,\n );\n }\n\n /**\n * The reviewers that wrote a verdict without opening the diff — WARNED about (default) or returned for\n * {@link refuse} to block on (opt-in).\n *\n * Default-warn because the signal is derived from undocumented Claude Code transcript internals: if the\n * format shifts, a blocking check wedges every PR in every consumer repo with no self-service recovery.\n * `requireDiffEvidence` lets a repo that has watched the warning promote it deliberately.\n *\n * Returns the checklist ids rather than a finished sentence so the caller can count CHECKLISTS at fault —\n * a name can appear in this list and in `missing`, and it must be one checklist in the total, not two.\n */\n private blindReviewers(evidence: readonly ReviewerEvidence[], config: PrGateConfig): string[] {\n const blind = evidence.filter((e: ReviewerEvidence): boolean => !e.readDiff);\n if (blind.length === 0) return [];\n const names = blind.map((e: ReviewerEvidence): string => e.checklistId);\n if (config.requireDiffEvidence) return names;\n process.stderr.write(\n `\\n⚠️ ${blind.length} reviewer(s) wrote a verdict with no record of opening the extracted diff: ${names.join(', ')}\\n` +\n ' Published on the PR as a note. Not blocking — set pr-gate.requireDiffEvidence:true to make it one.\\n');\n return [];\n }\n}\n"]}
|
|
@@ -4,6 +4,8 @@ exports.PushDevStateStore = exports.PushDevState = void 0;
|
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
7
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
8
|
+
const to_error_1 = require("@webpieces/tooling-common/to-error");
|
|
7
9
|
const inversify_1 = require("inversify");
|
|
8
10
|
const SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n';
|
|
9
11
|
/**
|
|
@@ -93,7 +95,7 @@ let PushDevStateStore = class PushDevStateStore {
|
|
|
93
95
|
// recover from.
|
|
94
96
|
}
|
|
95
97
|
catch (err) {
|
|
96
|
-
const error = (0,
|
|
98
|
+
const error = (0, to_error_1.toError)(err);
|
|
97
99
|
void error;
|
|
98
100
|
return null;
|
|
99
101
|
}
|
|
@@ -156,6 +158,6 @@ let PushDevStateStore = class PushDevStateStore {
|
|
|
156
158
|
exports.PushDevStateStore = PushDevStateStore;
|
|
157
159
|
exports.PushDevStateStore = PushDevStateStore = tslib_1.__decorate([
|
|
158
160
|
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
159
|
-
tslib_1.__metadata("design:paramtypes", [
|
|
161
|
+
tslib_1.__metadata("design:paramtypes", [tooling_common_1.DotWebpieces])
|
|
160
162
|
], PushDevStateStore);
|
|
161
163
|
//# sourceMappingURL=push-dev-state.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"push-dev-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/push-dev-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,0DAOiC;AACjC,yCAA2D;AAE3D,MAAM,GAAG,GAAG,0DAA0D,CAAC;AAEvE;;;;;;;;;GASG;AACH,MAAa,YAAY;IACrB,kGAAkG;IAClG,cAAc,CAAS;IACvB,uFAAuF;IACvF,SAAS,CAAS;IAClB,iFAAiF;IACjF,SAAS,CAAS;IAClB,mEAAmE;IACnE,KAAK,CAAW;IAChB,8EAA8E;IAC9E,OAAO,CAAS;IAEhB,yDAAyD;IACzD,YACI,cAAsB,EACtB,SAAiB,EACjB,SAAiB,EACjB,KAAe,EACf,OAAO,GAAG,EAAE;QAEZ,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AA1BD,oCA0BC;AAED,sGAAsG;AACtG,4FAA4F;AAC5F,kGAAkG;AAClG,iGAAiG;AACjG,EAAE;AACF,wGAAwG;AACxG,mGAAmG;AACnG,uEAAuE;AACvE,MAAM,sBAAsB,GAAsB;IAC9C,iBAAiB;IACjB,kBAAkB;IAClB,oBAAoB;IACpB,qBAAqB;IACrB,qBAAqB;IACrB,kBAAkB;IAClB,qBAAqB;IACrB,YAAY;IACZ,YAAY;CACf,CAAC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YAAE,OAAO;QAC3B,MAAM,IAAI,2BAAY,CAClB,CAAC,EACD,IAAI;YACA,GAAG;YACH,kDAAkD,SAAS,iBAAiB;YAC5E,GAAG;YACH,IAAI;YACJ,8CAA8C,KAAK,CAAC,SAAS,gBAAgB,KAAK,CAAC,cAAc,OAAO;YACxG,MAAM,IAAI,CAAC,kBAAkB,EAAE,uCAAuC;YACtE,sDAAsD;YACtD,mGAAmG;YACnG,qDAAqD;YACrD,KAAK,iCAAkB,2EAA2E;YAClG,KAAK,iCAAkB,4DAA4D,KAAK,CAAC,cAAc,QAAQ;YAC/G,eAAe,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAC7C,CAAC;IACN,CAAC;IAED,gFAAgF;IACxE,kBAAkB;QACtB,OAAO,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAS,EAAU,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzF,CAAC;IAED,uFAAuF;IACvF,sBAAsB,CAAC,OAAe;QAClC,OAAO,sBAAsB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACpD,CAAC;CACJ,CAAA;AArGY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEM,2BAAY;GAD9C,iBAAiB,CAqG7B","sourcesContent":["import * as fs from 'fs';\n\nimport {\n CliExitError,\n DotWebpieces,\n PUSH_DEV_STATE_FILE,\n WP_FINISH_PUSH_DEV,\n WP_PUSH_DEV,\n toError,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The persisted half of the `wp-push-dev --resolve` state machine.\n *\n * A single-shot wrapper is IMPOSSIBLE here and that is why this file exists: `git merge` halts on\n * conflict with markers in the working tree and a non-zero exit, and a human or an AI has to edit files\n * before anything can be committed. So the command must be able to stop, hand the tree over, and be\n * resumed by a second command that knows exactly where it left off.\n *\n * Data-only (per CLAUDE.md) — the behaviour lives in {@link PushDevStateStore}.\n */\nexport class PushDevState {\n /** The branch to return to when the resolve finishes or aborts. NEVER written to by this flow. */\n originalBranch: string;\n /** The local throwaway branch the merges happen on. Deleted on finish and on abort. */\n tmpBranch: string;\n /** `<namespace>/<originalBranch>` — the remote copy this resolve republishes. */\n targetRef: string;\n /** The copy refs still to merge, in the order CI composes them. */\n queue: string[];\n /** The ref currently mid-merge (conflicted), or '' when nothing is halted. */\n current: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n originalBranch: string,\n tmpBranch: string,\n targetRef: string,\n queue: string[],\n current = '',\n ) {\n this.originalBranch = originalBranch;\n this.tmpBranch = tmpBranch;\n this.targetRef = targetRef;\n this.queue = queue;\n this.current = current;\n }\n}\n\n// The wp-* commands that must REFUSE while a resolve is half-finished, and the ONE place that list is\n// written. The blocked-list sentence below RENDERS ITSELF from this array — the same lesson\n// merge-in-progress-guard already learned the hard way: a hand-written \"don't run other commands\"\n// survives every edit to the actual enforcement and ends up forbidding things the flow requires.\n//\n// Why these and not everything: each one either rewrites the current branch (the two starts), pushes it\n// (the finishes), or deletes branches (cleanup) — and during a resolve the checkout is a throwaway\n// branch, not the feature branch any of them think they are acting on.\nconst BLOCKED_DURING_RESOLVE: readonly string[] = [\n 'wp-start-update',\n 'wp-finish-update',\n 'wp-start-upsert-pr',\n 'wp-review-upsert-pr',\n 'wp-finish-upsert-pr',\n 'wp-human-post-pr',\n 'wp-upsert-hotfix-pr',\n 'wp-land-pr',\n 'wp-cleanup',\n];\n\n/**\n * Reads, writes and clears the resolve state file, and refuses the other `wp-*` commands while it\n * exists.\n *\n * LOCAL scope, deliberately: a resolve halts one worktree's checkout on a throwaway branch, and another\n * worktree has no reason to care. Sharing it would block a colleague's PR flow on state that says\n * nothing about their tree.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PushDevStateStore {\n constructor(private readonly dotWebpieces: DotWebpieces) {}\n\n path(repoRoot: string): string {\n return this.dotWebpieces.localFile(repoRoot, PUSH_DEV_STATE_FILE);\n }\n\n exists(repoRoot: string): boolean {\n return fs.existsSync(this.path(repoRoot));\n }\n\n /** The in-flight resolve, or null when none is. A corrupt file reads as null rather than crashing. */\n read(repoRoot: string): PushDevState | null {\n const file = this.path(repoRoot);\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- a truncated/hand-edited state file must degrade to \"no resolve in progress\" (recoverable via --abort or a fresh --resolve), never crash every wp-* command in the tree\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- JSON.parse is untyped until narrowed on the next line\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<PushDevState>;\n if (typeof raw.originalBranch !== 'string' || typeof raw.tmpBranch !== 'string')\n return null;\n return new PushDevState(\n raw.originalBranch,\n raw.tmpBranch,\n raw.targetRef ?? '',\n Array.isArray(raw.queue) ? raw.queue : [],\n raw.current ?? '',\n );\n // The parse error carries nothing a caller could act on: the ONLY meaningful reading of an\n // unparseable state file is \"no resolve in progress\", which --abort and a fresh --resolve both\n // recover from.\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n write(repoRoot: string, state: PushDevState): void {\n fs.mkdirSync(this.dotWebpieces.local(repoRoot), { recursive: true });\n fs.writeFileSync(this.path(repoRoot), JSON.stringify(state, null, 2) + '\\n', 'utf8');\n }\n\n clear(repoRoot: string): void {\n const file = this.path(repoRoot);\n if (fs.existsSync(file)) fs.rmSync(file);\n }\n\n /** The read that MUST find a resolve — used by `wp-finish-push-dev`, whose whole job is resuming one. */\n require(repoRoot: string): PushDevState {\n const state = this.read(repoRoot);\n if (state !== null) return state;\n throw new CliExitError(\n 2,\n '\\n' +\n SEP +\n '⛔ No dev-deploy resolve is in progress\\n' +\n SEP +\n '\\n' +\n `${WP_FINISH_PUSH_DEV} resumes a resolve that \\`${WP_PUSH_DEV} --resolve\\` started, and there is no\\n` +\n `state file at:\\n ${this.path(repoRoot)}\\n\\n` +\n 'If you meant to publish your branch to the shared dev server, that is the one-command form:\\n' +\n ` ${WP_PUSH_DEV}\\n`,\n );\n }\n\n /**\n * Refuse `attempted` while a resolve is half-finished. Called from the app root for every command in\n * {@link BLOCKED_DURING_RESOLVE}, so no individual command has to remember to ask.\n */\n assertIdle(repoRoot: string, attempted: string): void {\n const state = this.read(repoRoot);\n if (state === null) return;\n throw new CliExitError(\n 2,\n '\\n' +\n SEP +\n `⛔ A dev-deploy resolve is in progress — \\`pnpm ${attempted}\\` is blocked\\n` +\n SEP +\n '\\n' +\n `You are standing on the throwaway branch \\`${state.tmpBranch}\\`, not on \\`${state.originalBranch}\\`,\\n` +\n `so ${this.blockedCommandList()} would all act on the wrong branch.\\n` +\n 'That is the whole list; nothing else is blocked.\\n\\n' +\n 'EXPECTED of you right now, and NOT blocked: read the conflicted files and edit them until every\\n' +\n 'conflict marker is gone. Then finish or bail out:\\n' +\n ` ${WP_FINISH_PUSH_DEV} ← commit the resolution, resume the queue, publish the copy\\n` +\n ` ${WP_FINISH_PUSH_DEV} --abort ← throw the resolution away and go back to \\`${state.originalBranch}\\`\\n\\n` +\n `State file: ${this.path(repoRoot)}\\n`,\n );\n }\n\n // Rendered from BLOCKED_DURING_RESOLVE, never hand-written — see that constant.\n private blockedCommandList(): string {\n return BLOCKED_DURING_RESOLVE.map((c: string): string => `\\`pnpm ${c}\\``).join(', ');\n }\n\n /** Is `command` one of the ones that must refuse mid-resolve? Used by the app root. */\n isBlockedDuringResolve(command: string): boolean {\n return BLOCKED_DURING_RESOLVE.includes(command);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"push-dev-state.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/pr-gate/src/scripts/workflow/push-dev-state.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AAEzB,0DAA6G;AAC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4DAA4D,KAAK,CAAC,cAAc,QAAQ;YAC/G,eAAe,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAC7C,CAAC;IACN,CAAC;IAED,gFAAgF;IACxE,kBAAkB;QACtB,OAAO,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAS,EAAU,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzF,CAAC;IAED,uFAAuF;IACvF,sBAAsB,CAAC,OAAe;QAClC,OAAO,sBAAsB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACpD,CAAC;CACJ,CAAA;AArGY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEM,6BAAY;GAD9C,iBAAiB,CAqG7B","sourcesContent":["import * as fs from 'fs';\n\nimport { CliExitError, PUSH_DEV_STATE_FILE, WP_FINISH_PUSH_DEV, WP_PUSH_DEV } from '@webpieces/rules-config';\nimport { DotWebpieces } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nconst SEP = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n';\n\n/**\n * The persisted half of the `wp-push-dev --resolve` state machine.\n *\n * A single-shot wrapper is IMPOSSIBLE here and that is why this file exists: `git merge` halts on\n * conflict with markers in the working tree and a non-zero exit, and a human or an AI has to edit files\n * before anything can be committed. So the command must be able to stop, hand the tree over, and be\n * resumed by a second command that knows exactly where it left off.\n *\n * Data-only (per CLAUDE.md) — the behaviour lives in {@link PushDevStateStore}.\n */\nexport class PushDevState {\n /** The branch to return to when the resolve finishes or aborts. NEVER written to by this flow. */\n originalBranch: string;\n /** The local throwaway branch the merges happen on. Deleted on finish and on abort. */\n tmpBranch: string;\n /** `<namespace>/<originalBranch>` — the remote copy this resolve republishes. */\n targetRef: string;\n /** The copy refs still to merge, in the order CI composes them. */\n queue: string[];\n /** The ref currently mid-merge (conflicted), or '' when nothing is halted. */\n current: string;\n\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n originalBranch: string,\n tmpBranch: string,\n targetRef: string,\n queue: string[],\n current = '',\n ) {\n this.originalBranch = originalBranch;\n this.tmpBranch = tmpBranch;\n this.targetRef = targetRef;\n this.queue = queue;\n this.current = current;\n }\n}\n\n// The wp-* commands that must REFUSE while a resolve is half-finished, and the ONE place that list is\n// written. The blocked-list sentence below RENDERS ITSELF from this array — the same lesson\n// merge-in-progress-guard already learned the hard way: a hand-written \"don't run other commands\"\n// survives every edit to the actual enforcement and ends up forbidding things the flow requires.\n//\n// Why these and not everything: each one either rewrites the current branch (the two starts), pushes it\n// (the finishes), or deletes branches (cleanup) — and during a resolve the checkout is a throwaway\n// branch, not the feature branch any of them think they are acting on.\nconst BLOCKED_DURING_RESOLVE: readonly string[] = [\n 'wp-start-update',\n 'wp-finish-update',\n 'wp-start-upsert-pr',\n 'wp-review-upsert-pr',\n 'wp-finish-upsert-pr',\n 'wp-human-post-pr',\n 'wp-upsert-hotfix-pr',\n 'wp-land-pr',\n 'wp-cleanup',\n];\n\n/**\n * Reads, writes and clears the resolve state file, and refuses the other `wp-*` commands while it\n * exists.\n *\n * LOCAL scope, deliberately: a resolve halts one worktree's checkout on a throwaway branch, and another\n * worktree has no reason to care. Sharing it would block a colleague's PR flow on state that says\n * nothing about their tree.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PushDevStateStore {\n constructor(private readonly dotWebpieces: DotWebpieces) {}\n\n path(repoRoot: string): string {\n return this.dotWebpieces.localFile(repoRoot, PUSH_DEV_STATE_FILE);\n }\n\n exists(repoRoot: string): boolean {\n return fs.existsSync(this.path(repoRoot));\n }\n\n /** The in-flight resolve, or null when none is. A corrupt file reads as null rather than crashing. */\n read(repoRoot: string): PushDevState | null {\n const file = this.path(repoRoot);\n if (!fs.existsSync(file)) return null;\n // webpieces-disable no-unmanaged-exceptions -- a truncated/hand-edited state file must degrade to \"no resolve in progress\" (recoverable via --abort or a fresh --resolve), never crash every wp-* command in the tree\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-any-unknown -- JSON.parse is untyped until narrowed on the next line\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<PushDevState>;\n if (typeof raw.originalBranch !== 'string' || typeof raw.tmpBranch !== 'string')\n return null;\n return new PushDevState(\n raw.originalBranch,\n raw.tmpBranch,\n raw.targetRef ?? '',\n Array.isArray(raw.queue) ? raw.queue : [],\n raw.current ?? '',\n );\n // The parse error carries nothing a caller could act on: the ONLY meaningful reading of an\n // unparseable state file is \"no resolve in progress\", which --abort and a fresh --resolve both\n // recover from.\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n write(repoRoot: string, state: PushDevState): void {\n fs.mkdirSync(this.dotWebpieces.local(repoRoot), { recursive: true });\n fs.writeFileSync(this.path(repoRoot), JSON.stringify(state, null, 2) + '\\n', 'utf8');\n }\n\n clear(repoRoot: string): void {\n const file = this.path(repoRoot);\n if (fs.existsSync(file)) fs.rmSync(file);\n }\n\n /** The read that MUST find a resolve — used by `wp-finish-push-dev`, whose whole job is resuming one. */\n require(repoRoot: string): PushDevState {\n const state = this.read(repoRoot);\n if (state !== null) return state;\n throw new CliExitError(\n 2,\n '\\n' +\n SEP +\n '⛔ No dev-deploy resolve is in progress\\n' +\n SEP +\n '\\n' +\n `${WP_FINISH_PUSH_DEV} resumes a resolve that \\`${WP_PUSH_DEV} --resolve\\` started, and there is no\\n` +\n `state file at:\\n ${this.path(repoRoot)}\\n\\n` +\n 'If you meant to publish your branch to the shared dev server, that is the one-command form:\\n' +\n ` ${WP_PUSH_DEV}\\n`,\n );\n }\n\n /**\n * Refuse `attempted` while a resolve is half-finished. Called from the app root for every command in\n * {@link BLOCKED_DURING_RESOLVE}, so no individual command has to remember to ask.\n */\n assertIdle(repoRoot: string, attempted: string): void {\n const state = this.read(repoRoot);\n if (state === null) return;\n throw new CliExitError(\n 2,\n '\\n' +\n SEP +\n `⛔ A dev-deploy resolve is in progress — \\`pnpm ${attempted}\\` is blocked\\n` +\n SEP +\n '\\n' +\n `You are standing on the throwaway branch \\`${state.tmpBranch}\\`, not on \\`${state.originalBranch}\\`,\\n` +\n `so ${this.blockedCommandList()} would all act on the wrong branch.\\n` +\n 'That is the whole list; nothing else is blocked.\\n\\n' +\n 'EXPECTED of you right now, and NOT blocked: read the conflicted files and edit them until every\\n' +\n 'conflict marker is gone. Then finish or bail out:\\n' +\n ` ${WP_FINISH_PUSH_DEV} ← commit the resolution, resume the queue, publish the copy\\n` +\n ` ${WP_FINISH_PUSH_DEV} --abort ← throw the resolution away and go back to \\`${state.originalBranch}\\`\\n\\n` +\n `State file: ${this.path(repoRoot)}\\n`,\n );\n }\n\n // Rendered from BLOCKED_DURING_RESOLVE, never hand-written — see that constant.\n private blockedCommandList(): string {\n return BLOCKED_DURING_RESOLVE.map((c: string): string => `\\`pnpm ${c}\\``).join(', ');\n }\n\n /** Is `command` one of the ones that must refuse mid-resolve? Used by the app root. */\n isBlockedDuringResolve(command: string): boolean {\n return BLOCKED_DURING_RESOLVE.includes(command);\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { AtomicFile
|
|
1
|
+
import { AtomicFile } from '@webpieces/tooling-common';
|
|
2
|
+
import { ChecklistResult, ReviewJsonService } from '@webpieces/rules-config';
|
|
2
3
|
import { ReviewStageReceipt } from './review-stage-receipt';
|
|
3
4
|
import { VerdictProvenanceService } from './verdict-provenance';
|
|
4
5
|
import { DiffBasis } from './diff-basis';
|