@vite-hub/presets 0.3.1 → 0.4.1

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,5 +1,5 @@
1
- import { a as isRuntimeString, i as isRuntimeRecord, n as hasRuntimeType, r as isRuntimeNumber, t as presetsErrorDiagnostics } from "./error-diagnostics-BTBW9sZx.js";
2
- import { A as actionLocation, C as normalizeGitHubMentionAllowlist, D as invariantError, E as invariant, F as isBabysitterCheckRun, I as createBabysitterPassResultSchema, M as hydrateFailedCiEvidence, N as newestCheckRun, O as hasGitHubLogin, P as createBabysitterCheckRuns, S as isReviewThreadOutcome, T as reviewerLabeledSevere, _ as matchesMergeReviewEvidence, a as isBabysitterPlacementCapacityError, b as snapshotCheckEvidence, c as workspaceDecision, f as directMergeReadiness, g as liveMergeReadiness, h as isAutomatedFeedback, j as failed$1, k as matchesBabysitterPullRequestFilter, l as babysitterModelAdmission, m as hasHumanComment, p as feedbackFingerprints, r as resolveBabysitterLifecycleFilter, s as providerSessionDecision, v as mergeReviewEvidenceKey, w as reviewThreadOutcomes, x as createGitHubPullRequestOperations, y as resolveBabysitterMerge } from "./babysitter-C71pgjkv.js";
1
+ import { a as isRuntimeString, i as isRuntimeRecord, n as hasRuntimeType, r as isRuntimeNumber, t as presetsErrorDiagnostics } from "./error-diagnostics-o3pHscWs.js";
2
+ import { A as matchesBabysitterPullRequestFilter, C as isReviewThreadOutcome, D as invariant, E as reviewerLabeledSevere, F as createBabysitterCheckRuns, I as isBabysitterCheckRun, L as createBabysitterPassResultSchema, M as failed$1, N as hydrateFailedCiEvidence, O as invariantError, P as newestCheckRun, S as createGitHubPullRequestOperations, T as reviewThreadOutcomes, _ as liveMergeReadiness, a as isBabysitterPlacementCapacityError, b as resolveBabysitterMerge, c as workspaceDecision, g as isAutomatedFeedback, h as hasHumanComment, j as actionLocation, k as hasGitHubLogin, l as babysitterModelAdmission, m as feedbackFingerprints, p as directMergeReadiness, r as resolveBabysitterLifecycleFilter, s as providerSessionDecision, v as matchesMergeReviewEvidence, w as normalizeGitHubMentionAllowlist, x as snapshotCheckEvidence, y as mergeReviewEvidenceKey } from "./babysitter-DQeA81N0.js";
3
3
  import { activeProviderSandbox, agentInvocationId, agentSettings, createMessage, defineAgent, defineCapability, publishAgentActivity, recordProviderCheckout, runAgent, withoutForgeAccess } from "@vite-hub/agent";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { consoleInvocationUrl, resolvePublicUrl, resolveRuntimeValue } from "@vite-hub/runtime";
@@ -3603,9 +3603,14 @@ var PullRequestInbox = class {
3603
3603
  });
3604
3604
  await this.ready;
3605
3605
  }
3606
- async transaction(run) {
3606
+ async transaction(run, signal) {
3607
3607
  await this.init();
3608
- return await this.storage.transaction(run);
3608
+ return await this.storage.transaction(async (tx) => {
3609
+ signal?.throwIfAborted();
3610
+ const result = await run(tx);
3611
+ signal?.throwIfAborted();
3612
+ return result;
3613
+ });
3609
3614
  }
3610
3615
  async read(statement, args = []) {
3611
3616
  await this.init();
@@ -3830,13 +3835,13 @@ var PullRequestInbox = class {
3830
3835
  prefix
3831
3836
  ])).map((row) => [stringValue(row.key), JSON.parse(stringValue(row.value))]);
3832
3837
  }
3833
- async deleteMeta(key) {
3838
+ async deleteMeta(key, signal) {
3834
3839
  await this.transaction(async (tx) => {
3835
3840
  await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key=?`, [this.scope, key]);
3836
- });
3841
+ }, signal);
3837
3842
  }
3838
- async setMeta(key, value) {
3839
- await this.transaction((tx) => this.setMetaIn(tx, key, value));
3843
+ async setMeta(key, value, signal) {
3844
+ await this.transaction((tx) => this.setMetaIn(tx, key, value), signal);
3840
3845
  }
3841
3846
  async enqueueStatusResult(tx, snapshot, claim, resultHead) {
3842
3847
  if (!this.activityAuthors.size || !snapshot.lastResult?.trim()) return;
@@ -4142,12 +4147,16 @@ var PullRequestInbox = class {
4142
4147
  return true;
4143
4148
  }
4144
4149
  /** Upgrade historical waiting results without synthetic webhooks or model passes. */
4145
- async backfillStatusDeliveries() {
4146
- for (const observed of await this.waitsToEvaluate(true, true)) await this.transaction(async (tx) => {
4147
- const current = await this.getIn(tx, observed.repository, observed.number);
4148
- if (!current || current.lease || current.status !== "waiting" || current.generation !== current.handled || current.generation !== observed.generation || (current.revision ?? 0) !== (observed.revision ?? 0)) return;
4149
- await this.enqueueStatusResult(tx, current, void 0, current.wait?.headSha);
4150
- });
4150
+ async backfillStatusDeliveries(signal) {
4151
+ for (const observed of await this.waitsToEvaluate(true, true)) {
4152
+ signal?.throwIfAborted();
4153
+ await this.transaction(async (tx) => {
4154
+ const current = await this.getIn(tx, observed.repository, observed.number);
4155
+ signal?.throwIfAborted();
4156
+ if (!current || current.lease || current.status !== "waiting" || current.generation !== current.handled || current.generation !== observed.generation || (current.revision ?? 0) !== (observed.revision ?? 0)) return;
4157
+ await this.enqueueStatusResult(tx, current, void 0, current.wait?.headSha);
4158
+ });
4159
+ }
4151
4160
  }
4152
4161
  async recordWorkerBlocker(observed, revision) {
4153
4162
  await this.transaction(async (tx) => {
@@ -4421,7 +4430,7 @@ var PullRequestInbox = class {
4421
4430
  eligible(repository, pr) {
4422
4431
  return Boolean(pr && pr.state === "open" && matchesBabysitterPullRequestFilter(pullRequestFilterContext(repository, pr), this.filter, "pull-request"));
4423
4432
  }
4424
- async seed(repository, value) {
4433
+ async seed(repository, value, signal) {
4425
4434
  repository = repository.toLowerCase();
4426
4435
  invariant(this.repositories.includes(repository), "the runtime seeds only repositories that its repository source lists");
4427
4436
  const pr = normalizePullRequest(value);
@@ -4439,9 +4448,9 @@ var PullRequestInbox = class {
4439
4448
  }
4440
4449
  await this.put(tx, s);
4441
4450
  return s;
4442
- });
4451
+ }, signal);
4443
4452
  }
4444
- async ingest(id, event, value) {
4453
+ async ingest(id, event, value, signal) {
4445
4454
  const payload = parseDelivery(value);
4446
4455
  return await this.transaction(async (tx) => {
4447
4456
  const t = this.tables;
@@ -4701,12 +4710,13 @@ var PullRequestInbox = class {
4701
4710
  if (wake && !s.wait && s.status !== "terminal" && !exhausted) queued.push(number);
4702
4711
  }
4703
4712
  return await finish(numbers.size ? void 0 : "no matching PR head");
4704
- });
4713
+ }, signal);
4705
4714
  }
4706
4715
  /** Leases up to `limit` eligible PRs. `skip` leaves a candidate unclaimed for this call. */
4707
4716
  async claim(limit, options = {}) {
4708
4717
  if (!this.repositories.length || limit < 1) return [];
4709
4718
  return await this.transaction(async (tx) => {
4719
+ options.signal?.throwIfAborted();
4710
4720
  const now = this.clock(), claims = [], t = this.tables;
4711
4721
  const repositories = this.repositoryFilter("p.repository");
4712
4722
  const mainRepair = this.mainRepairBranchPrefix;
@@ -4730,6 +4740,7 @@ var PullRequestInbox = class {
4730
4740
  ...this.priorityLabels
4731
4741
  ]);
4732
4742
  for (const candidate of candidates) {
4743
+ options.signal?.throwIfAborted();
4733
4744
  if (claims.length >= limit) break;
4734
4745
  const repository = stringValue(candidate.repository), number = Number(candidate.number);
4735
4746
  if (!this.claimStackChildren && candidate.base_ref !== null && candidate.base_ref !== void 0 && (await tx.execute(`SELECT 1 FROM ${t.pullRequests}
@@ -4742,6 +4753,7 @@ var PullRequestInbox = class {
4742
4753
  candidate.base_repository
4743
4754
  ])).length) continue;
4744
4755
  const s = await this.getRowIn(tx, candidate);
4756
+ options.signal?.throwIfAborted();
4745
4757
  if (!s) continue;
4746
4758
  if (s.pr && !this.eligible(s.repository, s.pr)) continue;
4747
4759
  if (options.only && !options.only(s)) continue;
@@ -4758,6 +4770,7 @@ var PullRequestInbox = class {
4758
4770
  snapshot: structuredClone(s)
4759
4771
  });
4760
4772
  }
4773
+ options.signal?.throwIfAborted();
4761
4774
  return claims;
4762
4775
  });
4763
4776
  }
@@ -4790,7 +4803,7 @@ var PullRequestInbox = class {
4790
4803
  return true;
4791
4804
  });
4792
4805
  }
4793
- async refreshThreads(observed, threads) {
4806
+ async refreshThreads(observed, threads, signal) {
4794
4807
  return await this.transaction(async (tx) => {
4795
4808
  const s = await this.getIn(tx, observed.repository, observed.number);
4796
4809
  if (!s || s.lease || s.generation !== observed.generation || (s.revision ?? 0) !== (observed.revision ?? 0)) return false;
@@ -4814,7 +4827,7 @@ var PullRequestInbox = class {
4814
4827
  if (changed && s.status !== "terminal") this.dirty(s, "review-threads:reconciled");
4815
4828
  await this.put(tx, s);
4816
4829
  return true;
4817
- });
4830
+ }, signal);
4818
4831
  }
4819
4832
  /** Retain a worker's verified thread resolution even when its webhook is missing. */
4820
4833
  async recordThreadResolution(claim, id, observed) {
@@ -5095,7 +5108,7 @@ var PullRequestInbox = class {
5095
5108
  AND waiting=1 AND status<>'terminal' AND lease IS NULL ${includeExternal || includeIdle ? "" : "AND generation>handled"} ORDER BY dirty_at, number`, [this.scope, ...repositories.args])).flatMap((row) => this.parseRow(row, (value) => this.cleanSnapshot(parseSnapshot(value))) ?? []).filter((snapshot) => snapshot.generation > snapshot.handled || includeExternal && (snapshot.wait?.wake || snapshot.wait?.retryAt !== void 0) || includeIdle && !snapshot.wait?.wake);
5096
5109
  }
5097
5110
  /** Records that the host evaluated a wait's new events and the wait still holds. */
5098
- async acknowledgeWait(observed) {
5111
+ async acknowledgeWait(observed, signal) {
5099
5112
  return await this.transaction(async (tx) => {
5100
5113
  const s = await this.getIn(tx, observed.repository, observed.number);
5101
5114
  if (!s?.wait || s.lease || s.status === "terminal" || s.generation !== observed.generation || (s.revision ?? 0) !== (observed.revision ?? 0)) return false;
@@ -5104,7 +5117,7 @@ var PullRequestInbox = class {
5104
5117
  await this.put(tx, s);
5105
5118
  await this.enqueueStatusResult(tx, s, void 0, s.wait.headSha);
5106
5119
  return true;
5107
- });
5120
+ }, signal);
5108
5121
  }
5109
5122
  /** Re-evaluate structured evidence outside an Agent invocation before calling this method. */
5110
5123
  async wake(observed, evidenceKey, options = {}) {
@@ -5132,7 +5145,7 @@ var PullRequestInbox = class {
5132
5145
  this.dirty(s, "wait:evidence-changed");
5133
5146
  await this.put(tx, s);
5134
5147
  return true;
5135
- });
5148
+ }, options.signal);
5136
5149
  }
5137
5150
  /**
5138
5151
  * Frees every lease in this scope at startup and returns how many were held. Call it only when one
@@ -5154,18 +5167,21 @@ var PullRequestInbox = class {
5154
5167
  return released;
5155
5168
  });
5156
5169
  }
5157
- async recoverLeases() {
5170
+ async recoverLeases(signal) {
5158
5171
  await this.transaction(async (tx) => {
5172
+ signal?.throwIfAborted();
5159
5173
  const now = this.clock();
5160
5174
  const rows = await tx.execute(`SELECT repository, number FROM ${this.tables.pullRequests} WHERE scope=? AND lease IS NOT NULL AND lease_until<=?`, [this.scope, now]);
5161
5175
  for (const row of rows) {
5162
5176
  const s = await this.getRowIn(tx, row);
5177
+ signal?.throwIfAborted();
5163
5178
  if (!s?.lease || s.leaseUntil > now) continue;
5164
5179
  s.lease = null;
5165
5180
  s.leaseUntil = 0;
5166
5181
  if (s.status !== "terminal") s.status = "ready";
5167
5182
  await this.put(tx, s);
5168
5183
  }
5184
+ signal?.throwIfAborted();
5169
5185
  });
5170
5186
  }
5171
5187
  async summary() {
@@ -5293,14 +5309,18 @@ var PullRequestInbox = class {
5293
5309
  }
5294
5310
  }
5295
5311
  /** Drops delivery payloads after `payloadMs` and delivery IDs after `idMs`. Recent IDs still deduplicate redeliveries. */
5296
- async pruneDeliveries({ payloadMs = 864e5, idMs = 6048e5 } = {}) {
5312
+ async pruneDeliveries({ payloadMs = 864e5, idMs = 6048e5, signal } = {}) {
5297
5313
  const now = this.clock();
5298
5314
  await this.transaction(async (tx) => {
5315
+ signal?.throwIfAborted();
5299
5316
  await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key>='ci-evidence:v1:' AND key<'ci-evidence:v1;'
5300
5317
  AND CASE WHEN NOT json_valid(value) THEN 1 WHEN json_type(value)<>'object' THEN 1
5301
5318
  WHEN coalesce(json_type(value, '$.fetchedAt'), '') NOT IN ('integer', 'real') THEN 1 ELSE json_extract(value, '$.fetchedAt')<? END`, [this.scope, now - payloadMs]);
5319
+ signal?.throwIfAborted();
5302
5320
  await tx.execute(`DELETE FROM ${this.tables.deliveries} WHERE scope=? AND received<?`, [this.scope, now - idMs]);
5321
+ signal?.throwIfAborted();
5303
5322
  await tx.execute(`UPDATE ${this.tables.deliveries} SET payload=NULL WHERE scope=? AND received<? AND payload IS NOT NULL`, [this.scope, now - payloadMs]);
5323
+ signal?.throwIfAborted();
5304
5324
  });
