looply-cli 0.5.38 → 0.5.39

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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_LOGIN_RETRIES = exports.FAILED_RECHECK_MS = exports.FOLLOW_DEPLOYS_MS = exports.NO_CHECKS_GRACE_MS = exports.CHECKS_PATIENCE_MS = exports.BRANCH_DELIVERIES_FILE = void 0;
3
+ exports.MAX_LOGIN_RETRIES = exports.FAILED_RECHECK_MS = exports.LIVE_BUILDING_DEADLINE_MS = exports.LIVE_DEADLINE_MS = exports.FOLLOW_DEPLOYS_MS = exports.NO_CHECKS_GRACE_MS = exports.REJUDGE_MAX_AGE_MS = exports.CHECKS_PATIENCE_MS = exports.BRANCH_DELIVERIES_FILE = void 0;
4
4
  exports.nodeDeliveryGit = nodeDeliveryGit;
5
5
  exports.makeDeployPush = makeDeployPush;
6
6
  exports.makeDeployTip = makeDeployTip;
@@ -25,6 +25,8 @@ exports.redOnBase = redOnBase;
25
25
  exports.redBaseNote = redBaseNote;
26
26
  exports.advanceDeliveries = advanceDeliveries;
27
27
  exports.noNewCommits = noNewCommits;
28
+ exports.conflictMoved = conflictMoved;
29
+ exports.ticketAttemptOf = ticketAttemptOf;
28
30
  exports.herokuLoginSentence = herokuLoginSentence;
29
31
  exports.herokuAuthRefusal = herokuAuthRefusal;
30
32
  exports.makeReleaseRunner = makeReleaseRunner;
@@ -515,6 +517,12 @@ function pullBody(input) {
515
517
  lines.push('');
516
518
  lines.push(`This branch was rebuilt from \`${input.rebuilt.from}\` onto the base with only this goal's own commits: ${input.rebuilt.without}.`);
517
519
  }
