specrails-desktop 2.29.2 → 2.29.3
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/client/dist/assets/{ActivityFeedPage-ClpD5CFj.js → ActivityFeedPage-CFB4UBhT.js} +1 -1
- package/client/dist/assets/{AgentBrowserCapture-CSPs9Ofc.js → AgentBrowserCapture-C-T0r16B.js} +1 -1
- package/client/dist/assets/{AgentModeCodePane-DwcyklA5.js → AgentModeCodePane-IljV5FOQ.js} +2 -2
- package/client/dist/assets/{AgentModeJobsPane-C69bqlMa.js → AgentModeJobsPane-B5miH10_.js} +1 -1
- package/client/dist/assets/{AgentsPage-pRiRr9-W.js → AgentsPage-BgYQrAcH.js} +1 -1
- package/client/dist/assets/{AnalyticsPage-C14exKsC.js → AnalyticsPage-BtVCuNjL.js} +1 -1
- package/client/dist/assets/{CodePage-CK76JKm9.js → CodePage-Cb_jAjSV.js} +1 -1
- package/client/dist/assets/{DesktopAnalyticsPage-Cnv0f3XQ.js → DesktopAnalyticsPage-s_Cc_JL1.js} +1 -1
- package/client/dist/assets/{DocsDialog-CHUm_Ym0.js → DocsDialog-Cr47QI9L.js} +1 -1
- package/client/dist/assets/{DocsPage-COI-oDok.js → DocsPage-C_WPRuG_.js} +1 -1
- package/client/dist/assets/{InteractiveJobComposer-CypM7R1F.js → InteractiveJobComposer-NfFOciRB.js} +1 -1
- package/client/dist/assets/{JobDetailModal-B_W0H9dw.js → JobDetailModal-DqEW7Z7K.js} +1 -1
- package/client/dist/assets/{JobDetailPage-CeeXOoKS.js → JobDetailPage-D4ppEpDE.js} +1 -1
- package/client/dist/assets/{JobsPage-CwhJG9jw.js → JobsPage-DStSoMyq.js} +1 -1
- package/client/dist/assets/{LoopBuilderPage-C51t1WOM.js → LoopBuilderPage-DltCwS4P.js} +1 -1
- package/client/dist/assets/{LoopPreviewModal-Y2HgtIJu.js → LoopPreviewModal-BWaiAbUq.js} +1 -1
- package/client/dist/assets/{LoopsPage-Bvn1Kw5V.js → LoopsPage-BqjbXuBZ.js} +1 -1
- package/client/dist/assets/{MinimizedChatsContext-DiFvZDPW.js → MinimizedChatsContext--o3JAM9F.js} +1 -1
- package/client/dist/assets/{PluginsPage-BGPRJpdf.js → PluginsPage-B-UOmzXw.js} +1 -1
- package/client/dist/assets/{ProjectSettingsDialog-D_GTyGLc.js → ProjectSettingsDialog-DkGajIxE.js} +1 -1
- package/client/dist/assets/{TemplatePreviewModal-szwBhd7h.js → TemplatePreviewModal-5CUXlkw7.js} +1 -1
- package/client/dist/assets/{TicketDetailModal-9UEyK974.js → TicketDetailModal-B_igqmti.js} +4 -4
- package/client/dist/assets/{Trans-B_vKZ-Hb.js → Trans-DDMIBBUd.js} +1 -1
- package/client/dist/assets/agent-BXc59ARK2.js +1 -0
- package/client/dist/assets/agent-BbIFXdDq.js +1 -0
- package/client/dist/assets/agent-BqEfA5u5.js +1 -0
- package/client/dist/assets/agent-BtGzgTC4.js +1 -0
- package/client/dist/assets/agent-CIhys_5d.js +1 -0
- package/client/dist/assets/agent-CJPaqsVR.js +1 -0
- package/client/dist/assets/agent-n-hY4GuL.js +1 -0
- package/client/dist/assets/agent-tJ-efa3_2.js +1 -0
- package/client/dist/assets/common-6MLbD-jM.js +1 -0
- package/client/dist/assets/common-BKGEu4rm.js +1 -0
- package/client/dist/assets/common-BNbnv8cE2.js +1 -0
- package/client/dist/assets/common-BqGWtDbt.js +1 -0
- package/client/dist/assets/common-DBtTzeYm2.js +1 -0
- package/client/dist/assets/common-DEW3Nr8n.js +1 -0
- package/client/dist/assets/{common-DVQuhs-m.js → common-DHsv9N5d.js} +1 -1
- package/client/dist/assets/common-mkrEcW-Y.js +1 -0
- package/client/dist/assets/dashboard-BYzxom0L.js +1 -0
- package/client/dist/assets/dashboard-BmDZmHyY.js +1 -0
- package/client/dist/assets/dashboard-CnNtJBQ5.js +1 -0
- package/client/dist/assets/dashboard-D4Uj-XWc2.js +1 -0
- package/client/dist/assets/dashboard-D57uRaGw2.js +1 -0
- package/client/dist/assets/dashboard-DAr6F9et.js +1 -0
- package/client/dist/assets/dashboard-vAcsn0L3.js +1 -0
- package/client/dist/assets/dashboard-vrjZvxWy.js +1 -0
- package/client/dist/assets/{dist-js-CcBCbb32.js → dist-js-BCUhGUXS.js} +1 -1
- package/client/dist/assets/{dist-js-VwztRkGj.js → dist-js-DcoXTnEI.js} +1 -1
- package/client/dist/assets/{formatDistanceToNow-ByHIauTQ.js → formatDistanceToNow-DP3Ab6fX.js} +1 -1
- package/client/dist/assets/{getTimezoneOffsetInMilliseconds-BxHAksaU.js → getTimezoneOffsetInMilliseconds-DdKKL8Fx.js} +1 -1
- package/client/dist/assets/{i18n-CgaRxpII.js → i18n-DREQCE2F.js} +2 -2
- package/client/dist/assets/index-B784m8RT.js +76 -0
- package/client/dist/assets/index-CQBIemiz.css +2 -0
- package/client/dist/assets/{spending-C4p06nen.js → spending-CtY7yYes.js} +1 -1
- package/client/dist/assets/{useBrowserCaptureSession-2OqX0vap.js → useBrowserCaptureSession-BFBdW59q.js} +1 -1
- package/client/dist/assets/{useDesktop-X8YB9xzv.js → useDesktop-uWVZ8eia.js} +1 -1
- package/client/dist/index.html +14 -14
- package/docs/internals/safe-pr-review-flow.md +221 -38
- package/package.json +1 -1
- package/server/dist/active-pr-continuation.js +237 -52
- package/server/dist/agent-chat-manager.js +29 -12
- package/server/dist/agent-store.js +19 -4
- package/server/dist/db.js +21 -0
- package/server/dist/pr-lifecycle.js +100 -8
- package/server/dist/project-git.js +62 -2
- package/server/dist/rail-isolated-launch.js +644 -108
- package/server/dist/rail-pr-decision.js +1065 -181
- package/server/dist/rail-pr-recovery-git.js +235 -0
- package/server/dist/rail-pr-store.js +120 -9
- package/server/dist/rail-worktree-release.js +290 -4
- package/server/dist/rails-router.js +97 -9
- package/server/dist/worktree-manager.js +120 -16
- package/server/dist/worktree-overlay.js +166 -4
- package/client/dist/assets/agent-4rmXoo_p.js +0 -1
- package/client/dist/assets/agent-BxZuNGih.js +0 -1
- package/client/dist/assets/agent-C3uXOYv_.js +0 -1
- package/client/dist/assets/agent-CA8Y4wbw.js +0 -1
- package/client/dist/assets/agent-CASKrhG12.js +0 -1
- package/client/dist/assets/agent-Cv-jud5n2.js +0 -1
- package/client/dist/assets/agent-DitUxYh2.js +0 -1
- package/client/dist/assets/agent-Doow4X7o.js +0 -1
- package/client/dist/assets/common-CD1QHriA2.js +0 -1
- package/client/dist/assets/common-CwwPaRxx.js +0 -1
- package/client/dist/assets/common-Dg2jaX7d.js +0 -1
- package/client/dist/assets/common-DuBwj6tK.js +0 -1
- package/client/dist/assets/common-MRj9MHcc.js +0 -1
- package/client/dist/assets/common-O4ZpnMLp.js +0 -1
- package/client/dist/assets/common-fyeF0v7C2.js +0 -1
- package/client/dist/assets/dashboard-B_NkSHYm.js +0 -1
- package/client/dist/assets/dashboard-ClBb_3pq.js +0 -1
- package/client/dist/assets/dashboard-CpCmJvMB.js +0 -1
- package/client/dist/assets/dashboard-Czohu35O2.js +0 -1
- package/client/dist/assets/dashboard-DcjbD0UK.js +0 -1
- package/client/dist/assets/dashboard-Dvx5F3we.js +0 -1
- package/client/dist/assets/dashboard-R1bOPjBh2.js +0 -1
- package/client/dist/assets/dashboard-owcDucDi.js +0 -1
- package/client/dist/assets/index-BflYQpWm.css +0 -2
- package/client/dist/assets/index-C1_-BTXy.js +0 -72
|
@@ -65,6 +65,7 @@ exports.executePrDecision = executePrDecision;
|
|
|
65
65
|
* without git/gh/net — the route in rails-router validates and delegates here.
|
|
66
66
|
*/
|
|
67
67
|
const path = __importStar(require("path"));
|
|
68
|
+
const fs = __importStar(require("fs"));
|
|
68
69
|
const artifact_registry_1 = require("./artifact-registry");
|
|
69
70
|
const worktree_manager_1 = require("./worktree-manager");
|
|
70
71
|
const pr_publisher_1 = require("./pr-publisher");
|
|
@@ -82,7 +83,15 @@ const ids_1 = require("./ids");
|
|
|
82
83
|
const repo_lock_1 = require("./repo-lock");
|
|
83
84
|
const rail_pr_ticket_effects_1 = require("./rail-pr-ticket-effects");
|
|
84
85
|
const pr_lifecycle_1 = require("./pr-lifecycle");
|
|
85
|
-
|
|
86
|
+
const rail_pr_recovery_git_1 = require("./rail-pr-recovery-git");
|
|
87
|
+
exports.PR_DECISION_ACTIONS = ['create-pr', 'publish', 'discard', 'dismiss', 'poll-merge', 'reopen', 'merge-local', 'acknowledge-no-changes', 'recover-and-retry'];
|
|
88
|
+
function safetyArchiveRecorder(deps, row) {
|
|
89
|
+
return (archive) => {
|
|
90
|
+
if (!(0, rail_pr_store_1.appendPrDeliverySafetyArchive)(deps.db, row.id, archive)) {
|
|
91
|
+
throw new Error(`delivery ${row.id} disappeared while recording safety archive ${archive}`);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
86
95
|
function isPrDecisionAction(v) {
|
|
87
96
|
return typeof v === 'string' && exports.PR_DECISION_ACTIONS.includes(v);
|
|
88
97
|
}
|
|
@@ -121,8 +130,7 @@ function actionAllowed(action, row) {
|
|
|
121
130
|
row.decision === 'pr_failed';
|
|
122
131
|
case 'dismiss':
|
|
123
132
|
return row.is_continuation === 1 && row.decision !== 'building' &&
|
|
124
|
-
row.decision !== 'merged' && row.decision !== 'discarded' && row.decision !== 'superseded'
|
|
125
|
-
row.delivery_outcome !== 'blocked';
|
|
133
|
+
row.decision !== 'merged' && row.decision !== 'discarded' && row.decision !== 'superseded';
|
|
126
134
|
case 'poll-merge':
|
|
127
135
|
return (row.decision === 'pr_draft' || row.decision === 'pr_ready' || row.decision === 'pr_closed') && row.pr_url !== null;
|
|
128
136
|
case 'reopen':
|
|
@@ -134,6 +142,12 @@ function actionAllowed(action, row) {
|
|
|
134
142
|
(row.decision === 'on_review' || row.decision === 'pr_failed' || row.decision === 'pr_draft');
|
|
135
143
|
case 'acknowledge-no-changes':
|
|
136
144
|
return row.decision === 'no_changes' && row.is_continuation !== 1;
|
|
145
|
+
case 'recover-and-retry':
|
|
146
|
+
return row.decision === 'pr_failed' && row.delivery_outcome === 'blocked' &&
|
|
147
|
+
(row.status_code === 'settlement_interrupted' || row.status_code === 'recovery_unavailable') &&
|
|
148
|
+
row.is_continuation === 1 &&
|
|
149
|
+
(row.implementation_outcome === 'succeeded' || row.implementation_outcome === 'partially_succeeded') &&
|
|
150
|
+
row.pr_url !== null && row.branch !== null;
|
|
137
151
|
}
|
|
138
152
|
}
|
|
139
153
|
async function executePrDecision(deps, input) {
|
|
@@ -173,6 +187,7 @@ async function executePrDecision(deps, input) {
|
|
|
173
187
|
case 'reopen': return await runReopen(deps, claimedRow);
|
|
174
188
|
case 'merge-local': return await runMergeLocal(deps, claimedRow);
|
|
175
189
|
case 'acknowledge-no-changes': return await runAcknowledgeNoChanges(deps, claimedRow);
|
|
190
|
+
case 'recover-and-retry': return await runRecoverAndRetry(deps, claimedRow);
|
|
176
191
|
}
|
|
177
192
|
return illegalAction(row.decision);
|
|
178
193
|
}
|
|
@@ -270,6 +285,49 @@ function ownedDeliveryBranches(row, snap, cleanupWarnings) {
|
|
|
270
285
|
owned.add(row.branch);
|
|
271
286
|
return owned;
|
|
272
287
|
}
|
|
288
|
+
function immutableHeadForOwnedBranch(row, snap, branch) {
|
|
289
|
+
if (branch === row.branch && row.delivery_sha && COMMIT_SHA_RE.test(row.delivery_sha)) {
|
|
290
|
+
return row.delivery_sha.toLowerCase();
|
|
291
|
+
}
|
|
292
|
+
const unitHeads = new Set(snap.branches
|
|
293
|
+
.filter((unit) => unitWasDelivered(unit) && unit.branch === branch && unit.finalSha && COMMIT_SHA_RE.test(unit.finalSha))
|
|
294
|
+
.map((unit) => unit.finalSha.toLowerCase()));
|
|
295
|
+
return unitHeads.size === 1 ? [...unitHeads][0] : null;
|
|
296
|
+
}
|
|
297
|
+
async function deleteOwnedBranchesIfUnchanged(deps, row, snap, cleanupWarnings, protectedBranches = new Set()) {
|
|
298
|
+
for (const branch of ownedDeliveryBranches(row, snap, cleanupWarnings)) {
|
|
299
|
+
if (!branch || branch === row.base_branch)
|
|
300
|
+
continue;
|
|
301
|
+
// A failed release leaves the linked worktree mounted for inspection. Do
|
|
302
|
+
// not even attempt to delete its checked-out branch: preserving the files
|
|
303
|
+
// while erasing their durable ref would make the recovery story depend on
|
|
304
|
+
// Git's incidental checked-out-branch rejection.
|
|
305
|
+
if (protectedBranches.has(branch)) {
|
|
306
|
+
cleanupWarnings.push(`branch ${branch}: retained with its worktree for inspection`);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
const expectedHead = immutableHeadForOwnedBranch(row, snap, branch);
|
|
311
|
+
if (!expectedHead) {
|
|
312
|
+
cleanupWarnings.push(`branch ${branch}: retained because no unambiguous immutable delivered HEAD was recorded`);
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
const observed = await deps.git.run(['rev-parse', '--verify', `refs/heads/${branch}`], deps.project.path);
|
|
316
|
+
const observedHead = observed.code === 0 ? observed.stdout.trim().toLowerCase() : '';
|
|
317
|
+
if (!COMMIT_SHA_RE.test(observedHead) || observedHead !== expectedHead) {
|
|
318
|
+
cleanupWarnings.push(`branch ${branch}: retained because its current tip no longer matches delivered HEAD ${expectedHead.slice(0, 12)}`);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
const deleted = await deps.git.run(['branch', '-D', branch], deps.project.path);
|
|
322
|
+
if (deleted.code !== 0) {
|
|
323
|
+
cleanupWarnings.push(`branch ${branch}: ${(deleted.stderr.trim() || deleted.stdout.trim()).split('\n')[0] || `exit ${deleted.code}`}`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
cleanupWarnings.push(`branch ${branch}: ${err instanceof Error ? err.message : String(err)}`);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
273
331
|
function releasableWorktreeIds(deps, snap) {
|
|
274
332
|
const preservedBranches = new Set(snap.branches.filter((unit) => !unitWasDelivered(unit)).map((unit) => unit.branch));
|
|
275
333
|
return snap.worktreeIds.filter((id) => {
|
|
@@ -277,10 +335,6 @@ function releasableWorktreeIds(deps, snap) {
|
|
|
277
335
|
return !wt || !preservedBranches.has(wt.branch);
|
|
278
336
|
});
|
|
279
337
|
}
|
|
280
|
-
async function observePrLifecycle(deps, prUrl) {
|
|
281
|
-
const observed = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, prUrl);
|
|
282
|
-
return observed.ok ? { state: observed.state, isDraft: observed.isDraft } : null;
|
|
283
|
-
}
|
|
284
338
|
function mergedEvidenceDetail(observation) {
|
|
285
339
|
return observation.includesExpectedSha === null
|
|
286
340
|
? 'GitHub did not return enough commit evidence to prove the previous PR included the verified implementation commit'
|
|
@@ -291,15 +345,19 @@ async function rerouteFromStalePr(deps, row, detail, exactWasPushed) {
|
|
|
291
345
|
const cleanupWarnings = await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
292
346
|
db: deps.db, git: deps.git, repoDir: deps.project.path,
|
|
293
347
|
worktreeIds: releasableWorktreeIds(deps, snap),
|
|
348
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
349
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
350
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
294
351
|
});
|
|
295
352
|
const partial = row.implementation_outcome === 'partially_succeeded';
|
|
353
|
+
const preserved = row.delivery_sha ? 'the preserved exact commit' : 'the preserved recorded branch';
|
|
296
354
|
const conflict = casTransition(deps, row, 'on_review', {
|
|
297
355
|
prUrl: null,
|
|
298
356
|
prNumber: null,
|
|
299
357
|
prState: exactWasPushed ? 'pushed' : 'local-only',
|
|
300
358
|
deliveryOutcome: partial ? 'partial' : 'ready',
|
|
301
359
|
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : partial ? 'partial_success' : 'ready_for_review',
|
|
302
|
-
statusDetail: `${detail}; create a new draft PR from
|
|
360
|
+
statusDetail: `${detail}; create a new draft PR from ${preserved}`,
|
|
303
361
|
cleanupWarnings,
|
|
304
362
|
// The replacement PR belongs to this generation. Per-unit branch ownership
|
|
305
363
|
// remains unchanged so a borrowed/pre-existing ref is still never deleted.
|
|
@@ -320,23 +378,76 @@ async function rerouteFromStalePr(deps, row, detail, exactWasPushed) {
|
|
|
320
378
|
},
|
|
321
379
|
};
|
|
322
380
|
}
|
|
323
|
-
async function settleObservedExistingPr(deps, row, observation) {
|
|
381
|
+
async function settleObservedExistingPr(deps, row, observation, pushed) {
|
|
324
382
|
const next = observation.state === 'MERGED' || observation.isDraft === false ? 'pr_ready' : 'pr_draft';
|
|
325
383
|
const snap = (0, rail_pr_store_1.toPrDeliverySnapshot)(row);
|
|
326
384
|
const cleanupWarnings = await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
327
385
|
db: deps.db, git: deps.git, repoDir: deps.project.path,
|
|
328
386
|
worktreeIds: releasableWorktreeIds(deps, snap),
|
|
387
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
388
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
389
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
329
390
|
});
|
|
330
391
|
const conflict = casTransition(deps, row, next, {
|
|
331
392
|
prState: 'pr-created',
|
|
332
393
|
deliveryOutcome: 'delivered',
|
|
333
394
|
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : next === 'pr_ready' ? 'pr_ready' : 'existing_pr_updated',
|
|
395
|
+
statusDetail: null,
|
|
334
396
|
cleanupWarnings,
|
|
335
397
|
});
|
|
336
398
|
if (conflict)
|
|
337
399
|
return conflict;
|
|
400
|
+
await releaseDeliveredRecoveryLineage(deps, row, row.delivery_sha);
|
|
338
401
|
const after = finalizeTransition(deps, row.id);
|
|
339
|
-
return {
|
|
402
|
+
return {
|
|
403
|
+
status: 200,
|
|
404
|
+
body: {
|
|
405
|
+
ok: true,
|
|
406
|
+
decision: next,
|
|
407
|
+
prUrl: after?.prUrl ?? row.pr_url,
|
|
408
|
+
prState: 'pr-created',
|
|
409
|
+
deliveryVerified: true,
|
|
410
|
+
verifiedSha: row.delivery_sha,
|
|
411
|
+
remoteHeadSha: observation.headRefOid,
|
|
412
|
+
pushed,
|
|
413
|
+
},
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
async function settleObservedClosedPr(deps, row, observation) {
|
|
417
|
+
const snap = (0, rail_pr_store_1.toPrDeliverySnapshot)(row);
|
|
418
|
+
const cleanupWarnings = await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
419
|
+
db: deps.db, git: deps.git, repoDir: deps.project.path,
|
|
420
|
+
worktreeIds: releasableWorktreeIds(deps, snap),
|
|
421
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
422
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
423
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
424
|
+
});
|
|
425
|
+
const conflict = casTransition(deps, row, 'pr_closed', {
|
|
426
|
+
prState: 'pr-created',
|
|
427
|
+
deliveryOutcome: 'delivered',
|
|
428
|
+
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : 'pr_closed',
|
|
429
|
+
statusDetail: null,
|
|
430
|
+
cleanupWarnings,
|
|
431
|
+
});
|
|
432
|
+
if (conflict)
|
|
433
|
+
return conflict;
|
|
434
|
+
await releaseDeliveredRecoveryLineage(deps, row, row.delivery_sha);
|
|
435
|
+
const after = finalizeTransition(deps, row.id);
|
|
436
|
+
return {
|
|
437
|
+
status: 200,
|
|
438
|
+
body: {
|
|
439
|
+
ok: true,
|
|
440
|
+
decision: 'pr_closed',
|
|
441
|
+
closed: true,
|
|
442
|
+
merged: false,
|
|
443
|
+
prUrl: after?.prUrl ?? row.pr_url,
|
|
444
|
+
prState: 'pr-created',
|
|
445
|
+
deliveryVerified: true,
|
|
446
|
+
verifiedSha: row.delivery_sha,
|
|
447
|
+
remoteHeadSha: observation.headRefOid,
|
|
448
|
+
pushed: false,
|
|
449
|
+
},
|
|
450
|
+
};
|
|
340
451
|
}
|
|
341
452
|
function persistRetryablePrObservationFailure(deps, row, detail) {
|
|
342
453
|
const conflict = casTransition(deps, row, 'pr_failed', {
|
|
@@ -360,6 +471,580 @@ function persistMovedPrHead(deps, row, detail) {
|
|
|
360
471
|
finalizeTransition(deps, row.id);
|
|
361
472
|
return { status: 200, body: { ok: true, decision: 'pr_failed', prUrl: row.pr_url, detail } };
|
|
362
473
|
}
|
|
474
|
+
function persistRecoveryBlocked(deps, row, detail, deliverySha) {
|
|
475
|
+
const conflict = casTransition(deps, row, 'pr_failed', {
|
|
476
|
+
deliveryOutcome: 'blocked',
|
|
477
|
+
statusCode: 'recovery_unavailable',
|
|
478
|
+
statusDetail: detail,
|
|
479
|
+
...(deliverySha !== undefined ? { deliverySha } : {}),
|
|
480
|
+
isContinuation: true,
|
|
481
|
+
});
|
|
482
|
+
if (conflict)
|
|
483
|
+
return conflict;
|
|
484
|
+
finalizeTransition(deps, row.id);
|
|
485
|
+
return {
|
|
486
|
+
status: 200,
|
|
487
|
+
body: {
|
|
488
|
+
ok: true,
|
|
489
|
+
decision: 'pr_failed',
|
|
490
|
+
prUrl: row.pr_url,
|
|
491
|
+
recoveryUnavailable: true,
|
|
492
|
+
detail,
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function persistProtectedRecoveryRetry(deps, row, snap, matchingUnitIndexes, runId, candidateSha, detail) {
|
|
497
|
+
const recoveredIndexes = new Set(matchingUnitIndexes);
|
|
498
|
+
const recoveredBranches = snap.branches.map((unit, index) => recoveredIndexes.has(index)
|
|
499
|
+
? {
|
|
500
|
+
...unit,
|
|
501
|
+
runId,
|
|
502
|
+
branch: row.branch,
|
|
503
|
+
succeeded: true,
|
|
504
|
+
implementationOutcome: 'succeeded',
|
|
505
|
+
deliveryOutcome: 'ready',
|
|
506
|
+
finalSha: candidateSha,
|
|
507
|
+
changed: unit.changed ?? (unit.initialSha ? unit.initialSha.toLowerCase() !== candidateSha.toLowerCase() : true),
|
|
508
|
+
failureCode: null,
|
|
509
|
+
branchOwnership: 'borrowed-pr',
|
|
510
|
+
}
|
|
511
|
+
: unit);
|
|
512
|
+
const conflict = casTransition(deps, row, 'pr_failed', {
|
|
513
|
+
branches: recoveredBranches,
|
|
514
|
+
deliverySha: candidateSha,
|
|
515
|
+
deliveryOutcome: 'retryable_failure',
|
|
516
|
+
statusCode: 'settlement_interrupted',
|
|
517
|
+
statusDetail: detail,
|
|
518
|
+
isContinuation: true,
|
|
519
|
+
});
|
|
520
|
+
if (conflict)
|
|
521
|
+
return conflict;
|
|
522
|
+
finalizeTransition(deps, row.id);
|
|
523
|
+
return {
|
|
524
|
+
status: 200,
|
|
525
|
+
body: {
|
|
526
|
+
ok: true,
|
|
527
|
+
decision: 'pr_failed',
|
|
528
|
+
prUrl: row.pr_url,
|
|
529
|
+
recovered: true,
|
|
530
|
+
detail,
|
|
531
|
+
},
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
async function exactRefSha(deps, cwd, ref) {
|
|
535
|
+
try {
|
|
536
|
+
const result = await deps.git.run(['rev-parse', '--verify', ref], cwd);
|
|
537
|
+
const sha = result.code === 0 ? result.stdout.trim() : '';
|
|
538
|
+
return COMMIT_SHA_RE.test(sha) ? sha : null;
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
async function isFastForwardCandidate(deps, baselineSha, candidateSha) {
|
|
545
|
+
if (baselineSha === candidateSha)
|
|
546
|
+
return true;
|
|
547
|
+
try {
|
|
548
|
+
return (await deps.git.run(['merge-base', '--is-ancestor', baselineSha, candidateSha], deps.project.path)).code === 0;
|
|
549
|
+
}
|
|
550
|
+
catch {
|
|
551
|
+
return false;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
async function releaseDeliveredRecoveryLineage(deps, row, deliveredSha) {
|
|
555
|
+
if (!deliveredSha || !COMMIT_SHA_RE.test(deliveredSha))
|
|
556
|
+
return;
|
|
557
|
+
const currentProtection = await (0, rail_pr_recovery_git_1.inspectRecoveryCommitProtection)(deps.git, deps.project.path, row.id);
|
|
558
|
+
if (currentProtection.kind === 'present' &&
|
|
559
|
+
currentProtection.sha.toLowerCase() === deliveredSha.toLowerCase()) {
|
|
560
|
+
await (0, rail_pr_recovery_git_1.releaseRecoveryCommit)(deps.git, deps.project.path, row.id, deliveredSha);
|
|
561
|
+
}
|
|
562
|
+
const visited = new Set([row.id]);
|
|
563
|
+
let predecessorId = row.supersedes_delivery_id;
|
|
564
|
+
for (let depth = 0; predecessorId && depth < 32 && !visited.has(predecessorId); depth++) {
|
|
565
|
+
visited.add(predecessorId);
|
|
566
|
+
const predecessor = (0, rail_pr_store_1.getPrDelivery)(deps.db, predecessorId);
|
|
567
|
+
if (!predecessor)
|
|
568
|
+
break;
|
|
569
|
+
if (predecessor.decision !== 'discarded' && predecessor.decision !== 'superseded')
|
|
570
|
+
break;
|
|
571
|
+
const protection = await (0, rail_pr_recovery_git_1.inspectRecoveryCommitProtection)(deps.git, deps.project.path, predecessor.id);
|
|
572
|
+
if (protection.kind === 'present' && await isFastForwardCandidate(deps, protection.sha, deliveredSha)) {
|
|
573
|
+
await (0, rail_pr_recovery_git_1.releaseRecoveryCommit)(deps.git, deps.project.path, predecessor.id, protection.sha);
|
|
574
|
+
}
|
|
575
|
+
predecessorId = predecessor.supersedes_delivery_id;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function parseRegisteredGitWorktrees(stdout) {
|
|
579
|
+
const worktrees = [];
|
|
580
|
+
let current = null;
|
|
581
|
+
const finish = () => {
|
|
582
|
+
if (current)
|
|
583
|
+
worktrees.push(current);
|
|
584
|
+
current = null;
|
|
585
|
+
};
|
|
586
|
+
for (const field of stdout.split('\0')) {
|
|
587
|
+
if (field === '') {
|
|
588
|
+
finish();
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
if (field.startsWith('worktree ')) {
|
|
592
|
+
finish();
|
|
593
|
+
current = { worktreePath: field.slice('worktree '.length), head: null, branch: null };
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
if (!current)
|
|
597
|
+
continue;
|
|
598
|
+
if (field.startsWith('HEAD '))
|
|
599
|
+
current.head = field.slice('HEAD '.length);
|
|
600
|
+
if (field.startsWith('branch '))
|
|
601
|
+
current.branch = field.slice('branch '.length);
|
|
602
|
+
}
|
|
603
|
+
finish();
|
|
604
|
+
return worktrees;
|
|
605
|
+
}
|
|
606
|
+
/** Authenticate a ledger path as a live, non-symlink worktree registered by
|
|
607
|
+
* this exact repository. The main checkout and ordinary directories fail
|
|
608
|
+
* closed. Callers repeat this immediately before staging to close the useful
|
|
609
|
+
* path-replacement window between inspection and mutation. */
|
|
610
|
+
async function authenticateRecoveryWorktree(deps, ledgerPath, expectedBranch, expectedHead) {
|
|
611
|
+
if (!path.isAbsolute(ledgerPath)) {
|
|
612
|
+
return { ok: false, detail: 'the recorded worktree path is not absolute' };
|
|
613
|
+
}
|
|
614
|
+
let realPath;
|
|
615
|
+
let projectRealPath;
|
|
616
|
+
try {
|
|
617
|
+
const ledgerStat = fs.lstatSync(ledgerPath);
|
|
618
|
+
if (ledgerStat.isSymbolicLink()) {
|
|
619
|
+
return { ok: false, detail: 'the recorded worktree path is a symbolic link' };
|
|
620
|
+
}
|
|
621
|
+
if (!ledgerStat.isDirectory()) {
|
|
622
|
+
return { ok: false, detail: 'the recorded worktree path is not a directory' };
|
|
623
|
+
}
|
|
624
|
+
realPath = fs.realpathSync(ledgerPath);
|
|
625
|
+
projectRealPath = fs.realpathSync(deps.project.path);
|
|
626
|
+
if (!fs.statSync(realPath).isDirectory()) {
|
|
627
|
+
return { ok: false, detail: 'the canonical worktree path is not a directory' };
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
catch {
|
|
631
|
+
return { ok: false, detail: 'the recorded worktree path could not be resolved safely' };
|
|
632
|
+
}
|
|
633
|
+
if (realPath === projectRealPath) {
|
|
634
|
+
return { ok: false, detail: 'the recorded worktree path resolves to the main project checkout' };
|
|
635
|
+
}
|
|
636
|
+
let listed;
|
|
637
|
+
try {
|
|
638
|
+
listed = await deps.git.run(['worktree', 'list', '--porcelain', '-z'], deps.project.path);
|
|
639
|
+
}
|
|
640
|
+
catch {
|
|
641
|
+
return { ok: false, detail: 'Git worktree registration could not be verified' };
|
|
642
|
+
}
|
|
643
|
+
if (listed.code !== 0) {
|
|
644
|
+
return { ok: false, detail: 'Git worktree registration could not be verified' };
|
|
645
|
+
}
|
|
646
|
+
const matches = parseRegisteredGitWorktrees(listed.stdout).filter((registered) => {
|
|
647
|
+
try {
|
|
648
|
+
return fs.realpathSync(registered.worktreePath) === realPath;
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
if (matches.length !== 1) {
|
|
655
|
+
return { ok: false, detail: 'the recorded path is not uniquely registered as a Git worktree of this project' };
|
|
656
|
+
}
|
|
657
|
+
const registered = matches[0];
|
|
658
|
+
if (registered.branch !== `refs/heads/${expectedBranch}`) {
|
|
659
|
+
return { ok: false, detail: 'the registered Git worktree is not on the recorded delivery branch' };
|
|
660
|
+
}
|
|
661
|
+
if (!registered.head || !COMMIT_SHA_RE.test(registered.head)) {
|
|
662
|
+
return { ok: false, detail: 'the registered Git worktree has no verifiable commit identity' };
|
|
663
|
+
}
|
|
664
|
+
if (expectedHead && registered.head.toLowerCase() !== expectedHead.toLowerCase()) {
|
|
665
|
+
return { ok: false, detail: 'the registered Git worktree changed commits before staging' };
|
|
666
|
+
}
|
|
667
|
+
return { ok: true, realPath, head: registered.head };
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Explicit recovery for a legacy successful continuation whose automatic
|
|
671
|
+
* causal scan could not freeze a commit. Unlike Checkout, this operates only
|
|
672
|
+
* on the delivery-owned isolated worktree/branch and never changes the user's
|
|
673
|
+
* main checkout. The user's confirmation authorizes adopting already-committed
|
|
674
|
+
* progress on that exact branch, but only as a non-force fast-forward of the
|
|
675
|
+
* live PR head.
|
|
676
|
+
*/
|
|
677
|
+
async function runRecoverAndRetry(deps, row) {
|
|
678
|
+
if (!row.pr_url || !row.branch || !row.operation_token)
|
|
679
|
+
return illegalAction(row.decision);
|
|
680
|
+
const snap = (0, rail_pr_store_1.toPrDeliverySnapshot)(row);
|
|
681
|
+
const runIds = [...new Set(snap.runIds.filter((runId) => typeof runId === 'string' && runId.length > 0))];
|
|
682
|
+
if (runIds.length !== 1) {
|
|
683
|
+
return persistRecoveryBlocked(deps, row, `Commit & retry push requires exactly one recorded implementation run; found ${runIds.length}. No local evidence was changed.`);
|
|
684
|
+
}
|
|
685
|
+
const runId = runIds[0];
|
|
686
|
+
const matchingUnitIndexes = snap.branches
|
|
687
|
+
.map((branch, index) => branch.branch === row.branch && branch.runId === runId ? index : -1)
|
|
688
|
+
.filter((index) => index >= 0);
|
|
689
|
+
if (matchingUnitIndexes.length === 0) {
|
|
690
|
+
return persistRecoveryBlocked(deps, row, 'Commit & retry push could not prove an exact recorded unit for this run and PR branch. No local evidence was changed.');
|
|
691
|
+
}
|
|
692
|
+
const matchingUnits = matchingUnitIndexes.map((index) => snap.branches[index]);
|
|
693
|
+
const recordedFinalValues = matchingUnits.map((unit) => unit.finalSha);
|
|
694
|
+
const hasAnyRecordedFinal = recordedFinalValues.some((sha) => sha != null);
|
|
695
|
+
const recordedFinalShas = [...new Set(recordedFinalValues
|
|
696
|
+
.filter((sha) => typeof sha === 'string' && COMMIT_SHA_RE.test(sha))
|
|
697
|
+
.map((sha) => sha.toLowerCase()))];
|
|
698
|
+
const recordedFinalEvidenceUnsafe = hasAnyRecordedFinal && (recordedFinalValues.some((sha) => typeof sha !== 'string' || !COMMIT_SHA_RE.test(sha)) ||
|
|
699
|
+
recordedFinalShas.length !== 1);
|
|
700
|
+
// Durable final evidence is one sufficient ownership proof, not a veto over
|
|
701
|
+
// the independent exact run-marker proof. Incomplete/disagreeing migrated
|
|
702
|
+
// unit fields are ignored here; a unique causal commit may still recover the
|
|
703
|
+
// result without adopting any of those disputed SHAs.
|
|
704
|
+
const recordedFinalSha = recordedFinalEvidenceUnsafe ? null : recordedFinalShas[0] ?? null;
|
|
705
|
+
let discovery = null;
|
|
706
|
+
const discoverCandidate = async () => {
|
|
707
|
+
if (!discovery) {
|
|
708
|
+
discovery = await (0, rail_pr_recovery_git_1.discoverRunMarkedCommit)(deps.git, deps.project.path, runId);
|
|
709
|
+
}
|
|
710
|
+
return discovery;
|
|
711
|
+
};
|
|
712
|
+
const ownedWorktrees = snap.worktreeIds
|
|
713
|
+
.map((worktreeId) => (0, rail_worktrees_store_1.getRailWorktree)(deps.db, worktreeId))
|
|
714
|
+
.filter((worktree) => Boolean(worktree && worktree.branch === row.branch && worktree.run_id === runId));
|
|
715
|
+
const presentWorktrees = ownedWorktrees.filter((worktree) => {
|
|
716
|
+
try {
|
|
717
|
+
fs.lstatSync(worktree.worktree_path);
|
|
718
|
+
return true;
|
|
719
|
+
}
|
|
720
|
+
catch {
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
const worktree = presentWorktrees[0] ?? null;
|
|
725
|
+
let preprotectedCandidateSha = null;
|
|
726
|
+
let preprotectedCandidateSource = null;
|
|
727
|
+
// Discover and pin an exact object before any network dependency, even when
|
|
728
|
+
// a ledger path still exists. A recreated/unsafe/dirty path must not hide an
|
|
729
|
+
// older run-owned orphan or leave it exposed to Git GC.
|
|
730
|
+
{
|
|
731
|
+
if (recordedFinalSha && await commitObjectExists(deps, recordedFinalSha)) {
|
|
732
|
+
preprotectedCandidateSha = recordedFinalSha;
|
|
733
|
+
preprotectedCandidateSource = 'recorded-final';
|
|
734
|
+
}
|
|
735
|
+
else {
|
|
736
|
+
const found = await discoverCandidate();
|
|
737
|
+
if (found.kind === 'ambiguous') {
|
|
738
|
+
return persistRecoveryBlocked(deps, row, `Git found ${found.count} different run-marked commits. No ambiguous object, branch, or worktree was changed.`);
|
|
739
|
+
}
|
|
740
|
+
if (found.kind === 'scan_failed') {
|
|
741
|
+
return persistRecoveryBlocked(deps, row, `${found.detail}. No branch, worktree, or object was changed.`);
|
|
742
|
+
}
|
|
743
|
+
if (found.kind === 'unique') {
|
|
744
|
+
preprotectedCandidateSha = found.sha;
|
|
745
|
+
preprotectedCandidateSource = 'run-marker';
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
if (preprotectedCandidateSha) {
|
|
749
|
+
const protection = await (0, rail_pr_recovery_git_1.protectRecoveryCommit)(deps.git, deps.project.path, row.id, preprotectedCandidateSha);
|
|
750
|
+
if (!protection.ok) {
|
|
751
|
+
return persistRecoveryBlocked(deps, row, `${protection.detail}. The candidate object and every user-visible branch were left unchanged.`);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
if (presentWorktrees.length > 1) {
|
|
756
|
+
return persistRecoveryBlocked(deps, row, 'Multiple live worktrees claim this run and branch, so Specrails refused to choose one. Every local result remains intact.', preprotectedCandidateSha);
|
|
757
|
+
}
|
|
758
|
+
const observed = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, row.pr_url, preprotectedCandidateSha);
|
|
759
|
+
if (!observed.ok) {
|
|
760
|
+
if (preprotectedCandidateSha) {
|
|
761
|
+
if (worktree) {
|
|
762
|
+
return persistRecoveryBlocked(deps, row, `Protected an exact run-owned commit, but a live worktree also exists and the PR could not be observed: ${observed.detail}. Both local results were preserved and neither was selected or pushed.`, preprotectedCandidateSha);
|
|
763
|
+
}
|
|
764
|
+
const durablyProvenNoChange = row.implementation_outcome === 'succeeded' &&
|
|
765
|
+
matchingUnitIndexes.length === snap.branches.length &&
|
|
766
|
+
matchingUnits.every((unit) => (unit.changed === false &&
|
|
767
|
+
unit.initialSha?.toLowerCase() === preprotectedCandidateSha.toLowerCase() &&
|
|
768
|
+
unit.finalSha?.toLowerCase() === preprotectedCandidateSha.toLowerCase()));
|
|
769
|
+
const detail = `Recovered and protected the exact run-owned commit, but the recorded PR could not be observed: ${observed.detail}; retry will revalidate before any push.`;
|
|
770
|
+
if (durablyProvenNoChange) {
|
|
771
|
+
return persistRecoveryBlocked(deps, row, detail, preprotectedCandidateSha);
|
|
772
|
+
}
|
|
773
|
+
return persistProtectedRecoveryRetry(deps, row, snap, matchingUnitIndexes, runId, preprotectedCandidateSha, detail);
|
|
774
|
+
}
|
|
775
|
+
return persistRecoveryBlocked(deps, row, `The existing PR could not be verified before local recovery: ${observed.detail}. No local evidence was changed.`);
|
|
776
|
+
}
|
|
777
|
+
if (!(0, pr_lifecycle_1.isExactOpenPr)(observed, row.branch, row.base_branch) || !observed.headRefOid) {
|
|
778
|
+
if (preprotectedCandidateSha) {
|
|
779
|
+
if (worktree) {
|
|
780
|
+
return persistRecoveryBlocked(deps, row, 'A protected run-owned commit and a live worktree both exist while the recorded PR lifecycle changed. Specrails preserved both and refused to choose or push either automatically.', preprotectedCandidateSha);
|
|
781
|
+
}
|
|
782
|
+
const frozen = persistProtectedRecoveryRetry(deps, row, snap, matchingUnitIndexes, runId, preprotectedCandidateSha, 'Protected the exact run-owned commit; revalidating the changed PR lifecycle before any push.');
|
|
783
|
+
if (frozen.status !== 200 || frozen.body.decision !== 'pr_failed')
|
|
784
|
+
return frozen;
|
|
785
|
+
const recoveredRow = (0, rail_pr_store_1.getPrDelivery)(deps.db, row.id);
|
|
786
|
+
if (!recoveredRow || recoveredRow.operation_token !== row.operation_token) {
|
|
787
|
+
return staleDecision(recoveredRow?.decision ?? row.decision);
|
|
788
|
+
}
|
|
789
|
+
return retryExistingPrFollowupPush(deps, recoveredRow);
|
|
790
|
+
}
|
|
791
|
+
return persistRecoveryBlocked(deps, row, 'The recorded PR is no longer an exact open head/base recovery target. No local evidence was changed.');
|
|
792
|
+
}
|
|
793
|
+
const baselineSha = observed.headRefOid;
|
|
794
|
+
// Ensure the live remote baseline object is available for the ancestry proof
|
|
795
|
+
// without advancing any local branch or touching the main checkout.
|
|
796
|
+
if (!(await commitObjectExists(deps, baselineSha))) {
|
|
797
|
+
try {
|
|
798
|
+
await deps.git.run(['fetch', 'origin', `refs/heads/${row.branch}`], deps.project.path);
|
|
799
|
+
}
|
|
800
|
+
catch { /* the exact object check below remains authoritative */ }
|
|
801
|
+
}
|
|
802
|
+
if (!(await commitObjectExists(deps, baselineSha))) {
|
|
803
|
+
return persistRecoveryBlocked(deps, row, 'The live PR head object is unavailable locally, so fast-forward recovery cannot be proven. No local evidence was changed.', preprotectedCandidateSha);
|
|
804
|
+
}
|
|
805
|
+
let candidateSha = preprotectedCandidateSha;
|
|
806
|
+
let candidateOwned = preprotectedCandidateSha !== null;
|
|
807
|
+
let candidateSource = preprotectedCandidateSource ?? 'baseline';
|
|
808
|
+
let committed = false;
|
|
809
|
+
if (worktree) {
|
|
810
|
+
const authenticated = await authenticateRecoveryWorktree(deps, worktree.worktree_path, row.branch);
|
|
811
|
+
if (!authenticated.ok) {
|
|
812
|
+
return persistRecoveryBlocked(deps, row, `The preserved path at ${worktree.worktree_path} could not be authenticated safely: ${authenticated.detail}. Nothing was staged, pushed, or removed.`, preprotectedCandidateSha);
|
|
813
|
+
}
|
|
814
|
+
const authenticatedPath = authenticated.realPath;
|
|
815
|
+
const [actualBranch, worktreeHead, branchHead] = await Promise.all([
|
|
816
|
+
deps.git.run(['rev-parse', '--abbrev-ref', 'HEAD'], authenticatedPath).catch(() => ({ code: 1, stdout: '', stderr: '' })),
|
|
817
|
+
exactRefSha(deps, authenticatedPath, 'HEAD'),
|
|
818
|
+
exactRefSha(deps, deps.project.path, `refs/heads/${row.branch}`),
|
|
819
|
+
]);
|
|
820
|
+
if (actualBranch.code !== 0 || actualBranch.stdout.trim() !== row.branch ||
|
|
821
|
+
!worktreeHead || !branchHead || worktreeHead !== branchHead ||
|
|
822
|
+
authenticated.head.toLowerCase() !== worktreeHead.toLowerCase()) {
|
|
823
|
+
return persistRecoveryBlocked(deps, row, `The preserved worktree at ${worktree.worktree_path} is not on the exact recorded branch/HEAD. It was left untouched.`, preprotectedCandidateSha);
|
|
824
|
+
}
|
|
825
|
+
if (preprotectedCandidateSha &&
|
|
826
|
+
worktreeHead.toLowerCase() !== preprotectedCandidateSha.toLowerCase()) {
|
|
827
|
+
return persistRecoveryBlocked(deps, row, `A protected run-owned commit and a different live worktree result both exist. Specrails preserved both and refused to choose or bundle them automatically. Inspect ${worktree.worktree_path} before retrying or discarding either result.`, preprotectedCandidateSha);
|
|
828
|
+
}
|
|
829
|
+
if (!(await isFastForwardCandidate(deps, baselineSha, worktreeHead))) {
|
|
830
|
+
return persistRecoveryBlocked(deps, row, `The preserved branch diverges from the live PR head. The worktree at ${worktree.worktree_path} was left untouched.`, preprotectedCandidateSha);
|
|
831
|
+
}
|
|
832
|
+
let skipWorktreeCommit = false;
|
|
833
|
+
if (worktreeHead === baselineSha) {
|
|
834
|
+
candidateOwned = true;
|
|
835
|
+
candidateSource = 'baseline';
|
|
836
|
+
}
|
|
837
|
+
else if (recordedFinalSha && worktreeHead.toLowerCase() === recordedFinalSha) {
|
|
838
|
+
candidateOwned = true;
|
|
839
|
+
candidateSource = 'recorded-final';
|
|
840
|
+
}
|
|
841
|
+
else {
|
|
842
|
+
const found = await discoverCandidate();
|
|
843
|
+
if (found.kind === 'unique' && found.sha === worktreeHead.toLowerCase()) {
|
|
844
|
+
candidateOwned = true;
|
|
845
|
+
candidateSource = 'run-marker';
|
|
846
|
+
}
|
|
847
|
+
else if (found.kind === 'unique') {
|
|
848
|
+
// A later/unrelated checked-out tip must not be bundled into the
|
|
849
|
+
// recovered result. Preserve it untouched and use only the exact
|
|
850
|
+
// run-owned object discovered independently.
|
|
851
|
+
candidateSha = found.sha;
|
|
852
|
+
candidateOwned = true;
|
|
853
|
+
candidateSource = 'run-marker';
|
|
854
|
+
skipWorktreeCommit = true;
|
|
855
|
+
}
|
|
856
|
+
else {
|
|
857
|
+
const reason = found.kind === 'ambiguous'
|
|
858
|
+
? `Git found ${found.count} run-marked commits, so no unique worktree baseline could be chosen.`
|
|
859
|
+
: found.kind === 'scan_failed'
|
|
860
|
+
? `${found.detail}.`
|
|
861
|
+
: 'The preserved worktree branch advanced beyond every delivery-owned commit.';
|
|
862
|
+
return persistRecoveryBlocked(deps, row, `${reason} The worktree at ${worktree.worktree_path} was left untouched.`);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (!skipWorktreeCommit) {
|
|
866
|
+
deps.assertAdmission?.();
|
|
867
|
+
const reauthenticated = await authenticateRecoveryWorktree(deps, worktree.worktree_path, row.branch, worktreeHead);
|
|
868
|
+
if (!reauthenticated.ok || reauthenticated.realPath !== authenticatedPath) {
|
|
869
|
+
const detail = reauthenticated.ok
|
|
870
|
+
? 'the canonical worktree path changed before staging'
|
|
871
|
+
: reauthenticated.detail;
|
|
872
|
+
return persistRecoveryBlocked(deps, row, `The preserved path at ${worktree.worktree_path} failed final authentication: ${detail}. Nothing was staged, pushed, or removed.`);
|
|
873
|
+
}
|
|
874
|
+
deps.assertAdmission?.();
|
|
875
|
+
const overlayExcludes = [...new Set(matchingUnits.flatMap((unit) => unit.overlayExcludes ?? []))];
|
|
876
|
+
const commit = await (0, worktree_manager_1.commitWorktreeAndVerify)(deps.git, reauthenticated.realPath, `specrails: recovered follow-up (run ${runId})`, overlayExcludes);
|
|
877
|
+
if (!commit.clean) {
|
|
878
|
+
return persistRecoveryBlocked(deps, row, `The preserved worktree could not be committed safely: ${commit.error ?? (commit.dirty.join(', ') || 'deliverable changes remain')}. It was left intact at ${worktree.worktree_path}.`);
|
|
879
|
+
}
|
|
880
|
+
committed = commit.committed;
|
|
881
|
+
const [afterBranch, afterHead, afterBranchHead] = await Promise.all([
|
|
882
|
+
deps.git.run(['rev-parse', '--abbrev-ref', 'HEAD'], reauthenticated.realPath).catch(() => ({ code: 1, stdout: '', stderr: '' })),
|
|
883
|
+
exactRefSha(deps, reauthenticated.realPath, 'HEAD'),
|
|
884
|
+
exactRefSha(deps, deps.project.path, `refs/heads/${row.branch}`),
|
|
885
|
+
]);
|
|
886
|
+
if (afterBranch.code !== 0 || afterBranch.stdout.trim() !== row.branch ||
|
|
887
|
+
!afterHead || afterHead !== afterBranchHead) {
|
|
888
|
+
return persistRecoveryBlocked(deps, row, `The recovery commit exists, but final branch verification failed. It remains preserved at ${worktree.worktree_path}.`);
|
|
889
|
+
}
|
|
890
|
+
candidateSha = afterHead;
|
|
891
|
+
if (committed) {
|
|
892
|
+
candidateOwned = true;
|
|
893
|
+
candidateSource = 'worktree';
|
|
894
|
+
}
|
|
895
|
+
if (candidateSource === 'baseline' && recordedFinalSha && afterHead.toLowerCase() === recordedFinalSha) {
|
|
896
|
+
candidateSource = 'recorded-final';
|
|
897
|
+
}
|
|
898
|
+
candidateOwned = candidateOwned || committed || candidateSource !== 'baseline' || afterHead === baselineSha;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
else {
|
|
902
|
+
candidateSha ??= await exactRefSha(deps, deps.project.path, `refs/heads/${row.branch}`);
|
|
903
|
+
}
|
|
904
|
+
// A consistent durable final SHA outranks a mutable branch name. This also
|
|
905
|
+
// lets another checkout recover an object whose branch was later reset.
|
|
906
|
+
if (!committed && recordedFinalSha &&
|
|
907
|
+
await commitObjectExists(deps, recordedFinalSha) &&
|
|
908
|
+
(!candidateOwned || candidateSha === baselineSha)) {
|
|
909
|
+
candidateSha = recordedFinalSha;
|
|
910
|
+
candidateOwned = true;
|
|
911
|
+
candidateSource = 'recorded-final';
|
|
912
|
+
}
|
|
913
|
+
// Before claiming absence, inspect the same complete causal surface as
|
|
914
|
+
// startup. A unique run-marked object may survive after both the worktree and
|
|
915
|
+
// visible branch were removed.
|
|
916
|
+
const baselineHasDurableFinalProof = candidateSha === baselineSha && recordedFinalSha === baselineSha;
|
|
917
|
+
if (!candidateSha || (candidateSha === baselineSha && !baselineHasDurableFinalProof) || !candidateOwned) {
|
|
918
|
+
const found = await discoverCandidate();
|
|
919
|
+
if (found.kind === 'ambiguous') {
|
|
920
|
+
return persistRecoveryBlocked(deps, row, `Git found ${found.count} different run-marked commits. No ambiguous object, branch, or worktree was changed.`);
|
|
921
|
+
}
|
|
922
|
+
if (found.kind === 'scan_failed') {
|
|
923
|
+
return persistRecoveryBlocked(deps, row, `${found.detail}. No branch, worktree, or object was changed.`);
|
|
924
|
+
}
|
|
925
|
+
if (found.kind === 'unique') {
|
|
926
|
+
candidateSha = found.sha;
|
|
927
|
+
candidateOwned = true;
|
|
928
|
+
candidateSource = 'run-marker';
|
|
929
|
+
}
|
|
930
|
+
else if (candidateSha && candidateSha !== baselineSha && !candidateOwned) {
|
|
931
|
+
return persistRecoveryBlocked(deps, row, 'The recorded local branch advanced beyond the run-owned result. The later branch tip was preserved and was not committed or pushed.');
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
if (!candidateSha || !(await commitObjectExists(deps, candidateSha))) {
|
|
935
|
+
return persistRecoveryBlocked(deps, row, 'No delivery-owned commit is available in this clone’s refs, reflogs, worktrees, or unreachable objects. The result may still exist on the computer where the run executed; nothing here was changed or removed.');
|
|
936
|
+
}
|
|
937
|
+
if (candidateSha === baselineSha) {
|
|
938
|
+
const provesNoChanges = row.implementation_outcome === 'succeeded' &&
|
|
939
|
+
matchingUnitIndexes.length === snap.branches.length &&
|
|
940
|
+
matchingUnits.every((unit) => (unit.changed === false &&
|
|
941
|
+
unit.initialSha?.toLowerCase() === baselineSha.toLowerCase() &&
|
|
942
|
+
unit.finalSha?.toLowerCase() === baselineSha.toLowerCase()));
|
|
943
|
+
if (provesNoChanges) {
|
|
944
|
+
const noChangeIndexes = new Set(matchingUnitIndexes);
|
|
945
|
+
const noChangeBranches = snap.branches.map((unit, index) => noChangeIndexes.has(index)
|
|
946
|
+
? {
|
|
947
|
+
...unit,
|
|
948
|
+
succeeded: true,
|
|
949
|
+
implementationOutcome: 'succeeded',
|
|
950
|
+
deliveryOutcome: 'no_changes',
|
|
951
|
+
initialSha: baselineSha,
|
|
952
|
+
finalSha: baselineSha,
|
|
953
|
+
changed: false,
|
|
954
|
+
failureCode: null,
|
|
955
|
+
}
|
|
956
|
+
: unit);
|
|
957
|
+
const conflict = casTransition(deps, row, 'no_changes', {
|
|
958
|
+
branches: noChangeBranches,
|
|
959
|
+
deliverySha: baselineSha,
|
|
960
|
+
deliveryOutcome: 'no_changes',
|
|
961
|
+
statusCode: 'no_changes',
|
|
962
|
+
statusDetail: null,
|
|
963
|
+
isContinuation: true,
|
|
964
|
+
});
|
|
965
|
+
if (conflict)
|
|
966
|
+
return conflict;
|
|
967
|
+
await releaseDeliveredRecoveryLineage(deps, row, baselineSha);
|
|
968
|
+
finalizeTransition(deps, row.id);
|
|
969
|
+
return {
|
|
970
|
+
status: 200,
|
|
971
|
+
body: {
|
|
972
|
+
ok: true,
|
|
973
|
+
decision: 'no_changes',
|
|
974
|
+
prUrl: row.pr_url,
|
|
975
|
+
noChanges: true,
|
|
976
|
+
deliveryVerified: true,
|
|
977
|
+
verifiedSha: baselineSha,
|
|
978
|
+
pushed: false,
|
|
979
|
+
},
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
const alreadyDelivered = recordedFinalSha === baselineSha || candidateSource === 'run-marker';
|
|
983
|
+
if (!alreadyDelivered) {
|
|
984
|
+
return persistRecoveryBlocked(deps, row, 'This clone contains only the current PR head and no additional run-owned result. The original execution computer may still retain its worktree or orphan commit; nothing here was changed or removed.');
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
else {
|
|
988
|
+
const protection = preprotectedCandidateSha &&
|
|
989
|
+
preprotectedCandidateSha.toLowerCase() !== candidateSha.toLowerCase()
|
|
990
|
+
? await (0, rail_pr_recovery_git_1.advanceRecoveryCommitProtection)(deps.git, deps.project.path, row.id, preprotectedCandidateSha, candidateSha)
|
|
991
|
+
: await (0, rail_pr_recovery_git_1.protectRecoveryCommit)(deps.git, deps.project.path, row.id, candidateSha);
|
|
992
|
+
if (!protection.ok) {
|
|
993
|
+
return persistRecoveryBlocked(deps, row, `${protection.detail}. The candidate object and every user-visible branch were left unchanged.`, preprotectedCandidateSha);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
if (!(await isFastForwardCandidate(deps, baselineSha, candidateSha))) {
|
|
997
|
+
return persistRecoveryBlocked(deps, row, 'The exact run-owned recovery commit is not a fast-forward of the live PR head. It remains protected locally and nothing was pushed or removed.', candidateSha);
|
|
998
|
+
}
|
|
999
|
+
const recoveredIndexes = new Set(matchingUnitIndexes);
|
|
1000
|
+
const recoveredBranches = snap.branches.map((unit, index) => recoveredIndexes.has(index)
|
|
1001
|
+
? {
|
|
1002
|
+
...unit,
|
|
1003
|
+
runId,
|
|
1004
|
+
branch: row.branch,
|
|
1005
|
+
succeeded: true,
|
|
1006
|
+
implementationOutcome: 'succeeded',
|
|
1007
|
+
deliveryOutcome: 'ready',
|
|
1008
|
+
// Equality with the live PR head can mean the exact run commit was
|
|
1009
|
+
// already delivered; it is not no-change evidence. Preserve a durable
|
|
1010
|
+
// initial SHA when available and infer the observed baseline only for
|
|
1011
|
+
// a still-missing descendant. The proven no-change branch returned
|
|
1012
|
+
// above before reaching this mapping.
|
|
1013
|
+
initialSha: unit.initialSha ?? (candidateSha !== baselineSha ? baselineSha : null),
|
|
1014
|
+
finalSha: candidateSha,
|
|
1015
|
+
changed: true,
|
|
1016
|
+
failureCode: null,
|
|
1017
|
+
branchOwnership: 'borrowed-pr',
|
|
1018
|
+
...(worktree ? { worktreePath: worktree.worktree_path } : {}),
|
|
1019
|
+
}
|
|
1020
|
+
: unit);
|
|
1021
|
+
// Freeze before the network mutation. A crash after this write leaves a
|
|
1022
|
+
// normal immutable Retry push card; a crash before it leaves the run-marked
|
|
1023
|
+
// commit discoverable by startup recovery.
|
|
1024
|
+
if (!(0, rail_pr_store_1.transitionClaimedDecision)(deps.db, row.id, row.decision, 'pr_failed', row.operation_token, {
|
|
1025
|
+
branches: recoveredBranches,
|
|
1026
|
+
deliverySha: candidateSha,
|
|
1027
|
+
deliveryOutcome: 'retryable_failure',
|
|
1028
|
+
statusCode: 'settlement_interrupted',
|
|
1029
|
+
statusDetail: candidateSource === 'worktree'
|
|
1030
|
+
? `Committed the preserved worktree as ${candidateSha.slice(0, 8)}; validating the exact PR before push.`
|
|
1031
|
+
: candidateSource === 'run-marker'
|
|
1032
|
+
? `Protected the unique run-owned commit ${candidateSha.slice(0, 8)}; validating the exact PR before push.`
|
|
1033
|
+
: `Recovered the durable final commit ${candidateSha.slice(0, 8)}; validating the exact PR before push.`,
|
|
1034
|
+
isContinuation: true,
|
|
1035
|
+
})) {
|
|
1036
|
+
const current = (0, rail_pr_store_1.getPrDelivery)(deps.db, row.id);
|
|
1037
|
+
return staleDecision(current?.decision ?? row.decision);
|
|
1038
|
+
}
|
|
1039
|
+
if (worktree)
|
|
1040
|
+
(0, rail_worktrees_store_1.updateRailWorktreeState)(deps.db, worktree.id, 'built');
|
|
1041
|
+
const recoveredRow = (0, rail_pr_store_1.getPrDelivery)(deps.db, row.id);
|
|
1042
|
+
if (!recoveredRow || recoveredRow.operation_token !== row.operation_token) {
|
|
1043
|
+
return staleDecision(recoveredRow?.decision ?? row.decision);
|
|
1044
|
+
}
|
|
1045
|
+
deps.assertAdmission?.();
|
|
1046
|
+
return retryExistingPrFollowupPush(deps, recoveredRow);
|
|
1047
|
+
}
|
|
363
1048
|
async function retryExistingPrFollowupPush(deps, row) {
|
|
364
1049
|
if (!row.branch || !row.pr_url)
|
|
365
1050
|
return { status: 502, body: { error: 'push_failed', detail: 'missing PR branch/url' } };
|
|
@@ -380,21 +1065,51 @@ async function retryExistingPrFollowupPush(deps, row) {
|
|
|
380
1065
|
return persistRetryablePrObservationFailure(deps, row, `could not confirm the existing PR is open before retry: ${beforePush.detail}`);
|
|
381
1066
|
}
|
|
382
1067
|
if (!(0, pr_lifecycle_1.isExactOpenPr)(beforePush, row.branch, row.base_branch)) {
|
|
383
|
-
|
|
384
|
-
|
|
1068
|
+
const identityMatches = (0, pr_lifecycle_1.matchesRecordedPrIdentity)(beforePush, row.branch, row.base_branch);
|
|
1069
|
+
if (beforePush.state === 'MERGED' && identityMatches && beforePush.includesExpectedSha === true) {
|
|
1070
|
+
return settleMergedPr(deps, row);
|
|
385
1071
|
}
|
|
386
1072
|
if (beforePush.state === 'MERGED') {
|
|
387
|
-
return rerouteFromStalePr(deps, row, mergedEvidenceDetail(beforePush), false);
|
|
1073
|
+
return rerouteFromStalePr(deps, row, identityMatches ? mergedEvidenceDetail(beforePush) : 'the previous PR merged after its recorded head/base identity changed', false);
|
|
388
1074
|
}
|
|
389
1075
|
if (beforePush.state === 'CLOSED') {
|
|
1076
|
+
if (identityMatches && beforePush.includesExpectedSha === true) {
|
|
1077
|
+
return settleObservedClosedPr(deps, row, beforePush);
|
|
1078
|
+
}
|
|
390
1079
|
return rerouteFromStalePr(deps, row, 'the previous PR closed before this implementation was delivered', false);
|
|
391
1080
|
}
|
|
392
|
-
return
|
|
1081
|
+
return rerouteFromStalePr(deps, row, 'the existing open PR no longer matches its recorded head/base identity', false);
|
|
1082
|
+
}
|
|
1083
|
+
if (beforePush.includesExpectedSha === true) {
|
|
1084
|
+
return settleObservedExistingPr(deps, row, beforePush, false);
|
|
1085
|
+
}
|
|
1086
|
+
if (!beforePush.headRefOid) {
|
|
1087
|
+
return persistRetryablePrObservationFailure(deps, row, 'the open PR did not expose a verifiable head commit; Retry push will revalidate before mutation');
|
|
1088
|
+
}
|
|
1089
|
+
if (!(await commitObjectExists(deps, beforePush.headRefOid))) {
|
|
1090
|
+
try {
|
|
1091
|
+
await deps.git.run(['fetch', 'origin', `refs/heads/${row.branch}`], deps.project.path);
|
|
1092
|
+
}
|
|
1093
|
+
catch { /* the immutable object check below remains authoritative */ }
|
|
1094
|
+
}
|
|
1095
|
+
if (!(await commitObjectExists(deps, beforePush.headRefOid))) {
|
|
1096
|
+
return persistRetryablePrObservationFailure(deps, row, 'the live PR head object is unavailable locally; Retry push will revalidate before mutation');
|
|
1097
|
+
}
|
|
1098
|
+
if (!(await isFastForwardCandidate(deps, beforePush.headRefOid, row.delivery_sha))) {
|
|
1099
|
+
const detail = 'the exact delivery commit is not a fast-forward of the live PR head; it was not pushed';
|
|
1100
|
+
return row.is_continuation === 1
|
|
1101
|
+
? persistRecoveryBlocked(deps, row, `${detail} and remains protected`, row.delivery_sha)
|
|
1102
|
+
: persistMovedPrHead(deps, row, detail);
|
|
1103
|
+
}
|
|
1104
|
+
const remote = await (0, pr_lifecycle_1.verifyPushRemoteForPr)(deps.exec, deps.project.path, row.pr_url);
|
|
1105
|
+
if (!remote.ok) {
|
|
1106
|
+
return persistRetryablePrObservationFailure(deps, row, `refusing to push until the PR repository and origin are proven identical: ${remote.detail}`);
|
|
393
1107
|
}
|
|
394
1108
|
const pushed = await (0, pr_publisher_1.pushBranch)(deps.exec, {
|
|
395
1109
|
repoDir: deps.project.path,
|
|
396
1110
|
branch: row.branch,
|
|
397
1111
|
baseBranch: row.base_branch,
|
|
1112
|
+
remote: remote.pushTarget,
|
|
398
1113
|
sourceSha: row.delivery_sha,
|
|
399
1114
|
});
|
|
400
1115
|
if (pushed.state === 'local-only') {
|
|
@@ -414,21 +1129,25 @@ async function retryExistingPrFollowupPush(deps, row) {
|
|
|
414
1129
|
return persistRetryablePrObservationFailure(deps, row, `exact commit was pushed, but the PR lifecycle could not be confirmed: ${afterPush.detail}`);
|
|
415
1130
|
}
|
|
416
1131
|
if ((0, pr_lifecycle_1.isExactOpenPr)(afterPush, row.branch, row.base_branch)) {
|
|
417
|
-
if (afterPush.
|
|
418
|
-
return
|
|
1132
|
+
if (afterPush.includesExpectedSha !== true) {
|
|
1133
|
+
return persistRetryablePrObservationFailure(deps, row, 'the exact push completed, but the PR does not yet expose the verified commit as its head; Retry push remains safe and uses the preserved SHA');
|
|
419
1134
|
}
|
|
420
|
-
return settleObservedExistingPr(deps, row, afterPush);
|
|
1135
|
+
return settleObservedExistingPr(deps, row, afterPush, true);
|
|
421
1136
|
}
|
|
422
|
-
|
|
423
|
-
|
|
1137
|
+
const identityMatches = (0, pr_lifecycle_1.matchesRecordedPrIdentity)(afterPush, row.branch, row.base_branch);
|
|
1138
|
+
if (afterPush.state === 'MERGED' && identityMatches && afterPush.includesExpectedSha === true) {
|
|
1139
|
+
return settleMergedPr(deps, row);
|
|
424
1140
|
}
|
|
425
1141
|
if (afterPush.state === 'MERGED') {
|
|
426
|
-
return rerouteFromStalePr(deps, row, mergedEvidenceDetail(afterPush), true);
|
|
1142
|
+
return rerouteFromStalePr(deps, row, identityMatches ? mergedEvidenceDetail(afterPush) : 'the previous PR merged after its recorded head/base identity changed', true);
|
|
427
1143
|
}
|
|
428
1144
|
if (afterPush.state === 'CLOSED') {
|
|
1145
|
+
if (identityMatches && afterPush.includesExpectedSha === true) {
|
|
1146
|
+
return settleObservedClosedPr(deps, row, afterPush);
|
|
1147
|
+
}
|
|
429
1148
|
return rerouteFromStalePr(deps, row, 'the previous PR closed before this implementation was delivered', true);
|
|
430
1149
|
}
|
|
431
|
-
return
|
|
1150
|
+
return rerouteFromStalePr(deps, row, 'the existing open PR no longer matches its recorded head/base identity after the exact push', true);
|
|
432
1151
|
}
|
|
433
1152
|
/**
|
|
434
1153
|
* Load the PR's ticket data (title/labels/description) from the ticket store,
|
|
@@ -504,11 +1223,19 @@ async function runCreatePr(deps, row) {
|
|
|
504
1223
|
// belongs to the same ticket.
|
|
505
1224
|
let effectiveBranches = snap.branches;
|
|
506
1225
|
let branchEvidenceCaptured = false;
|
|
1226
|
+
const singleDeliverable = snap.branches.filter((unit) => unit.succeeded).length === 1;
|
|
1227
|
+
const frozenSingleSha = singleDeliverable && row.delivery_sha && COMMIT_SHA_RE.test(row.delivery_sha) &&
|
|
1228
|
+
await commitObjectExists(deps, row.delivery_sha)
|
|
1229
|
+
? row.delivery_sha
|
|
1230
|
+
: null;
|
|
507
1231
|
for (let index = 0; index < snap.branches.length; index++) {
|
|
508
1232
|
const unit = snap.branches[index];
|
|
509
1233
|
if (!unit.succeeded)
|
|
510
1234
|
continue;
|
|
511
|
-
|
|
1235
|
+
// A detached/stale single-unit delivery already has authoritative immutable
|
|
1236
|
+
// evidence. Prefer it over both legacy unit gaps and a branch ref that may
|
|
1237
|
+
// have advanced while the card waited for the user's decision.
|
|
1238
|
+
let sourceSha = frozenSingleSha ?? (unit.finalSha && COMMIT_SHA_RE.test(unit.finalSha) ? unit.finalSha : null);
|
|
512
1239
|
if (sourceSha) {
|
|
513
1240
|
if (!(await commitObjectExists(deps, sourceSha)))
|
|
514
1241
|
sourceSha = null;
|
|
@@ -668,11 +1395,19 @@ async function runCreatePr(deps, row) {
|
|
|
668
1395
|
if ((next === 'pr_draft' || next === 'pr_ready') && patch.prUrl) {
|
|
669
1396
|
patch.cleanupWarnings = await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
670
1397
|
db: deps.db, git: deps.git, repoDir: deps.project.path, worktreeIds: releasableWorktreeIds(deps, snap),
|
|
1398
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(effectiveBranches),
|
|
1399
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(effectiveBranches),
|
|
1400
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
671
1401
|
});
|
|
1402
|
+
if (patch.cleanupWarnings.length > 0)
|
|
1403
|
+
patch.statusCode = 'cleanup_incomplete';
|
|
672
1404
|
}
|
|
673
1405
|
const conflict = casTransition(deps, row, next, patch);
|
|
674
1406
|
if (conflict)
|
|
675
1407
|
return conflict;
|
|
1408
|
+
if ((next === 'pr_draft' || next === 'pr_ready') && patch.prUrl) {
|
|
1409
|
+
await releaseDeliveredRecoveryLineage(deps, row, patch.deliverySha ?? row.delivery_sha);
|
|
1410
|
+
}
|
|
676
1411
|
const after = finalizeTransition(deps, row.id);
|
|
677
1412
|
// Tickets stay on_review — a draft PR is still awaiting the engineer's merge.
|
|
678
1413
|
return {
|
|
@@ -687,6 +1422,32 @@ async function runCreatePr(deps, row) {
|
|
|
687
1422
|
};
|
|
688
1423
|
}
|
|
689
1424
|
async function runPublish(deps, row) {
|
|
1425
|
+
if (!row.delivery_sha || !row.branch) {
|
|
1426
|
+
return persistMovedPrHead(deps, row, 'the draft PR has no immutable delivery SHA/head identity; refusing to mutate unverifiable review state');
|
|
1427
|
+
}
|
|
1428
|
+
const beforePublish = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, row.pr_url, row.delivery_sha);
|
|
1429
|
+
if (!beforePublish.ok) {
|
|
1430
|
+
return { status: 502, body: { error: 'gh_failed', detail: beforePublish.detail } };
|
|
1431
|
+
}
|
|
1432
|
+
if (!(0, pr_lifecycle_1.matchesRecordedPrIdentity)(beforePublish, row.branch, row.base_branch)) {
|
|
1433
|
+
return rerouteFromStalePr(deps, row, `the recorded PR is ${beforePublish.state.toLowerCase()} but no longer matches its original head/base identity`, beforePublish.includesExpectedSha === true);
|
|
1434
|
+
}
|
|
1435
|
+
if (beforePublish.state === 'MERGED') {
|
|
1436
|
+
return beforePublish.includesExpectedSha === true
|
|
1437
|
+
? settleMergedPr(deps, row)
|
|
1438
|
+
: rerouteFromStalePr(deps, row, mergedEvidenceDetail(beforePublish), false);
|
|
1439
|
+
}
|
|
1440
|
+
if (beforePublish.state === 'CLOSED') {
|
|
1441
|
+
return beforePublish.includesExpectedSha === true
|
|
1442
|
+
? settleObservedClosedPr(deps, row, beforePublish)
|
|
1443
|
+
: rerouteFromStalePr(deps, row, 'the draft PR closed without the verified implementation commit', false);
|
|
1444
|
+
}
|
|
1445
|
+
if (beforePublish.includesExpectedSha !== true) {
|
|
1446
|
+
return persistRetryablePrObservationFailure(deps, row, 'the draft PR no longer exposes the verified implementation commit; Retry push is available and will use the preserved exact SHA');
|
|
1447
|
+
}
|
|
1448
|
+
if (beforePublish.isDraft === false) {
|
|
1449
|
+
return settleObservedExistingPr(deps, row, beforePublish, false);
|
|
1450
|
+
}
|
|
690
1451
|
let r;
|
|
691
1452
|
try {
|
|
692
1453
|
r = await deps.exec.run('gh', ['pr', 'ready', row.pr_url], deps.project.path);
|
|
@@ -694,46 +1455,53 @@ async function runPublish(deps, row) {
|
|
|
694
1455
|
catch (err) {
|
|
695
1456
|
r = { code: 1, stdout: '', stderr: err instanceof Error ? err.message : String(err) };
|
|
696
1457
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
if (lifecycle?.state === 'CLOSED') {
|
|
703
|
-
const conflict = casTransition(deps, row, 'pr_closed', {
|
|
704
|
-
deliveryOutcome: 'delivered', statusCode: 'pr_closed',
|
|
705
|
-
});
|
|
706
|
-
if (conflict)
|
|
707
|
-
return conflict;
|
|
708
|
-
finalizeTransition(deps, row.id);
|
|
709
|
-
return { status: 200, body: { ok: true, decision: 'pr_closed', closed: true, prUrl: row.pr_url } };
|
|
710
|
-
}
|
|
711
|
-
if (lifecycle?.state !== 'OPEN' || lifecycle.isDraft)
|
|
1458
|
+
// `gh pr ready` is externally mutating and may return an ambiguous error.
|
|
1459
|
+
// Re-observe exact remote truth in every case before changing the ledger.
|
|
1460
|
+
const afterPublish = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, row.pr_url, row.delivery_sha);
|
|
1461
|
+
if (!afterPublish.ok) {
|
|
1462
|
+
if (r.code !== 0)
|
|
712
1463
|
return ghFailed(r);
|
|
1464
|
+
return { status: 502, body: { error: 'gh_failed', detail: `PR readiness could not be verified: ${afterPublish.detail}` } };
|
|
713
1465
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
1466
|
+
if (!(0, pr_lifecycle_1.matchesRecordedPrIdentity)(afterPublish, row.branch, row.base_branch)) {
|
|
1467
|
+
return rerouteFromStalePr(deps, row, `the PR identity changed while publishing it for review (${afterPublish.state.toLowerCase()})`, afterPublish.includesExpectedSha === true);
|
|
1468
|
+
}
|
|
1469
|
+
if (afterPublish.state === 'MERGED') {
|
|
1470
|
+
return afterPublish.includesExpectedSha === true
|
|
1471
|
+
? settleMergedPr(deps, row)
|
|
1472
|
+
: rerouteFromStalePr(deps, row, mergedEvidenceDetail(afterPublish), false);
|
|
1473
|
+
}
|
|
1474
|
+
if (afterPublish.state === 'CLOSED') {
|
|
1475
|
+
return afterPublish.includesExpectedSha === true
|
|
1476
|
+
? settleObservedClosedPr(deps, row, afterPublish)
|
|
1477
|
+
: rerouteFromStalePr(deps, row, 'the PR closed without the verified implementation commit while being published', false);
|
|
1478
|
+
}
|
|
1479
|
+
if (afterPublish.includesExpectedSha !== true) {
|
|
1480
|
+
return persistRetryablePrObservationFailure(deps, row, 'the PR no longer exposes the verified implementation commit after publishing; Retry push is available');
|
|
1481
|
+
}
|
|
1482
|
+
if (afterPublish.isDraft) {
|
|
1483
|
+
if (r.code !== 0)
|
|
1484
|
+
return ghFailed(r);
|
|
1485
|
+
return { status: 502, body: { error: 'gh_failed', detail: 'PR remained a draft after publishing' } };
|
|
1486
|
+
}
|
|
1487
|
+
return settleObservedExistingPr(deps, row, afterPublish, false);
|
|
725
1488
|
}
|
|
726
1489
|
async function runDiscard(deps, row, opts = { removeNeedsReview: true }) {
|
|
727
1490
|
const snap = (0, rail_pr_store_1.toPrDeliverySnapshot)(row);
|
|
728
1491
|
const implementationFailed = row.decision === 'implementation_failed';
|
|
729
|
-
|
|
1492
|
+
// PR lifecycle ownership and head-ref ownership are separate. Startup repairs
|
|
1493
|
+
// historical continuation rows before admission opens; only that durable bit
|
|
1494
|
+
// borrows the PR/ticket lifecycle. Per-unit ownership below independently
|
|
1495
|
+
// prevents deletion of borrowed/pre-existing head refs for fresh replacements.
|
|
1496
|
+
const preserveExternalReview = row.is_continuation === 1;
|
|
730
1497
|
const cleanupWarnings = [];
|
|
731
1498
|
// A continuation borrows an existing PR/head. Discarding its local iteration
|
|
732
1499
|
// may remove Specrails' worktree, but never closes or deletes borrowed review
|
|
733
|
-
// state.
|
|
734
|
-
|
|
1500
|
+
// state. A fresh PR is closed without GitHub's unleased --delete-branch: its
|
|
1501
|
+
// remote head may have advanced since the card was rendered.
|
|
1502
|
+
if (row.pr_url && !implementationFailed && !preserveExternalReview) {
|
|
735
1503
|
try {
|
|
736
|
-
const r = await deps.exec.run('gh', ['pr', 'close', row.pr_url
|
|
1504
|
+
const r = await deps.exec.run('gh', ['pr', 'close', row.pr_url], deps.project.path);
|
|
737
1505
|
if (r.code !== 0) {
|
|
738
1506
|
const detail = (r.stderr.trim() || r.stdout.trim()).split('\n')[0] || `exit ${r.code}`;
|
|
739
1507
|
cleanupWarnings.push(`PR close ${row.pr_url}: ${detail}`);
|
|
@@ -745,59 +1513,82 @@ async function runDiscard(deps, row, opts = { removeNeedsReview: true }) {
|
|
|
745
1513
|
console.warn('[rail-pr-decision] gh pr close threw (continuing discard):', err);
|
|
746
1514
|
}
|
|
747
1515
|
}
|
|
748
|
-
// 2.
|
|
749
|
-
//
|
|
750
|
-
//
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
try {
|
|
762
|
-
await (0, worktree_manager_1.removeWorktree)(deps.git, {
|
|
763
|
-
repoDir: deps.project.path, worktreePath: wt.worktree_path, branch: wt.branch, deleteBranch: false,
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
catch (err) {
|
|
767
|
-
const detail = err instanceof Error ? err.message : String(err);
|
|
768
|
-
cleanupWarnings.push(`worktree ${wt.worktree_path}: ${detail}`);
|
|
769
|
-
console.warn(`[rail-pr-decision] discard could not remove worktree ${wt.worktree_path}: ${detail}`);
|
|
770
|
-
continue;
|
|
771
|
-
}
|
|
772
|
-
if (!(0, rail_worktrees_store_1.isTerminalMergeState)(wt.merge_state))
|
|
773
|
-
(0, rail_worktrees_store_1.updateRailWorktreeState)(deps.db, wt.id, 'failed');
|
|
1516
|
+
// 2. Release only worktrees whose live tracked/untracked/ignored state and
|
|
1517
|
+
// exact HEAD/ref still match durable settlement evidence. Explicit
|
|
1518
|
+
// discard is not permission to contradict the confirmation copy by
|
|
1519
|
+
// force-removing subsequently changed local work. Authenticated overlays
|
|
1520
|
+
// take the same lossless quarantine path as automatic settlement.
|
|
1521
|
+
const deleteOwnedBranches = !implementationFailed && !preserveExternalReview;
|
|
1522
|
+
const skippedNeedsReview = opts.removeNeedsReview === true
|
|
1523
|
+
? []
|
|
1524
|
+
: snap.worktreeIds
|
|
1525
|
+
.map((wtId) => (0, rail_worktrees_store_1.getRailWorktree)(deps.db, wtId))
|
|
1526
|
+
.filter((wt) => wt?.merge_state === 'needs-review');
|
|
1527
|
+
for (const worktree of skippedNeedsReview) {
|
|
1528
|
+
cleanupWarnings.push(`worktree ${worktree.worktree_path}: preserved for inspection because it already requires review`);
|
|
774
1529
|
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
1530
|
+
const skippedIds = new Set(skippedNeedsReview.map((wt) => wt.id));
|
|
1531
|
+
const worktreeIds = snap.worktreeIds.filter((wtId) => !skippedIds.has(wtId));
|
|
1532
|
+
cleanupWarnings.push(...await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
1533
|
+
db: deps.db,
|
|
1534
|
+
git: deps.git,
|
|
1535
|
+
repoDir: deps.project.path,
|
|
1536
|
+
worktreeIds,
|
|
1537
|
+
state: 'failed',
|
|
1538
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
1539
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
1540
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
1541
|
+
}));
|
|
1542
|
+
const retainedWorktreeBranches = new Set(snap.worktreeIds
|
|
1543
|
+
.map((wtId) => (0, rail_worktrees_store_1.getRailWorktree)(deps.db, wtId))
|
|
1544
|
+
.filter((wt) => Boolean(wt && (wt.merge_state === 'needs-review' || fs.existsSync(wt.worktree_path))))
|
|
1545
|
+
.map((wt) => wt.branch));
|
|
1546
|
+
// 3. Delete only branches this delivery durably records as created, and only
|
|
1547
|
+
// while their live tips still equal the immutable delivered commits.
|
|
1548
|
+
// Later user/collaborator commits are retained with a cleanup warning.
|
|
780
1549
|
if (deleteOwnedBranches) {
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1550
|
+
await deleteOwnedBranchesIfUnchanged(deps, row, snap, cleanupWarnings, retainedWorktreeBranches);
|
|
1551
|
+
}
|
|
1552
|
+
// Explicit Discard local result is also the only authority (besides proven
|
|
1553
|
+
// delivery) to release a pinned orphan. A crash can occur after the atomic
|
|
1554
|
+
// ref creation but before delivery_sha is written, so recover that ownership
|
|
1555
|
+
// only from this delivery's exact durable final SHA or run-marker evidence.
|
|
1556
|
+
if (opts.removeNeedsReview === true) {
|
|
1557
|
+
let recoverySha = row.delivery_sha && COMMIT_SHA_RE.test(row.delivery_sha)
|
|
1558
|
+
? row.delivery_sha.toLowerCase()
|
|
1559
|
+
: null;
|
|
1560
|
+
if (!recoverySha && row.is_continuation === 1 &&
|
|
1561
|
+
(row.status_code === 'settlement_interrupted' || row.status_code === 'recovery_unavailable')) {
|
|
1562
|
+
const protection = await (0, rail_pr_recovery_git_1.inspectRecoveryCommitProtection)(deps.git, deps.project.path, row.id);
|
|
1563
|
+
if (protection.kind === 'present') {
|
|
1564
|
+
const durableFinalShas = [...new Set(snap.branches
|
|
1565
|
+
.map((unit) => unit.finalSha)
|
|
1566
|
+
.filter((sha) => typeof sha === 'string' && COMMIT_SHA_RE.test(sha))
|
|
1567
|
+
.map((sha) => sha.toLowerCase()))];
|
|
1568
|
+
const runIds = [...new Set(snap.runIds.filter(Boolean))];
|
|
1569
|
+
const exactDurableFinal = durableFinalShas.length === 1 && durableFinalShas[0] === protection.sha;
|
|
1570
|
+
const exactRunMarker = runIds.length === 1 && await (0, rail_pr_recovery_git_1.commitCarriesRunMarker)(deps.git, deps.project.path, protection.sha, runIds[0]);
|
|
1571
|
+
if (exactDurableFinal || exactRunMarker) {
|
|
1572
|
+
recoverySha = protection.sha;
|
|
1573
|
+
}
|
|
1574
|
+
else {
|
|
1575
|
+
cleanupWarnings.push(`recovery ref ${protection.ref}: preserved because its commit could not be proven to belong to this delivery`);
|
|
788
1576
|
}
|
|
789
1577
|
}
|
|
790
|
-
|
|
791
|
-
cleanupWarnings.push(`
|
|
1578
|
+
else if (protection.kind === 'unreadable') {
|
|
1579
|
+
cleanupWarnings.push(`recovery ref ${protection.ref}: preserved because its exact commit could not be read safely`);
|
|
792
1580
|
}
|
|
793
1581
|
}
|
|
1582
|
+
if (recoverySha && !await (0, rail_pr_recovery_git_1.releaseRecoveryCommit)(deps.git, deps.project.path, row.id, recoverySha)) {
|
|
1583
|
+
cleanupWarnings.push('the delivery recovery ref changed or could not be removed; it was preserved for inspection');
|
|
1584
|
+
}
|
|
794
1585
|
}
|
|
795
1586
|
const terminalPatch = {
|
|
796
1587
|
deliveryOutcome: 'not_started',
|
|
797
1588
|
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : 'discarded',
|
|
798
1589
|
cleanupWarnings,
|
|
799
1590
|
};
|
|
800
|
-
const conflict =
|
|
1591
|
+
const conflict = preserveExternalReview
|
|
801
1592
|
? casTransition(deps, row, 'discarded', terminalPatch)
|
|
802
1593
|
: casTransitionWithTicketEffect(deps, row, 'discarded', terminalPatch, {
|
|
803
1594
|
deliveryId: row.id,
|
|
@@ -810,7 +1601,7 @@ async function runDiscard(deps, row, opts = { removeNeedsReview: true }) {
|
|
|
810
1601
|
});
|
|
811
1602
|
if (conflict)
|
|
812
1603
|
return conflict;
|
|
813
|
-
if (!
|
|
1604
|
+
if (!preserveExternalReview)
|
|
814
1605
|
applyTerminalTicketEffect(deps, row, 'discarded', cleanupWarnings);
|
|
815
1606
|
finalizeTransition(deps, row.id);
|
|
816
1607
|
return {
|
|
@@ -819,7 +1610,7 @@ async function runDiscard(deps, row, opts = { removeNeedsReview: true }) {
|
|
|
819
1610
|
ok: true,
|
|
820
1611
|
decision: 'discarded',
|
|
821
1612
|
...(cleanupWarnings.length > 0 ? { cleanupWarnings } : {}),
|
|
822
|
-
...(
|
|
1613
|
+
...(preserveExternalReview ? { preservedBorrowedReview: true, preservedExternalReview: true } : {}),
|
|
823
1614
|
},
|
|
824
1615
|
};
|
|
825
1616
|
}
|
|
@@ -835,6 +1626,9 @@ async function runAcknowledgeNoChanges(deps, row) {
|
|
|
835
1626
|
git: deps.git,
|
|
836
1627
|
repoDir: deps.project.path,
|
|
837
1628
|
worktreeIds: snap.worktreeIds,
|
|
1629
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
1630
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
1631
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
838
1632
|
});
|
|
839
1633
|
// A fresh no-change branch is disposable only while Git still proves that it
|
|
840
1634
|
// has no commits ahead of the integration base. If the user added work after
|
|
@@ -882,21 +1676,89 @@ async function runAcknowledgeNoChanges(deps, row) {
|
|
|
882
1676
|
},
|
|
883
1677
|
};
|
|
884
1678
|
}
|
|
1679
|
+
async function settleMergedPr(deps, row) {
|
|
1680
|
+
const snap = (0, rail_pr_store_1.toPrDeliverySnapshot)(row);
|
|
1681
|
+
const cleanupWarnings = await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
1682
|
+
db: deps.db, git: deps.git, repoDir: deps.project.path,
|
|
1683
|
+
worktreeIds: releasableWorktreeIds(deps, snap), state: 'merged',
|
|
1684
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
1685
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
1686
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
1687
|
+
});
|
|
1688
|
+
await deleteOwnedBranchesIfUnchanged(deps, row, snap, cleanupWarnings);
|
|
1689
|
+
const conflict = casTransitionWithTicketEffect(deps, row, 'merged', {
|
|
1690
|
+
deliveryOutcome: 'delivered',
|
|
1691
|
+
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : 'merged',
|
|
1692
|
+
statusDetail: null,
|
|
1693
|
+
cleanupWarnings,
|
|
1694
|
+
}, {
|
|
1695
|
+
deliveryId: row.id,
|
|
1696
|
+
ticketIds: snap.ticketIds,
|
|
1697
|
+
targetStatus: 'done',
|
|
1698
|
+
jiraAction: 'merged',
|
|
1699
|
+
prUrl: row.pr_url,
|
|
1700
|
+
});
|
|
1701
|
+
if (conflict)
|
|
1702
|
+
return conflict;
|
|
1703
|
+
await releaseDeliveredRecoveryLineage(deps, row, row.delivery_sha);
|
|
1704
|
+
applyTerminalTicketEffect(deps, row, 'merged', cleanupWarnings);
|
|
1705
|
+
finalizeTransition(deps, row.id);
|
|
1706
|
+
return {
|
|
1707
|
+
status: 200,
|
|
1708
|
+
body: {
|
|
1709
|
+
ok: true,
|
|
1710
|
+
decision: 'merged',
|
|
1711
|
+
merged: true,
|
|
1712
|
+
prUrl: row.pr_url,
|
|
1713
|
+
...(row.delivery_sha ? {
|
|
1714
|
+
deliveryVerified: true,
|
|
1715
|
+
verifiedSha: row.delivery_sha,
|
|
1716
|
+
pushed: false,
|
|
1717
|
+
} : {}),
|
|
1718
|
+
},
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
885
1721
|
async function runPollMerge(deps, row) {
|
|
886
1722
|
const observed = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, row.pr_url, row.delivery_sha);
|
|
887
1723
|
if (!observed.ok)
|
|
888
1724
|
return { status: 502, body: { error: 'gh_failed', detail: observed.detail } };
|
|
889
1725
|
const { state, isDraft } = observed;
|
|
1726
|
+
if (!row.branch) {
|
|
1727
|
+
return persistMovedPrHead(deps, row, `the ${state.toLowerCase()} PR has no recorded delivery branch; refusing to infer recoverable work`);
|
|
1728
|
+
}
|
|
1729
|
+
if (!row.delivery_sha) {
|
|
1730
|
+
// A legacy OPEN row cannot be retried without an immutable object. Once the
|
|
1731
|
+
// attached PR is terminal, however, keeping that stale URL would strand the
|
|
1732
|
+
// only recorded branch behind Discard. Detach it so Create PR can perform
|
|
1733
|
+
// the existing one-time legacy ref capture, without claiming any delivery.
|
|
1734
|
+
if (state === 'CLOSED' || state === 'MERGED') {
|
|
1735
|
+
return rerouteFromStalePr(deps, row, `the previous PR is ${state.toLowerCase()} and this legacy delivery has no persisted verified SHA`, false);
|
|
1736
|
+
}
|
|
1737
|
+
return persistMovedPrHead(deps, row, 'the open PR has no persisted verified delivery SHA; refusing to infer delivery from a mutable branch');
|
|
1738
|
+
}
|
|
1739
|
+
if (!(0, pr_lifecycle_1.matchesRecordedPrIdentity)(observed, row.branch, row.base_branch)) {
|
|
1740
|
+
return rerouteFromStalePr(deps, row, `the recorded PR is ${state.toLowerCase()} but no longer matches its original head/base identity`, observed.includesExpectedSha === true);
|
|
1741
|
+
}
|
|
890
1742
|
if (state === 'CLOSED') {
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
return conflict;
|
|
896
|
-
finalizeTransition(deps, row.id);
|
|
897
|
-
return { status: 200, body: { ok: true, decision: 'pr_closed', merged: false, closed: true, prUrl: row.pr_url } };
|
|
1743
|
+
if (observed.includesExpectedSha !== true) {
|
|
1744
|
+
return rerouteFromStalePr(deps, row, 'the previous PR closed without the verified implementation commit', false);
|
|
1745
|
+
}
|
|
1746
|
+
return settleObservedClosedPr(deps, row, observed);
|
|
898
1747
|
}
|
|
899
1748
|
if (state === 'OPEN') {
|
|
1749
|
+
if (observed.includesExpectedSha !== true) {
|
|
1750
|
+
const detail = 'the open PR no longer exposes the verified implementation commit; Retry push is available and will use the preserved exact SHA';
|
|
1751
|
+
const result = persistRetryablePrObservationFailure(deps, row, detail);
|
|
1752
|
+
return {
|
|
1753
|
+
...result,
|
|
1754
|
+
body: {
|
|
1755
|
+
...result.body,
|
|
1756
|
+
deliveryVerified: false,
|
|
1757
|
+
verifiedSha: row.delivery_sha,
|
|
1758
|
+
remoteHeadSha: observed.headRefOid,
|
|
1759
|
+
},
|
|
1760
|
+
};
|
|
1761
|
+
}
|
|
900
1762
|
// A successful reopen can be observed even if the explicit action lost its
|
|
901
1763
|
// follow-up `gh view` response. Polling heals pr_closed from remote truth.
|
|
902
1764
|
if (row.decision === 'pr_closed') {
|
|
@@ -907,9 +1769,33 @@ async function runPollMerge(deps, row) {
|
|
|
907
1769
|
if (conflict)
|
|
908
1770
|
return conflict;
|
|
909
1771
|
finalizeTransition(deps, row.id);
|
|
910
|
-
return {
|
|
1772
|
+
return {
|
|
1773
|
+
status: 200,
|
|
1774
|
+
body: {
|
|
1775
|
+
ok: true,
|
|
1776
|
+
decision: next,
|
|
1777
|
+
merged: false,
|
|
1778
|
+
reopened: true,
|
|
1779
|
+
prUrl: row.pr_url,
|
|
1780
|
+
deliveryVerified: true,
|
|
1781
|
+
verifiedSha: row.delivery_sha,
|
|
1782
|
+
remoteHeadSha: observed.headRefOid,
|
|
1783
|
+
pushed: false,
|
|
1784
|
+
},
|
|
1785
|
+
};
|
|
911
1786
|
}
|
|
912
|
-
return {
|
|
1787
|
+
return {
|
|
1788
|
+
status: 200,
|
|
1789
|
+
body: {
|
|
1790
|
+
ok: true,
|
|
1791
|
+
decision: row.decision,
|
|
1792
|
+
merged: false,
|
|
1793
|
+
deliveryVerified: true,
|
|
1794
|
+
verifiedSha: row.delivery_sha,
|
|
1795
|
+
remoteHeadSha: observed.headRefOid,
|
|
1796
|
+
pushed: false,
|
|
1797
|
+
},
|
|
1798
|
+
};
|
|
913
1799
|
}
|
|
914
1800
|
if (state !== 'MERGED') {
|
|
915
1801
|
return { status: 502, body: { error: 'gh_failed', detail: `unexpected PR state: ${state}` } };
|
|
@@ -917,49 +1803,43 @@ async function runPollMerge(deps, row) {
|
|
|
917
1803
|
// A PR can merge just before a continuation push; GitHub may then accept a
|
|
918
1804
|
// later update to the head branch even though that object was never part of
|
|
919
1805
|
// the merge. Never move tickets to Done from state=MERGED alone.
|
|
920
|
-
if (!row.delivery_sha) {
|
|
921
|
-
return persistMovedPrHead(deps, row, 'the merged PR has no persisted verified delivery SHA; refusing to infer delivery from a mutable branch');
|
|
922
|
-
}
|
|
923
1806
|
if (observed.includesExpectedSha !== true) {
|
|
924
|
-
return rerouteFromStalePr(deps, row, mergedEvidenceDetail(observed),
|
|
1807
|
+
return rerouteFromStalePr(deps, row, mergedEvidenceDetail(observed), false);
|
|
925
1808
|
}
|
|
926
|
-
|
|
927
|
-
const cleanupWarnings = await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
928
|
-
db: deps.db, git: deps.git, repoDir: deps.project.path,
|
|
929
|
-
worktreeIds: releasableWorktreeIds(deps, snap), state: 'merged',
|
|
930
|
-
});
|
|
931
|
-
const branchSet = ownedDeliveryBranches(row, snap, cleanupWarnings);
|
|
932
|
-
for (const branch of branchSet) {
|
|
933
|
-
if (!branch || branch === row.base_branch)
|
|
934
|
-
continue;
|
|
935
|
-
try {
|
|
936
|
-
const deleted = await deps.git.run(['branch', '-D', branch], deps.project.path);
|
|
937
|
-
if (deleted.code !== 0) {
|
|
938
|
-
cleanupWarnings.push(`branch ${branch}: ${(deleted.stderr.trim() || deleted.stdout.trim()).split('\n')[0] || `exit ${deleted.code}`}`);
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
catch (err) {
|
|
942
|
-
cleanupWarnings.push(`branch ${branch}: ${err instanceof Error ? err.message : String(err)}`);
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
const conflict = casTransitionWithTicketEffect(deps, row, 'merged', {
|
|
946
|
-
deliveryOutcome: 'delivered',
|
|
947
|
-
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : 'merged',
|
|
948
|
-
cleanupWarnings,
|
|
949
|
-
}, {
|
|
950
|
-
deliveryId: row.id,
|
|
951
|
-
ticketIds: snap.ticketIds,
|
|
952
|
-
targetStatus: 'done',
|
|
953
|
-
jiraAction: 'merged',
|
|
954
|
-
prUrl: row.pr_url,
|
|
955
|
-
});
|
|
956
|
-
if (conflict)
|
|
957
|
-
return conflict;
|
|
958
|
-
applyTerminalTicketEffect(deps, row, 'merged', cleanupWarnings);
|
|
959
|
-
finalizeTransition(deps, row.id);
|
|
960
|
-
return { status: 200, body: { ok: true, decision: 'merged', merged: true, prUrl: row.pr_url } };
|
|
1809
|
+
return settleMergedPr(deps, row);
|
|
961
1810
|
}
|
|
962
1811
|
async function runReopen(deps, row) {
|
|
1812
|
+
if (!row.delivery_sha || !row.branch) {
|
|
1813
|
+
return rerouteFromStalePr(deps, row, 'the closed PR cannot be reopened safely because its immutable delivery SHA/head identity is unavailable', false);
|
|
1814
|
+
}
|
|
1815
|
+
const beforeReopen = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, row.pr_url, row.delivery_sha);
|
|
1816
|
+
if (!beforeReopen.ok) {
|
|
1817
|
+
return { status: 502, body: { error: 'gh_failed', detail: beforeReopen.detail } };
|
|
1818
|
+
}
|
|
1819
|
+
if (!(0, pr_lifecycle_1.matchesRecordedPrIdentity)(beforeReopen, row.branch, row.base_branch) ||
|
|
1820
|
+
beforeReopen.includesExpectedSha !== true) {
|
|
1821
|
+
return rerouteFromStalePr(deps, row, 'the closed PR no longer proves the recorded head/base and verified implementation commit', false);
|
|
1822
|
+
}
|
|
1823
|
+
if (beforeReopen.state === 'MERGED')
|
|
1824
|
+
return settleMergedPr(deps, row);
|
|
1825
|
+
if (beforeReopen.state === 'OPEN') {
|
|
1826
|
+
const next = beforeReopen.isDraft ? 'pr_draft' : 'pr_ready';
|
|
1827
|
+
const conflict = casTransition(deps, row, next, {
|
|
1828
|
+
deliveryOutcome: 'delivered', statusCode: beforeReopen.isDraft ? 'pr_draft_ready' : 'pr_ready',
|
|
1829
|
+
statusDetail: null,
|
|
1830
|
+
});
|
|
1831
|
+
if (conflict)
|
|
1832
|
+
return conflict;
|
|
1833
|
+
finalizeTransition(deps, row.id);
|
|
1834
|
+
return {
|
|
1835
|
+
status: 200,
|
|
1836
|
+
body: {
|
|
1837
|
+
ok: true, decision: next, reopened: true, prUrl: row.pr_url,
|
|
1838
|
+
deliveryVerified: true, verifiedSha: row.delivery_sha,
|
|
1839
|
+
remoteHeadSha: beforeReopen.headRefOid, pushed: false,
|
|
1840
|
+
},
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
963
1843
|
let reopened;
|
|
964
1844
|
try {
|
|
965
1845
|
reopened = await deps.exec.run('gh', ['pr', 'reopen', row.pr_url], deps.project.path);
|
|
@@ -967,20 +1847,45 @@ async function runReopen(deps, row) {
|
|
|
967
1847
|
catch (err) {
|
|
968
1848
|
reopened = { code: 1, stdout: '', stderr: err instanceof Error ? err.message : String(err) };
|
|
969
1849
|
}
|
|
970
|
-
const
|
|
971
|
-
if (
|
|
1850
|
+
const observed = await (0, pr_lifecycle_1.observePrLifecycle)(deps.exec, deps.project.path, row.pr_url, row.delivery_sha);
|
|
1851
|
+
if (!observed.ok) {
|
|
972
1852
|
if (reopened.code !== 0)
|
|
973
1853
|
return ghFailed(reopened);
|
|
974
|
-
return { status: 502, body: { error: 'gh_failed', detail:
|
|
1854
|
+
return { status: 502, body: { error: 'gh_failed', detail: observed.detail } };
|
|
1855
|
+
}
|
|
1856
|
+
const identityMatches = (0, pr_lifecycle_1.matchesRecordedPrIdentity)(observed, row.branch, row.base_branch);
|
|
1857
|
+
if (observed.state === 'MERGED') {
|
|
1858
|
+
if (identityMatches && observed.includesExpectedSha === true)
|
|
1859
|
+
return settleMergedPr(deps, row);
|
|
1860
|
+
return rerouteFromStalePr(deps, row, identityMatches ? mergedEvidenceDetail(observed) : 'the PR identity changed while it was being reopened', false);
|
|
1861
|
+
}
|
|
1862
|
+
if (observed.state === 'CLOSED') {
|
|
1863
|
+
if (!identityMatches || observed.includesExpectedSha !== true) {
|
|
1864
|
+
return rerouteFromStalePr(deps, row, 'the PR remained closed without proving the recorded head/base and verified implementation commit', false);
|
|
1865
|
+
}
|
|
1866
|
+
if (reopened.code !== 0)
|
|
1867
|
+
return ghFailed(reopened);
|
|
1868
|
+
return { status: 502, body: { error: 'gh_failed', detail: 'PR remained closed after reopen' } };
|
|
975
1869
|
}
|
|
976
|
-
|
|
1870
|
+
if (!identityMatches || observed.includesExpectedSha !== true) {
|
|
1871
|
+
return rerouteFromStalePr(deps, row, 'the reopened PR no longer proves the recorded head/base and verified implementation commit', true);
|
|
1872
|
+
}
|
|
1873
|
+
const next = observed.isDraft ? 'pr_draft' : 'pr_ready';
|
|
977
1874
|
const conflict = casTransition(deps, row, next, {
|
|
978
|
-
deliveryOutcome: 'delivered', statusCode:
|
|
1875
|
+
deliveryOutcome: 'delivered', statusCode: observed.isDraft ? 'pr_draft_ready' : 'pr_ready',
|
|
1876
|
+
statusDetail: null,
|
|
979
1877
|
});
|
|
980
1878
|
if (conflict)
|
|
981
1879
|
return conflict;
|
|
982
1880
|
finalizeTransition(deps, row.id);
|
|
983
|
-
return {
|
|
1881
|
+
return {
|
|
1882
|
+
status: 200,
|
|
1883
|
+
body: {
|
|
1884
|
+
ok: true, decision: next, reopened: true, prUrl: row.pr_url,
|
|
1885
|
+
deliveryVerified: true, verifiedSha: row.delivery_sha,
|
|
1886
|
+
remoteHeadSha: observed.headRefOid, pushed: false,
|
|
1887
|
+
},
|
|
1888
|
+
};
|
|
984
1889
|
}
|
|
985
1890
|
async function runMergeLocal(deps, row) {
|
|
986
1891
|
return (0, repo_lock_1.withRepoLock)(deps.project.path, () => runMergeLocalLocked(deps, row));
|
|
@@ -1136,38 +2041,17 @@ async function runMergeLocalLocked(deps, row) {
|
|
|
1136
2041
|
await removeAssembly();
|
|
1137
2042
|
// Post-advance sweep: the work now lives on
|
|
1138
2043
|
// the integration branch, so the launch's worktrees + branches are spent.
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
const detail = err instanceof Error ? err.message : String(err);
|
|
1151
|
-
cleanupWarnings.push(`worktree ${wt.worktree_path}: ${detail}`);
|
|
1152
|
-
console.warn(`[rail-pr-decision] merge-local could not remove worktree ${wt.worktree_path}: ${detail}`);
|
|
1153
|
-
continue;
|
|
1154
|
-
}
|
|
1155
|
-
if (!(0, rail_worktrees_store_1.isTerminalMergeState)(wt.merge_state))
|
|
1156
|
-
(0, rail_worktrees_store_1.updateRailWorktreeState)(deps.db, wt.id, 'merged');
|
|
1157
|
-
}
|
|
1158
|
-
for (const branch of branchSet) {
|
|
1159
|
-
if (!branch || branch === row.base_branch)
|
|
1160
|
-
continue;
|
|
1161
|
-
try {
|
|
1162
|
-
const deleted = await deps.git.run(['branch', '-D', branch], deps.project.path);
|
|
1163
|
-
if (deleted.code !== 0) {
|
|
1164
|
-
cleanupWarnings.push(`branch ${branch}: ${(deleted.stderr.trim() || deleted.stdout.trim()).split('\n')[0] || `exit ${deleted.code}`}`);
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
catch (err) {
|
|
1168
|
-
cleanupWarnings.push(`branch ${branch}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
2044
|
+
cleanupWarnings.push(...await (0, rail_worktree_release_1.releaseRailWorktrees)({
|
|
2045
|
+
db: deps.db,
|
|
2046
|
+
git: deps.git,
|
|
2047
|
+
repoDir: deps.project.path,
|
|
2048
|
+
worktreeIds: releasableWorktreeIds(deps, snap),
|
|
2049
|
+
state: 'merged',
|
|
2050
|
+
expectedHeadByBranch: (0, rail_worktree_release_1.durableBranchHeads)(snap.branches),
|
|
2051
|
+
overlayEvidenceByBranch: (0, rail_worktree_release_1.durableOverlayCleanupEvidence)(snap.branches),
|
|
2052
|
+
onSafetyArchive: safetyArchiveRecorder(deps, row),
|
|
2053
|
+
}));
|
|
2054
|
+
await deleteOwnedBranchesIfUnchanged(deps, row, snap, cleanupWarnings);
|
|
1171
2055
|
const conflict = casTransitionWithTicketEffect(deps, row, 'merged', {
|
|
1172
2056
|
deliveryOutcome: 'delivered',
|
|
1173
2057
|
statusCode: cleanupWarnings.length > 0 ? 'cleanup_incomplete' : 'merged',
|