5305
5325
  }
5306
5326
  };
@@ -5649,14 +5669,17 @@ async function readThreadComments(request, id) {
5649
5669
  /** REST snapshots fill webhook gaps without asking an LLM to poll GitHub. */
5650
5670
  async function readSnapshot(read, repository, number, readThreads, activityAuthors = [], signal) {
5651
5671
  const prefix = `repos/${repository}`;
5652
- const [raw] = await read(`${prefix}/pulls/${number}`, ".");
5672
+ signal?.throwIfAborted();
5673
+ const [raw] = await read(`${prefix}/pulls/${number}`, ".", signal);
5674
+ signal?.throwIfAborted();
5653
5675
  const pr = parsePullRequest(raw);
5654
5676
  if (!pr.head?.sha) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_GITHUB_HEAD_MISSING();
5655
5677
  if (pr.state !== "open") return { pr };
5656
5678
  const readAll = async (path, projection) => {
5657
5679
  const items = [];
5658
5680
  for (let page = 1;; page++) {
5659
- const batch = await read(`${path}&page=${page}`, projection);
5681
+ const batch = await read(`${path}&page=${page}`, projection, signal);
5682
+ signal?.throwIfAborted();
5660
5683
  items.push(...batch);
5661
5684
  if (batch.length < 100) return items;
5662
5685
  }
@@ -5709,27 +5732,33 @@ async function hydrateSnapshot(inbox, claim, read, readThreads, activityAuthors
5709
5732
  });
5710
5733
  return Object.keys(patch).length ? await inbox.hydrate(claim, patch) : true;
5711
5734
  }
5712
- async function reconcileOneSnapshot(inbox, read, now = Date.now(), readThreads, activityAuthors = []) {
5735
+ async function reconcileOneSnapshot(inbox, read, now = Date.now(), readThreads, activityAuthors = [], signal) {
5713
5736
  const globalKey = "snapshot-reconcile-next";
5714
5737
  const globalNext = await inbox.metaNumber(globalKey);
5738
+ signal?.throwIfAborted();
5715
5739
  if (globalNext === void 0) {
5716
- await inbox.setMeta(globalKey, now + 9e5);
5740
+ await inbox.setMeta(globalKey, now + 9e5, signal);
5717
5741
  return;
5718
5742
  }
5719
5743
  if (globalNext > now) return;
5720
- await inbox.setMeta(globalKey, now + 6e4);
5744
+ await inbox.setMeta(globalKey, now + 6e4, signal);
5745
+ signal?.throwIfAborted();
5721
5746
  const next = await inbox.nextProbe();
5747
+ signal?.throwIfAborted();
5722
5748
  if (!next || next.probedAt > now) return;
5723
5749
  const s = await inbox.get(next.repository, next.number);
5724
5750
  if (!s) return;
5725
- await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors);
5751
+ await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors, signal);
5726
5752
  }
5727
5753
  /** Reads one PR over REST and ingests it as synthetic deliveries, so missed webhooks are recovered. */
5728
- async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors = []) {
5729
- await inbox.setMeta(`snapshot-probe:${s.repository}:${s.number}`, now + 9e5);
5730
- const snapshot = await readSnapshot(read, s.repository, s.number, readThreads, activityAuthors);
5731
- if (snapshot.threads) await inbox.refreshThreads(s, snapshot.threads);
5754
+ async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors = [], signal) {
5755
+ signal?.throwIfAborted();
5756
+ await inbox.setMeta(`snapshot-probe:${s.repository}:${s.number}`, now + 9e5, signal);
5757
+ const snapshot = await readSnapshot(read, s.repository, s.number, readThreads, activityAuthors, signal);
5758
+ signal?.throwIfAborted();
5759
+ if (snapshot.threads) await inbox.refreshThreads(s, snapshot.threads, signal);
5732
5760
  const ingest = async (event, payload) => {
5761
+ signal?.throwIfAborted();
5733
5762
  const full = {
5734
5763
  repository: { full_name: s.repository },
5735
5764
  ...payload
@@ -5743,7 +5772,7 @@ async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors =
5743
5772
  }
5744
5773
  };
5745
5774
  const id = `reconcile:${createHash("sha256").update(JSON.stringify([event, identity])).digest("hex")}`;
5746
- await inbox.ingest(id, event, full);
5775
+ await inbox.ingest(id, event, full, signal);
5747
5776
  };
5748
5777
  await ingest("pull_request", {
5749
5778
  action: snapshot.pr.state === "closed" ? "closed" : "synchronize",
@@ -5779,7 +5808,8 @@ async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors =
5779
5808
  for (const [key, item] of Object.entries(s.checks)) {
5780
5809
  const kind = key.slice(0, key.indexOf(":"));
5781
5810
  if (kind !== "workflow_run" && kind !== "check_suite" || item.deleted || item.status === "completed" || item.head_sha !== snapshot.pr.head?.sha) continue;
5782
- const [fresh] = await read(kind === "workflow_run" ? `repos/${s.repository}/actions/runs/${item.id}` : `repos/${s.repository}/check-suites/${item.id}`, ".");
5811
+ signal?.throwIfAborted();
5812
+ const [fresh] = await read(kind === "workflow_run" ? `repos/${s.repository}/actions/runs/${item.id}` : `repos/${s.repository}/check-suites/${item.id}`, ".", signal);
5783
5813
  const evidence = parseEvidence(fresh);
5784
5814
  await ingest(kind, {
5785
5815
  action: evidence.status === "completed" ? "completed" : String(evidence.status ?? ""),
@@ -5865,19 +5895,23 @@ function openPullRequestChecksSettled(pr) {
5865
5895
  const state = pr.commits.nodes[0]?.commit.statusCheckRollup?.state;
5866
5896
  return typeof state === "string" && !runningRollup.has(state);
5867
5897
  }
5868
- const changeDetectionInFlight = /* @__PURE__ */ new WeakSet();
5898
+ const changeDetectionInFlight = /* @__PURE__ */ new WeakMap();
5869
5899
  /**
5870
5900
  * Reads every open PR of each repository in one GraphQL query per 50 PRs, at most once a minute,
5871
5901
  * and at most once per 1.5 seconds per repository, so many repositories stay within the GraphQL rate limit.
5872
5902
  * Seeds new PRs and marks PRs whose fingerprint changed, or that closed, for a targeted REST probe.
5873
5903
  * This recovers lost webhook deliveries without probing unchanged PRs.
5874
5904
  */
5875
- async function detectChangedPullRequests(inbox, graphql, repositories, now = Date.now(), allowSeed = true, onError) {
5876
- if (changeDetectionInFlight.has(inbox)) return;
5877
- changeDetectionInFlight.add(inbox);
5905
+ async function detectChangedPullRequests(inbox, graphql, repositories, now = Date.now(), allowSeed = true, onError, signal) {
5906
+ const pendingRun = changeDetectionInFlight.get(inbox);
5907
+ if (pendingRun && !pendingRun.signal?.aborted) return;
5908
+ const run = { signal };
5909
+ changeDetectionInFlight.set(inbox, run);
5878
5910
  try {
5879
5911
  if ((await inbox.metaNumber("change-detect-next") ?? 0) > now) return;
5880
- await inbox.setMeta("change-detect-next", now + Math.max(6e4, repositories.length * 1500));
5912
+ signal?.throwIfAborted();
5913
+ await inbox.setMeta("change-detect-next", now + Math.max(6e4, repositories.length * 1500), signal);
5914
+ signal?.throwIfAborted();
5881
5915
  const tracked = await inbox.summary();
5882
5916
  const trackedKeys = new Set(tracked.map((item) => `${item.repository}:${item.number}`));
5883
5917
  for (const repository of repositories.map((r) => r.toLowerCase())) try {
@@ -5887,11 +5921,13 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5887
5921
  const cursors = /* @__PURE__ */ new Set();
5888
5922
  let after = null;
5889
5923
  do {
5924
+ signal?.throwIfAborted();
5890
5925
  const raw = await graphql(repository)(OPEN_PULL_REQUESTS, {
5891
5926
  owner,
5892
5927
  name,
5893
5928
  after
5894
5929
  });
5930
+ signal?.throwIfAborted();
5895
5931
  const response = v.parse(envelope, raw);
5896
5932
  if (response.errors?.length) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_GITHUB_QUERY_FAILED({
5897
5933
  query: "open pull request",
@@ -5904,23 +5940,28 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5904
5940
  if (after) cursors.add(after);
5905
5941
  } while (after);
5906
5942
  const mark = async (number, fingerprint, settled) => {
5943
+ signal?.throwIfAborted();
5907
5944
  const key = `snapshot-changed:${repository}:${number}`;
5908
5945
  const pending = v.safeParse(pendingChangeSchema, await inbox.meta(key));
5946
+ signal?.throwIfAborted();
5909
5947
  if (await inbox.meta(`change-fingerprint:${repository}:${number}`) === fingerprint || pending.success && pending.output.fingerprint === fingerprint) return;
5948
+ signal?.throwIfAborted();
5910
5949
  await inbox.setMeta(key, {
5911
5950
  fingerprint,
5912
5951
  retryAt: 0,
5913
5952
  settled,
5914
5953
  markedAt: pending.success ? pending.output.markedAt ?? now : now
5915
- });
5954
+ }, signal);
5916
5955
  };
5917
5956
  for (const [number, pr] of open) {
5957
+ signal?.throwIfAborted();
5918
5958
  const fingerprint = openPullRequestFingerprint(pr);
5919
5959
  const key = `${repository}:${number}`;
5920
5960
  if (trackedKeys.has(key) || await inbox.get(repository, number)) {
5921
5961
  await mark(number, fingerprint, openPullRequestChecksSettled(pr));
5922
5962
  continue;
5923
5963
  }
5964
+ signal?.throwIfAborted();
5924
5965
  if (!allowSeed) continue;
5925
5966
  await inbox.seed(repository, {
5926
5967
  number,
@@ -5941,31 +5982,33 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5941
5982
  sha: pr.baseRefOid ?? void 0,
5942
5983
  ref: pr.baseRefName
5943
5984
  }
5944
- });
5945
- await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint);
5985
+ }, signal);
5986
+ signal?.throwIfAborted();
5987
+ await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint, signal);
5946
5988
  }
5947
5989
  for (const item of tracked) if (item.repository === repository && item.status !== "terminal" && !open.has(item.number)) await mark(item.number, "closed", true);
5948
5990
  } catch (error) {
5991
+ signal?.throwIfAborted();
5949
5992
  onError?.(repository, error);
5950
5993
  }
5951
5994
  } finally {
5952
- changeDetectionInFlight.delete(inbox);
5995
+ if (changeDetectionInFlight.get(inbox) === run) changeDetectionInFlight.delete(inbox);
5953
5996
  }
5954
5997
  }
5955
5998
  /**
5956
5999
  * Probes up to `limit` PRs that change detection marked, then records their fingerprints. PRs whose
5957
- * checks settled or that closed come first, up to `settledLimit`: on 2026-11-16 a third of webhook
5958
- * deliveries timed out, 43 PRs waited for a probe, and green PRs waited 30 minutes or more while the
5959
- * probes read PRs whose checks were still running. Older marks come before newer ones.
6000
+ * checks settled or that closed come first, up to `settledLimit`: when many webhook deliveries are
6001
+ * lost, green PRs must not wait while the probes read PRs whose checks are still running. Older marks come before newer ones.
5960
6002
  */
5961
- async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads, activityAuthors = [], limit = 3, settledLimit = 10) {
6003
+ async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads, activityAuthors = [], limit = 3, settledLimit = 10, signal) {
5962
6004
  let probed = 0;
5963
6005
  const due = [];
5964
6006
  for (const [key, value] of await inbox.metaEntries("snapshot-changed:")) {
6007
+ signal?.throwIfAborted();
5965
6008
  const pending = v.safeParse(pendingChangeSchema, value);
5966
6009
  const [, repository, number] = /^snapshot-changed:(.+):(\d+)$/.exec(key) ?? [];
5967
6010
  if (!pending.success || !repository || !number) {
5968
- await inbox.deleteMeta(key);
6011
+ await inbox.deleteMeta(key, signal);
5969
6012
  continue;
5970
6013
  }
5971
6014
  if (pending.output.retryAt <= now) due.push({
@@ -5978,21 +6021,25 @@ async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads,
5978
6021
  due.sort((a, b) => Number(Boolean(b.pending.settled)) - Number(Boolean(a.pending.settled)) || (a.pending.markedAt ?? 0) - (b.pending.markedAt ?? 0));
5979
6022
  let settled = 0;
5980
6023
  for (const { key, repository, number, pending } of due) {
6024
+ signal?.throwIfAborted();
5981
6025
  if (pending.settled ? settled >= settledLimit : probed - settled >= limit) continue;
5982
6026
  const s = await inbox.get(repository, Number(number));
6027
+ signal?.throwIfAborted();
5983
6028
  if (!s) {
5984
- await inbox.deleteMeta(key);
6029
+ await inbox.deleteMeta(key, signal);
5985
6030
  continue;
5986
6031
  }
5987
6032
  await inbox.setMeta(key, {
5988
6033
  ...pending,
5989
6034
  retryAt: now + 12e4
5990
- });
6035
+ }, signal);
5991
6036
  probed++;
5992
6037
  if (pending.settled) settled++;
5993
- await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors);
5994
- await inbox.setMeta(`change-fingerprint:${repository}:${number}`, pending.fingerprint);
5995
- await inbox.deleteMeta(key);
6038
+ await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors, signal);
6039
+ signal?.throwIfAborted();
6040
+ await inbox.setMeta(`change-fingerprint:${repository}:${number}`, pending.fingerprint, signal);
6041
+ signal?.throwIfAborted();
6042
+ await inbox.deleteMeta(key, signal);
5996
6043
  }