520
+ if (input.conflictWith) {
521
+ const c = input.conflictWith;
522
+ lines.push('');
523
+ lines.push(`This branch was rebuilt from \`${c.from}\` onto the current \`${c.base}\`, because ${c.replaces ?? 'its earlier pull request'} conflicted with it. ` +
524
+ "It holds the same changes, each of this goal's commits applied as it was; nothing was resolved by guesswork.");
525
+ }
518
526
  if (input.foreign) {
519
527
  lines.push('');
520
528
  lines.push(`⚠️ ${input.foreign.charAt(0).toUpperCase()}${input.foreign.slice(1)}. Looply will not merge this while that is so.`);
@@ -554,6 +562,7 @@ async function deliverOnce(deps, input) {
554
562
  mode: input.mode,
555
563
  ...((input.maintenance && !input.maintenance.autoMerge) || input.noAutoMerge === true ? { noAutoMerge: true } : {}),
556
564
  ...(input.checks ? { checks: { ...input.checks } } : {}),
565
+ ...(input.clientRef ? { clientRef: input.clientRef } : {}),
557
566
  state: 'not-pushed',
558
567
  note: null,
559
568
  dependsOn: null,
@@ -784,37 +793,47 @@ async function planRebuild(deps, input, at) {
784
793
  const replayed = await deps.git.replay(ref, owned.own);
785
794
  if (!replayed.ok)
786
795
  return { kind: 'stacked', foreign, because: replayed.because };
787
- // `<branch>-solo`, or the next free `-solo-N`; one already here with exactly this content is reused.
788
- const stem = at.branch.replace(/-solo(-\d+)?$/, '');
796
+ const named = await soloBranch(deps, { goalId: input.goalId, claims: input.claims, from: at.branch, replayed, ref, branches: at.branches, onOrigin: at.onOrigin, at: at.at });
797
+ if (!named.ok)
798
+ return { kind: 'stacked', foreign, because: named.because };
799
+ const without = foreign.map((f) => ({ goalId: f.goalId ?? null, branch: f.branch, commits: f.commits.length }));
800
+ return { kind: 'rebuilt', branch: named.name, sha: named.sha, without, withoutText: withoutSentence(without) };
801
+ }
802
+ /**
803
+ * THE NAME A REBUILD GOES OUT UNDER: `<branch>-solo`, or the next free `-solo-N` — never one origin
804
+ * already has; one already here with exactly this content on this base is reused. The new branch is
805
+ * named as the goal's in the lane claims, from the original branch's own record.
806
+ */
807
+ async function soloBranch(deps, x) {
808
+ const stem = x.from.replace(/-solo(-\d+)?$/, '');
789
809
  let name = null;
790
- let sha = replayed.sha;
810
+ let sha = x.replayed.sha;
791
811
  for (let i = 1; i <= 20 && name === null; i++) {
792
812
  const candidate = i === 1 ? `${stem}${commit_ownership_1.SOLO_SUFFIX}` : `${stem}${commit_ownership_1.SOLO_SUFFIX}-${i}`;
793
- const existing = at.branches.find((b) => b.name === candidate);
794
- if (existing === undefined && !at.onOrigin.has(candidate)) {
795
- if (!(await deps.git.createBranch(candidate, replayed.sha))) {
796
- return { kind: 'stacked', foreign, because: `the branch ${candidate} could not be created` };
797
- }
813
+ const existing = x.branches.find((b) => b.name === candidate);
814
+ if (existing === undefined && !x.onOrigin.has(candidate)) {
815
+ if (!(await deps.git.createBranch(candidate, x.replayed.sha)))
816
+ return { ok: false, because: `the branch ${candidate} could not be created` };
798
817
  name = candidate;
799
818
  }
800
- else if (existing !== undefined && (await deps.git.treeOf(existing.sha)) === replayed.tree && (await deps.git.isAncestor(ref, existing.sha))) {
819
+ else if (existing !== undefined && (await deps.git.treeOf(existing.sha)) === x.replayed.tree && (await deps.git.isAncestor(x.ref, existing.sha))) {
801
820
  name = candidate;
802
821
  sha = existing.sha;
803
822
  }
804
823
  }
805
824
  if (name === null)
806
- return { kind: 'stacked', foreign, because: `every ${stem}${commit_ownership_1.SOLO_SUFFIX} name up to -20 is taken` };
807
- // Name the rebuilt branch as this goal's in the lane claims, from the original branch's own record.
808
- const source = [...input.claims].reverse().find((r) => r.branch === at.branch && r.goalId === input.goalId);
825
+ return { ok: false, because: `every ${stem}${commit_ownership_1.SOLO_SUFFIX} name up to -20 is taken` };
826
+ const source = [...x.claims].reverse().find((r) => r.branch === stem && r.goalId === x.goalId)
827
+ ?? [...x.claims].reverse().find((r) => r.branch === x.from && r.goalId === x.goalId);
809
828
  if (source !== undefined && deps.recordClaim !== undefined) {
810
829
  try {
811
830
  deps.recordClaim({
812
831
  schema: source.schema,
813
832
  kind: 'claims',
814
- at: at.at,
833
+ at: x.at,
815
834
  branch: name,
816
835
  runId: source.runId,
817
- goalId: input.goalId,
836
+ goalId: x.goalId,
818
837
  goalVersion: source.goalVersion,
819
838
  planRevision: source.planRevision,
820
839
  servings: [],
@@ -825,8 +844,7 @@ async function planRebuild(deps, input, at) {
825
844
  /* bookkeeping; `ownerOfBranch` still reads a -solo branch through its original */
826
845
  }
827
846
  }
828
- const without = foreign.map((f) => ({ goalId: f.goalId ?? null, branch: f.branch, commits: f.commits.length }));
829
- return { kind: 'rebuilt', branch: name, sha, without, withoutText: withoutSentence(without) };
847
+ return { ok: true, name, sha };
830
848
  }
831
849
  function plural(n, word) {
832
850
  return `${n} ${word}${n === 1 ? '' : 's'}`;
@@ -921,6 +939,8 @@ async function mergeGuard(deps, e, head) {
921
939
  /* ─────────────────────────────────────────────── merge, then deploy ── */
922
940
  /** How long `merge` waits for checks before handing the pull request to a person. */
923
941
  exports.CHECKS_PATIENCE_MS = 24 * 60 * 60_000;
942
+ /** A pull request older than this is not re-judged under a stronger mode: its checks ran against a base long gone. */
943
+ exports.REJUDGE_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
924
944
  /** How long a pull request with NO checks at all is given for CI to show up. */
925
945
  exports.NO_CHECKS_GRACE_MS = 15 * 60_000;
926
946
  /**
@@ -1034,6 +1054,12 @@ const APPROVABLE = ['pr-open', 'waiting-checks', 'checks-failed', 'blocked'];
1034
1054
  * Each step is recorded on the goal, which is what puts an audit line on the ticket. Never throws.
1035
1055
  */
1036
1056
  async function advanceDeliveries(deps) {
1057
+ try {
1058
+ await closeSuperseded(deps);
1059
+ }
1060
+ catch (err) {
1061
+ deps.log(`deliver : superseded pull requests: ${err.message}`);
1062
+ }
1037
1063
  for (const e of deps.store.all()) {
1038
1064
  if (!ADVANCING.includes(e.state))
1039
1065
  continue;
@@ -1060,7 +1086,7 @@ async function advanceOne(deps, e) {
1060
1086
  // A person's approval, read from the goal mirror.
1061
1087
  if (!e.approvedAt && APPROVABLE.includes(e.state) && e.pullNumber !== null) {
1062
1088
  const approved = deps.shipRequested(e.goalId);
1063
- if (approved !== null) {
1089
+ if (approved !== null && approved !== e.voidedApproval) {
1064
1090
  // 🔴 A BLOCKED ONE STAYS BLOCKED: the approval is kept, and acted on once it unblocks.
1065
1091
  e =
1066
1092
  e.state === 'blocked'
@@ -1164,11 +1190,59 @@ async function advanceOne(deps, e) {
1164
1190
  }
1165
1191
  const moved = `its head moved to ${pull.headSha.slice(0, 7)} and its checks now pass`;
1166
1192
  if (!wantsMerge) {
1167
- await save(deps, { ...e, state: 'pr-open', failedHead: null, note: `${moved}; a person merges`, updatedAt: at });
1193
+ await save(deps, { ...e, mode, state: 'pr-open', failedHead: null, note: `${moved}; a person merges`, updatedAt: at });
1168
1194
  return;
1169
1195
  }
1170
1196
  deps.log(`deliver : ${e.goalId}: ${moved}; merging once the checks allow`);
1171
- await save(deps, { ...e, state: 'waiting-checks', failedHead: null, note: `${moved}; merging once the checks allow`, updatedAt: at });
1197
+ await save(deps, { ...e, state: 'waiting-checks', failedHead: null, waitingSince: at, note: `${moved}; merging once the checks allow`, updatedAt: at });
1198
+ return;
1199
+ }
1200
+ else if (
1201
+ /**
1202
+ * 🔴 PARKED BECAUSE OF THE MODE IT WAS DELIVERED UNDER, AND THE MODE IS STRONGER NOW
1203
+ * (georgeemichel/robinbet#3, RBB-B-214: opened 2026-10-18 under "PRs only"; the component was
1204
+ * switched to merge, and the pull request still waited for a person). A `pr-open` entry whose
1205
+ * recorded mode is `pr` was handed to a person ONLY because of the mode — every other reason
1206
+ * (red CI, a day without checks, no CI) records the mode it was parked under. Under a mode
1207
+ * that merges, it goes back to `waiting-checks`, which decides exactly as for a fresh delivery:
1208
+ * the merge guard, a conflict, the checks, Looply's own gates when there is no CI.
1209
+ */
1210
+ e.state === 'pr-open' && e.mode === 'pr' && wantsMerge && !approved && pull.state === 'open') {
1211
+ /**
1212
+ * 🔴 NOT EVERY OLD pr-open PULL REQUEST — and not by way of a conflict rebuild either (the rebuild
1213
+ * would open a fresh pull request nobody reviewed). The guards in `rejudgeHold` come first.
1214
+ */
1215
+ const why = await rejudgeHold(api, e, pull, now);
1216
+ if (why !== null) {
1217
+ const note = `delivery is now "${mode}", but ${why}; a person merges it`;
1218
+ if (e.note !== note)
1219
+ await save(deps, { ...e, note, updatedAt: at });
1220
+ return;
1221
+ }
1222
+ deps.log(`deliver : ${e.goalId}: delivered under "pr", delivery is now "${mode}"; re-judged`);
1223
+ if (pull.conflicted === true) {
1224
+ await rebuildOnBase(deps, api, e, pull, at, mode);
1225
+ return;
1226
+ }
1227
+ await save(deps, { ...e, mode, state: 'waiting-checks', waitingSince: at, note: `delivery is now "${mode}"; merging once the checks allow`, updatedAt: at });
1228
+ return;
1229
+ }
1230
+ else if (wantsMerge && pull.state === 'open' && pull.conflicted === true && conflictMoved(e, pull)) {
1231
+ /**
1232
+ * 🔴 IT CONFLICTS WITH THE BASE, AND LOOPLY WOULD MERGE IT. A conflicting pull request never
1233
+ * merges and, on GitHub, usually gets no CI run at all — so it sat with a person (or parked
1234
+ * "no CI checks report") until somebody rebuilt it by hand. Rebuilt on the current base instead
1235
+ * (`rebuildOnBase`); held, saying why, only when that cannot be done without resolving anything.
1236
+ */
1237
+ await rebuildOnBase(deps, api, e, pull, at, mode);
1238
+ return;
1239
+ }
1240
+ else if (
1241
+ // A conflict a person resolved (or a base that moved past it): judged again, as for a fresh delivery.
1242
+ // GitHub's "not worked out yet" (null, right after the base moved) is not "resolved": asked again next pass.
1243
+ e.state === 'pr-open' && e.conflict && pull.conflicted === false && conflictMoved(e, pull) && wantsMerge && !approved && pull.state === 'open') {
1244
+ const base = e.projectBase ?? pull.base;
1245
+ await save(deps, { ...e, mode, state: 'waiting-checks', conflict: null, waitingSince: at, note: `it no longer conflicts with ${base}; merging once the checks allow`, updatedAt: at });
1172
1246
  return;
1173
1247
  }
1174
1248
  else if (
@@ -1267,8 +1341,15 @@ async function advanceOne(deps, e) {
1267
1341
  await save(deps, { ...e, state: 'blocked', note: guard.note, updatedAt: at });
1268
1342
  return;
1269
1343
  }
1344
+ // A conflict never merges, and GitHub runs no CI on it: rebuilt on the current base, or held saying why.
1345
+ if (pull.conflicted === true) {
1346
+ await rebuildOnBase(deps, api, e, pull, at, mode);
1347
+ return;
1348
+ }
1270
1349
  const verdict = decideChecks(await api.requiredChecks(pull.base), await api.checksFor(pull.headSha));
1271
- const age = now - Date.parse(e.approvedAt ?? e.openedAt);
1350
+ // Patience runs from the latest of: opened, re-judged, approved.
1351
+ const since = [e.openedAt, e.waitingSince, e.approvedAt].map((t) => (t ? Date.parse(t) : NaN)).filter((t) => !Number.isNaN(t));
1352
+ const age = since.length === 0 ? NaN : now - Math.max(...since);
1272
1353
  let redBaseMerge = null;
1273
1354
  if (verdict.kind === 'red') {
1274
1355
  const red = await redOnBase(api, pull, verdict.failed);
@@ -1382,6 +1463,286 @@ async function mergedByHand(deps, api, e, pull, head, at, wantsDeploy, mode) {
1382
1463
  await save(deps, merged);
1383
1464
  await followDeploys(deps, api, merged, wantsDeploy, mode);
1384
1465
  }
1466
+ /* ─────────────────────────────────────────── a conflict with the base ── */
1467
+ /**
1468
+ * Why a pull request handed to a person under "pr" stays with them although the mode now merges — or
1469
+ * null when nothing does. A draft is a person's work in progress; one a reviewer asked changes on waits
1470
+ * for those changes (a client that cannot read reviews counts as asked); one opened more than a week
1471
+ * ago was checked against a base long gone.
1472
+ */
1473
+ async function rejudgeHold(api, e, pull, now) {
1474
+ if (pull.draft === true)
1475
+ return 'it is a draft';
1476
+ const opened = Date.parse(e.openedAt);
1477
+ if (Number.isNaN(opened) || now - opened > exports.REJUDGE_MAX_AGE_MS)
1478
+ return 'it was opened more than 7 days ago, against an older base';
1479
+ if (api.changesRequested === undefined)
1480
+ return 'Looply cannot read its reviews';
1481
+ return (await api.changesRequested(pull.number)) ? 'a reviewer requested changes' : null;
1482
+ }
1483
+ /** Open deliveries whose pull request targets this one's branch (stacked on it), which closing it would strand. */
1484
+ function dependents(store, e) {
1485
+ const mine = new Set([e.branch, e.rebuiltFrom?.branch].filter((b) => typeof b === 'string'));
1486
+ return store.all().filter((x) => x.goalId !== e.goalId && x.done !== true && x.pullNumber !== null && OPEN_STATES.includes(x.state) && x.base !== null && mine.has(x.base));
1487
+ }
1488
+ /** Has the pull request's head or base moved since a conflict rebuild last failed (or was none tried)? */
1489
+ function conflictMoved(e, pull) {
1490
+ const c = e.conflict;
1491
+ return !c || c.head !== (pull.headSha || e.sha) || c.baseSha !== (pull.baseSha ?? '');
1492
+ }
1493
+ /**
1494
+ * 🔴 A PULL REQUEST THAT CONFLICTS WITH ITS BASE, REBUILT ON THE CURRENT BASE.
1495
+ *
1496
+ * Its own commits — the goal's, and those on its own run branch — are replayed onto origin's base,
1497
+ * fetched fresh, the way a `-solo` rebuild is (`branch-replay.ts`: each commit's own diff, applied
1498
+ * with `git apply --check` first, never a three-way merge). Commits of other goals that are merged
1499
+ * already (a dependency a person squashed: the usual cause of the conflict) are left out. The result
1500
+ * goes out as `<run branch>-solo[-N]` under the same push rules as any delivery, a new pull request
1501
+ * is opened, and the conflicting one is closed with a link to it. The new one is judged like any
1502
+ * other: the guard, then CI. It is not the commit Looply's own gates judged, so those never stand in
1503
+ * for missing CI on it.
1504
+ *
1505
+ * Held with a person, saying why, whenever that cannot be done WITHOUT resolving anything: a head
1506
+ * somebody else pushed, other goals' unmerged work, a merge among its commits, a commit whose
1507
+ * change no longer applies — a real conflict is a decision, and Looply never makes it up. Tried
1508
+ * again only when the head or the base moves.
1509
+ */
1510
+ async function rebuildOnBase(deps, api, e, pull, at, mode) {
1511
+ const base = e.projectBase ?? pull.base;
1512
+ const head = pull.headSha || e.sha;
1513
+ const held = async (because) => {
1514
+ const note = `not merged: it conflicts with ${base}, and Looply could not rebuild it on the current ${base} (${because}); a person resolves the conflict`.slice(0, 600);
1515
+ if (e.state !== 'pr-open' || e.note !== note)
1516
+ deps.log(`deliver : ${e.goalId}: ${note}`);
1517
+ await save(deps, { ...e, mode, state: 'pr-open', conflict: { head, baseSha: pull.baseSha ?? '', because: because.slice(0, 300), at }, note, updatedAt: at });
1518
+ };
1519
+ if (pull.draft === true)
1520
+ return held('it is a draft, so a person is still working on it');
1521
+ // A reviewer's requested changes are not bypassed by a fresh pull request; unreadable reviews count as requested.
1522
+ if (api.changesRequested === undefined || (await api.changesRequested(pull.number))) {
1523
+ return held(api.changesRequested === undefined ? 'Looply cannot read its reviews' : 'a reviewer requested changes on it');
1524
+ }
1525
+ if (head !== e.sha)
1526
+ return held(`its head ${head.slice(0, 7)} is not the commit Looply delivered; somebody pushed to it`);
1527
+ if (e.projectBase !== null && pull.base !== e.projectBase)
1528
+ return held(`it targets ${pull.base}, not ${e.projectBase}`);
1529
+ // 🔴 Closing it would strand the pull requests built on its branch.
1530
+ const stackedOnIt = dependents(deps.store, e);
1531
+ if (stackedOnIt.length > 0)
1532
+ return held(`${stackedOnIt.map((d) => d.pullRequestUrl ?? `#${d.pullNumber}`).join(', ')} ${stackedOnIt.length === 1 ? 'builds' : 'build'} on its branch`);
1533
+ const ref = await deps.git.freshBase(base);
1534
+ const branches = await deps.git.runBranches().catch(() => []);
1535
+ const onOrigin = await deps.git.remoteRunBranches().catch(() => new Set());
1536
+ const claims = deps.claims?.() ?? [];
1537
+ const owned = await (0, commit_ownership_1.commitOwnership)(deps.git, { tip: head, base: ref, goalId: e.goalId, claims, branches, onOrigin });
1538
+ const range = owned === null ? null : await deps.git.commitsBetween(ref, head);
1539
+ if (owned === null || range === null)
1540
+ return held(`its commits (${head.slice(0, 12)}) could not be read on this machine`);
1541
+ // Its own run branch is its own work, claimed or not (as in `mergeGuard`).
1542
+ const ownBranches = new Set([e.branch, e.rebuiltFrom?.branch].filter((b) => typeof b === 'string'));
1543
+ const carried = owned.foreign.filter((f) => ownBranches.has(f.branch) && (f.goalId === undefined || f.goalId === e.goalId));
1544
+ const others = owned.foreign.filter((f) => !carried.includes(f));
1545
+ /**
1546
+ * 🔴 ONLY WORK THAT IS MERGED IS LEFT OUT. A goal this pull request ABSORBS (a fix-up's red
1547
+ * predecessor, an older attempt it superseded) was closed, not merged: its commits are part of
1548
+ * this change and are carried, never dropped. Any other unmerged work holds it.
1549
+ */
1550
+ const unmerged = await unmergedForeign(deps.git, deps.store, others, []);
1551
+ const absorbed = unmerged.filter((f) => f.goalId !== undefined && (e.absorbs ?? []).includes(f.goalId));
1552
+ const blocking = unmerged.filter((f) => !absorbed.includes(f));
1553
+ if (blocking.length > 0)
1554
+ return held(describeForeign(deps.store, blocking, base));
1555
+ const mine = new Set([...owned.own, ...carried.flatMap((f) => f.commits), ...absorbed.flatMap((f) => f.commits)]);
1556
+ const commits = range.filter((c) => mine.has(c.sha));
1557
+ if (commits.some((c) => c.parents.length !== 1))
1558
+ return held("its own commits include a merge, which Looply never replays");
1559
+ const replayed = await deps.git.replay(ref, commits.map((c) => c.sha));
1560
+ if (!replayed.ok)
1561
+ return held(replayed.because);
1562
+ const original = { branch: e.rebuiltFrom?.branch ?? e.branch, sha: e.rebuiltFrom?.sha ?? e.sha };
1563
+ const named = await soloBranch(deps, { goalId: e.goalId, claims, from: original.branch, replayed, ref, branches, onOrigin, at });
1564
+ if (!named.ok)
1565
+ return held(named.because);
1566
+ const protectedBranches = [...(deps.protectedBranches?.() ?? [])];
1567
+ if ((await api.branchProtected(named.name).catch(() => null)) === true)
1568
+ protectedBranches.push(named.name);
1569
+ const refused = (0, delivery_rules_1.pushRefusal)({ remote: delivery_rules_1.DELIVERY_REMOTE, remoteUrl: await deps.git.remoteUrl(), branch: named.name, base, protectedBranches });
1570
+ if (refused !== null)
1571
+ return held(refused);
1572
+ const theirs = await deps.git.remoteSha(named.name);
1573
+ if (theirs !== null && theirs !== named.sha && !(await deps.git.isAncestor(theirs, named.sha))) {
1574
+ return held(`origin already has ${named.name} at ${theirs.slice(0, 12)}, which the rebuild does not contain; Looply never force-pushes`);
1575
+ }
1576
+ if (theirs !== named.sha) {
1577
+ const pushed = await deps.git.push((0, delivery_rules_1.deliveryPushArgv)(named.name, named.sha));
1578
+ if (!pushed.ok)
1579
+ return held(`git push to origin failed: ${pushed.because}`);
1580
+ deps.log(`deliver : pushed ${named.name} (${named.sha.slice(0, 12)}) to origin, rebuilt on the current ${base}`);
1581
+ }
1582
+ let fresh = await api.findPull(named.name).catch(() => null);
1583
+ if (fresh === null || fresh.state !== 'open') {
1584
+ try {
1585
+ fresh = await api.createPull({
1586
+ title: pullTitle(e.goalText),
1587
+ head: named.name,
1588
+ base,
1589
+ body: pullBody({
1590
+ goalId: e.goalId,
1591
+ goalText: e.goalText,
1592
+ branch: named.name,
1593
+ sha: named.sha,
1594
+ ...(e.checks ? { checks: e.checks } : {}),
1595
+ mode,
1596
+ stacked: null,
1597
+ conflictWith: { base, replaces: e.pullRequestUrl, from: original.branch },
1598
+ }),
1599
+ });
1600
+ }
1601
+ catch (err) {
1602
+ return held(`GitHub refused the rebuilt pull request: ${err.message}`);
1603
+ }
1604
+ }
1605
+ await api
1606
+ .closePull(pull.number, `Rebuilt on the current ${base} as ${fresh.url}, because this pull request conflicted with ${base}. Same changes, each commit applied as it was; nothing was resolved by guesswork.`)
1607
+ .catch((err) => deps.log(`deliver : ${e.goalId}: could not close ${e.pullRequestUrl ?? `#${pull.number}`} (${err.message})`));
1608
+ deps.log(`deliver : ${e.goalId}: ${e.pullRequestUrl ?? `#${pull.number}`} conflicted with ${base}; rebuilt as ${fresh.url}`);
1609
+ const without = others.filter((f) => !unmerged.includes(f)).map((f) => ({ goalId: f.goalId ?? null, branch: f.branch, commits: f.commits.length }));
1610
+ const changes = deps.git.changeSummary === undefined ? null : await deps.git.changeSummary(ref, named.sha).catch(() => null);
1611
+ await save(deps, {
1612
+ ...e,
1613
+ ...(changes === null ? {} : { changes }),
1614
+ branch: named.name,
1615
+ sha: named.sha,
1616
+ pullNumber: fresh.number,
1617
+ pullRequestUrl: fresh.url,
1618
+ base: fresh.base || base,
1619
+ dependsOn: null,
1620
+ mode,
1621
+ state: 'waiting-checks',
1622
+ rebuiltFrom: { branch: original.branch, sha: original.sha, without },
1623
+ // 🔴 Nobody approved this commit: an earlier "Approve and ship" does not carry over to it.
1624
+ approvedAt: null,
1625
+ voidedApproval: e.approvedAt ?? e.voidedApproval ?? null,
1626
+ conflict: null,
1627
+ failedHead: null,
1628
+ baseCiRed: null,
1629
+ // The age clock is the original pull request's: a rebuild is not a newer piece of work.
1630
+ openedAt: e.openedAt,
1631
+ waitingSince: at,
1632
+ note: `it conflicted with ${base}, so Looply rebuilt it on the current ${base} as ${fresh.url} (replaces ${e.pullRequestUrl ?? `#${pull.number}`}); merging once the checks allow`.slice(0, 600),
1633
+ updatedAt: at,
1634
+ });
1635
+ }
1636
+ /* ──────────────────────────────────────── a newer attempt at a ticket ── */
1637
+ /**
1638
+ * WHICH TICKET A GOAL IS AN ATTEMPT AT, AND WHICH ATTEMPT — from its `clientRef`, when the caller
1639
+ * names one the way AutoRyn does for a ticket it sends: `<caller>:<tenant>:<task|bug>:<ticket>:<n>`,
1640
+ * `n` counting the attempts at that ticket. Anything else is null: a batch of tickets, a programme
1641
+ * part, or another caller's key (`<source>:<ordinal>` counts requirements, not attempts) is never
1642
+ * read as "the same ticket again".
1643
+ */
1644
+ function ticketAttemptOf(clientRef) {
1645
+ const m = /^([a-z][a-z0-9-]*:[^:\s]+:(?:task|bug):[^:\s]+):(\d{1,6})$/.exec(clientRef ?? '');
1646
+ return m === null ? null : { ticket: m[1], attempt: Number(m[2]) };
1647
+ }
1648
+ /** States of a delivery whose pull request is still open and still Looply's to move. */
1649
+ const OPEN_STATES = ['pr-open', 'waiting-checks', 'checks-failed', 'blocked'];
1650
+ /**
1651
+ * 🔴 A NEWER ATTEMPT AT THE SAME TICKET SUPERSEDES THE OLDER ONE'S PULL REQUEST (georgeemichel/tabsy
1652
+ * #22 and #23, TAB-B-78, 2026-10-22: the second attempt opened #23, and #22 stayed open beside it
1653
+ * until a person closed it by hand).
1654
+ *
1655
+ * AutoRyn counts EVERY new goal for a ticket as an attempt — a retry, but also a follow-up QA sent
1656
+ * back and a fix-up of a red pull request — so a higher attempt alone never closes anything. The
1657
+ * older attempt's open pull request is closed, with a comment linking the newer, only when ALL hold:
1658
+ * - the newer attempt either CONTAINS the older head (it was cut on that work, and now carries it
1659
+ * on purpose: `absorbs`, so the merge guard does not hold it for those commits), or asks for
1660
+ * exactly the same thing (a plain retry: the same goal wording);
1661
+ * - GitHub, read now, says the newer pull request is merged, or open — not a draft, and its
1662
+ * checks not red — and Looply has it waiting on checks or with a person, never `checks-failed`,
1663
+ * `blocked`, held on a red base or on a conflict;
1664
+ * - the older one is still open on GitHub, not a draft, not approved by a person ("Approve and
1665
+ * ship"), not work marked never to merge automatically, and no other pull request builds on
1666
+ * its branch; the newer one does not target or build on it either.
1667
+ * Anything else is left for the normal pass and for a person.
1668
+ */
1669
+ async function closeSuperseded(deps) {
1670
+ const tagged = deps.store
1671
+ .all()
1672
+ .map((e) => ({ e, t: ticketAttemptOf(e.clientRef ?? deps.clientRefOf?.(e.goalId) ?? null) }))
1673
+ .filter((x) => x.t !== null && x.e.pullNumber !== null && x.e.owner !== null && x.e.repo !== null);
1674
+ for (const old of tagged) {
1675
+ const o = old.e;
1676
+ if (o.done === true || !OPEN_STATES.includes(o.state) || o.approvedAt || o.noAutoMerge === true)
1677
+ continue;
1678
+ // An approval the mirror holds that this pass has not copied onto the entry yet counts too (a voided one does not).
1679
+ const asked = deps.shipRequested(o.goalId);
1680
+ if (asked !== null && asked !== o.voidedApproval)
1681
+ continue;
1682
+ if (dependents(deps.store, o).length > 0)
1683
+ continue;
1684
+ const candidates = tagged
1685
+ .filter((n) => n.e.goalId !== o.goalId &&
1686
+ n.t.ticket === old.t.ticket &&
1687
+ n.t.attempt > old.t.attempt &&
1688
+ n.e.owner === o.owner &&
1689
+ n.e.repo === o.repo &&
1690
+ (MERGED.includes(n.e.state) || (n.e.done !== true && (n.e.state === 'waiting-checks' || n.e.state === 'pr-open') && !n.e.baseCiRed && !n.e.conflict)) &&
1691
+ n.e.base !== o.branch &&
1692
+ n.e.dependsOn !== o.branch)
1693
+ .sort((a, b) => b.t.attempt - a.t.attempt);
1694
+ for (const newer of candidates) {
1695
+ try {
1696
+ if (await supersede(deps, o, newer.e))
1697
+ break;
1698
+ }
1699
+ catch (err) {
1700
+ deps.log(`deliver : ${o.goalId}: could not close it as superseded by ${newer.e.goalId} (${err.message}); tried again next pass`);
1701
+ break;
1702
+ }
1703
+ }
1704
+ }
1705
+ }
1706
+ /** The goal wording, compared for "the same request again": whitespace and line endings do not count. */
1707
+ function sameRequest(a, b) {
1708
+ const norm = (t) => t.replace(/<br\s*\/?>/gi, '\n').replace(/\s+/g, ' ').trim();
1709
+ return norm(a) !== '' && norm(a) === norm(b);
1710
+ }
1711
+ /** Close `old` as superseded by `newer` when every rule above holds; true when it was closed. */
1712
+ async function supersede(deps, old, newer) {
1713
+ const tips = [newer.sha, newer.rebuiltFrom?.sha].filter((s) => typeof s === 'string' && s !== '');
1714
+ let contains = false;
1715
+ for (const tip of tips)
1716
+ if (tip === old.sha || (await deps.git.isAncestor(old.sha, tip).catch(() => false)))
1717
+ contains = true;
1718
+ if (!contains && !sameRequest(old.goalText, newer.goalText))
1719
+ return false;
1720
+ const client = await deps.github(old.owner, old.repo);
1721
+ if (client.api === null)
1722
+ return false; // no credentials right now: next pass
1723
+ const api = client.api;
1724
+ const theirs = await api.getPull(newer.pullNumber);
1725
+ if (!theirs.merged) {
1726
+ if (theirs.state !== 'open' || theirs.draft === true)
1727
+ return false;
1728
+ const verdict = decideChecks(await api.requiredChecks(theirs.base), await api.checksFor(theirs.headSha));
1729
+ if (verdict.kind === 'red')
1730
+ return false;
1731
+ }
1732
+ const pull = await api.getPull(old.pullNumber);
1733
+ if (pull.merged || pull.state !== 'open' || pull.draft === true)
1734
+ return false; // the normal pass records what happened to it
1735
+ const url = newer.pullRequestUrl ?? `#${newer.pullNumber}`;
1736
+ await api.closePull(old.pullNumber, `Superseded by ${url}: a newer attempt at the same ticket (goal ${newer.goalId}) ${contains ? 'carries this work' : 'asks for the same change'} in its own pull request.`);
1737
+ deps.log(`deliver : ${old.goalId}: closed ${old.pullRequestUrl ?? `#${old.pullNumber}`}, superseded by ${url}`);
1738
+ const at = new Date(deps.now()).toISOString();
1739
+ await save(deps, { ...old, state: 'pr-open', done: true, note: `superseded by ${url}, a newer attempt at the same ticket; closed`, updatedAt: at });
1740
+ const current = deps.store.get(newer.goalId);
1741
+ if (contains && current !== null && !(current.absorbs ?? []).includes(old.goalId)) {
1742
+ deps.store.put({ ...current, absorbs: [...(current.absorbs ?? []), old.goalId] });
1743
+ }
1744
+ return true;
1745
+ }
1385
1746
  /* ────────────────────────────────────────── where the merge got to ── */
1386
1747
  /** How long a merged commit's deploys are followed for, so one done outside Looply is still seen. */
1387
1748
  exports.FOLLOW_DEPLOYS_MS = 14 * 24 * 60 * 60_000;
@@ -1428,7 +1789,9 @@ function pendingPromotes(deps, e) {
1428
1789
  * commit (an environment of the same name — any, for the one unnamed environment — `success` is
1429
1790
  * `deployed`, `failure`/`error` is `failed`, still running is `deploying`); GitHub's newest
1430
1791
  * successful deployment of that environment when it is of a LATER commit that contains this one;
1431
- * and a Heroku app's newest release, by the same rule. That is how a Heroku or Netlify deploy, or one
1792
+ * and a Heroku app's newest release, by the same rule; and, for a `merge-deploys` environment that names
1793
+ * where to look (`netlifySite`, `liveCommitUrl`), the commit its site SERVES (`confirmLive`), which also
1794
+ * flags one still not live 30 minutes after the merge. That is how a Heroku or Netlify deploy, or one
1432
1795
  * a person ran by hand, is seen. Nothing else ever makes a row `deployed`.
1433
1796
  *
1434
1797
  * The delivery is `done` once every environment is deployed or failed, or 14 days after the merge;
@@ -1468,6 +1831,7 @@ async function followDeploys(deps, api, e, wantsDeploy, mode) {
1468
1831
  x = { ...x, environments: (x.environments ?? []).map((row) => fromGitHub(row, plans, found)) };
1469
1832
  }
1470
1833
  x = await laterDeploys(deps, api, x, plans, sha, base, at, asked);
1834
+ x = await confirmLive(deps, x, plans, sha, base, at);
1471
1835
  x = await recheckFailed(deps, x, plans, sha, base, at, asked);
1472
1836
  }
1473
1837
  const rows = x.environments ?? [];
@@ -1571,8 +1935,11 @@ async function deployOne(deps, e, p, sha, at, asked) {
1571
1935
  const d = p.deploy;
1572
1936
  if (d.kind === 'none')
1573
1937
  return row('waiting', `no deploy step is configured for ${p.name}`);
1574
- if (d.kind === 'merge-deploys')
1575
- return row('unconfirmed', `merged into ${base}, which should deploy it; not confirmed yet`);
1938
+ if (d.kind === 'merge-deploys') {
1939
+ return deps.liveCommit?.can(d) === true
1940
+ ? row('unconfirmed', `merged into ${base}, which should deploy it; waiting to see it live`)
1941
+ : row('unconfirmed', `merged into ${base}, which should deploy it; not confirmed yet`);
1942
+ }
1576
1943
  if (d.kind === 'push') {
1577
1944
  if (sha === null)
1578
1945
  return row('failed', 'merged, but GitHub did not say which commit the merge made, so nothing was pushed to deploy');
@@ -1690,6 +2057,84 @@ async function laterDeploys(deps, api, e, plans, sha, base, at, asked) {
1690
2057
  }
1691
2058
  return { ...e, environments: rows };
1692
2059
  }
2060
+ /* ──────────────────────────── a site Looply does not deploy, seen live ── */
2061
+ /** How long after the merge a `merge-deploys` site may take to serve the commit before the row says it is not live. */
2062
+ exports.LIVE_DEADLINE_MS = 30 * 60_000;
2063
+ /** A build the host says is still running gets this long instead. */
2064
+ exports.LIVE_BUILDING_DEADLINE_MS = 60 * 60_000;
2065
+ /**
2066
+ * IS THIS COMMIT WHAT THE SITE SERVES? (`live-commit.ts` reads it.) The site serves this commit, or a
2067
+ * later one that contains it: `deployed`. Else the host's own build of this commit, when it has one
2068
+ * (Netlify): failed — `failed`; running — `deploying`. Anything else, or the site not answering:
2069
+ * `unconfirmed`, saying what it does serve. `older`: the site ANSWERED and serves another commit that
2070
+ * does not contain this one — the only thing the 30-minute deadline may call a failure.
2071
+ */
2072
+ async function liveState(deps, d, sha, base) {
2073
+ const unconfirmed = (detail, older = false) => ({ state: 'unconfirmed', at: null, url: null, detail, older });
2074
+ if (!deps.liveCommit)
2075
+ return unconfirmed('the live commit cannot be read here');
2076
+ const r = await deps.liveCommit.read(d, sha).catch(() => ({ ok: false, because: 'the reader failed' }));
2077
+ if (!r.ok)
2078
+ return unconfirmed(`its live commit could not be read: ${r.because}`);
2079
+ const { read } = r;
2080
+ const at = read.at !== null && !Number.isNaN(Date.parse(read.at)) ? new Date(read.at).toISOString() : null;
2081
+ const exact = read.serves.find((s) => s === sha || (s.length >= 7 && sha.startsWith(s)));
2082
+ if (exact !== undefined)
2083
+ return { state: 'deployed', at, url: read.url, detail: `${read.source} serves this commit`, older: false };
2084
+ if (deps.git.contains !== undefined) {
2085
+ for (const s of read.serves) {
2086
+ if (await deps.git.contains(sha, s, base).catch(() => false)) {
2087
+ return { state: 'deployed', at, url: read.url, detail: `${read.source} serves ${s.slice(0, 12)}, which contains this commit`, older: false };
2088
+ }
2089
+ }
2090
+ }
2091
+ if (read.own?.state === 'error') {
2092
+ return { state: 'failed', at: read.own.at, url: read.url, detail: `${read.source}: the build of this commit failed${read.own.because ? ` (${read.own.because})` : ''}`, older: false };
2093
+ }
2094
+ if (read.own?.state === 'building')
2095
+ return { state: 'deploying', at: read.own.at, url: read.url, detail: `${read.source} is building this commit`, older: read.serves.length > 0 };
2096
+ return unconfirmed(read.serves.length === 0
2097
+ ? `${read.source} does not show the commit it serves`
2098
+ : `${read.source} serves ${read.serves[0].slice(0, 12)}, which does not contain ${sha.slice(0, 12)} yet`, read.serves.length > 0);
2099
+ }
2100
+ /**
2101
+ * 🔴 A MERGE THAT SHOULD DEPLOY IT, SEEN LIVE — OR SAID NOT TO BE (RBB-B-204…218, 2026-10-19/22: every RDY
2102
+ * website ticket ended "merged, deploy not confirmed" for good while play.rdy.fun served the change).
2103
+ * Every pass, an open `merge-deploys` row whose environment names where to look is read: live — `deployed`;
2104
+ * the host's build of it failed — `failed`; building — `deploying`. Still not live 30 minutes after the
2105
+ * merge (60 while the host says it is building) while the site ANSWERS with an older commit: `failed`,
2106
+ * "not live N minutes after the merge: …", so
2107
+ * the ticket says so within the hour instead of never — and it is looked at again every 15 minutes
2108
+ * (`recheckFailed`), becoming "deployed later" once the site serves it. A read that failed (no token, a
2109
+ * refused token, the site down, no marker on the page) is never a failed deploy: it stays `unconfirmed`,
2110
+ * saying why, for as long as it lasts.
2111
+ */
2112
+ async function confirmLive(deps, e, plans, sha, base, at) {
2113
+ if (!deps.liveCommit)
2114
+ return e;
2115
+ const rows = [...(e.environments ?? [])];
2116
+ let changed = false;
2117
+ const since = e.mergedAt ? deps.now() - Date.parse(e.mergedAt) : 0;
2118
+ for (const [i, row] of rows.entries()) {
2119
+ if (row.state === 'deployed' || row.state === 'failed' || row.state === 'waiting')
2120
+ continue;
2121
+ const d = plans.find((p) => p.name === row.name)?.deploy;
2122
+ if (d?.kind !== 'merge-deploys' || !deps.liveCommit.can(d))
2123
+ continue;
2124
+ const c = await liveState(deps, d, sha, base);
2125
+ let next = { ...row, state: c.state, at: c.at ?? (c.state === 'unconfirmed' ? row.at : at), url: row.url ?? c.url, detail: c.detail.slice(0, 600) };
2126
+ const limit = c.state === 'deploying' ? exports.LIVE_BUILDING_DEADLINE_MS : exports.LIVE_DEADLINE_MS;
2127
+ if ((c.state === 'unconfirmed' || c.state === 'deploying') && c.older && since > limit) {
2128
+ next = { ...next, state: 'failed', at, detail: `not live ${Math.round(limit / 60_000)} minutes after the merge: ${c.detail}`.slice(0, 600) };
2129
+ deps.log(`deliver : ${e.goalId}: ${row.name} is not live ${Math.round(limit / 60_000)} minutes after the merge — ${c.detail}`);
2130
+ }
2131
+ if (JSON.stringify(next) === JSON.stringify(row))
2132
+ continue;
2133
+ rows[i] = next;
2134
+ changed = true;
2135
+ }
2136
+ return changed ? { ...e, environments: rows } : e;
2137
+ }
1693
2138
  /* ─────────────────────────────── a failed deploy is looked at again ── */
1694
2139
  /** How often a failed deploy is looked at again, inside the follow window. */
1695
2140
  exports.FAILED_RECHECK_MS = 15 * 60_000;
@@ -1740,6 +2185,8 @@ function accountInRow(detail) {
1740
2185
  *
1741
2186
  * - is it live after all? A Heroku app's newest release that is or contains the commit, else the
1742
2187
  * deploy branch's tip that does — `deployed`, "deployed later: …";
2188
+ * A `merge-deploys` row Looply never deployed changes only this way: its site serving the commit
2189
+ * (`liveState`) makes it "deployed later";
1743
2190
  * - else, a push refused for the Heroku LOGIN is pushed again once the login is right: the named
1744
2191
  * `herokuAccount`, or (none named) any account other than the one that was refused.
1745
2192
  * Nothing else about a failed row changes; its own failure stays its own until one of those is so.
@@ -1759,6 +2206,17 @@ async function recheckFailed(deps, e, plans, sha, base, at, asked) {
1759
2206
  continue;
1760
2207
  const plan = plans.find((p) => p.name === row.name);
1761
2208
  const d = plan?.deploy;
2209
+ if (plan !== undefined && d?.kind === 'merge-deploys') {
2210
+ // Not deployed by Looply: live after all is the only way it changes.
2211
+ if (deps.liveCommit?.can(d) !== true)
2212
+ continue;
2213
+ const c = await liveState(deps, d, sha, base);
2214
+ if (c.state === 'deployed') {
2215
+ rows[i] = { ...row, state: 'deployed', at: c.at ?? at, url: row.url ?? c.url, detail: `deployed later: ${c.detail}`.slice(0, 600) };
2216
+ deps.log(`deliver : ${e.goalId}: ${row.name} is live after all — ${c.detail}`);
2217
+ }
2218
+ continue;
2219
+ }
1762
2220
  if (plan === undefined || d?.kind !== 'push')
1763
2221
  continue;
1764
2222
  // Live after all?