5997
6044
  return probed;
5998
6045
  }
@@ -6699,9 +6746,8 @@ const failedConclusions = failed;
6699
6746
  const stuckCheckMs = 18e5;
6700
6747
  /**
6701
6748
  * GitHub Actions keeps a job queued for up to 24 hours and runs it for up to 6, so only its check runs
6702
- * past those limits are stuck. GitHub sets a queued run's `started_at` when it creates the run. On
6703
- * 2026-11-07 vite-hub/vitehub jobs waited up to 3 hours for a runner, and a 30-minute limit let
6704
- * passes push over 62 queued CI runs in 17 hours.
6749
+ * past those limits are stuck. GitHub sets a queued run's `started_at` when it creates the run. A job
6750
+ * can wait hours for a runner, and a shorter limit lets passes push over CI runs that are only queued.
6705
6751
  */
6706
6752
  const stuckQueuedCheckMs = 864e5;
6707
6753
  const stuckRunningCheckMs = 288e5;
@@ -6845,8 +6891,8 @@ function checksStillRunning(s, now = Date.now(), policy) {
6845
6891
  }
6846
6892
  /**
6847
6893
  * Required checks that never reported on a head whose checks all finished ten minutes ago. Waiting never
6848
- * brings them: on 2026-11-01 the `ci` job was missing from the successful runs of vitehub #3161 and
6849
- * #3162, and both waited overnight for "required checks pending".
6894
+ * brings them: a required job can be missing from a run that succeeded, and the PR then waits for
6895
+ * "required checks pending" forever.
6850
6896
  */
6851
6897
  function missingRequiredChecks(s, evaluation, now = Date.now()) {
6852
6898
  if (evaluation?.state !== "pending" || !evaluation.missing.length) return [];
@@ -7091,19 +7137,45 @@ const pushMarginMs = 12e4;
7091
7137
  */
7092
7138
  async function checksTestedBase(reader, snapshot, head, baseRef, conclusions, signal) {
7093
7139
  const { repository } = snapshot;
7094
- const runIds = [...new Set(Object.values(snapshot.checks).flatMap((check) => {
7095
- if (check.deleted || check.head_sha !== head || isBabysitterCheckRun(check) || !conclusions.has(String(check.conclusion).toLowerCase())) return [];
7096
- const id = String(check.html_url ?? check.details_url ?? "").match(/\/actions\/runs\/(\d+)/)?.[1];
7140
+ const source = snapshot.pr?.head;
7141
+ const sourceRepository = source?.repo?.full_name;
7142
+ const fork = sourceRepository != null && sourceRepository.toLowerCase() !== repository.toLowerCase();
7143
+ const readRun = (id) => reader.page(`repos/${repository}/actions/runs/${id}`, signal);
7144
+ const candidates = Object.values(snapshot.checks).filter((check) => !check.deleted && check.head_sha === head && !isBabysitterCheckRun(check) && conclusions.has(String(check.conclusion).toLowerCase()));
7145
+ const checkTime = (check) => String(check.started_at ?? check.completed_at ?? "");
7146
+ const ordered = candidates.sort((left, right) => checkTime(right).localeCompare(checkTime(left)));
7147
+ const newest = /* @__PURE__ */ new Map();
7148
+ const reads = /* @__PURE__ */ new Map();
7149
+ for (const check of ordered) {
7150
+ const name = String(check.name);
7151
+ if (newest.has(name)) continue;
7152
+ if (fork) {
7153
+ const id = actionLocation(repository, check)?.runId;
7154
+ if (!id) continue;
7155
+ const pending = reads.get(id) ?? readRun(id);
7156
+ reads.set(id, pending);
7157
+ const run = await pending;
7158
+ if (!isRuntimeRecord(run) || run.event !== "pull_request" || run.head_sha !== head || !source?.ref || run.head_branch !== source.ref || !isRuntimeRecord(run.head_repository) || String(run.head_repository.full_name).toLowerCase() !== sourceRepository.toLowerCase()) continue;
7159
+ }
7160
+ newest.set(name, check);
7161
+ }
7162
+ const runIds = [...new Set([...newest.values()].flatMap((check) => {
7163
+ const id = actionLocation(repository, check)?.runId;
7097
7164
  return id ? [id] : [];
7098
7165
  }))];
7099
7166
  const runs = await Promise.all(runIds.map(async (id) => {
7100
- const run = await reader.page(`repos/${repository}/actions/runs/${id}`, signal);
7167
+ const run = await (reads.get(id) ?? readRun(id));
7101
7168
  if (!isRuntimeRecord(run)) return {
7102
7169
  created: NaN,
7103
7170
  base: void 0,
7104
7171
  hasPullRequestMetadata: false
7105
7172
  };
7106
- const bases = Array.isArray(run.pull_requests) ? run.pull_requests.map((pr) => isRuntimeRecord(pr) && isRuntimeRecord(pr.base) ? pr.base.sha : void 0).filter((base) => hasRuntimeType(base, "string")) : [];
7173
+ const bases = Array.isArray(run.pull_requests) ? run.pull_requests.flatMap((pr) => isRuntimeRecord(pr) && isRuntimeRecord(pr.base) && (!fork || pr.number === snapshot.number && pr.base.ref === baseRef) && hasRuntimeType(pr.base.sha, "string") ? [pr.base.sha] : []) : [];
7174
+ if (fork && Array.isArray(run.pull_requests) && !run.pull_requests.length) return {
7175
+ created: Date.parse(String(run.created_at)),
7176
+ base: void 0,
7177
+ hasPullRequestMetadata: false
7178
+ };
7107
7179
  return {
7108
7180
  created: Date.parse(String(run.created_at)),
7109
7181
  base: bases.length === 1 ? bases[0] : void 0,
@@ -7113,7 +7185,7 @@ async function checksTestedBase(reader, snapshot, head, baseRef, conclusions, si
7113
7185
  const exactBases = runs.filter((run) => run.hasPullRequestMetadata).map((run) => run.base);
7114
7186
  if (exactBases.length && exactBases.some((base) => !base)) return void 0;
7115
7187
  const exact = runs.slice().sort((a, b) => a.created - b.created).find((run) => run.hasPullRequestMetadata && run.base)?.base;
7116
- if (exact) return exact;
7188
+ if (exact && (!fork || runs.every((run) => run.hasPullRequestMetadata))) return exact;
7117
7189
  const started = runs.map((run) => run.created);
7118
7190
  const ranAt = Math.min(...started.filter(Number.isFinite));
7119
7191
  if (!Number.isFinite(ranAt)) return void 0;
@@ -7137,7 +7209,8 @@ async function staleBaseOverlap(reader, snapshot, live, signal, testedConclusion
7137
7209
  const changed = new Set(files.flatMap((file) => isRuntimeRecord(file) ? [file.filename, file.previous_filename] : []).filter((file) => hasRuntimeType(file, "string")));
7138
7210
  if (!testedBase) return [...changed];
7139
7211
  const compare = await reader.page(`repos/${repository}/compare/${testedBase}...${encodeURIComponent(live.base.ref)}?per_page=100`, signal);
7140
- if (!isRuntimeRecord(compare) || !compare.ahead_by) return [];
7212
+ if (!isRuntimeRecord(compare) || typeof compare.ahead_by !== "number" || Number(compare.behind_by) > 0) return [...changed];
7213
+ if (compare.ahead_by === 0) return [];
7141
7214
  if (!Array.isArray(compare.files) || compare.files.length >= 100) return [...changed];
7142
7215
  const baseFiles = compare.files.flatMap((file) => isRuntimeRecord(file) ? [file.filename, file.previous_filename] : []);
7143
7216
  return [...new Set(baseFiles.filter((file) => hasRuntimeType(file, "string") && changed.has(file)))];
@@ -7246,8 +7319,7 @@ function jobFailureFacts(log) {
7246
7319
  }
7247
7320
  /**
7248
7321
  * The wait for a PR whose failing checks it did not cause, or undefined when a pass has work: one `pr`
7249
- * failure, or no failure. On 2026-11-05 vitehub#3024 and comark-ui#351 spent their repair pushes on
7250
- * failures their changes did not cause.
7322
+ * failure, or no failure. Without it, a pass spends its repair pushes on failures the PR did not cause.
7251
7323
  */
7252
7324
  function unrelatedFailureWait(causes, base, now = Date.now()) {
7253
7325
  const covered = (gate) => gate.cause === "pr" && gate.gate && causes.some((other) => other !== gate && !(other.cause === "pr" && other.gate) && other.runId !== void 0 && other.runId === gate.runId);
@@ -7287,8 +7359,7 @@ function failedOwnActions(snapshot, reviewChecks, inheritedCheckIds = /* @__PURE
7287
7359
  }
7288
7360
  /**
7289
7361
  * The required-check evaluation with the PR's own failing Actions counted. Where a branch requires no
7290
- * checks, GitHub reported `passed` beside failing CI, so an assessed head could merge red
7291
- * (comark-plugins#45). Failures inherited from the base do not count against the PR, and a required
7362
+ * checks, GitHub reports `passed` beside failing CI, so an assessed head could merge red. Failures inherited from the base do not count against the PR, and a required
7292
7363
  * check named in `bypassChecks` that only repeats the base's failure passes.
7293
7364
  */
7294
7365
  function inheritedCheckEvaluation(snapshot, policy, inheritedCheckIds, reviewChecks, bypassChecks = /* @__PURE__ */ new Set()) {
@@ -7438,6 +7509,11 @@ function directMergeBranchSafety(repository, pr, openChildren) {
7438
7509
  if (!hasRuntimeType(branch, "string")) return "pull request source branch unavailable";
7439
7510
  return openChildren.some((child) => String(field(child, "state")).toLowerCase() === "open" && field(child, "base", "ref") === branch) ? stackChildBaseDeletion : true;
7440
7511
  }
7512
+ /** Whether a PR's head branch lives in another repository than `repository`, such as a fork. */
7513
+ function isForkHead(pr, repository) {
7514
+ const headRepository = field(pr, "head", "repo", "full_name");
7515
+ return hasRuntimeType(headRepository, "string") && headRepository.toLowerCase() !== repository.toLowerCase();
7516
+ }
7441
7517
  /** The head and base branch of a PR whose head branch lives in `repository`, which the host can push to. */
7442
7518
  function sameRepositoryBranches(pr, repository) {
7443
7519
  const head = field(pr, "head", "ref");
@@ -7457,6 +7533,51 @@ function sameRepositoryBranches(pr, repository) {
7457
7533
  function foldMethod(method, repository) {
7458
7534
  return isRuntimeRecord(repository) && repository.allow_merge_commit === false ? method : "merge";
7459
7535
  }
7536
+ /**
7537
+ * Whether a workflow can run on a push or creation of `branch`, including as a local reusable
7538
+ * workflow called by another workflow. Anything we cannot read counts as yes.
7539
+ */
7540
+ function runsOnPush(workflow, branch) {
7541
+ let document;
7542
+ try {
7543
+ document = parse(workflow);
7544
+ } catch {
7545
+ return true;
7546
+ }
7547
+ if (!isRuntimeRecord(document)) return true;
7548
+ const on = document.on ?? document.true;
7549
+ if (typeof on === "string" || Array.isArray(on)) return [on].flat().some((event) => event === "push" || event === "create" || event === "workflow_call");
7550
+ if (!isRuntimeRecord(on)) return true;
7551
+ if ("create" in on || "workflow_call" in on) return true;
7552
+ if (!("push" in on)) return false;
7553
+ const push = on.push;
7554
+ if (push == null) return true;
7555
+ if (!isRuntimeRecord(push)) return true;
7556
+ const list = (value) => value === void 0 ? void 0 : [value].flat().map(String);
7557
+ const branches = list(push.branches);
7558
+ const ignored = list(push["branches-ignore"]);
7559
+ if ([...branches ?? [], ...ignored ?? []].some((pattern) => /[[\\?+]/.test(pattern))) return true;
7560
+ if (!branches && !ignored) return push.tags === void 0 && push["tags-ignore"] === void 0;
7561
+ if (ignored) return !ignored.some((pattern) => branchFilter(pattern).test(branch));
7562
+ let match = false;
7563
+ for (const pattern of branches) if (pattern.startsWith("!")) {
7564
+ if (branchFilter(pattern.slice(1)).test(branch)) match = false;
7565
+ } else if (branchFilter(pattern).test(branch)) match = true;
7566
+ return match;
7567
+ }
7568
+ /** GitHub's branch filter pattern as a regular expression: `**` crosses `/`, `*` does not. */
7569
+ function branchFilter(pattern) {
7570
+ let source = "";
7571
+ for (let index = 0; index < pattern.length; index++) {
7572
+ const char = pattern[index];
7573
+ if (char === "*" && pattern[index + 1] === "*") {
7574
+ source += ".*";
7575
+ index++;
7576
+ } else if (char === "*") source += "[^/]*";
7577
+ else source += char.replace(/[.^${}()|[\]\\]/g, "\\$&");
7578
+ }
7579
+ return new RegExp(`^${source}$`);
7580
+ }
7460
7581
  //#endregion
7461
7582
  //#region src/babysitter/merge-ready.ts
7462
7583
  /** Fence application callbacks so stalled or rejected readiness never retains a scheduler slot. */
@@ -8032,9 +8153,11 @@ function createBabysitterStatusRecovery(options) {
8032
8153
  }
8033
8154
  })) await inbox.recordWorkerBlocker(snapshot, revision);
8034
8155
  },
8035
- async recover() {
8036
- await inbox.backfillStatusDeliveries();
8156
+ async recover(signal) {
8157
+ await inbox.backfillStatusDeliveries(signal);
8158
+ signal?.throwIfAborted();
8037
8159
  for (const snapshot of await inbox.waitsToEvaluate(true, true)) {
8160
+ signal?.throwIfAborted();
8038
8161
  if (!isWorkerBlocker(snapshot)) continue;
8039
8162
  const head = snapshot.pr?.head?.sha;
8040
8163
  const evidence = createHash("sha256").update(JSON.stringify([
@@ -8078,15 +8201,43 @@ function isTransientNetworkError(error) {
8078
8201
  }
8079
8202
  /** Runs a read again after 1 and 3 seconds while it fails with a transient network error. */
8080
8203
  async function retryTransient(read, signal) {
8081
- for (let attempt = 0;; attempt++) try {
8082
- return await read();
8083
- } catch (error) {
8084
- const delay = retryDelaysMs[attempt];
8085
- if (delay === void 0 || signal?.aborted || !isTransientNetworkError(error)) throw error;
8086
- await setTimeout$1(delay, void 0, { signal });
8204
+ for (let attempt = 0;; attempt++) {
8205
+ signal?.throwIfAborted();
8206
+ try {
8207
+ return await read();
8208
+ } catch (error) {
8209
+ const delay = retryDelaysMs[attempt];
8210
+ if (delay === void 0 || signal?.aborted || !isTransientNetworkError(error)) throw error;
8211
+ await setTimeout$1(delay, void 0, { signal });
8212
+ }
8087
8213
  }
8088
8214
  }
8089
8215
  //#endregion
8216
+ //#region src/babysitter/queue-health.ts
8217
+ /** Derive bounded operational counters from the durable queue, including scheduled retries. */
8218
+ function babysitterQueueHealth(items, now = Date.now()) {
8219
+ const mergedTerminal = (result) => result?.startsWith("Merged ") || result === "Asynchronous merge confirmed by GitHub." || result === "Direct merge outcome reconciled: GitHub reports the pull request merged.";
8220
+ const ready = items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt <= now);
8221
+ const waiting = items.filter((item) => item.status === "waiting");
8222
+ return {
8223
+ working: items.filter((item) => item.status === "working").length,
8224
+ ready: ready.length,
8225
+ scheduled: items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt > now).length,
8226
+ stackBlocked: items.filter((item) => item.stackBlocked).length,
8227
+ waiting: waiting.length,
8228
+ suppressed: items.filter((item) => item.status === "terminal" && item.state === "open" && !mergedTerminal(item.lastResult)).length,
8229
+ oldestReadyAgeMs: ready.reduce((age, item) => Math.max(age, item.dirtyAt === void 0 ? 0 : now - item.dirtyAt), 0),
8230
+ blockers: {
8231
+ checks: waiting.filter((item) => item.wait && item.wait.kind !== "external" && !item.wait.wake).length,
8232
+ dependency: waiting.filter((item) => item.wait?.wake).length,
8233
+ manual: waiting.filter((item) => item.wait?.kind === "external" && !item.wait.wake && item.wait.retryAt === void 0).length,
8234
+ timed: waiting.filter((item) => item.wait?.retryAt !== void 0).length,
8235
+ installCapacity: waiting.filter((item) => item.wait?.reasonCode === "install-capacity").length,
8236
+ noProgress: waiting.filter((item) => item.progressBudget?.exhausted && item.progressBudget.head === item.head).length
8237
+ }
8238
+ };
8239
+ }
8240
+ //#endregion
8090
8241
  //#region src/babysitter/main-repair.ts
8091
8242
  const defaultStuckJobMinutes = 90;
8092
8243
  const branchSchema = v.looseObject({
@@ -8333,7 +8484,7 @@ const stoppedMergeRetryMs = 72e5;
8333
8484
  /**
8334
8485
  * GitHub settles most asynchronous merges in seconds, so poll a pending request less often as it ages:
8335
8486
  * after 30 seconds at first, then after as long as it has been pending, at most every five minutes.
8336
- * vite-hub/vitehub#3350 was polled every 30 seconds for 19 hours.
8487
+ * A fixed 30-second poll can run for hours on a request that GitHub never settles.
8337
8488
  */
8338
8489
  function pendingMergeRetryAt(startedAt, now) {
8339
8490
  return now + Math.min(3e5, Math.max(3e4, now - startedAt));
@@ -8365,6 +8516,11 @@ function createBabysitterRuntime(options) {
8365
8516
  option: "concurrency",
8366
8517
  expected: "a positive integer"
8367
8518
  });
8519
+ const stallMs = options.stallMs ?? 9e5;
8520
+ if (!Number.isFinite(stallMs) || stallMs < 1 || stallMs > 2147483647) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_OPTION_INVALID({
8521
+ option: "stallMs",
8522
+ expected: "milliseconds from 1 to 2147483647"
8523
+ });
8368
8524
  const baseAgent = options.agent;
8369
8525
  assertBabysitterAgent(baseAgent);
8370
8526
  const presetOptions = baseAgent.options;
@@ -8453,7 +8609,7 @@ function createBabysitterRuntime(options) {
8453
8609
  ignoreAssessedBotThreads: presetOptions.ignoreAssessedBotThreads === true
8454
8610
  };
8455
8611
  const schedulerEvent = (name, properties = {}) => options.event?.(name, properties);
8456
- const release = baseAgent.version ?? "36cb7f3d81a66e753f82ebfb46bda4f9cdcc713a9a7ab3953bc1baa6b2c1bd26";
8612
+ const release = baseAgent.version ?? "91ca93f60843c0df231a3f438cf1c2ef1587bfc67b8791323ef4f38cc44ca863";
8457
8613
  const workspaces = options.workspaces;
8458
8614
  const schedulerError = (name, error, properties = {}) => options.error?.(name, error, properties);
8459
8615
  const statusComment = !!verifiedHostIdentity && presetOptions.status?.comment !== false;
@@ -8603,12 +8759,15 @@ function createBabysitterRuntime(options) {
8603
8759
  }
8604
8760
  };
8605
8761
  }
8606
- async function checkMainRepairs(repositories, track) {
8762
+ async function checkMainRepairs(repositories, track, signal) {
8607
8763
  if (!mainRepair || !mainRepairPrefix) return;
8608
8764
  for (const repository of repositories) {
8765
+ signal.throwIfAborted();
8609
8766
  if (!mainRepairWatches(repository) || mainRepairRunning.has(repository)) continue;
8610
8767
  if ((await pullRequestInbox.metaNumber(mainRepairKey(repository)) ?? 0) > Date.now()) continue;
8611
- await pullRequestInbox.setMeta(mainRepairKey(repository), Date.now() + mainRepairIntervalMs);
8768
+ signal.throwIfAborted();
8769
+ await pullRequestInbox.setMeta(mainRepairKey(repository), Date.now() + mainRepairIntervalMs, signal);
8770
+ signal.throwIfAborted();
8612
8771
  mainRepairRunning.add(repository);
8613
8772
  track(repairBaseBranch(mainRepairGitHub(repository, AbortSignal.timeout(3e5)), {
8614
8773
  repository,
@@ -8676,7 +8835,8 @@ function createBabysitterRuntime(options) {
8676
8835
  * Merges the base into the PR branch through GitHub, without a model pass. False when GitHub refuses.
8677
8836
  * `pr` is the live or snapshot PR; its branches allow the merges API fallback.
8678
8837
  */
8679
- async function updateBranch(owner, repository, number, head, signal, pr) {
8838
+ async function updateBranch(owner, repository, number, head, signal, pr, { reopenFork = true } = {}) {
8839
+ if (reopenFork && isForkHead(pr, repository)) return await reopenForkPullRequest(owner, repository, number, head, signal);
8680
8840
  try {
8681
8841
  const { provider } = await forge(repository, signal);
8682
8842
  await provider.request("PUT", `/repos/${repository}/pulls/${number}/update-branch`, {
@@ -8724,6 +8884,109 @@ function createBabysitterRuntime(options) {
8724
8884
  }
8725
8885
  }
8726
8886
  /**
8887
+ * Closes and reopens a fork PR, so its `pull_request` workflows run again on the merge with the current
8888
+ * base. The host cannot update a fork branch: GitHub refuses App pushes to forks. At most hourly per PR.
8889
+ * The host records the close before it sends it, so `recoverForkReopens` reopens a PR that a restart
8890
+ * or a GitHub error left closed.
8891
+ */
8892
+ async function reopenForkPullRequest(owner, repository, number, head, signal) {
8893
+ if (!hostIdentity) return false;
8894
+ const key = forkReopenKey(repository, number);
8895
+ const previous = await pullRequestInbox.meta(key);
8896
+ if (isRuntimeRecord(previous) && (previous.closing === true || Number(previous.at) > Date.now() - 36e5)) return false;
8897
+ const { provider } = await forge(repository, signal);
8898
+ try {
8899
+ const live = (await provider.request("GET", `/repos/${repository}/pulls/${number}`, { signal })).data;
8900
+ if (!isRuntimeRecord(live) || live.state !== "open" || !isRuntimeRecord(live.head) || live.head.sha !== head) {
8901
+ schedulerEvent("babysitter.fork_checks.reopen_skipped", {
8902
+ ...owner,
8903
+ reason: "head changed"
8904
+ });
8905
+ return false;
8906
+ }
8907
+ } catch (error) {
8908
+ await noteForgeQuota(error, "fork-reopen");
8909
+ return false;
8910
+ }
8911
+ await pullRequestInbox.setMeta(key, {
8912
+ at: Date.now(),
8913
+ head,
8914
+ closing: true,
8915
+ login: hostIdentity.toLowerCase()
8916
+ });
8917
+ try {
8918
+ await provider.request("PATCH", `/repos/${repository}/pulls/${number}`, {
8919
+ body: { state: "closed" },
8920
+ signal
8921
+ });
8922
+ await reopenPullRequest(repository, number);
8923
+ } catch (error) {
8924
+ await noteForgeQuota(error, "fork-reopen");
8925
+ schedulerEvent("babysitter.fork_checks.reopen_failed", {
8926
+ ...owner,
8927
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
8928
+ });
8929
+ return false;
8930
+ }
8931
+ await pullRequestInbox.setMeta(key, {
8932
+ at: Date.now(),
8933
+ head,
8934
+ closing: false
8935
+ });
8936
+ schedulerEvent("babysitter.fork_checks.reopened", {
8937
+ ...owner,
8938
+ head_sha: head
8939
+ });
8940
+ return true;
8941
+ }
8942
+ async function reopenPullRequest(repository, number) {
8943
+ const { provider } = await forge(repository, new AbortController().signal);
8944
+ await provider.request("PATCH", `/repos/${repository}/pulls/${number}`, { body: { state: "open" } });
8945
+ }
8946
+ const forkReopenKey = (repository, number) => `fork-reopen:${repository}#${number}`;
8947
+ /**
8948
+ * Finishes a close and reopen that a restart or a GitHub error interrupted. A PR that is still closed
8949
+ * is reopened only when this host's identity closed it while the close was in flight.
8950
+ */
8951
+ async function recoverForkReopens(signal) {
8952
+ for (const [key, value] of await pullRequestInbox.metaEntries("fork-reopen:")) {
8953
+ signal.throwIfAborted();
8954
+ const match = /^fork-reopen:(.+)#(\d+)$/.exec(key);
8955
+ if (!match || !isRuntimeRecord(value) || value.closing !== true || Number(value.at) > Date.now() - 12e4) continue;
8956
+ const [, repository, number] = match;
8957
+ const owner = {
8958
+ repository,
8959
+ pullRequest: Number(number)
8960
+ };
8961
+ try {
8962
+ const { provider } = await forge(repository, signal);
8963
+ const issue = (await provider.request("GET", `/repos/${repository}/issues/${number}`, { signal })).data;
8964
+ if (!isRuntimeRecord(issue)) continue;
8965
+ const closedBy = isRuntimeRecord(issue.closed_by) ? issue.closed_by : void 0;
8966
+ const ours = issue.state === "closed" && typeof value.login === "string" && String(closedBy?.login).toLowerCase() === value.login && Date.parse(String(issue.closed_at)) >= Math.floor(Number(value.at) / 1e3) * 1e3;
8967
+ const merged = isRuntimeRecord(issue.pull_request) && issue.pull_request.merged_at != null;
8968
+ if (ours && !merged) {
8969
+ await reopenPullRequest(repository, Number(number));
8970
+ schedulerEvent("babysitter.fork_checks.reopen_recovered", owner);
8971
+ } else if (issue.state === "closed") schedulerEvent("babysitter.fork_checks.reopen_abandoned", {
8972
+ ...owner,
8973
+ reason: merged ? "merged" : "closed by someone else"
8974
+ });
8975
+ await pullRequestInbox.setMeta(key, {
8976
+ ...value,
8977
+ closing: false
8978
+ }, signal);
8979
+ } catch (error) {
8980
+ signal.throwIfAborted();
8981
+ await noteForgeQuota(error, "fork-reopen-recover");
8982
+ schedulerEvent("babysitter.fork_checks.reopen_failed", {
8983
+ ...owner,
8984
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
8985
+ });
8986
+ }
8987
+ }
8988
+ }
8989
+ /**
8727
8990
  * Failed checks that ran on an older base get one retest on the current base before a model pass,
8728
8991
  * when the base tip has no failing check. One retest per PR every six hours.
8729
8992
  */
@@ -8748,8 +9011,8 @@ function createBabysitterRuntime(options) {
8748
9011
  const conflicted = (snapshot) => snapshot.pr?.mergeable === false || snapshot.pr?.mergeable_state === "dirty";
8749
9012
  /**
8750
9013
  * A job that a runner or network error stopped gets a fresh CI run: the host updates the branch, once
8751
- * per head and base and at most hourly per PR. On 2026-11-09 vitehub#3534 waited 14 hours on a 504
8752
- * from setup-deno that nothing retried.
9014
+ * per head and base and at most hourly per PR. Without it, a PR waits for hours on a transient error,
9015
+ * such as a 504 from a setup action, that nothing retries.
8753
9016
  */
8754
9017
  async function retestInfrastructureFailure(snapshot, owner, signal) {
8755
9018
  const { repository, number } = snapshot;
@@ -8772,8 +9035,216 @@ function createBabysitterRuntime(options) {
8772
9035
  return true;
8773
9036
  }
8774
9037
  /**
8775
- * A required check that never reported gets a fresh run: a branch behind its base is updated, and a
8776
- * current one has its head's Actions runs rerun. Once per head every six hours.
9038
+ * Pushes a fork PR's head to its `merge.forkHeadBranches` branch, so required checks that run only on
9039
+ * pushes to the repository report on it. A push runs the workflow files of the pushed commit with the
9040
+ * repository's permissions, so the host pushes only a head that GitHub reports, now, as:
9041
+ * - approved at that exact SHA by a reviewer with write access, with no change request standing;
9042
+ * - carrying no local action and no workflow that a push to that branch starts, unless the base branch has
9043
+ * the same file now.
9044
+ * It moves only a branch it created itself. Once per head; a refused or failed push is tried again after an hour.
9045
+ */
9046
+ async function pushForkHead(snapshot, owner, missing, signal) {
9047
+ const { repository, number } = snapshot;
9048
+ const head = snapshot.pr?.head?.sha;
9049
+ const baseRef = snapshot.pr?.base?.ref;
9050
+ const template = merge.mode === "direct" ? merge.forkHeadBranches?.get(repository.toLowerCase()) : void 0;
9051
+ if (!template || !head || !baseRef || !isForkHead(snapshot.pr, repository)) return false;
9052
+ const key = forkHeadKey(repository, number);
9053
+ const previous = await pullRequestInbox.meta(key);
9054
+ const record = isRuntimeRecord(previous) ? previous : {};
9055
+ if (record.head === head && (record.pushed === true || Number(record.at) > Date.now() - 36e5)) return false;
9056
+ const branch = template.replaceAll("{number}", String(number));
9057
+ const settle = async (pushed, fields) => {
9058
+ await pullRequestInbox.setMeta(key, {
9059
+ ...record,
9060
+ head,
9061
+ at: Date.now(),
9062
+ pushed,
9063
+ ...fields
9064
+ });
9065
+ };
9066
+ try {
9067
+ const { provider } = await forge(repository, signal);
9068
+ const read = async (path) => (await retryTransient(() => provider.request("GET", path, { signal }), signal)).data;
9069
+ const refusal = await forkHeadRefusal(repository, number, head, baseRef, branch, read);
9070
+ if (refusal) {
9071
+ await settle(false, {});
9072
+ schedulerEvent("babysitter.fork_head.skipped", {
9073
+ ...owner,
9074
+ missing,
9075
+ branch,
9076
+ reason: refusal
9077
+ });
9078
+ return false;
9079
+ }
9080
+ const ref = await read(`/repos/${repository}/git/ref/heads/${branch}`).catch((error) => {
9081
+ if (forgeErrorStatus(error) === 404) return void 0;
9082
+ throw error;
9083
+ });
9084
+ const tip = isRuntimeRecord(ref) && isRuntimeRecord(ref.object) ? ref.object.sha : void 0;
9085
+ if (tip === head) {
9086
+ await settle(true, {
9087
+ branch,
9088
+ sha: head
9089
+ });
9090
+ return false;
9091
+ }
9092
+ if (ref !== void 0 && !(record.branch === branch && tip === record.sha)) {
9093
+ await settle(false, {});
9094
+ schedulerEvent("babysitter.fork_head.skipped", {
9095
+ ...owner,
9096
+ missing,
9097
+ branch,
9098
+ reason: "branch exists and the host did not create it"
9099
+ });
9100
+ return false;
9101
+ }
9102
+ if (ref !== void 0) await provider.request("PATCH", `/repos/${repository}/git/refs/heads/${branch}`, {
9103
+ body: {
9104
+ sha: head,
9105
+ force: true
9106
+ },
9107
+ signal
9108
+ });
9109
+ else await provider.request("POST", `/repos/${repository}/git/refs`, {
9110
+ body: {
9111
+ ref: `refs/heads/${branch}`,
9112
+ sha: head
9113
+ },
9114
+ signal
9115
+ });
9116
+ } catch (error) {
9117
+ await noteForgeQuota(error, "fork-head-push");
9118
+ await settle(false, {});
9119
+ schedulerEvent("babysitter.fork_head.push_failed", {
9120
+ ...owner,
9121
+ missing,
9122
+ branch,
9123
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
9124
+ });
9125
+ return false;
9126
+ }
9127
+ await settle(true, {
9128
+ branch,
9129
+ sha: head
9130
+ });
9131
+ schedulerEvent("babysitter.fork_head.pushed", {
9132
+ ...owner,
9133
+ missing,
9134
+ branch,
9135
+ head_sha: head
9136
+ });
9137
+ return true;
9138
+ }
9139
+ /** Why GitHub's current state does not allow pushing a fork head, or undefined when it does. */
9140
+ async function forkHeadRefusal(repository, number, head, baseRef, branch, read) {
9141
+ const pr = await read(`/repos/${repository}/pulls/${number}`);
9142
+ if (!isRuntimeRecord(pr) || pr.state !== "open" || !isRuntimeRecord(pr.head) || pr.head.sha !== head) return "head changed";
9143
+ const latest = /* @__PURE__ */ new Map();
9144
+ const reviews = await readRest(`repos/${repository}/pulls/${number}/reviews?per_page=100`, ".[]");
9145
+ for (const review of reviews) {
9146
+ if (!isRuntimeRecord(review) || !isRuntimeRecord(review.user) || !hasRuntimeType(review.user.login, "string")) continue;
9147
+ const state = String(review.state ?? "").toUpperCase();
9148
+ if (state === "APPROVED" || state === "CHANGES_REQUESTED" || state === "DISMISSED") latest.set(review.user.login.toLowerCase(), {
9149
+ state,
9150
+ commit: review.commit_id
9151
+ });
9152
+ }
9153
+ if ([...latest.values()].some((review) => review.state === "CHANGES_REQUESTED")) return "changes requested";
9154
+ let approved = false;
9155
+ for (const [login, review] of latest) {
9156
+ if (review.state !== "APPROVED" || review.commit !== head) continue;
9157
+ const permission = await read(`/repos/${repository}/collaborators/${encodeURIComponent(login)}/permission`);
9158
+ if (isRuntimeRecord(permission) && [
9159
+ "admin",
9160
+ "maintain",
9161
+ "write"
9162
+ ].includes(String(permission.permission))) approved = true;
9163
+ }
9164
+ if (!approved) return `no approval of ${head.slice(0, 7)} by a reviewer with write access`;
9165
+ const entries = async (treeish) => {
9166
+ const tree = await read(`/repos/${repository}/git/trees/${encodeURIComponent(treeish)}`);
9167
+ const list = isRuntimeRecord(tree) && Array.isArray(tree.tree) ? tree.tree : [];
9168
+ return new Map(list.flatMap((item) => isRuntimeRecord(item) && hasRuntimeType(item.path, "string") && hasRuntimeType(item.sha, "string") ? [[item.path, {
9169
+ sha: item.sha,
9170
+ type: item.type
9171
+ }]] : []));
9172
+ };
9173
+ const child = async (tree, name) => {
9174
+ const entry = tree.get(name);
9175
+ return entry?.type === "tree" ? {
9176
+ sha: entry.sha,
9177
+ entries: await entries(entry.sha)
9178
+ } : void 0;
9179
+ };
9180
+ const [headRoot, baseRoot] = await Promise.all([entries(head), entries(baseRef)]);
9181
+ if (headRoot.get(".github")?.sha === baseRoot.get(".github")?.sha) return void 0;
9182
+ const [headGithub, baseGithub] = await Promise.all([child(headRoot, ".github"), child(baseRoot, ".github")]);
9183
+ if (!headGithub) return void 0;
9184
+ if (headGithub.entries.has("actions") && headGithub.entries.get("actions")?.sha !== baseGithub?.entries.get("actions")?.sha) return `the PR's .github/actions differs from ${baseRef}`;
9185
+ const [headFlows, baseFlows] = await Promise.all([child(headGithub.entries, "workflows"), baseGithub && child(baseGithub.entries, "workflows")]);
9186
+ if (!headFlows || headFlows.sha === baseFlows?.sha) return void 0;
9187
+ for (const [name, entry] of headFlows.entries) {
9188
+ if (baseFlows?.entries.get(name)?.sha === entry.sha) continue;
9189
+ const blob = await read(`/repos/${repository}/git/blobs/${entry.sha}`);
9190
+ const text = isRuntimeRecord(blob) && hasRuntimeType(blob.content, "string") ? Buffer.from(blob.content, "base64").toString("utf8") : void 0;
9191
+ if (text === void 0 || runsOnPush(text, branch)) return `.github/workflows/${name} can run on push and differs from ${baseRef}`;
9192
+ }
9193
+ }
9194
+ const forkHeadKey = (repository, number) => `fork-head-push:${repository}#${number}`;
9195
+ /**
9196
+ * Deletes the `merge.forkHeadBranches` branches of PRs that are no longer open, at most every ten minutes.
9197
+ * A branch is deleted only while it still points at the SHA the host pushed.
9198
+ */
9199
+ async function sweepForkHeadBranches(signal) {
9200
+ if (merge.mode !== "direct" || !merge.forkHeadBranches?.size) return;
9201
+ if ((await pullRequestInbox.metaNumber("fork-head-sweep-next") ?? 0) > Date.now()) return;
9202
+ signal.throwIfAborted();
9203
+ await pullRequestInbox.setMeta("fork-head-sweep-next", Date.now() + 6e5, signal);
9204
+ signal.throwIfAborted();
9205
+ for (const [key, value] of await pullRequestInbox.metaEntries("fork-head-push:")) {
9206
+ signal.throwIfAborted();
9207
+ const match = /^fork-head-push:(.+)#(\d+)$/.exec(key);
9208
+ if (!match || !isRuntimeRecord(value) || !hasRuntimeType(value.branch, "string") || !hasRuntimeType(value.sha, "string")) continue;
9209
+ const [, repository, number] = match;
9210
+ if ((await pullRequestInbox.get(repository, Number(number)))?.status !== "terminal") continue;
9211
+ const reopen = await pullRequestInbox.meta(forkReopenKey(repository, Number(number)));
9212
+ if (isRuntimeRecord(reopen) && reopen.closing === true) continue;
9213
+ try {
9214
+ signal.throwIfAborted();
9215
+ const { provider } = await forge(repository, signal);
9216
+ signal.throwIfAborted();
9217
+ const ref = await provider.request("GET", `/repos/${repository}/git/ref/heads/${value.branch}`, { signal }).then((response) => response.data, (error) => {
9218
+ if (forgeErrorStatus(error) === 404) return void 0;
9219
+ throw error;
9220
+ });
9221
+ signal.throwIfAborted();
9222
+ if (isRuntimeRecord(ref) && isRuntimeRecord(ref.object) && ref.object.sha === value.sha) {
9223
+ await provider.request("DELETE", `/repos/${repository}/git/refs/heads/${value.branch}`, { signal });
9224
+ signal.throwIfAborted();
9225
+ schedulerEvent("babysitter.fork_head.deleted", {
9226
+ repository,
9227
+ pullRequest: Number(number),
9228
+ branch: value.branch
9229
+ });
9230
+ }
9231
+ await pullRequestInbox.deleteMeta(key, signal);
9232
+ } catch (error) {
9233
+ signal.throwIfAborted();
9234
+ await noteForgeQuota(error, "fork-head-delete");
9235
+ schedulerEvent("babysitter.fork_head.delete_failed", {
9236
+ repository,
9237
+ pullRequest: Number(number),
9238
+ branch: value.branch,
9239
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
9240
+ });
9241
+ }
9242
+ }
9243
+ }
9244
+ /**
9245
+ * A required check that never reported gets a fresh run: an approved fork head is pushed to its
9246
+ * `merge.forkHeadBranches` branch, a branch behind its base is updated, and a current one has its
9247
+ * head's Actions runs rerun. Once per head every six hours.
8777
9248
  */
8778
9249
  async function retestMissingRequiredChecks(snapshot, owner, signal) {
8779
9250
  const { repository, number } = snapshot;
@@ -8783,6 +9254,7 @@ function createBabysitterRuntime(options) {
8783
9254
  if (!head || !baseRef || pr.draft || conflicted(snapshot)) return false;
8784
9255
  const missing = missingRequiredChecks(snapshot, await requiredCheckEvaluation(snapshot, signal));
8785
9256
  if (!missing.length) return false;
9257
+ if (await pushForkHead(snapshot, owner, missing, signal)) return true;
8786
9258
  const key = `missing-check-retest:${repository}#${number}`;
8787
9259
  const previous = await pullRequestInbox.meta(key);
8788
9260
  if (isRuntimeRecord(previous) && previous.head === head && Number(previous.at) > Date.now() - 216e5) return false;
@@ -8791,7 +9263,7 @@ function createBabysitterRuntime(options) {
8791
9263
  at: Date.now()
8792
9264
  });
8793
9265
  const compare = await readOnePage(`repos/${repository}/compare/${head}...${encodeURIComponent(baseRef)}?per_page=1`, signal).catch(() => void 0);
8794
- if (isRuntimeRecord(compare) && Number(compare.ahead_by) > 0 && await updateBranch(owner, repository, number, head, signal, pr)) {
9266
+ if (isRuntimeRecord(compare) && Number(compare.ahead_by) > 0 && await updateBranch(owner, repository, number, head, signal, pr, { reopenFork: false })) {
8795
9267
  schedulerEvent("babysitter.required_check.retest", {
8796
9268
  ...owner,
8797
9269
  missing,
@@ -8863,62 +9335,53 @@ function createBabysitterRuntime(options) {
8863
9335
  }
8864
9336
  return newest;
8865
9337
  }
8866
- /**
8867
- * Current-head Actions checks that only repeat the base's failure: the same job fails in the same step
8868
- * on the base tip, and the PR's output names no failure the base's lacks. A missing log proves nothing.
8869
- * `baseSha` pins the base commit; without it, a tip whose checks still run falls back to the base that
8870
- * these checks tested, unless the tip already finished that check.
8871
- */
8872
- async function readInheritedBaseFailures(snapshot, signal, baseSha) {
9338
+ async function liveBaseTip(repository, base, signal) {
9339
+ const tip = await readOnePage(`repos/${repository}/git/ref/heads/${encodeURIComponent(base)}`, signal);
9340
+ const sha = isRuntimeRecord(tip) && isRuntimeRecord(tip.object) ? tip.object.sha : void 0;
9341
+ return hasRuntimeType(sha, "string") && /^[a-f\d]{40}$/i.test(sha) ? sha : void 0;
9342
+ }
9343
+ /** Current-head Actions checks that repeat the same job failure on the live base tip. */
9344
+ async function readInheritedBaseFailures(snapshot, signal, verificationBaseSha) {
8873
9345
  const { repository } = snapshot;
8874
9346
  const head = snapshot.pr?.head?.sha;
8875
9347
  const baseRef = snapshot.pr?.base?.ref;
8876
9348
  if (!head || !baseRef || conflicted(snapshot) || checksStillRunning(snapshot)) return [];
8877
9349
  const failing = currentActionRuns(snapshot, waitPolicy.pendingReviewChecks).filter((check) => failedConclusions.has(String(check.conclusion)));
8878
9350
  if (!failing.length) return [];
8879
- const tip = await baseActionRuns(repository, baseSha ?? encodeURIComponent(baseRef), signal);
8880
- const inherited = new Map([...tip].filter(([, check]) => failedConclusions.has(String(check.conclusion))));
8881
- if (!baseSha && failing.some((check) => tip.get(String(check.name))?.status !== "completed")) {
8882
- const tested = await checksTestedBase(freshnessReader, snapshot, head, baseRef, failedConclusions, signal);
8883
- if (tested) {
8884
- for (const [name, check] of await baseActionRuns(repository, tested, signal)) if (tip.get(name)?.status !== "completed" && failedConclusions.has(String(check.conclusion))) inherited.set(name, check);
8885
- }
8886
- }
9351
+ const tip = verificationBaseSha ?? await liveBaseTip(repository, baseRef, signal);
9352
+ if (!tip) return [];
9353
+ const key = JSON.stringify([
9354
+ repository.toLowerCase(),
9355
+ tip,
9356
+ head,
9357
+ failureKeys(snapshot)
9358
+ ]);
9359
+ const cached = inheritedFailures.get(key);
9360
+ if (!verificationBaseSha && cached && cached.expiresAt > Date.now()) return cached.ids;
9361
+ const runs = await baseActionRuns(repository, tip, signal);
8887
9362
  const ids = [];
8888
9363
  for (const check of failing) {
8889
- const base = inherited.get(String(check.name));
8890
- if (!base) continue;
9364
+ const base = runs.get(String(check.name));
9365
+ if (!base || base.status !== "completed" || !failedConclusions.has(String(base.conclusion))) continue;
8891
9366
  const [own, tested] = await Promise.all([jobFailure(repository, check, signal), jobFailure(repository, base, signal)]);
8892
9367
  if (sameActionFailure(own?.output, tested?.output)) ids.push(Number(check.id));
8893
9368
  }
9369
+ if (inheritedFailures.size >= 128) inheritedFailures.delete(inheritedFailures.keys().next().value);
9370
+ inheritedFailures.set(key, {
9371
+ ids,
9372
+ expiresAt: Date.now() + 3e5
9373
+ });
8894
9374
  return ids;
8895
9375
  }
8896
9376
  const inheritedFailures = /* @__PURE__ */ new Map();
8897
- /** `readInheritedBaseFailures()` for the base branch, cached for five minutes per head, base and failures. */
8898
9377
  async function inheritedBaseFailures(snapshot, signal) {
8899
- const key = JSON.stringify([
8900
- snapshot.repository,
8901
- snapshot.pr?.base?.ref,
8902
- snapshot.pr?.base?.sha,
8903
- snapshot.pr?.head?.sha,
8904
- failureKeys(snapshot)
8905
- ]);
8906
- const cached = inheritedFailures.get(key);
8907
- if (cached && cached.expiresAt > Date.now()) return cached.ids;
8908
- let ids;
8909
9378
  try {
8910
- ids = await readInheritedBaseFailures(snapshot, signal);
9379
+ return await readInheritedBaseFailures(snapshot, signal);
8911
9380
  } catch (error) {
8912
9381
  if (isAbortError(error)) throw error;
8913
9382
  await noteForgeQuota(error, "inherited-failures");
8914
9383
  return [];
8915
9384
  }
8916
- if (inheritedFailures.size >= 128) inheritedFailures.delete(inheritedFailures.keys().next().value);
8917
- inheritedFailures.set(key, {
8918
- ids,
8919
- expiresAt: Date.now() + 3e5
8920
- });
8921
- return ids;
8922
9385
  }
8923
9386
  /** Why each failing current-head check outside the review checks fails. A cause the host cannot prove is `pr`. */
8924
9387
  async function failureCauses(snapshot, signal) {
@@ -9227,7 +9690,7 @@ function createBabysitterRuntime(options) {
9227
9690
  reason: current.reason
9228
9691
  });
9229
9692
  if (!pending && current.reason === "mergeable_state behind") {
9230
- if (!await updateBranch(owner, repository, number, decision.head, signal, live)) return "not-ready";
9693
+ if (!await updateBranch(owner, repository, number, decision.head, signal, live, { reopenFork: false })) return "not-ready";
9231
9694
  schedulerEvent("babysitter.branch.updated", {
9232
9695
  ...owner,
9233
9696
  reason: "behind"
@@ -9408,7 +9871,7 @@ function createBabysitterRuntime(options) {
9408
9871
  /**
9409
9872
  * Proves from fresh GitHub reads that a bypass merge only skips inherited failures. The failures must
9410
9873
  * repeat on the base branch tip, where the merge lands: the PR's `base.sha` can be a day old and have no
9411
- * CI runs (vitehub#3715). Every other branch rule must be known and satisfied. Returns why it cannot.
9874
+ * CI runs. Every other branch rule must be known and satisfied. Returns why it cannot.
9412
9875
  */
9413
9876
  async function verifyInheritedMerge(snapshot, live, signal) {
9414
9877
  const { repository, number } = snapshot;
@@ -9416,9 +9879,8 @@ function createBabysitterRuntime(options) {
9416
9879
  const prBase = isRuntimeRecord(live.base) ? live.base : {};
9417
9880
  const base = prBase.ref;
9418
9881
  if (!hasRuntimeType(head, "string") || head !== snapshot.pr?.head?.sha || !hasRuntimeType(base, "string") || !/^[a-f\d]{40}$/i.test(String(prBase.sha))) return { refused: "Inherited-check bypass target changed." };
9419
- const tip = await readOnePage(`repos/${repository}/git/ref/heads/${encodeURIComponent(base)}`, signal);
9420
- const baseSha = isRuntimeRecord(tip) && isRuntimeRecord(tip.object) ? tip.object.sha : void 0;
9421
- if (!hasRuntimeType(baseSha, "string") || !/^[a-f\d]{40}$/i.test(baseSha)) return { refused: "Inherited-check bypass base tip unavailable." };
9882
+ const baseSha = await liveBaseTip(repository, base, signal);
9883
+ if (!baseSha) return { refused: "Inherited-check bypass base tip unavailable." };
9422
9884
  const [owner, name] = repository.split("/");
9423
9885
  const [protection, rules, review, threads] = await Promise.all([
9424
9886
  readOnePage(`repos/${repository}/branches/${encodeURIComponent(base)}/protection`, signal).catch(() => void 0),
@@ -9606,6 +10068,10 @@ function createBabysitterRuntime(options) {
9606
10068
  async function requiredCheckState(snapshot, signal, fold = false) {
9607
10069
  return (await requiredCheckEvaluation(snapshot, signal, fold))?.state ?? "unknown";
9608
10070
  }
10071
+ async function hasRepairableActionsFailure(snapshot, signal) {
10072
+ if (!failedOwnActions(snapshot, waitPolicy.pendingReviewChecks).length || await requiredCheckState(snapshot, signal) !== "failed") return false;
10073
+ return !unrelatedFailureWait(await failureCauses(snapshot, signal), snapshot.pr?.base?.ref ?? "the base");
10074
+ }
9609
10075
  /** Times of the PR's repair pushes in the last 24 hours, kept while `dailyPushBudget` is set. */
9610
10076
  async function repairPushTimes(snapshot) {
9611
10077
  const pushes = await pullRequestInbox.meta(`repair-pushes:${snapshot.repository}#${snapshot.number}`);
@@ -9734,9 +10200,9 @@ function createBabysitterRuntime(options) {
9734
10200
  }
9735
10201
  }
9736
10202
  const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
9737
- async function dependencyEvidence(wake) {
10203
+ async function dependencyEvidence(wake, signal) {
9738
10204
  if (wake.kind === "pull-request") {
9739
- const pr = await readPull(wake.repository, wake.number);
10205
+ const pr = await readPull(wake.repository, wake.number, signal);
9740
10206
  if (!isRuntimeRecord(pr)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_EXTERNAL_STATE_MISSING();
9741
10207
  return digest({
9742
10208
  state: pr.state,
@@ -9744,14 +10210,14 @@ function createBabysitterRuntime(options) {
9744
10210
  head: isRuntimeRecord(pr.head) ? pr.head.sha : void 0
9745
10211
  });
9746
10212
  }
9747
- const { provider, repo } = await forge(wake.repository);
9748
- return checksDependencyEvidence(await provider.checks.list(repo, wake.headSha));
10213
+ const { provider, repo } = await forge(wake.repository, signal);
10214
+ signal?.throwIfAborted();
10215
+ return checksDependencyEvidence(await provider.checks.list(repo, wake.headSha, { signal }));
9749
10216
  }
9750
10217
  /**
9751
10218
  * Only a wait for another pull request ends by itself, when it merges or closes. Every other external
9752
- * blocker gets a fresh pass after two hours: on 2026-10-19 about 45 PRs sat in external waits for
9753
- * 13 hours or more, 30 of them on an install error the host had already fixed, and one waited on the
9754
- * checks of a main commit 90 commits back, which never change. A host defect is the exception: only a
10219
+ * blocker gets a fresh pass after two hours: the blocker may be fixed already, such as an install
10220
+ * error the host repaired, or may never change, such as the checks of an old base commit. A host defect is the exception: only a
9755
10221
  * new worker release fixes it, and that release wakes the wait.
9756
10222
  */
9757
10223
  async function externalWait(observed, wake, reason) {
@@ -9786,16 +10252,22 @@ function createBabysitterRuntime(options) {
9786
10252
  ...otherPullRequest ? {} : { retryAt }
9787
10253
  };
9788
10254
  }
9789
- async function recoverFailedCiWaits() {
10255
+ async function recoverFailedCiWaits(step, signal) {
9790
10256
  for (const snapshot of await pullRequestInbox.waitsToEvaluate(false, true)) {
10257
+ step("ci-recovery", `${snapshot.repository}#${snapshot.number}`);
9791
10258
  if (snapshot.generation > snapshot.handled || isWorkerBlocker(snapshot) || !hasFailedActions(snapshot)) continue;
9792
10259
  const head = snapshot.pr?.head?.sha;
9793
10260
  if (!head) continue;
9794
10261
  if (snapshot.progressBudget?.exhausted && snapshot.progressBudget.head === head && (snapshot.wait?.retryAt ?? 0) > Date.now()) continue;
9795
10262
  const recoveryKey = `ci-recovery-next:${snapshot.repository}#${snapshot.number}:${head}`;
9796
10263
  if ((await pullRequestInbox.metaNumber(recoveryKey) ?? 0) > Date.now()) continue;
9797
- await pullRequestInbox.setMeta(recoveryKey, Date.now() + 6e5);
9798
- if (await pullRequestInbox.wake(snapshot, `ci-recovery:${head}`, { recovery: true })) schedulerEvent("babysitter.ci.recovery.woken", {
10264
+ signal.throwIfAborted();
10265
+ await pullRequestInbox.setMeta(recoveryKey, Date.now() + 6e5, signal);
10266
+ signal.throwIfAborted();
10267
+ if (await pullRequestInbox.wake(snapshot, `ci-recovery:${head}`, {
10268
+ recovery: true,
10269
+ signal
10270
+ })) schedulerEvent("babysitter.ci.recovery.woken", {
9799
10271
  repository: snapshot.repository,
9800
10272
  pull_request: snapshot.number,
9801
10273
  head_sha: head
@@ -9804,22 +10276,24 @@ function createBabysitterRuntime(options) {
9804
10276
  }
9805
10277
  /**
9806
10278
  * A parked PR on another PR's branch gets no event when that parent merges, so read its parents every
9807
- * ten minutes. On 2026-10-31 a child sat parked on its parent's branch two days after the parent merged.
10279
+ * ten minutes. Otherwise a child stays parked on its parent's branch after the parent merged.
9808
10280
  */
9809
- async function stackParentMerged(snapshot) {
10281
+ async function stackParentMerged(snapshot, signal) {
9810
10282
  const target = snapshot.pr && !snapshot.wait?.wake ? nonDefaultBase(snapshot.pr) : void 0;
9811
10283
  if (!snapshot.pr || !target) return false;
9812
10284
  const nextReadKey = `stack-parent-next:${snapshot.repository}#${snapshot.number}`;
9813
10285
  if ((await pullRequestInbox.metaNumber(nextReadKey) ?? 0) > Date.now()) return false;
9814
- await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e5);
10286
+ signal.throwIfAborted();
10287
+ await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e5, signal);
9815
10288
  try {
9816
10289
  const parents = await readPulls(snapshot.repository, {
9817
10290
  state: "all",
9818
10291
  head: `${target.owner}:${target.base}`,
9819
10292
  limit: 10
9820
- });
10293
+ }, signal);
9821
10294
  return stackRetargetBase(snapshot.pr, parents) !== void 0;
9822
10295
  } catch (error) {
10296
+ signal.throwIfAborted();
9823
10297
  await noteForgeQuota(error, "stack-parent");
9824
10298
  return false;
9825
10299
  }
@@ -9831,41 +10305,54 @@ function createBabysitterRuntime(options) {
9831
10305
  return new Set(snapshot.threads.filter((thread) => thread.isResolved !== true).map((thread) => String(thread.node_id ?? thread.id)).filter((id) => held.has(id)));
9832
10306
  }
9833
10307
  /** Wakes a parked PR only when its new events need a model pass or a direct merge. */
9834
- async function evaluateWaits() {
10308
+ async function evaluateWaits(step, signal) {
10309
+ signal.throwIfAborted();
9835
10310
  for (const snapshot of await pullRequestInbox.waitsToEvaluate(true, true)) {
9836
- const parentMerged = await stackParentMerged(snapshot);
10311
+ step("waits", `${snapshot.repository}#${snapshot.number}`);
10312
+ const parentMerged = await stackParentMerged(snapshot, signal);
10313
+ signal.throwIfAborted();
9837
10314
  if (!parentMerged && snapshot.generation <= snapshot.handled && (snapshot.wait?.retryAt ?? Infinity) > Date.now() && !snapshot.wait?.wake) continue;
9838
- const checks = await requiredCheckState(snapshot);
10315
+ const checkSignal = AbortSignal.any([signal, AbortSignal.timeout(12e4)]);
10316
+ const checks = await requiredCheckState(snapshot, checkSignal);
10317
+ signal.throwIfAborted();
9839
10318
  let reasons = wakeReasons(snapshot, checks, {
9840
10319
  ...waitPolicy,
9841
10320
  heldThreads: await heldOpenThreads(snapshot)
9842
10321
  });
10322
+ signal.throwIfAborted();
9843
10323
  if (parentMerged) reasons.push("stack-parent-merged");
9844
10324
  if (snapshot.wait?.reason === "non-default-base" && snapshot.pr && !nonDefaultBase(snapshot.pr)) reasons.push("base-retargeted");
9845
- const foldWake = foldStacks && snapshot.wait?.reason === "stack-parent" && snapshot.generation > snapshot.handled && !reasons.includes("ready-to-merge") && await requiredCheckState(snapshot, void 0, true) === "passed";
10325
+ const foldWake = foldStacks && snapshot.wait?.reason === "stack-parent" && snapshot.generation > snapshot.handled && !reasons.includes("ready-to-merge") && await requiredCheckState(snapshot, checkSignal, true) === "passed";
10326
+ signal.throwIfAborted();
9846
10327
  if (foldWake) reasons.push("ready-to-merge");
9847
10328
  if (reasons.includes("ready-to-merge") && !await directMergeWakeAllowed(snapshot, foldWake ? "passed" : checks)) reasons = reasons.filter((reason) => reason !== "ready-to-merge");
10329
+ signal.throwIfAborted();
9848
10330
  if (snapshot.wait?.retryAt !== void 0 && snapshot.wait.retryAt <= Date.now()) reasons.push("merge-retry");
9849
10331
  if (snapshot.wait?.wake) {
9850
10332
  const dependencyKey = `dependency:${snapshot.repository}#${snapshot.number}`;
9851
10333
  const nextReadKey = `dependency-next:${snapshot.repository}#${snapshot.number}`;
9852
10334
  if ((await pullRequestInbox.metaNumber(nextReadKey) ?? 0) <= Date.now()) {
9853
- await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e4);
9854
- if (await dependencyEvidence(snapshot.wait.wake) !== await pullRequestInbox.meta(dependencyKey)) reasons.push("external-dependency-changed");
10335
+ signal.throwIfAborted();
10336
+ await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e4, signal);
10337
+ signal.throwIfAborted();
10338
+ const next = await dependencyEvidence(snapshot.wait.wake, signal);
10339
+ signal.throwIfAborted();
10340
+ if (next !== await pullRequestInbox.meta(dependencyKey)) reasons.push("external-dependency-changed");
9855
10341
  }
9856
10342
  }
10343
+ signal.throwIfAborted();
9857
10344
  const owner = {
9858
10345
  pullRequest: snapshot.number,
9859
10346
  repository: snapshot.repository
9860
10347
  };
9861
10348
  if (!reasons.length) {
9862
- await pullRequestInbox.acknowledgeWait(snapshot);
10349
+ await pullRequestInbox.acknowledgeWait(snapshot, signal);
9863
10350
  schedulerEvent("babysitter.wait.kept", {
9864
10351
  ...owner,
9865
10352
  head_sha: snapshot.pr?.head?.sha,
9866
10353
  avoided_invocation: true
9867
10354
  });
9868
- } else if (await pullRequestInbox.wake(snapshot, `evaluated:${snapshot.generation}:${snapshot.revision ?? 0}`)) schedulerEvent("babysitter.wait.woken", {
10355
+ } else if (await pullRequestInbox.wake(snapshot, `evaluated:${snapshot.generation}:${snapshot.revision ?? 0}`, { signal })) schedulerEvent("babysitter.wait.woken", {
9869
10356
  ...owner,
9870
10357
  head_sha: snapshot.pr?.head?.sha,
9871
10358
  reasons
@@ -9944,7 +10431,76 @@ function createBabysitterRuntime(options) {
9944
10431
  }
9945
10432
  const hostOnlyChecked = /* @__PURE__ */ new Map();
9946
10433
  const hostOnlyStamp = (s) => `${s.generation}:${s.revision ?? 0}`;
9947
- async function reconcile(reason, { track }, isAccepting = () => true) {
10434
+ async function stallSnapshot(tick) {
10435
+ const now = Date.now();
10436
+ const snapshot = {
10437
+ reason: tick.reason,
10438
+ step: tick.step,
10439
+ ...tick.subject ? { subject: tick.subject } : {},
10440
+ step_ms: now - tick.stepAt,
10441
+ tick_ms: now - tick.startedAt,
10442
+ active_owners: [...active],
10443
+ model_passes: activeModelPasses,
10444
+ executing_model_passes: executingModelPasses,
10445
+ waiting_model_owners: [...waitingModelOwners],
10446
+ host_preparations: activeHostPreparations,
10447
+ main_repairs: [...mainRepairRunning]
10448
+ };
10449
+ let timer;
10450
+ const queue = await Promise.race([Promise.resolve().then(() => pullRequestInbox.summary()).then((items) => babysitterQueueHealth(items, now)), new Promise((resolve) => {
10451
+ timer = setTimeout(() => resolve(void 0), 5e3);
10452
+ timer.unref?.();
10453
+ })]).catch(() => void 0).finally(() => clearTimeout(timer));
10454
+ return {
10455
+ ...snapshot,
10456
+ ...queue ? {
10457
+ ready: queue.ready,
10458
+ working: queue.working,
10459
+ waiting: queue.waiting
10460
+ } : { queue: "unreadable" }
10461
+ };
10462
+ }
10463
+ /**
10464
+ * Runs one reconcile, and stops it when it waits longer than `stallMs`. The stall event names the step
10465
+ * that did not settle. A stopped reconcile ends at its next step, so it never claims next to the one
10466
+ * that replaced it.
10467
+ */
10468
+ async function reconcile(reason, context, isAccepting = () => true) {
10469
+ const startedAt = Date.now();
10470
+ const tick = {
10471
+ reason,
10472
+ startedAt,
10473
+ step: "start",
10474
+ stepAt: startedAt
10475
+ };
10476
+ const controller = new AbortController();
10477
+ const { signal } = controller;
10478
+ const step = (name, subject) => {
10479
+ signal.throwIfAborted();
10480
+ tick.step = name;
10481
+ tick.subject = subject;
10482
+ tick.stepAt = Date.now();
10483
+ };
10484
+ let timer;
10485
+ const stalled = new Promise((_resolve, reject) => {
10486
+ timer = setTimeout(() => {
10487
+ const error = presetsErrorDiagnostics.PRESETS_BABYSITTER_RECONCILE_STALLED({
10488
+ step: tick.subject ? `${tick.step} (${tick.subject})` : tick.step,
10489
+ minutes: Math.round((Date.now() - startedAt) / 6e4)
10490
+ });
10491
+ reject(error);
10492
+ controller.abort(error);
10493
+ stallSnapshot(tick).then((snapshot) => schedulerEvent("babysitter.reconcile.stalled", snapshot)).catch(() => {});
10494
+ }, stallMs);
10495
+ timer.unref?.();
10496
+ });
10497
+ try {
10498
+ await Promise.race([reconcileTick(reason, context, isAccepting, step, signal), stalled]);
10499
+ } finally {
10500
+ clearTimeout(timer);
10501
+ }
10502
+ }
10503
+ async function reconcileTick(reason, { track }, isAccepting, step, signal) {
9948
10504
  const startedAt = /* @__PURE__ */ new Date();
9949
10505
  const schedule = {
9950
10506
  id: "babysitter-demand",
@@ -9953,7 +10509,9 @@ function createBabysitterRuntime(options) {
9953
10509
  };
9954
10510
  const { publicUrl } = options;
9955
10511
  if (!isAccepting()) return;
10512
+ step("forge-quota");
9956
10513
  const forgeBlockedUntil = await forgeQuota.blockedUntil();
10514
+ signal.throwIfAborted();
9957
10515
  if (forgeBlockedUntil > Date.now()) {
9958
10516
  schedulerEvent("babysitter.forge.quota.waiting", {
9959
10517
  reason,
@@ -9961,18 +10519,23 @@ function createBabysitterRuntime(options) {
9961
10519
  });
9962
10520
  return;
9963
10521
  }
9964
- await statusRecovery.recover();
10522
+ step("status-recovery");
10523
+ await statusRecovery.recover(signal);
10524
+ signal.throwIfAborted();
9965
10525
  track(statusRecovery.flush().catch((failure) => schedulerError("babysitter.status.flush.failed", failure)));
9966
10526
  let modelAdmission = true;
9967
10527
  let hostAdmission = true;
9968
10528
  let modelRetryAt;
9969
10529
  if (options.admission) {
9970
- const admission = await options.admission();
10530
+ step("admission");
10531
+ const admission = await options.admission(signal);
10532
+ signal.throwIfAborted();
9971
10533
  if (!admission.accepting) {
9972
10534
  modelAdmission = false;
9973
10535
  hostAdmission = admission.reason === "token-budget-hourly" || admission.reason === "token-budget-daily";
9974
10536
  modelRetryAt = admission.retryAt ?? Date.now() + 6e4;
9975
10537
  const previous = await pullRequestInbox.meta("admission-skipped");
10538
+ signal.throwIfAborted();
9976
10539
  if (previous?.reason !== admission.reason || Date.now() - (previous?.at ?? 0) >= 9e5) {
9977
10540
  const skipped = {
9978
10541
  at: Date.now(),
@@ -9981,7 +10544,8 @@ function createBabysitterRuntime(options) {
9981
10544
  retryAt: admission.retryAt,
9982
10545
  active_owners: active.size
9983
10546
  };
9984
- await pullRequestInbox.setMeta("admission-skipped", skipped);
10547
+ await pullRequestInbox.setMeta("admission-skipped", skipped, signal);
10548
+ signal.throwIfAborted();
9985
10549
  schedulerEvent("babysitter.admission.skipped", {
9986
10550
  trigger: reason,
9987
10551
  ...skipped
@@ -9991,7 +10555,9 @@ function createBabysitterRuntime(options) {
9991
10555
  }
9992
10556
  }
9993
10557
  const ownerLimit = options.concurrency;
9994
- const repositories = await repositorySource.current().catch(async (error) => {
10558
+ step("repositories");
10559
+ const repositories = await repositorySource.current(signal).catch(async (error) => {
10560
+ signal.throwIfAborted();
9995
10561
  await noteForgeQuota(error, "repositories");
9996
10562
  schedulerError("babysitter.repositories.failed", error, { source: repositorySource.source });
9997
10563
  return repositorySource.known();
@@ -9999,61 +10565,94 @@ function createBabysitterRuntime(options) {
9999
10565
  const eventScopedBootstrap = Boolean(filter.actor || filter.action);
10000
10566
  for (const repository of repositories) {
10001
10567
  if (eventScopedBootstrap) continue;
10568
+ step("bootstrap", repository);
10002
10569
  const key = `bootstrap-rest-v1:${repository}`;
10003
10570
  const previous = await pullRequestInbox.meta(key);
10571
+ signal.throwIfAborted();
10004
10572
  if (previous && Date.now() - Date.parse(previous.at) < 18e5) continue;
10005
10573
  const nextKey = `${key}:next`;
10006
10574
  if ((await pullRequestInbox.meta(nextKey) ?? 0) > Date.now()) continue;
10007
- await pullRequestInbox.setMeta(nextKey, Date.now() + 12e4);
10575
+ signal.throwIfAborted();
10576
+ await pullRequestInbox.setMeta(nextKey, Date.now() + 12e4, signal);
10008
10577
  try {
10009
10578
  const prs = await readPulls(repository, {
10010
10579
  state: "open",
10011
10580
  limit: 1e4
10012
- });
10013
- for (const pr of prs) await pullRequestInbox.seed(repository, normalizePullRequest(pr));
10014
- await pullRequestInbox.setMeta(key, { at: (/* @__PURE__ */ new Date()).toISOString() });
10581
+ }, signal);
10582
+ for (const pr of prs) {
10583
+ signal.throwIfAborted();
10584
+ await pullRequestInbox.seed(repository, normalizePullRequest(pr), signal);
10585
+ }
10586
+ signal.throwIfAborted();
10587
+ await pullRequestInbox.setMeta(key, { at: (/* @__PURE__ */ new Date()).toISOString() }, signal);
10015
10588
  } catch (error) {
10589
+ signal.throwIfAborted();
10016
10590
  await noteForgeQuota(error, "bootstrap");
10017
10591
  schedulerError("babysitter.bootstrap.failed", error, { repository });
10018
10592
  }
10019
10593
  }
10020
- await checkMainRepairs(repositories, track);
10594
+ step("main-repair");
10595
+ await checkMainRepairs(repositories, track, signal);
10596
+ step("fork-head-sweep");
10597
+ await sweepForkHeadBranches(signal).catch((error) => {
10598
+ signal.throwIfAborted();
10599
+ schedulerError("babysitter.fork_head.sweep_failed", error);
10600
+ });
10601
+ await recoverForkReopens(signal).catch((error) => {
10602
+ signal.throwIfAborted();
10603
+ schedulerError("babysitter.fork_checks.recover_failed", error);
10604
+ });
10605
+ step("snapshot-detect");
10021
10606
  try {
10022
- await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository), repositories, Date.now(), !eventScopedBootstrap, (repository, error) => {
10607
+ await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository, signal), repositories, Date.now(), !eventScopedBootstrap, (repository, error) => {
10023
10608
  noteForgeQuota(error, "snapshot-detect");
10024
10609
  schedulerEvent("babysitter.snapshot.detect.failed", {
10025
10610
  repository,
10026
10611
  error: (error instanceof Error ? error.message : String(error)).slice(0, 300)
10027
10612
  });
10028
- });
10613
+ }, signal);
10029
10614
  } catch (error) {
10615
+ signal.throwIfAborted();
10030
10616
  await noteForgeQuota(error, "snapshot-detect");
10031
10617
  schedulerError("babysitter.snapshot.detect.failed", error);
10032
10618
  }
10619
+ step("snapshot-probe");
10033
10620
  try {
10034
- await probeChangedSnapshots(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors);
10035
- await reconcileOneSnapshot(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors);
10621
+ await probeChangedSnapshots(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors, void 0, void 0, signal);
10622
+ step("snapshot-sweep");
10623
+ await reconcileOneSnapshot(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors, signal);
10036
10624
  } catch (error) {
10625
+ signal.throwIfAborted();
10037
10626
  await noteForgeQuota(error, "snapshot-reconcile");
10038
10627
  schedulerError("babysitter.snapshot.reconcile.failed", error);
10039
10628
  }
10040
- await pullRequestInbox.recoverLeases();
10629
+ step("lease-recovery");
10630
+ await pullRequestInbox.recoverLeases(signal);
10631
+ step("waits");
10041
10632
  try {
10042
10633
  if ((await pullRequestInbox.metaNumber("idle-wait-sweep-next") ?? 0) <= Date.now()) {
10043
- await pullRequestInbox.setMeta("idle-wait-sweep-next", Date.now() + 6e5);
10044
- await recoverFailedCiWaits();
10634
+ signal.throwIfAborted();
10635
+ await pullRequestInbox.setMeta("idle-wait-sweep-next", Date.now() + 6e5, signal);
10636
+ signal.throwIfAborted();
10637
+ await recoverFailedCiWaits(step, signal);
10045
10638
  }
10046
- await evaluateWaits();
10639
+ await evaluateWaits(step, signal);
10047
10640
  } catch (error) {
10641
+ signal.throwIfAborted();
10048
10642
  await noteForgeQuota(error, "wait-evaluate");
10049
10643
  schedulerError("babysitter.wait.evaluate.failed", error);
10050
10644
  }
10645
+ step("delivery-prune");
10051
10646
  if ((await pullRequestInbox.metaNumber("deliveries-prune-next") ?? 0) <= Date.now()) {
10052
- await pullRequestInbox.setMeta("deliveries-prune-next", Date.now() + 36e5);
10053
- await pullRequestInbox.pruneDeliveries();
10647
+ signal.throwIfAborted();
10648
+ await pullRequestInbox.setMeta("deliveries-prune-next", Date.now() + 36e5, signal);
10649
+ signal.throwIfAborted();
10650
+ await pullRequestInbox.pruneDeliveries({ signal });
10054
10651
  }
10055
10652
  if (!isAccepting()) return;
10653
+ step("forge-quota");
10056
10654
  const forgeBlockedAfterReconcile = await forgeQuota.blockedUntil();
10655
+ signal.throwIfAborted();
10057
10656
  if (forgeBlockedAfterReconcile > Date.now()) {
10058
10657
  schedulerEvent("babysitter.forge.quota.waiting", {
10059
10658
  reason,
@@ -10061,7 +10660,9 @@ function createBabysitterRuntime(options) {
10061
10660
  });
10062
10661
  return;
10063
10662
  }
10663
+ step("provider-quota");
10064
10664
  const providerBlockedUntil = await providerQuota.blockedUntil();
10665
+ signal.throwIfAborted();
10065
10666
  if (providerBlockedUntil > Date.now() && modelAdmission) {
10066
10667
  modelAdmission = false;
10067
10668
  modelRetryAt = providerBlockedUntil;
@@ -10071,26 +10672,38 @@ function createBabysitterRuntime(options) {
10071
10672
  });
10072
10673
  }
10073
10674
  const claimLimit = ownerLimit;
10675
+ step("placement");
10074
10676
  const hostActive = active.size;
10075
- const placementAdmitted = presetOptions.placement?.admitted ? await presetOptions.placement.admitted() : Number.POSITIVE_INFINITY;
10677
+ const placementAdmitted = presetOptions.placement?.admitted ? await presetOptions.placement.admitted(signal) : Number.POSITIVE_INFINITY;
10076
10678
  const remainingCapacity = Math.max(0, Math.min(claimLimit, typeof placementAdmitted === "number" && placementAdmitted >= 0 ? placementAdmitted : 0) - hostActive);
10077
- const lane = await pullRequestInbox.claim(Math.min(5, remainingCapacity), {
10078
- only: (snapshot) => Boolean(snapshot.recoveryHead && snapshot.recoveryHead === snapshot.pr?.head?.sha),
10079
- includeBlocked: true,
10080
- skip: (snapshot) => !modelAdmission && hostOnlyChecked.get(`${snapshot.repository}#${snapshot.number}`) === hostOnlyStamp(snapshot)
10081
- });
10082
- const regularCapacity = Math.max(0, remainingCapacity - lane.length);
10083
- const regular = await pullRequestInbox.claim(regularCapacity, { skip: (snapshot) => !modelAdmission && hostOnlyChecked.get(`${snapshot.repository}#${snapshot.number}`) === hostOnlyStamp(snapshot) });
10084
- const exhausted = await pullRequestInbox.claim(Math.max(0, regularCapacity - regular.length), {
10085
- includeBlocked: true,
10086
- only: (snapshot) => snapshot.progressBudget?.exhausted === true && snapshot.progressBudget.head === snapshot.pr?.head?.sha,
10087
- skip: (snapshot) => !modelAdmission && hostOnlyChecked.get(`${snapshot.repository}#${snapshot.number}`) === hostOnlyStamp(snapshot)
10088
- });
10089
- const jobs = [
10090
- ...lane,
10091
- ...regular,
10092
- ...exhausted
10093
- ];
10679
+ step("claim");
10680
+ const jobs = [];
10681
+ const skip = (snapshot) => !modelAdmission && hostOnlyChecked.get(`${snapshot.repository}#${snapshot.number}`) === hostOnlyStamp(snapshot);
10682
+ try {
10683
+ jobs.push(...await pullRequestInbox.claim(Math.min(5, remainingCapacity), {
10684
+ only: (snapshot) => Boolean(snapshot.recoveryHead && snapshot.recoveryHead === snapshot.pr?.head?.sha),
10685
+ includeBlocked: true,
10686
+ skip,
10687
+ signal
10688
+ }));
10689
+ signal.throwIfAborted();
10690
+ jobs.push(...await pullRequestInbox.claim(remainingCapacity - jobs.length, {
10691
+ skip,
10692
+ signal
10693
+ }));
10694
+ signal.throwIfAborted();
10695
+ jobs.push(...await pullRequestInbox.claim(remainingCapacity - jobs.length, {
10696
+ includeBlocked: true,
10697
+ skip,
10698
+ signal,
10699
+ only: (snapshot) => snapshot.progressBudget?.exhausted === true && snapshot.progressBudget.head === snapshot.pr?.head?.sha
10700
+ }));
10701
+ signal.throwIfAborted();
10702
+ } catch (error) {
10703
+ const releases = await Promise.allSettled(jobs.map((claim) => pullRequestInbox.release(claim)));
10704
+ for (const release of releases) if (release.status === "rejected") schedulerError("babysitter.claim.release.failed", release.reason);
10705
+ throw error;
10706
+ }
10094
10707
  if (!jobs.length) return;
10095
10708
  for (const claim of jobs) active.add(`${claim.snapshot.repository}#${claim.snapshot.number}`);
10096
10709
  schedulerEvent("babysitter.queue.selected", {
@@ -10443,7 +11056,7 @@ function createBabysitterRuntime(options) {
10443
11056
  const held = await heldOpenThreads(inboxClaim.snapshot);
10444
11057
  let reviewedRetryAt = Date.now() + 12e4;
10445
11058
  let pushWindowRetry = false;
10446
- if (dailyPushBudget !== false && await requiredCheckState(inboxClaim.snapshot) === "failed") {
11059
+ if (isRuntimeRecord(assessment) && (dailyPushBudget !== false && await requiredCheckState(inboxClaim.snapshot) === "failed" || await hasRepairableActionsFailure(inboxClaim.snapshot, passSignal))) {
10447
11060
  const window = await repairPushWindow(inboxClaim.snapshot, "failed", false);
10448
11061
  reviewedRetryAt = window && !window.allowed ? window.nextAt + 6e4 : void 0;
10449
11062
  pushWindowRetry = reviewedRetryAt !== void 0;
@@ -11291,7 +11904,9 @@ function createBabysitterRuntime(options) {
11291
11904
  const reviewPushes = inboxClaim.snapshot.reviewPushBudget?.count ?? 0;
11292
11905
  const severityContext = minorReviewRounds !== false && !settled ? `\n\n<automated-review-severity>\nSet automatedReview in the JSON result to the highest class of valid finding in the automated reviews of HEAD ${pullRequest.headRefOid}: "P0" (security hole, data loss or a broken main path), "P1" (a real bug on a supported path or a broken documented contract), "P2" (an edge case, a missing test or a docs gap), "P3" (style or a nit), or "none" when they have no valid finding. A fixed or false finding has no class. Omit it when no automated review of that head exists yet. After ${minorReviewRounds} heads in a row with nothing above P2, bot feedback and review checks no longer start passes.\n</automated-review-severity>` : "";
11293
11906
  const convergenceContext = reviewConvergencePushes !== false && !settled && reviewPushes >= reviewConvergencePushes ? `\n\n<review-convergence>\nThis PR already has ${reviewPushes} review-driven repair pushes. Before you fix a finding, check whether it is another case of a class that an earlier push or thread already addressed. If it is, do not patch the new case: change the approach so that the whole class cannot occur (for example, narrow the contract or report an unknown value as unknown), in this one push, and say so in the thread replies. If no such change fits this PR's scope, decline the remaining P2 cases of that class with outcome declined.\n</review-convergence>` : "";
11294
- const userMessage = `${prompt}${mainRepairContext}${resumeContext}\n\n${snapshotContext}${installContext}${preparedConflicts?.resolved.length ? `\n\n<host-resolved-conflicts>\nThe host resolved and staged these merge conflicts mechanically. Review them instead of redoing them:\n${preparedConflicts.resolved.slice(0, 50).map(({ path, rule }) => `- ${path} (${rule})`).join("\n")}\n${preparedConflicts.remaining.length ? `Still conflicted: ${preparedConflicts.remaining.slice(0, 50).join(", ")}.` : "No conflicted file remains; review the merge, validate it and pass these paths to commitRepair."}\n</host-resolved-conflicts>` : ""}${pushContext}${severityContext}${convergenceContext}`;
11907
+ const conflictContext = preparedConflicts?.resolved.length ? `\n\n<host-resolved-conflicts>\nThe host resolved and staged these merge conflicts mechanically. Review them instead of redoing them:\n${preparedConflicts.resolved.slice(0, 50).map(({ path, rule }) => `- ${path} (${rule})`).join("\n")}\n${preparedConflicts.remaining.length ? `Still conflicted: ${preparedConflicts.remaining.slice(0, 50).join(", ")}.` : "No conflicted file remains; review the merge, validate it and pass these paths to commitRepair."}\n</host-resolved-conflicts>` : "";
11908
+ const inheritedIds = await inheritedBaseFailures(inboxClaim.snapshot, passSignal);
11909
+ const userMessage = `${prompt}${mainRepairContext}${resumeContext}\n\n${snapshotContext}${installContext}${conflictContext}${pushContext}${severityContext}${convergenceContext}${inheritedIds.length ? `\n\n<live-base-attribution>\nThe host verified matching CI failures on the live base tip for these current-head check IDs: ${inheritedIds.join(", ")}.\n</live-base-attribution>` : ""}`;
11295
11910
  assertPromptFits(userMessage);
11296
11911
  schedulerEvent("babysitter.context.prepared", {
11297
11912
  repository,
@@ -11384,7 +11999,9 @@ function createBabysitterRuntime(options) {
11384
11999
  workspaceRun.ok = true;
11385
12000
  if (modelWorkParked) return;
11386
12001
  const current = await pullRequestInbox.get(repository, number);
11387
- const assessed = (passResult?.wait?.kind !== "external" || merge.mode === "direct") && !pushedHead && disposition === "park" && passResult?.reviewedHead === pullRequest.headRefOid && current?.pr?.head?.sha === pullRequest.headRefOid && await pullRequestInbox.holdsClaimedHead(inboxClaim);
12002
+ const reportedAssessment = (passResult?.wait?.kind !== "external" || merge.mode === "direct") && !pushedHead && disposition === "park" && passResult?.reviewedHead === pullRequest.headRefOid && current?.pr?.head?.sha === pullRequest.headRefOid && await pullRequestInbox.holdsClaimedHead(inboxClaim);
12003
+ const rejectedAssessment = reportedAssessment && await hasRepairableActionsFailure(current, passSignal);
12004
+ const assessed = reportedAssessment && !rejectedAssessment;
11388
12005
  if (assessed) await recordAssessment(inboxClaim.snapshot, {
11389
12006
  head: pullRequest.headRefOid,
11390
12007
  evidenceKey: mergeReviewEvidenceKey(inboxClaim.snapshot, waitPolicy)
@@ -11406,7 +12023,7 @@ function createBabysitterRuntime(options) {
11406
12023
  progress: { kind: "no-progress" },
11407
12024
  wait: await externalWait(inboxClaim.snapshot, passResult.wait.wake, passResult.wait.reason)
11408
12025
  });
11409
- } else if (disposition === "park" && current?.pr?.head?.sha === pullRequest.headRefOid && (passResult?.wait?.kind === "checks" && passResult.wait.headSha === pullRequest.headRefOid || passResult?.waitForChecksHead === pullRequest.headRefOid || hasPendingChecks(inboxClaim.snapshot, waitPolicy))) {
12026
+ } else if (disposition === "park" && current?.pr?.head?.sha === pullRequest.headRefOid && (hasPendingChecks(inboxClaim.snapshot, waitPolicy) || !rejectedAssessment && (passResult?.wait?.kind === "checks" && passResult.wait.headSha === pullRequest.headRefOid || passResult?.waitForChecksHead === pullRequest.headRefOid))) {
11410
12027
  outcome = "waiting";
11411
12028
  recorded = await pullRequestInbox.finish(inboxClaim, {
11412
12029
  text: resultText,
@@ -11634,4 +12251,4 @@ function withoutCapacity(driver) {
11634
12251
  return rest;
11635
12252
  }
11636
12253
  //#endregion
11637
- export { pullRequestThreadId as a, budgetParks as i, isProviderRateLimit as n, createGitHubAppCredentials as o, pendingMergeRetryAt as r, createGitHubHost as s, createBabysitterRuntime as t };
12254
+ export { budgetParks as a, createGitHubHost as c, babysitterQueueHealth as i, isProviderRateLimit as n, pullRequestThreadId as o, pendingMergeRetryAt as r, createGitHubAppCredentials as s, createBabysitterRuntime as t };