@vite-hub/presets 0.3.1 → 0.5.0

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,8 +1,8 @@
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 invariantError, C as maintainerApproval, D as reviewThreadOutcomes, E as normalizeGitHubMentionAllowlist, F as hydrateFailedCiEvidence, I as newestCheckRun, L as createBabysitterCheckRuns, M as matchesBabysitterPullRequestFilter, N as actionLocation, O as reviewerLabeledSevere, P as failed$1, R as isBabysitterCheckRun, S as approvalReviewers, T as isReviewThreadOutcome, _ as liveMergeReadiness, a as isBabysitterPlacementCapacityError, b as resolveBabysitterMerge, c as workspaceDecision, g as isAutomatedFeedback, h as hasHumanComment, j as hasGitHubLogin, k as invariant, l as babysitterModelAdmission, m as feedbackFingerprints, p as directMergeReadiness, r as resolveBabysitterLifecycleFilter, s as providerSessionDecision, v as matchesMergeReviewEvidence, w as createGitHubPullRequestOperations, x as snapshotCheckEvidence, y as mergeReviewEvidenceKey, z as createBabysitterPassResultSchema } from "./babysitter-B5C0KLRl.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
- import { consoleInvocationUrl, resolvePublicUrl, resolveRuntimeValue } from "@vite-hub/runtime";
5
+ import { resolvePublicUrl } from "@vite-hub/runtime";
6
6
  import * as v from "valibot";
7
7
  import { MergeBlockedError, RateLimitedError, forgeBranchRules, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeMerge, forgeProvider, githubAppCredentials, githubBranchRuleDetails, githubInstallationFor, isForgeResponseError, repoRef, retargetPullRequest } from "@vite-hub/forge";
8
8
  import { github } from "@vite-hub/agent/channels";
@@ -15,8 +15,10 @@ import { promisify, stripVTControlCharacters } from "node:util";
15
15
  import { parse, parseAllDocuments } from "yaml";
16
16
  import { constants, createReadStream, mkdirSync } from "node:fs";
17
17
  import { parseSyml } from "@yarnpkg/parsers";
18
+ import { consoleInvocationUrl } from "@vite-hub/runtime/internal/console";
18
19
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
- import { resolveRegisteredWorkspaceDefinition } from "@vite-hub/workspace";
20
+ import { resolveRuntimeValue } from "@vite-hub/runtime/internal/context";
21
+ import { resolveRegisteredWorkspaceDefinition } from "@vite-hub/workspace/runtime";
20
22
  //#region src/github/checkout.ts
21
23
  const exec$6 = promisify(execFile);
22
24
  /** Credentials belong to the host. Never carry saved clone authentication into a worker. */
@@ -1940,7 +1942,6 @@ function createGitHubAppCredentials(app) {
1940
1942
  installations: Object.fromEntries(Object.entries(app.installations ?? {}).map(([name, id]) => [name.toLowerCase(), id]))
1941
1943
  };
1942
1944
  const installations = /* @__PURE__ */ new Map();
1943
- let identity;
1944
1945
  const client = githubAppCredentials(app);
1945
1946
  const installation = async (repository, signal) => {
1946
1947
  signal?.throwIfAborted();
@@ -1972,36 +1973,35 @@ function createGitHubAppCredentials(app) {
1972
1973
  redeliver: (id, signal) => client.redeliver(id, signal),
1973
1974
  /** The App bot's login and noreply email, used as the commit author. */
1974
1975
  async identity() {
1975
- identity ??= (async () => {
1976
- const { id: appId, login } = await client.app().catch((error) => {
1977
- const status = forgeErrorStatus(error);
1978
- if (status !== void 0) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_REQUEST_FAILED({
1979
- status,
1980
- cause: error
1981
- });
1982
- if (isForgeResponseError(error)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_RESPONSE_INVALID({ cause: error });
1983
- throw error;
1984
- });
1985
- const user = await (await forgeProvider({
1986
- forge: "github",
1987
- userAgent: app.userAgent
1988
- })).users.get(login).catch(() => void 0);
1989
- return {
1990
- appId,
1991
- login,
1992
- email: user?.id ? `${user.id}+${login}@users.noreply.github.com` : `${login}@users.noreply.github.com`
1993
- };
1994
- })();
1995
- identity.catch(() => {
1996
- identity = void 0;
1997
- });
1998
- return await identity;
1976
+ return await appIdentity(client);
1999
1977
  }
2000
1978
  };
2001
1979
  }
2002
1980
  function tokenKey(token) {
2003
1981
  return `token:${createHash("sha256").update(token).digest("base64url")}`;
2004
1982
  }
1983
+ async function appIdentity(client, signal) {
1984
+ const { id: appId, login, email } = await client.app(signal).catch((error) => {
1985
+ if (signal?.aborted) throw abortError(signal.reason);
1986
+ const status = forgeErrorStatus(error);
1987
+ if (status !== void 0) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_REQUEST_FAILED({
1988
+ status,
1989
+ cause: error
1990
+ });
1991
+ if (isForgeResponseError(error)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_RESPONSE_INVALID({ cause: error });
1992
+ throw error;
1993
+ });
1994
+ return {
1995
+ appId,
1996
+ login,
1997
+ email
1998
+ };
1999
+ }
2000
+ /** The App lookup or token request for a repository answered 404: the App is not installed there. */
2001
+ function notInstalled(error) {
2002
+ for (let cause = error, depth = 0; cause instanceof Error && depth < 4; cause = cause.cause, depth++) if (forgeErrorStatus(cause) === 404) return true;
2003
+ return false;
2004
+ }
2005
2005
  function owner(repository) {
2006
2006
  return repository.split("/", 1)[0].toLowerCase();
2007
2007
  }
@@ -2041,7 +2041,7 @@ async function waitForCaller(promise, options) {
2041
2041
  function createGitHubHost(options) {
2042
2042
  const checkoutScope = new AsyncLocalStorage();
2043
2043
  const maxBuffer = options.maxBuffer ?? 16777216;
2044
- const identity = options.identity ?? {};
2044
+ let appBot;
2045
2045
  const rateLimits = /* @__PURE__ */ new Map();
2046
2046
  /** Record the rate limit headers of each Forge response, keyed by credential and resource. */
2047
2047
  function observe(credentialKey) {
@@ -2083,14 +2083,23 @@ function createGitHubHost(options) {
2083
2083
  operation.close();
2084
2084
  }
2085
2085
  }
2086
+ async function appBotIdentity(appId, privateKey, signal) {
2087
+ appBot = await appIdentity(githubAppCredentials({
2088
+ appId,
2089
+ privateKey,
2090
+ userAgent: options.userAgent
2091
+ }), signal);
2092
+ return appBot;
2093
+ }
2086
2094
  function fallbackToken(config) {
2087
2095
  const configured = secret(config.token)?.trim();
2088
2096
  if (!configured) throw presetsErrorDiagnostics.PRESETS_GITHUB_AUTH_MISSING();
2089
2097
  return configured;
2090
2098
  }
2091
- async function scopedAccess(input) {
2099
+ async function scopedAccess(input, commits = true) {
2100
+ const installationRepository = input.installationRepository ?? input.repository;
2092
2101
  const config = await credentials({
2093
- repository: input.repository,
2102
+ repository: installationRepository,
2094
2103
  signal: input.signal
2095
2104
  });
2096
2105
  const appId = String(config.appId || "").trim();
@@ -2102,9 +2111,10 @@ function createGitHubHost(options) {
2102
2111
  installationId,
2103
2112
  privateKey
2104
2113
  ];
2105
- const repositoryOwner = input.repository ? owner(input.repository) : void 0;
2114
+ const repositoryOwner = installationRepository ? owner(installationRepository) : void 0;
2106
2115
  let token;
2107
2116
  let credentialKey;
2117
+ let identity = options.identity ?? {};
2108
2118
  if (appValues.some(Boolean)) {
2109
2119
  if (!appValues.every(Boolean)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_CREDENTIALS_INCOMPLETE();
2110
2120
  if (!appOwner) throw presetsErrorDiagnostics.PRESETS_GITHUB_HOST_APP_OWNER_MISSING();
@@ -2135,6 +2145,7 @@ function createGitHubHost(options) {
2135
2145
  if (isForgeResponseError(error)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_TOKEN_MISSING({ cause: error });
2136
2146
  throw error;
2137
2147
  }
2148
+ if (commits && !options.identity) identity = await appBotIdentity(numericAppId, privateKey, input.signal);
2138
2149
  }
2139
2150
  } else {
2140
2151
  token = fallbackToken(config);
@@ -2170,32 +2181,52 @@ function createGitHubHost(options) {
2170
2181
  return {
2171
2182
  env,
2172
2183
  credentialKey,
2173
- token
2184
+ token,
2185
+ identity
2174
2186
  };
2175
2187
  }
2176
- async function access(input = {}) {
2188
+ async function commitAccess(input) {
2177
2189
  const operation = controlledOperation(input);
2178
2190
  try {
2179
- const { env, token } = await scopedAccess({
2191
+ return await scopedAccess({
2180
2192
  ...input,
2181
2193
  signal: operation.signal,
2182
2194
  timeout: void 0
2183
2195
  });
2184
- return {
2185
- env,
2186
- token
2187
- };
2188
2196
  } finally {
2189
2197
  operation.close();
2190
2198
  }
2191
2199
  }
2200
+ async function access(input = {}) {
2201
+ const { env, token } = await commitAccess(input);
2202
+ return {
2203
+ env,
2204
+ token
2205
+ };
2206
+ }
2207
+ /**
2208
+ * Access to a fork head: the fork's own App installation, or the base repository's when the App is not
2209
+ * installed on the fork. The base's token pushes to the fork only while its author allows edits by maintainers.
2210
+ */
2211
+ async function headAccess(input, base) {
2212
+ if (!input.repository || input.repository === base) return await access(input);
2213
+ try {
2214
+ return await access(input);
2215
+ } catch (error) {
2216
+ if (input.signal?.aborted || !notInstalled(error)) throw error;
2217
+ return await access({
2218
+ ...input,
2219
+ installationRepository: base
2220
+ });
2221
+ }
2222
+ }
2192
2223
  async function forge(input = {}) {
2193
2224
  const operation = controlledOperation(input);
2194
2225
  try {
2195
2226
  const auth = await scopedAccess({
2196
2227
  repository: input.repository,
2197
2228
  signal: operation.signal
2198
- });
2229
+ }, false);
2199
2230
  return await forgeProvider({
2200
2231
  forge: "github",
2201
2232
  token: auth.token,
@@ -2316,11 +2347,11 @@ function createGitHubHost(options) {
2316
2347
  }
2317
2348
  if (pullRequest.headRef) {
2318
2349
  const sourceRepository = pullRequest.headRepository ?? pullRequest.repository;
2319
- const sourceAuth = sourceRepository === pullRequest.repository ? baseAuth : await access({
2350
+ const sourceAuth = sourceRepository === pullRequest.repository ? baseAuth : await headAccess({
2320
2351
  refresh: true,
2321
2352
  repository: sourceRepository,
2322
2353
  signal: operation.signal
2323
- });
2354
+ }, pullRequest.repository);
2324
2355
  await exec$2("git", [
2325
2356
  "-C",
2326
2357
  checkout,
@@ -2429,12 +2460,57 @@ function createGitHubHost(options) {
2429
2460
  signal: operation.signal
2430
2461
  });
2431
2462
  let pushHead = pullRequest.headSha;
2432
- const commitRepair = async (target, input, commitOptions) => await commitGitHubPullRequestWorkspace(target, input, {
2433
- expectedHead: pushHead,
2434
- signal: operation.signal,
2435
- identity: env,
2436
- verifyDependencies: commitOptions?.verifyDependencies
2437
- });
2463
+ const hostCommits = /* @__PURE__ */ new Set();
2464
+ const commitRepair = async (target, input, commitOptions) => {
2465
+ const before = (await exec$2("git", [
2466
+ "-C",
2467
+ target,
2468
+ "rev-parse",
2469
+ "HEAD"
2470
+ ], commandOptions)).stdout.trim();
2471
+ const head = await commitGitHubPullRequestWorkspace(target, input, {
2472
+ expectedHead: pushHead,
2473
+ signal: operation.signal,
2474
+ identity: env,
2475
+ verifyDependencies: commitOptions?.verifyDependencies
2476
+ });
2477
+ if (head !== before) hostCommits.add(head);
2478
+ return head;
2479
+ };
2480
+ const hostOnly = async (head, parent, signal) => {
2481
+ if (!hostCommits.size) return false;
2482
+ let base = [];
2483
+ if (pullRequest.baseRef) try {
2484
+ await exec$2("git", [
2485
+ "-C",
2486
+ checkout,
2487
+ ...fetchConfig,
2488
+ "fetch",
2489
+ "--no-tags",
2490
+ "--",
2491
+ "origin",
2492
+ `refs/heads/${pullRequest.baseRef}`
2493
+ ], {
2494
+ ...commandOptions,
2495
+ signal
2496
+ });
2497
+ base = ["^FETCH_HEAD"];
2498
+ } catch {
2499
+ if (signal.aborted) throw abortError(signal.reason);
2500
+ }
2501
+ const added = (await exec$2("git", [
2502
+ "-C",
2503
+ checkout,
2504
+ "rev-list",
2505
+ head,
2506
+ `^${parent}`,
2507
+ ...base
2508
+ ], {
2509
+ ...commandOptions,
2510
+ signal
2511
+ })).stdout.split("\n").filter(Boolean);
2512
+ return added.length > 0 && added.every((commit) => hostCommits.has(commit));
2513
+ };
2438
2514
  const push = async (target = checkout, options = {}) => {
2439
2515
  const signal = options.signal ? AbortSignal.any([operation.signal, options.signal]) : operation.signal;
2440
2516
  signal.throwIfAborted();
@@ -2493,13 +2569,16 @@ function createGitHubHost(options) {
2493
2569
  ...commandOptions,
2494
2570
  signal
2495
2571
  });
2496
- const refreshed = await access({
2572
+ const refreshed = await headAccess({
2497
2573
  refresh: true,
2498
2574
  repository: pullRequest.headRepository,
2499
2575
  signal
2500
- });
2576
+ }, pullRequest.repository);
2501
2577
  signal.throwIfAborted();
2502
- await options.beforePush?.(head);
2578
+ await options.beforePush?.(head, {
2579
+ parent: expectedHead,
2580
+ hostOnly: await hostOnly(head, expectedHead, signal)
2581
+ });
2503
2582
  await exec$2("git", [
2504
2583
  "-C",
2505
2584
  checkout,
@@ -2540,25 +2619,28 @@ function createGitHubHost(options) {
2540
2619
  if (!persistent) await cleanupCheckout().catch(() => void 0);
2541
2620
  }
2542
2621
  }
2543
- const host = {
2622
+ return {
2544
2623
  identity() {
2545
- return identity.login?.trim() || void 0;
2624
+ return (options.identity ?? appBot)?.login?.trim() || void 0;
2546
2625
  },
2547
2626
  appId() {
2548
- return identity.appId;
2627
+ return (options.identity ?? appBot)?.appId;
2549
2628
  },
2550
2629
  channel(channelOptions = {}) {
2551
- const login = host.identity();
2552
2630
  return github({
2553
2631
  ...channelOptions,
2554
- app: {
2555
- token: async (_context, scope) => (await access(scope)).token,
2556
- ...login ? { identity: {
2557
- login,
2558
- appId: host.appId?.(),
2559
- ...identity.email ? { email: identity.email } : {}
2560
- } } : {}
2561
- }
2632
+ app: { token: async (_context, scope) => {
2633
+ const { token, identity: { login, appId, email } } = await commitAccess(scope);
2634
+ const name = login?.trim();
2635
+ return {
2636
+ token,
2637
+ identity: name ? {
2638
+ login: name,
2639
+ appId,
2640
+ email
2641
+ } : void 0
2642
+ };
2643
+ } }
2562
2644
  });
2563
2645
  },
2564
2646
  async environment() {
@@ -2575,7 +2657,6 @@ function createGitHubHost(options) {
2575
2657
  rateLimit,
2576
2658
  withPullRequestCheckout
2577
2659
  };
2578
- return host;
2579
2660
  }
2580
2661
  //#endregion
2581
2662
  //#region src/github/pull-requests.ts
@@ -3327,6 +3408,11 @@ function parseSnapshot(value) {
3327
3408
  token: v.string(),
3328
3409
  heads: v.array(v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i)))
3329
3410
  }), input.prospectivePush);
3411
+ if (input.hostUpdates !== void 0) v.parse(v.array(v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i))), input.hostUpdates);
3412
+ if (input.hostHeads !== void 0) v.parse(v.array(v.object({
3413
+ head: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i)),
3414
+ parent: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i))
3415
+ })), input.hostHeads);
3330
3416
  if (input.threadReopens !== void 0) v.parse(v.record(v.string(), v.pipe(v.number(), v.integer(), v.minValue(0))), input.threadReopens);
3331
3417
  if (input.sourcePushHeads !== void 0) v.parse(v.array(v.string()), input.sourcePushHeads);
3332
3418
  if (input.sourcePushOverflow !== void 0) v.parse(v.boolean(), input.sourcePushOverflow);
@@ -3370,6 +3456,10 @@ function pullRequestFilterContext(repository, pr) {
3370
3456
  };
3371
3457
  }
3372
3458
  const stringValue = (value) => isRuntimeString(value) ? value : String(value);
3459
+ const databaseNow = "CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)";
3460
+ const clockSampleIntervalMs = 3e4;
3461
+ const ciEvidencePrefix = "ci-evidence:v1:";
3462
+ const ciEvidenceAtPrefix = "ci-evidence-at:v1:";
3373
3463
  const legacyRecordSchema = v.record(v.string(), v.unknown());
3374
3464
  const legacyWaitSchema = v.object({
3375
3465
  headSha: v.pipe(v.string(), v.minLength(1)),
@@ -3520,7 +3610,11 @@ var PullRequestInbox = class {
3520
3610
  tables;
3521
3611
  repositoryList;
3522
3612
  clock;
3613
+ usesDatabaseClock;
3614
+ clockSample;
3523
3615
  filter;
3616
+ /** Whether a maintainer's approval admits an author the filter leaves out. */
3617
+ admitApproved;
3524
3618
  activityAuthors;
3525
3619
  activityAppId;
3526
3620
  budgets;
@@ -3529,7 +3623,7 @@ var PullRequestInbox = class {
3529
3623
  claimStackChildren;
3530
3624
  invalidRow;
3531
3625
  reportedRows = /* @__PURE__ */ new Set();
3532
- constructor({ path, storage, scope = "", repositories, filter, clock = Date.now, budgets = {}, activityAuthors = [], activityAppId, priorityLabels = [], mainRepairBranchPrefix, claimStackChildren = false, invalidRow }) {
3626
+ constructor({ path, storage, scope = "", repositories, filter, admitApproved = false, clock, budgets = {}, activityAuthors = [], activityAppId, priorityLabels = [], mainRepairBranchPrefix, claimStackChildren = false, invalidRow }) {
3533
3627
  validateBudgets(budgets);
3534
3628
  if (path === void 0 === (storage === void 0)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_INBOX_STORAGE_MISSING();
3535
3629
  this.budgets = { ...budgets };
@@ -3542,8 +3636,13 @@ var PullRequestInbox = class {
3542
3636
  const fixed = repositories.map((repository) => repository.toLowerCase());
3543
3637
  this.repositoryList = () => fixed;
3544
3638
  }
3545
- this.clock = clock;
3639
+ this.usesDatabaseClock = clock === void 0 && storage !== void 0;
3640
+ this.clock = clock ?? (!this.usesDatabaseClock ? () => Date.now() : () => {
3641
+ const sample = this.clockSample;
3642
+ return sample ? sample.time + Math.floor(performance.now() - sample.sampledAt) : Date.now();
3643
+ });
3546
3644
  this.filter = filter;
3645
+ this.admitApproved = admitApproved;
3547
3646
  this.activityAuthors = new Set(activityAuthors.map((author) => author.trim().toLowerCase()));
3548
3647
  this.activityAppId = activityAppId === void 0 ? void 0 : v.parse(v.pipe(v.number(), v.integer(), v.minValue(1)), activityAppId);
3549
3648
  this.storage = storage ?? createNodeSqliteInboxStorage(path);
@@ -3603,12 +3702,33 @@ var PullRequestInbox = class {
3603
3702
  });
3604
3703
  await this.ready;
3605
3704
  }
3606
- async transaction(run) {
3705
+ /** The current time on the inbox clock. Compare lease ends from the inbox with it, not with `Date.now()`. */
3706
+ now() {
3707
+ return this.clock();
3708
+ }
3709
+ async syncClock(tx) {
3710
+ if (!this.usesDatabaseClock || this.clockSample && performance.now() - this.clockSample.sampledAt < clockSampleIntervalMs) return;
3711
+ const [row] = await tx.execute(`SELECT ${databaseNow} AS now`);
3712
+ const now = Number(row?.now);
3713
+ if (!Number.isFinite(now)) return;
3714
+ this.clockSample = {
3715
+ time: now,
3716
+ sampledAt: performance.now()
3717
+ };
3718
+ }
3719
+ async transaction(run, signal) {
3607
3720
  await this.init();
3608
- return await this.storage.transaction(run);
3721
+ return await this.storage.transaction(async (tx) => {
3722
+ signal?.throwIfAborted();
3723
+ await this.syncClock(tx);
3724
+ const result = await run(tx);
3725
+ signal?.throwIfAborted();
3726
+ return result;
3727
+ });
3609
3728
  }
3610
3729
  async read(statement, args = []) {
3611
3730
  await this.init();
3731
+ await this.syncClock(this.storage);
3612
3732
  return await this.storage.execute(statement, args);
3613
3733
  }
3614
3734
  /** Parses one stored row. An invalid row is reported once and skipped by queue-wide reads. */
@@ -3767,6 +3887,7 @@ var PullRequestInbox = class {
3767
3887
  s.wait?.headSha ?? null,
3768
3888
  leaseHeads ? JSON.stringify(leaseHeads) : null
3769
3889
  ]);
3890
+ if (s.pr?.state === "closed") await this.retireFoldIn(tx, s.repository, s.number);
3770
3891
  if (this.activityAuthors.size && (s.status === "terminal" || reopened || resumed || readySuperseded)) {
3771
3892
  const target = statusTargetKey(s);
3772
3893
  const pending = v.safeParse(statusDeliverySchema, await this.metaIn(tx, `${statusOutboxPrefix}${target}`));
@@ -3809,6 +3930,11 @@ var PullRequestInbox = class {
3809
3930
  key,
3810
3931
  JSON.stringify(value)
3811
3932
  ]);
3933
+ if (key.startsWith(ciEvidencePrefix) && isRuntimeRecord(value) && isRuntimeNumber(value.fetchedAt)) await tx.execute(`INSERT OR REPLACE INTO ${this.tables.meta} (scope, key, value) VALUES (?,?,?)`, [
3934
+ this.scope,
3935
+ ciEvidenceAtPrefix + key.slice(15),
3936
+ JSON.stringify(value.fetchedAt)
3937
+ ]);
3812
3938
  }
3813
3939
  async meta(key) {
3814
3940
  await this.init();
@@ -3830,13 +3956,13 @@ var PullRequestInbox = class {
3830
3956
  prefix
3831
3957
  ])).map((row) => [stringValue(row.key), JSON.parse(stringValue(row.value))]);
3832
3958
  }
3833
- async deleteMeta(key) {
3959
+ async deleteMeta(key, signal) {
3834
3960
  await this.transaction(async (tx) => {
3835
3961
  await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key=?`, [this.scope, key]);
3836
- });
3962
+ }, signal);
3837
3963
  }
3838
- async setMeta(key, value) {
3839
- await this.transaction((tx) => this.setMetaIn(tx, key, value));
3964
+ async setMeta(key, value, signal) {
3965
+ await this.transaction((tx) => this.setMetaIn(tx, key, value), signal);
3840
3966
  }
3841
3967
  async enqueueStatusResult(tx, snapshot, claim, resultHead) {
3842
3968
  if (!this.activityAuthors.size || !snapshot.lastResult?.trim()) return;
@@ -4142,12 +4268,16 @@ var PullRequestInbox = class {
4142
4268
  return true;
4143
4269
  }
4144
4270
  /** 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
- });
4271
+ async backfillStatusDeliveries(signal) {
4272
+ for (const observed of await this.waitsToEvaluate(true, true)) {
4273
+ signal?.throwIfAborted();
4274
+ await this.transaction(async (tx) => {
4275
+ const current = await this.getIn(tx, observed.repository, observed.number);
4276
+ signal?.throwIfAborted();
4277
+ if (!current || current.lease || current.status !== "waiting" || current.generation !== current.handled || current.generation !== observed.generation || (current.revision ?? 0) !== (observed.revision ?? 0)) return;
4278
+ await this.enqueueStatusResult(tx, current, void 0, current.wait?.headSha);
4279
+ });
4280
+ }
4151
4281
  }
4152
4282
  async recordWorkerBlocker(observed, revision) {
4153
4283
  await this.transaction(async (tx) => {
@@ -4199,6 +4329,19 @@ var PullRequestInbox = class {
4199
4329
  const attempt = await this.metaIn(tx, this.directMergeKey(repository, fold.child));
4200
4330
  return isRuntimeRecord(attempt) && attempt.token === fold.token && attempt.foldInto === parent ? fold.child : void 0;
4201
4331
  }
4332
+ /**
4333
+ * A closed child's fold has a known outcome, and its pending-merge path never runs again to clear it.
4334
+ * Retire the attempt with the parent's slot, so a reopened child must win the slot again before it folds.
4335
+ */
4336
+ async retireFoldIn(tx, repository, child) {
4337
+ const key = this.directMergeKey(repository, child);
4338
+ const attempt = await this.metaIn(tx, key);
4339
+ if (!isRuntimeRecord(attempt) || !isRuntimeNumber(attempt.foldInto)) return;
4340
+ await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key=?`, [this.scope, key]);
4341
+ const foldKey = this.stackFoldKey(repository, attempt.foldInto);
4342
+ const fold = await this.metaIn(tx, foldKey);
4343
+ if (isRuntimeRecord(fold) && fold.child === child && fold.token === attempt.token) await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key=?`, [this.scope, foldKey]);
4344
+ }
4202
4345
  async foldingChild(repository, parent) {
4203
4346
  await this.init();
4204
4347
  return await this.foldingChildIn({ execute: (statement, args) => this.storage.execute(statement, args) }, repository, parent);
@@ -4418,17 +4561,35 @@ var PullRequestInbox = class {
4418
4561
  isMainRepair(pr) {
4419
4562
  return this.mainRepairBranchPrefix !== void 0 && Boolean(pr?.head?.ref?.startsWith(this.mainRepairBranchPrefix));
4420
4563
  }
4421
- eligible(repository, pr) {
4422
- return Boolean(pr && pr.state === "open" && matchesBabysitterPullRequestFilter(pullRequestFilterContext(repository, pr), this.filter, "pull-request"));
4564
+ /**
4565
+ * Whether the runtime acts on `pr`. With `admitApproved`, a maintainer's approval of the head in
4566
+ * `snapshot` admits an author the filter leaves out. `writers` holds the reviewers whose write
4567
+ * permission the caller verified; without it, the review's association stands in, which only the
4568
+ * inbox's own bookkeeping relies on before a pass checks again.
4569
+ */
4570
+ eligible(repository, pr, snapshot, writers) {
4571
+ if (!pr || pr.state !== "open") return false;
4572
+ const context = pullRequestFilterContext(repository, pr);
4573
+ if (matchesBabysitterPullRequestFilter(context, this.filter, "pull-request")) return true;
4574
+ if (!this.admitApproved || !snapshot || !pr.head?.sha) return false;
4575
+ const { author, authorAssociation } = this.filter ?? {};
4576
+ const denyOnly = {
4577
+ ...this.filter,
4578
+ author: author?.deny ? { deny: author.deny } : void 0,
4579
+ authorAssociation: authorAssociation?.deny ? { deny: authorAssociation.deny } : void 0
4580
+ };
4581
+ if (!matchesBabysitterPullRequestFilter(context, denyOnly, "pull-request")) return false;
4582
+ const approval = maintainerApproval(snapshot, pr.head.sha, writers);
4583
+ return approval.approved && !approval.changesRequested.length;
4423
4584
  }
4424
- async seed(repository, value) {
4585
+ async seed(repository, value, signal) {
4425
4586
  repository = repository.toLowerCase();
4426
4587
  invariant(this.repositories.includes(repository), "the runtime seeds only repositories that its repository source lists");
4427
4588
  const pr = normalizePullRequest(value);
4428
4589
  return await this.transaction(async (tx) => {
4429
4590
  const s = await this.getIn(tx, repository, pr.number) ?? this.empty(repository, pr.number);
4430
4591
  if (this.updatePr(s, pr)) this.dirty(s, "bootstrap");
4431
- if (!this.eligible(repository, s.pr)) {
4592
+ if (!this.eligible(repository, s.pr, s)) {
4432
4593
  delete s.wait;
4433
4594
  s.status = "terminal";
4434
4595
  s.handled = s.generation;
@@ -4439,9 +4600,9 @@ var PullRequestInbox = class {
4439
4600
  }
4440
4601
  await this.put(tx, s);
4441
4602
  return s;
4442
- });
4603
+ }, signal);
4443
4604
  }
4444
- async ingest(id, event, value) {
4605
+ async ingest(id, event, value, signal) {
4445
4606
  const payload = parseDelivery(value);
4446
4607
  return await this.transaction(async (tx) => {
4447
4608
  const t = this.tables;
@@ -4560,6 +4721,7 @@ var PullRequestInbox = class {
4560
4721
  if (sha && s.pr?.head?.sha && s.pr.head.sha !== sha && !pushRefMatch && !pendingHead) continue;
4561
4722
  let changed = false;
4562
4723
  if (payload.pull_request) changed = this.updatePr(s, payload.pull_request);
4724
+ if (event === "pull_request" && payload.action === "synchronize" && s.hostUpdates?.length) this.settleHostUpdate(s, payload);
4563
4725
  const upsert = (map, value, itemKey) => {
4564
4726
  if (!value) return;
4565
4727
  const key = itemKey ?? String(value.id);
@@ -4687,7 +4849,7 @@ var PullRequestInbox = class {
4687
4849
  else if (changed) s.revision = (s.revision ?? 0) + 1;
4688
4850
  if (changed && human && feedbackEvent) s.humanFeedbackGeneration = s.generation;
4689
4851
  const exhausted = s.progressBudget?.exhausted && s.progressBudget.head === s.pr?.head?.sha;
4690
- const eligible = this.eligible(repository, s.pr);
4852
+ const eligible = this.eligible(repository, s.pr, s);
4691
4853
  if (s.pr && !eligible) {
4692
4854
  delete s.wait;
4693
4855
  s.status = "terminal";
@@ -4701,12 +4863,13 @@ var PullRequestInbox = class {
4701
4863
  if (wake && !s.wait && s.status !== "terminal" && !exhausted) queued.push(number);
4702
4864
  }
4703
4865
  return await finish(numbers.size ? void 0 : "no matching PR head");
4704
- });
4866
+ }, signal);
4705
4867
  }
4706
4868
  /** Leases up to `limit` eligible PRs. `skip` leaves a candidate unclaimed for this call. */
4707
4869
  async claim(limit, options = {}) {
4708
4870
  if (!this.repositories.length || limit < 1) return [];
4709
4871
  return await this.transaction(async (tx) => {
4872
+ options.signal?.throwIfAborted();
4710
4873
  const now = this.clock(), claims = [], t = this.tables;
4711
4874
  const repositories = this.repositoryFilter("p.repository");
4712
4875
  const mainRepair = this.mainRepairBranchPrefix;
@@ -4730,6 +4893,7 @@ var PullRequestInbox = class {
4730
4893
  ...this.priorityLabels
4731
4894
  ]);
4732
4895
  for (const candidate of candidates) {
4896
+ options.signal?.throwIfAborted();
4733
4897
  if (claims.length >= limit) break;
4734
4898
  const repository = stringValue(candidate.repository), number = Number(candidate.number);
4735
4899
  if (!this.claimStackChildren && candidate.base_ref !== null && candidate.base_ref !== void 0 && (await tx.execute(`SELECT 1 FROM ${t.pullRequests}
@@ -4742,8 +4906,9 @@ var PullRequestInbox = class {
4742
4906
  candidate.base_repository
4743
4907
  ])).length) continue;
4744
4908
  const s = await this.getRowIn(tx, candidate);
4909
+ options.signal?.throwIfAborted();
4745
4910
  if (!s) continue;
4746
- if (s.pr && !this.eligible(s.repository, s.pr)) continue;
4911
+ if (s.pr && !this.eligible(s.repository, s.pr, s)) continue;
4747
4912
  if (options.only && !options.only(s)) continue;
4748
4913
  if (options.skip && options.skip(s)) continue;
4749
4914
  s.lease = randomUUID();
@@ -4758,6 +4923,7 @@ var PullRequestInbox = class {
4758
4923
  snapshot: structuredClone(s)
4759
4924
  });
4760
4925
  }
4926
+ options.signal?.throwIfAborted();
4761
4927
  return claims;
4762
4928
  });
4763
4929
  }
@@ -4777,7 +4943,7 @@ var PullRequestInbox = class {
4777
4943
  Object.assign(s, patch);
4778
4944
  this.cleanSnapshot(s);
4779
4945
  if (patch.pr && before && before.head?.sha === s.pr?.head?.sha && conflicted$1(s.pr) && !conflicted$1(before)) this.grantProgress(s, "conflict");
4780
- if (s.pr && !this.eligible(s.repository, s.pr)) s.status = "terminal";
4946
+ if (s.pr && !this.eligible(s.repository, s.pr, s)) s.status = "terminal";
4781
4947
  await this.put(tx, s);
4782
4948
  Object.assign(claim.snapshot, patch, {
4783
4949
  comments: s.comments,
@@ -4790,7 +4956,7 @@ var PullRequestInbox = class {
4790
4956
  return true;
4791
4957
  });
4792
4958
  }
4793
- async refreshThreads(observed, threads) {
4959
+ async refreshThreads(observed, threads, signal) {
4794
4960
  return await this.transaction(async (tx) => {
4795
4961
  const s = await this.getIn(tx, observed.repository, observed.number);
4796
4962
  if (!s || s.lease || s.generation !== observed.generation || (s.revision ?? 0) !== (observed.revision ?? 0)) return false;
@@ -4814,7 +4980,7 @@ var PullRequestInbox = class {
4814
4980
  if (changed && s.status !== "terminal") this.dirty(s, "review-threads:reconciled");
4815
4981
  await this.put(tx, s);
4816
4982
  return true;
4817
- });
4983
+ }, signal);
4818
4984
  }
4819
4985
  /** Retain a worker's verified thread resolution even when its webhook is missing. */
4820
4986
  async recordThreadResolution(claim, id, observed) {
@@ -4842,8 +5008,12 @@ var PullRequestInbox = class {
4842
5008
  return true;
4843
5009
  });
4844
5010
  }
4845
- /** Retain CI for an exact candidate before its source-push webhook arrives. This is not a publication receipt. */
4846
- async registerProspectivePush(claim, head) {
5011
+ /**
5012
+ * Retain CI for an exact candidate before its source-push webhook arrives. This is not a publication receipt.
5013
+ * With `lineage.hostOnly`, it also records the head as the host's own work on `lineage.parent`, so an
5014
+ * approval of that parent carries over to it.
5015
+ */
5016
+ async registerProspectivePush(claim, head, lineage) {
4847
5017
  invariant(/^[a-f\d]{40}$/i.test(head), "the runtime registers the full commit SHA that the host push returned");
4848
5018
  return await this.transaction(async (tx) => {
4849
5019
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
@@ -4857,11 +5027,47 @@ var PullRequestInbox = class {
4857
5027
  token: claim.token,
4858
5028
  heads
4859
5029
  };
5030
+ if (lineage?.hostOnly && /^[a-f\d]{40}$/i.test(lineage.parent)) this.addHostHead(s, head, lineage.parent);
4860
5031
  s.revision = (s.revision ?? 0) + 1;
4861
5032
  await this.put(tx, s);
4862
5033
  return true;
4863
5034
  });
4864
5035
  }
5036
+ /**
5037
+ * Records that the host asks GitHub to update the PR's branch from `from` with its base, before it sends
5038
+ * the request. GitHub writes the merge commit and the response carries no SHA, so the `synchronize`
5039
+ * delivery that the host's own identity sends from `from` records the new head as the host's work. A
5040
+ * merges API call returns the commit: pass it as `head` to record it at once. Anything but a full commit
5041
+ * SHA records nothing, so the approval does not carry over.
5042
+ */
5043
+ async registerHostUpdate(repository, number, from, head) {
5044
+ if (!/^[a-f\d]{40}$/i.test(from) || head !== void 0 && !/^[a-f\d]{40}$/i.test(head)) return;
5045
+ await this.transaction(async (tx) => {
5046
+ const s = await this.getIn(tx, repository.toLowerCase(), number);
5047
+ if (!s) return;
5048
+ if (head) this.addHostHead(s, head, from);
5049
+ else s.hostUpdates = [...(s.hostUpdates ?? []).filter((entry) => entry !== from), from].slice(-8);
5050
+ await this.put(tx, s);
5051
+ });
5052
+ }
5053
+ addHostHead(s, head, parent) {
5054
+ if (s.hostHeads?.some((entry) => entry.head === head)) return;
5055
+ s.hostHeads = [...s.hostHeads ?? [], {
5056
+ head,
5057
+ parent
5058
+ }].slice(-64);
5059
+ }
5060
+ /**
5061
+ * A webhook head move ends every pending update. Only the host's own move from a registered head carries an
5062
+ * approval. A probe's synthetic `synchronize` has no `before` and leaves the updates for the webhook.
5063
+ */
5064
+ settleHostUpdate(s, payload) {
5065
+ const before = payload.before, after = payload.after ?? payload.pull_request?.head?.sha;
5066
+ if (typeof before !== "string") return;
5067
+ const sender = payload.sender;
5068
+ if (String(sender?.type ?? "").toLowerCase() === "bot" && this.activityAuthors.has(String(sender?.login ?? "").trim().toLowerCase()) && typeof after === "string" && /^[a-f\d]{40}$/i.test(after) && s.hostUpdates?.includes(before)) this.addHostHead(s, after, before);
5069
+ delete s.hostUpdates;
5070
+ }
4865
5071
  async release(claim) {
4866
5072
  return await this.transaction(async (tx) => {
4867
5073
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
@@ -5095,7 +5301,7 @@ var PullRequestInbox = class {
5095
5301
  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
5302
  }
5097
5303
  /** Records that the host evaluated a wait's new events and the wait still holds. */
5098
- async acknowledgeWait(observed) {
5304
+ async acknowledgeWait(observed, signal) {
5099
5305
  return await this.transaction(async (tx) => {
5100
5306
  const s = await this.getIn(tx, observed.repository, observed.number);
5101
5307
  if (!s?.wait || s.lease || s.status === "terminal" || s.generation !== observed.generation || (s.revision ?? 0) !== (observed.revision ?? 0)) return false;
@@ -5104,7 +5310,7 @@ var PullRequestInbox = class {
5104
5310
  await this.put(tx, s);
5105
5311
  await this.enqueueStatusResult(tx, s, void 0, s.wait.headSha);
5106
5312
  return true;
5107
- });
5313
+ }, signal);
5108
5314
  }
5109
5315
  /** Re-evaluate structured evidence outside an Agent invocation before calling this method. */
5110
5316
  async wake(observed, evidenceKey, options = {}) {
@@ -5132,7 +5338,7 @@ var PullRequestInbox = class {
5132
5338
  this.dirty(s, "wait:evidence-changed");
5133
5339
  await this.put(tx, s);
5134
5340
  return true;
5135
- });
5341
+ }, options.signal);
5136
5342
  }
5137
5343
  /**
5138
5344
  * Frees every lease in this scope at startup and returns how many were held. Call it only when one
@@ -5154,18 +5360,21 @@ var PullRequestInbox = class {
5154
5360
  return released;
5155
5361
  });
5156
5362
  }
5157
- async recoverLeases() {
5363
+ async recoverLeases(signal) {
5158
5364
  await this.transaction(async (tx) => {
5365
+ signal?.throwIfAborted();
5159
5366
  const now = this.clock();
5160
5367
  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
5368
  for (const row of rows) {
5162
5369
  const s = await this.getRowIn(tx, row);
5370
+ signal?.throwIfAborted();
5163
5371
  if (!s?.lease || s.leaseUntil > now) continue;
5164
5372
  s.lease = null;
5165
5373
  s.leaseUntil = 0;
5166
5374
  if (s.status !== "terminal") s.status = "ready";
5167
5375
  await this.put(tx, s);
5168
5376
  }
5377
+ signal?.throwIfAborted();
5169
5378
  });
5170
5379
  }
5171
5380
  async summary() {
@@ -5293,14 +5502,38 @@ var PullRequestInbox = class {
5293
5502
  }
5294
5503
  }
5295
5504
  /** Drops delivery payloads after `payloadMs` and delivery IDs after `idMs`. Recent IDs still deduplicate redeliveries. */
5296
- async pruneDeliveries({ payloadMs = 864e5, idMs = 6048e5 } = {}) {
5505
+ async pruneDeliveries({ payloadMs = 864e5, idMs = 6048e5, signal } = {}) {
5297
5506
  const now = this.clock();
5298
5507
  await this.transaction(async (tx) => {
5299
- await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key>='ci-evidence:v1:' AND key<'ci-evidence:v1;'
5300
- AND CASE WHEN NOT json_valid(value) THEN 1 WHEN json_type(value)<>'object' THEN 1
5301
- WHEN coalesce(json_type(value, '$.fetchedAt'), '') NOT IN ('integer', 'real') THEN 1 ELSE json_extract(value, '$.fetchedAt')<? END`, [this.scope, now - payloadMs]);
5508
+ signal?.throwIfAborted();
5509
+ const meta = this.tables.meta;
5510
+ const unindexed = `scope=? AND ${`key>='${ciEvidencePrefix}' AND key<'ci-evidence:v1;'`} AND NOT EXISTS (SELECT 1 FROM ${meta} WHERE scope=evidence.scope
5511
+ AND key='${ciEvidenceAtPrefix}' || substr(evidence.key, 16))`;
5512
+ await tx.execute(`INSERT INTO ${meta} (scope, key, value) SELECT scope, '${ciEvidenceAtPrefix}' || substr(key, 16),
5513
+ json_extract(value, '$.fetchedAt') FROM ${meta} AS evidence WHERE ${unindexed} AND json_valid(value) AND json_type(value)='object'
5514
+ AND json_type(value, '$.fetchedAt') IN ('integer', 'real')`, [this.scope]);
5515
+ await tx.execute(`DELETE FROM ${meta} AS evidence WHERE ${unindexed}`, [this.scope]);
5516
+ const expiredAt = `key>='${ciEvidenceAtPrefix}' AND key<'ci-evidence-at:v1;' AND CAST(value AS REAL)<?`;
5517
+ await tx.execute(`DELETE FROM ${meta} WHERE scope=? AND key IN (SELECT '${ciEvidencePrefix}' || substr(key, 19)
5518
+ FROM ${meta} WHERE scope=? AND ${expiredAt})`, [
5519
+ this.scope,
5520
+ this.scope,
5521
+ now - payloadMs
5522
+ ]);
5523
+ await tx.execute(`DELETE FROM ${meta} WHERE scope=? AND ${expiredAt}`, [this.scope, now - payloadMs]);
5524
+ signal?.throwIfAborted();
5302
5525
  await tx.execute(`DELETE FROM ${this.tables.deliveries} WHERE scope=? AND received<?`, [this.scope, now - idMs]);
5303
- await tx.execute(`UPDATE ${this.tables.deliveries} SET payload=NULL WHERE scope=? AND received<? AND payload IS NOT NULL`, [this.scope, now - payloadMs]);
5526
+ signal?.throwIfAborted();
5527
+ const cutoff = now - payloadMs;
5528
+ const prunedBefore = await this.metaIn(tx, "deliveries-payload-pruned-before");
5529
+ const from = isRuntimeNumber(prunedBefore) && prunedBefore <= cutoff ? prunedBefore : 0;
5530
+ await tx.execute(`UPDATE ${this.tables.deliveries} SET payload=NULL WHERE scope=? AND received>=? AND received<? AND payload IS NOT NULL`, [
5531
+ this.scope,
5532
+ from,
5533
+ cutoff
5534
+ ]);
5535
+ await this.setMetaIn(tx, "deliveries-payload-pruned-before", cutoff);
5536
+ signal?.throwIfAborted();
5304
5537
  });
5305
5538
  }
5306
5539
  };
@@ -5529,28 +5762,29 @@ function snapshotPullRequest(snapshot) {
5529
5762
  labels: (pr.labels ?? []).map((label) => hasRuntimeType(label, "string") ? { name: label } : label)
5530
5763
  };
5531
5764
  }
5532
- function claimStopReason(claim, current, acceptedSelfHead) {
5533
- if (!current || current.lease !== claim.token || current.leaseUntil <= Date.now()) return "Pull request lease lost.";
5765
+ /** `now` comes from the inbox clock (`PullRequestInbox.now()`), the clock that wrote `leaseUntil`. */
5766
+ function claimStopReason(claim, current, acceptedSelfHead, now = Date.now()) {
5767
+ if (!current || current.lease !== claim.token || current.leaseUntil <= now) return "Pull request lease lost.";
5534
5768
  if (current.status === "terminal" || current.pr?.state === "closed") return "Pull request is no longer open.";
5535
5769
  const expectedHead = claim.snapshot.pr?.head?.sha;
5536
5770
  if (current.pr?.head?.sha !== (acceptedSelfHead ?? expectedHead)) return "Pull request head changed.";
5537
5771
  }
5538
5772
  /** A new remote head may be our repair; prove it against the actual provider Git HEAD. */
5539
- function createClaimStopCheck(claim, readCurrent, readProviderHead) {
5773
+ function createClaimStopCheck(claim, readCurrent, readProviderHead, now = Date.now) {
5540
5774
  let acceptedSelfHead;
5541
5775
  return async () => {
5542
5776
  const observed = await readCurrent();
5543
- const reason = claimStopReason(claim, observed, acceptedSelfHead);
5777
+ const reason = claimStopReason(claim, observed, acceptedSelfHead, now());
5544
5778
  if (reason !== "Pull request head changed.") return reason;
5545
5779
  if (acceptedSelfHead && observed?.pr?.head?.sha === claim.snapshot.pr?.head?.sha) return reason;
5546
5780
  let providerHead;
5547
5781
  try {
5548
5782
  providerHead = await readProviderHead();
5549
5783
  } catch {
5550
- return claimStopReason(claim, await readCurrent(), acceptedSelfHead);
5784
+ return claimStopReason(claim, await readCurrent(), acceptedSelfHead, now());
5551
5785
  }
5552
5786
  const current = await readCurrent();
5553
- const latestReason = claimStopReason(claim, current, acceptedSelfHead);
5787
+ const latestReason = claimStopReason(claim, current, acceptedSelfHead, now());
5554
5788
  if (latestReason !== "Pull request head changed.") return latestReason;
5555
5789
  if (!providerHead || current?.pr?.head?.sha !== providerHead) return latestReason;
5556
5790
  acceptedSelfHead = providerHead;
@@ -5649,14 +5883,17 @@ async function readThreadComments(request, id) {
5649
5883
  /** REST snapshots fill webhook gaps without asking an LLM to poll GitHub. */
5650
5884
  async function readSnapshot(read, repository, number, readThreads, activityAuthors = [], signal) {
5651
5885
  const prefix = `repos/${repository}`;
5652
- const [raw] = await read(`${prefix}/pulls/${number}`, ".");
5886
+ signal?.throwIfAborted();
5887
+ const [raw] = await read(`${prefix}/pulls/${number}`, ".", signal);
5888
+ signal?.throwIfAborted();
5653
5889
  const pr = parsePullRequest(raw);
5654
5890
  if (!pr.head?.sha) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_GITHUB_HEAD_MISSING();
5655
5891
  if (pr.state !== "open") return { pr };
5656
5892
  const readAll = async (path, projection) => {
5657
5893
  const items = [];
5658
5894
  for (let page = 1;; page++) {
5659
- const batch = await read(`${path}&page=${page}`, projection);
5895
+ const batch = await read(`${path}&page=${page}`, projection, signal);
5896
+ signal?.throwIfAborted();
5660
5897
  items.push(...batch);
5661
5898
  if (batch.length < 100) return items;
5662
5899
  }
@@ -5709,27 +5946,33 @@ async function hydrateSnapshot(inbox, claim, read, readThreads, activityAuthors
5709
5946
  });
5710
5947
  return Object.keys(patch).length ? await inbox.hydrate(claim, patch) : true;
5711
5948
  }
5712
- async function reconcileOneSnapshot(inbox, read, now = Date.now(), readThreads, activityAuthors = []) {
5949
+ async function reconcileOneSnapshot(inbox, read, now = Date.now(), readThreads, activityAuthors = [], signal) {
5713
5950
  const globalKey = "snapshot-reconcile-next";
5714
5951
  const globalNext = await inbox.metaNumber(globalKey);
5952
+ signal?.throwIfAborted();
5715
5953
  if (globalNext === void 0) {
5716
- await inbox.setMeta(globalKey, now + 9e5);
5954
+ await inbox.setMeta(globalKey, now + 9e5, signal);
5717
5955
  return;
5718
5956
  }
5719
5957
  if (globalNext > now) return;
5720
- await inbox.setMeta(globalKey, now + 6e4);
5958
+ await inbox.setMeta(globalKey, now + 6e4, signal);
5959
+ signal?.throwIfAborted();
5721
5960
  const next = await inbox.nextProbe();
5961
+ signal?.throwIfAborted();
5722
5962
  if (!next || next.probedAt > now) return;
5723
5963
  const s = await inbox.get(next.repository, next.number);
5724
5964
  if (!s) return;
5725
- await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors);
5965
+ await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors, signal);
5726
5966
  }
5727
5967
  /** 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);
5968
+ async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors = [], signal) {
5969
+ signal?.throwIfAborted();
5970
+ await inbox.setMeta(`snapshot-probe:${s.repository}:${s.number}`, now + 9e5, signal);
5971
+ const snapshot = await readSnapshot(read, s.repository, s.number, readThreads, activityAuthors, signal);
5972
+ signal?.throwIfAborted();
5973
+ if (snapshot.threads) await inbox.refreshThreads(s, snapshot.threads, signal);
5732
5974
  const ingest = async (event, payload) => {
5975
+ signal?.throwIfAborted();
5733
5976
  const full = {
5734
5977
  repository: { full_name: s.repository },
5735
5978
  ...payload
@@ -5743,7 +5986,7 @@ async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors =
5743
5986
  }
5744
5987
  };
5745
5988
  const id = `reconcile:${createHash("sha256").update(JSON.stringify([event, identity])).digest("hex")}`;
5746
- await inbox.ingest(id, event, full);
5989
+ await inbox.ingest(id, event, full, signal);
5747
5990
  };
5748
5991
  await ingest("pull_request", {
5749
5992
  action: snapshot.pr.state === "closed" ? "closed" : "synchronize",
@@ -5779,7 +6022,8 @@ async function probeSnapshot(inbox, read, s, now, readThreads, activityAuthors =
5779
6022
  for (const [key, item] of Object.entries(s.checks)) {
5780
6023
  const kind = key.slice(0, key.indexOf(":"));
5781
6024
  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}`, ".");
6025
+ signal?.throwIfAborted();
6026
+ const [fresh] = await read(kind === "workflow_run" ? `repos/${s.repository}/actions/runs/${item.id}` : `repos/${s.repository}/check-suites/${item.id}`, ".", signal);
5783
6027
  const evidence = parseEvidence(fresh);
5784
6028
  await ingest(kind, {
5785
6029
  action: evidence.status === "completed" ? "completed" : String(evidence.status ?? ""),
@@ -5828,6 +6072,7 @@ const openPullRequestSchema = v.object({
5828
6072
  latestReviews: nodes,
5829
6073
  reviewThreads: nodes
5830
6074
  });
6075
+ const approvedReview = v.object({ state: v.literal("APPROVED") });
5831
6076
  const openPullRequestsSchema = v.object({ repository: v.object({ pullRequests: v.object({
5832
6077
  nodes: v.array(openPullRequestSchema),
5833
6078
  pageInfo: v.object({
@@ -5865,19 +6110,23 @@ function openPullRequestChecksSettled(pr) {
5865
6110
  const state = pr.commits.nodes[0]?.commit.statusCheckRollup?.state;
5866
6111
  return typeof state === "string" && !runningRollup.has(state);
5867
6112
  }
5868
- const changeDetectionInFlight = /* @__PURE__ */ new WeakSet();
6113
+ const changeDetectionInFlight = /* @__PURE__ */ new WeakMap();
5869
6114
  /**
5870
6115
  * Reads every open PR of each repository in one GraphQL query per 50 PRs, at most once a minute,
5871
6116
  * and at most once per 1.5 seconds per repository, so many repositories stay within the GraphQL rate limit.
5872
6117
  * Seeds new PRs and marks PRs whose fingerprint changed, or that closed, for a targeted REST probe.
5873
6118
  * This recovers lost webhook deliveries without probing unchanged PRs.
5874
6119
  */
5875
- async function detectChangedPullRequests(inbox, graphql, repositories, now = Date.now(), allowSeed = true, onError) {
5876
- if (changeDetectionInFlight.has(inbox)) return;
5877
- changeDetectionInFlight.add(inbox);
6120
+ async function detectChangedPullRequests(inbox, graphql, repositories, now = Date.now(), allowSeed = true, onError, signal) {
6121
+ const pendingRun = changeDetectionInFlight.get(inbox);
6122
+ if (pendingRun && !pendingRun.signal?.aborted) return;
6123
+ const run = { signal };
6124
+ changeDetectionInFlight.set(inbox, run);
5878
6125
  try {
5879
6126
  if ((await inbox.metaNumber("change-detect-next") ?? 0) > now) return;
5880
- await inbox.setMeta("change-detect-next", now + Math.max(6e4, repositories.length * 1500));
6127
+ signal?.throwIfAborted();
6128
+ await inbox.setMeta("change-detect-next", now + Math.max(6e4, repositories.length * 1500), signal);
6129
+ signal?.throwIfAborted();
5881
6130
  const tracked = await inbox.summary();
5882
6131
  const trackedKeys = new Set(tracked.map((item) => `${item.repository}:${item.number}`));
5883
6132
  for (const repository of repositories.map((r) => r.toLowerCase())) try {
@@ -5887,11 +6136,13 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5887
6136
  const cursors = /* @__PURE__ */ new Set();
5888
6137
  let after = null;
5889
6138
  do {
6139
+ signal?.throwIfAborted();
5890
6140
  const raw = await graphql(repository)(OPEN_PULL_REQUESTS, {
5891
6141
  owner,
5892
6142
  name,
5893
6143
  after
5894
6144
  });
6145
+ signal?.throwIfAborted();
5895
6146
  const response = v.parse(envelope, raw);
5896
6147
  if (response.errors?.length) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_GITHUB_QUERY_FAILED({
5897
6148
  query: "open pull request",
@@ -5904,25 +6155,30 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5904
6155
  if (after) cursors.add(after);
5905
6156
  } while (after);
5906
6157
  const mark = async (number, fingerprint, settled) => {
6158
+ signal?.throwIfAborted();
5907
6159
  const key = `snapshot-changed:${repository}:${number}`;
5908
6160
  const pending = v.safeParse(pendingChangeSchema, await inbox.meta(key));
6161
+ signal?.throwIfAborted();
5909
6162
  if (await inbox.meta(`change-fingerprint:${repository}:${number}`) === fingerprint || pending.success && pending.output.fingerprint === fingerprint) return;
6163
+ signal?.throwIfAborted();
5910
6164
  await inbox.setMeta(key, {
5911
6165
  fingerprint,
5912
6166
  retryAt: 0,
5913
6167
  settled,
5914
6168
  markedAt: pending.success ? pending.output.markedAt ?? now : now
5915
- });
6169
+ }, signal);
5916
6170
  };
5917
6171
  for (const [number, pr] of open) {
6172
+ signal?.throwIfAborted();
5918
6173
  const fingerprint = openPullRequestFingerprint(pr);
5919
6174
  const key = `${repository}:${number}`;
5920
6175
  if (trackedKeys.has(key) || await inbox.get(repository, number)) {
5921
6176
  await mark(number, fingerprint, openPullRequestChecksSettled(pr));
5922
6177
  continue;
5923
6178
  }
6179
+ signal?.throwIfAborted();
5924
6180
  if (!allowSeed) continue;
5925
- await inbox.seed(repository, {
6181
+ const seeded = await inbox.seed(repository, {
5926
6182
  number,
5927
6183
  title: pr.title,
5928
6184
  state: "open",
@@ -5941,31 +6197,34 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5941
6197
  sha: pr.baseRefOid ?? void 0,
5942
6198
  ref: pr.baseRefName
5943
6199
  }
5944
- });
5945
- await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint);
6200
+ }, signal);
6201
+ signal?.throwIfAborted();
6202
+ if (seeded.status === "terminal" && inbox.admitApproved && pr.latestReviews.nodes.some((review) => v.is(approvedReview, review))) await mark(number, fingerprint, openPullRequestChecksSettled(pr));
6203
+ else await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint, signal);
5946
6204
  }
5947
6205
  for (const item of tracked) if (item.repository === repository && item.status !== "terminal" && !open.has(item.number)) await mark(item.number, "closed", true);
5948
6206
  } catch (error) {
6207
+ signal?.throwIfAborted();
5949
6208
  onError?.(repository, error);
5950
6209
  }
5951
6210
  } finally {
5952
- changeDetectionInFlight.delete(inbox);
6211
+ if (changeDetectionInFlight.get(inbox) === run) changeDetectionInFlight.delete(inbox);
5953
6212
  }
5954
6213
  }
5955
6214
  /**
5956
6215
  * 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.
6216
+ * checks settled or that closed come first, up to `settledLimit`: when many webhook deliveries are
6217
+ * lost, green PRs must not wait while the probes read PRs whose checks are still running. Older marks come before newer ones.
5960
6218
  */
5961
- async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads, activityAuthors = [], limit = 3, settledLimit = 10) {
6219
+ async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads, activityAuthors = [], limit = 3, settledLimit = 10, signal) {
5962
6220
  let probed = 0;
5963
6221
  const due = [];
5964
6222
  for (const [key, value] of await inbox.metaEntries("snapshot-changed:")) {
6223
+ signal?.throwIfAborted();
5965
6224
  const pending = v.safeParse(pendingChangeSchema, value);
5966
6225
  const [, repository, number] = /^snapshot-changed:(.+):(\d+)$/.exec(key) ?? [];
5967
6226
  if (!pending.success || !repository || !number) {
5968
- await inbox.deleteMeta(key);
6227
+ await inbox.deleteMeta(key, signal);
5969
6228
  continue;
5970
6229
  }
5971
6230
  if (pending.output.retryAt <= now) due.push({
@@ -5978,21 +6237,25 @@ async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads,
5978
6237
  due.sort((a, b) => Number(Boolean(b.pending.settled)) - Number(Boolean(a.pending.settled)) || (a.pending.markedAt ?? 0) - (b.pending.markedAt ?? 0));
5979
6238
  let settled = 0;
5980
6239
  for (const { key, repository, number, pending } of due) {
6240
+ signal?.throwIfAborted();
5981
6241
  if (pending.settled ? settled >= settledLimit : probed - settled >= limit) continue;
5982
6242
  const s = await inbox.get(repository, Number(number));
6243
+ signal?.throwIfAborted();
5983
6244
  if (!s) {
5984
- await inbox.deleteMeta(key);
6245
+ await inbox.deleteMeta(key, signal);
5985
6246
  continue;
5986
6247
  }
5987
6248
  await inbox.setMeta(key, {
5988
6249
  ...pending,
5989
6250
  retryAt: now + 12e4
5990
- });
6251
+ }, signal);
5991
6252
  probed++;
5992
6253
  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);
6254
+ await probeSnapshot(inbox, read, s, now, readThreads, activityAuthors, signal);
6255
+ signal?.throwIfAborted();
6256
+ await inbox.setMeta(`change-fingerprint:${repository}:${number}`, pending.fingerprint, signal);
6257
+ signal?.throwIfAborted();
6258
+ await inbox.deleteMeta(key, signal);
5996
6259
  }
5997
6260
  return probed;
5998
6261
  }
@@ -6699,9 +6962,8 @@ const failedConclusions = failed;
6699
6962
  const stuckCheckMs = 18e5;
6700
6963
  /**
6701
6964
  * 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.
6965
+ * past those limits are stuck. GitHub sets a queued run's `started_at` when it creates the run. A job
6966
+ * can wait hours for a runner, and a shorter limit lets passes push over CI runs that are only queued.
6705
6967
  */
6706
6968
  const stuckQueuedCheckMs = 864e5;
6707
6969
  const stuckRunningCheckMs = 288e5;
@@ -6845,8 +7107,8 @@ function checksStillRunning(s, now = Date.now(), policy) {
6845
7107
  }
6846
7108
  /**
6847
7109
  * 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".
7110
+ * brings them: a required job can be missing from a run that succeeded, and the PR then waits for
7111
+ * "required checks pending" forever.
6850
7112
  */
6851
7113
  function missingRequiredChecks(s, evaluation, now = Date.now()) {
6852
7114
  if (evaluation?.state !== "pending" || !evaluation.missing.length) return [];
@@ -7091,19 +7353,45 @@ const pushMarginMs = 12e4;
7091
7353
  */
7092
7354
  async function checksTestedBase(reader, snapshot, head, baseRef, conclusions, signal) {
7093
7355
  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];
7356
+ const source = snapshot.pr?.head;
7357
+ const sourceRepository = source?.repo?.full_name;
7358
+ const fork = sourceRepository != null && sourceRepository.toLowerCase() !== repository.toLowerCase();
7359
+ const readRun = (id) => reader.page(`repos/${repository}/actions/runs/${id}`, signal);
7360
+ const candidates = Object.values(snapshot.checks).filter((check) => !check.deleted && check.head_sha === head && !isBabysitterCheckRun(check) && conclusions.has(String(check.conclusion).toLowerCase()));
7361
+ const checkTime = (check) => String(check.started_at ?? check.completed_at ?? "");
7362
+ const ordered = candidates.sort((left, right) => checkTime(right).localeCompare(checkTime(left)));
7363
+ const newest = /* @__PURE__ */ new Map();
7364
+ const reads = /* @__PURE__ */ new Map();
7365
+ for (const check of ordered) {
7366
+ const name = String(check.name);
7367
+ if (newest.has(name)) continue;
7368
+ if (fork) {
7369
+ const id = actionLocation(repository, check)?.runId;
7370
+ if (!id) continue;
7371
+ const pending = reads.get(id) ?? readRun(id);
7372
+ reads.set(id, pending);
7373
+ const run = await pending;
7374
+ 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;
7375
+ }
7376
+ newest.set(name, check);
7377
+ }
7378
+ const runIds = [...new Set([...newest.values()].flatMap((check) => {
7379
+ const id = actionLocation(repository, check)?.runId;
7097
7380
  return id ? [id] : [];
7098
7381
  }))];
7099
7382
  const runs = await Promise.all(runIds.map(async (id) => {
7100
- const run = await reader.page(`repos/${repository}/actions/runs/${id}`, signal);
7383
+ const run = await (reads.get(id) ?? readRun(id));
7101
7384
  if (!isRuntimeRecord(run)) return {
7102
7385
  created: NaN,
7103
7386
  base: void 0,
7104
7387
  hasPullRequestMetadata: false
7105
7388
  };
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")) : [];
7389
+ 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] : []) : [];
7390
+ if (fork && Array.isArray(run.pull_requests) && !run.pull_requests.length) return {
7391
+ created: Date.parse(String(run.created_at)),
7392
+ base: void 0,
7393
+ hasPullRequestMetadata: false
7394
+ };
7107
7395
  return {
7108
7396
  created: Date.parse(String(run.created_at)),
7109
7397
  base: bases.length === 1 ? bases[0] : void 0,
@@ -7113,7 +7401,7 @@ async function checksTestedBase(reader, snapshot, head, baseRef, conclusions, si
7113
7401
  const exactBases = runs.filter((run) => run.hasPullRequestMetadata).map((run) => run.base);
7114
7402
  if (exactBases.length && exactBases.some((base) => !base)) return void 0;
7115
7403
  const exact = runs.slice().sort((a, b) => a.created - b.created).find((run) => run.hasPullRequestMetadata && run.base)?.base;
7116
- if (exact) return exact;
7404
+ if (exact && (!fork || runs.every((run) => run.hasPullRequestMetadata))) return exact;
7117
7405
  const started = runs.map((run) => run.created);
7118
7406
  const ranAt = Math.min(...started.filter(Number.isFinite));
7119
7407
  if (!Number.isFinite(ranAt)) return void 0;
@@ -7137,7 +7425,8 @@ async function staleBaseOverlap(reader, snapshot, live, signal, testedConclusion
7137
7425
  const changed = new Set(files.flatMap((file) => isRuntimeRecord(file) ? [file.filename, file.previous_filename] : []).filter((file) => hasRuntimeType(file, "string")));
7138
7426
  if (!testedBase) return [...changed];
7139
7427
  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 [];
7428
+ if (!isRuntimeRecord(compare) || typeof compare.ahead_by !== "number" || Number(compare.behind_by) > 0) return [...changed];
7429
+ if (compare.ahead_by === 0) return [];
7141
7430
  if (!Array.isArray(compare.files) || compare.files.length >= 100) return [...changed];
7142
7431
  const baseFiles = compare.files.flatMap((file) => isRuntimeRecord(file) ? [file.filename, file.previous_filename] : []);
7143
7432
  return [...new Set(baseFiles.filter((file) => hasRuntimeType(file, "string") && changed.has(file)))];
@@ -7246,8 +7535,7 @@ function jobFailureFacts(log) {
7246
7535
  }
7247
7536
  /**
7248
7537
  * 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.
7538
+ * failure, or no failure. Without it, a pass spends its repair pushes on failures the PR did not cause.
7251
7539
  */
7252
7540
  function unrelatedFailureWait(causes, base, now = Date.now()) {
7253
7541
  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 +7575,7 @@ function failedOwnActions(snapshot, reviewChecks, inheritedCheckIds = /* @__PURE
7287
7575
  }
7288
7576
  /**
7289
7577
  * 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
7578
+ * 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
7579
  * check named in `bypassChecks` that only repeats the base's failure passes.
7293
7580
  */
7294
7581
  function inheritedCheckEvaluation(snapshot, policy, inheritedCheckIds, reviewChecks, bypassChecks = /* @__PURE__ */ new Set()) {
@@ -7438,6 +7725,11 @@ function directMergeBranchSafety(repository, pr, openChildren) {
7438
7725
  if (!hasRuntimeType(branch, "string")) return "pull request source branch unavailable";
7439
7726
  return openChildren.some((child) => String(field(child, "state")).toLowerCase() === "open" && field(child, "base", "ref") === branch) ? stackChildBaseDeletion : true;
7440
7727
  }
7728
+ /** Whether a PR's head branch lives in another repository than `repository`, such as a fork. */
7729
+ function isForkHead(pr, repository) {
7730
+ const headRepository = field(pr, "head", "repo", "full_name");
7731
+ return hasRuntimeType(headRepository, "string") && headRepository.toLowerCase() !== repository.toLowerCase();
7732
+ }
7441
7733
  /** The head and base branch of a PR whose head branch lives in `repository`, which the host can push to. */
7442
7734
  function sameRepositoryBranches(pr, repository) {
7443
7735
  const head = field(pr, "head", "ref");
@@ -7457,6 +7749,51 @@ function sameRepositoryBranches(pr, repository) {
7457
7749
  function foldMethod(method, repository) {
7458
7750
  return isRuntimeRecord(repository) && repository.allow_merge_commit === false ? method : "merge";
7459
7751
  }
7752
+ /**
7753
+ * Whether a workflow can run on a push or creation of `branch`, including as a local reusable
7754
+ * workflow called by another workflow. Anything we cannot read counts as yes.
7755
+ */
7756
+ function runsOnPush(workflow, branch) {
7757
+ let document;
7758
+ try {
7759
+ document = parse(workflow);
7760
+ } catch {
7761
+ return true;
7762
+ }
7763
+ if (!isRuntimeRecord(document)) return true;
7764
+ const on = document.on ?? document.true;
7765
+ if (typeof on === "string" || Array.isArray(on)) return [on].flat().some((event) => event === "push" || event === "create" || event === "workflow_call");
7766
+ if (!isRuntimeRecord(on)) return true;
7767
+ if ("create" in on || "workflow_call" in on) return true;
7768
+ if (!("push" in on)) return false;
7769
+ const push = on.push;
7770
+ if (push == null) return true;
7771
+ if (!isRuntimeRecord(push)) return true;
7772
+ const list = (value) => value === void 0 ? void 0 : [value].flat().map(String);
7773
+ const branches = list(push.branches);
7774
+ const ignored = list(push["branches-ignore"]);
7775
+ if ([...branches ?? [], ...ignored ?? []].some((pattern) => /[[\\?+]/.test(pattern))) return true;
7776
+ if (!branches && !ignored) return push.tags === void 0 && push["tags-ignore"] === void 0;
7777
+ if (ignored) return !ignored.some((pattern) => branchFilter(pattern).test(branch));
7778
+ let match = false;
7779
+ for (const pattern of branches) if (pattern.startsWith("!")) {
7780
+ if (branchFilter(pattern.slice(1)).test(branch)) match = false;
7781
+ } else if (branchFilter(pattern).test(branch)) match = true;
7782
+ return match;
7783
+ }
7784
+ /** GitHub's branch filter pattern as a regular expression: `**` crosses `/`, `*` does not. */
7785
+ function branchFilter(pattern) {
7786
+ let source = "";
7787
+ for (let index = 0; index < pattern.length; index++) {
7788
+ const char = pattern[index];
7789
+ if (char === "*" && pattern[index + 1] === "*") {
7790
+ source += ".*";
7791
+ index++;
7792
+ } else if (char === "*") source += "[^/]*";
7793
+ else source += char.replace(/[.^${}()|[\]\\]/g, "\\$&");
7794
+ }
7795
+ return new RegExp(`^${source}$`);
7796
+ }
7460
7797
  //#endregion
7461
7798
  //#region src/babysitter/merge-ready.ts
7462
7799
  /** Fence application callbacks so stalled or rejected readiness never retains a scheduler slot. */
@@ -8032,9 +8369,11 @@ function createBabysitterStatusRecovery(options) {
8032
8369
  }
8033
8370
  })) await inbox.recordWorkerBlocker(snapshot, revision);
8034
8371
  },
8035
- async recover() {
8036
- await inbox.backfillStatusDeliveries();
8372
+ async recover(signal) {
8373
+ await inbox.backfillStatusDeliveries(signal);
8374
+ signal?.throwIfAborted();
8037
8375
  for (const snapshot of await inbox.waitsToEvaluate(true, true)) {
8376
+ signal?.throwIfAborted();
8038
8377
  if (!isWorkerBlocker(snapshot)) continue;
8039
8378
  const head = snapshot.pr?.head?.sha;
8040
8379
  const evidence = createHash("sha256").update(JSON.stringify([
@@ -8078,15 +8417,43 @@ function isTransientNetworkError(error) {
8078
8417
  }
8079
8418
  /** Runs a read again after 1 and 3 seconds while it fails with a transient network error. */
8080
8419
  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 });
8420
+ for (let attempt = 0;; attempt++) {
8421
+ signal?.throwIfAborted();
8422
+ try {
8423
+ return await read();
8424
+ } catch (error) {
8425
+ const delay = retryDelaysMs[attempt];
8426
+ if (delay === void 0 || signal?.aborted || !isTransientNetworkError(error)) throw error;
8427
+ await setTimeout$1(delay, void 0, { signal });
8428
+ }
8087
8429
  }
8088
8430
  }
8089
8431
  //#endregion
8432
+ //#region src/babysitter/queue-health.ts
8433
+ /** Derive bounded operational counters from the durable queue, including scheduled retries. */
8434
+ function babysitterQueueHealth(items, now = Date.now()) {
8435
+ const mergedTerminal = (result) => result?.startsWith("Merged ") || result === "Asynchronous merge confirmed by GitHub." || result === "Direct merge outcome reconciled: GitHub reports the pull request merged.";
8436
+ const ready = items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt <= now);
8437
+ const waiting = items.filter((item) => item.status === "waiting");
8438
+ return {
8439
+ working: items.filter((item) => item.status === "working").length,
8440
+ ready: ready.length,
8441
+ scheduled: items.filter((item) => item.status === "ready" && item.dirty && !item.stackBlocked && item.nextAt > now).length,
8442
+ stackBlocked: items.filter((item) => item.stackBlocked).length,
8443
+ waiting: waiting.length,
8444
+ suppressed: items.filter((item) => item.status === "terminal" && item.state === "open" && !mergedTerminal(item.lastResult)).length,
8445
+ oldestReadyAgeMs: ready.reduce((age, item) => Math.max(age, item.dirtyAt === void 0 ? 0 : now - item.dirtyAt), 0),
8446
+ blockers: {
8447
+ checks: waiting.filter((item) => item.wait && item.wait.kind !== "external" && !item.wait.wake).length,
8448
+ dependency: waiting.filter((item) => item.wait?.wake).length,
8449
+ manual: waiting.filter((item) => item.wait?.kind === "external" && !item.wait.wake && item.wait.retryAt === void 0).length,
8450
+ timed: waiting.filter((item) => item.wait?.retryAt !== void 0).length,
8451
+ installCapacity: waiting.filter((item) => item.wait?.reasonCode === "install-capacity").length,
8452
+ noProgress: waiting.filter((item) => item.progressBudget?.exhausted && item.progressBudget.head === item.head).length
8453
+ }
8454
+ };
8455
+ }
8456
+ //#endregion
8090
8457
  //#region src/babysitter/main-repair.ts
8091
8458
  const defaultStuckJobMinutes = 90;
8092
8459
  const branchSchema = v.looseObject({
@@ -8234,11 +8601,17 @@ async function repairBaseBranch(github, options) {
8234
8601
  head
8235
8602
  };
8236
8603
  }
8237
- const open = v.parse(pullsSchema, await github.read(`repos/${repository}/pulls`, {
8238
- state: "open",
8239
- base,
8240
- per_page: 100
8241
- })).find(repairPull);
8604
+ let open;
8605
+ for (let page = 1; !open; page++) {
8606
+ const pulls = v.parse(pullsSchema, await github.read(`repos/${repository}/pulls`, {
8607
+ state: "open",
8608
+ base,
8609
+ per_page: 100,
8610
+ page
8611
+ }));
8612
+ open = pulls.find(repairPull);
8613
+ if (pulls.length < 100) break;
8614
+ }
8242
8615
  if (open) {
8243
8616
  event("repair_open", {
8244
8617
  head,
@@ -8333,7 +8706,7 @@ const stoppedMergeRetryMs = 72e5;
8333
8706
  /**
8334
8707
  * GitHub settles most asynchronous merges in seconds, so poll a pending request less often as it ages:
8335
8708
  * 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.
8709
+ * A fixed 30-second poll can run for hours on a request that GitHub never settles.
8337
8710
  */
8338
8711
  function pendingMergeRetryAt(startedAt, now) {
8339
8712
  return now + Math.min(3e5, Math.max(3e4, now - startedAt));
@@ -8365,10 +8738,16 @@ function createBabysitterRuntime(options) {
8365
8738
  option: "concurrency",
8366
8739
  expected: "a positive integer"
8367
8740
  });
8741
+ const stallMs = options.stallMs ?? 9e5;
8742
+ if (!Number.isFinite(stallMs) || stallMs < 1 || stallMs > 2147483647) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_OPTION_INVALID({
8743
+ option: "stallMs",
8744
+ expected: "milliseconds from 1 to 2147483647"
8745
+ });
8368
8746
  const baseAgent = options.agent;
8369
8747
  assertBabysitterAgent(baseAgent);
8370
8748
  const presetOptions = baseAgent.options;
8371
8749
  const filter = resolveBabysitterLifecycleFilter(presetOptions.filter, presetOptions.lifecycle);
8750
+ const approvalAdmission = presetOptions.lifecycle?.approval === true;
8372
8751
  const merge = resolveBabysitterMerge(presetOptions.merge);
8373
8752
  const github = options.github;
8374
8753
  const hostIdentity = github.identity()?.trim();
@@ -8391,6 +8770,7 @@ function createBabysitterRuntime(options) {
8391
8770
  } : { path: options.inboxPath },
8392
8771
  repositories: () => repositorySource.known(),
8393
8772
  filter,
8773
+ admitApproved: approvalAdmission,
8394
8774
  activityAuthors,
8395
8775
  activityAppId: verifiedHostIdentity ? github.appId?.() : void 0,
8396
8776
  budgets: {
@@ -8453,7 +8833,7 @@ function createBabysitterRuntime(options) {
8453
8833
  ignoreAssessedBotThreads: presetOptions.ignoreAssessedBotThreads === true
8454
8834
  };
8455
8835
  const schedulerEvent = (name, properties = {}) => options.event?.(name, properties);
8456
- const release = baseAgent.version ?? "36cb7f3d81a66e753f82ebfb46bda4f9cdcc713a9a7ab3953bc1baa6b2c1bd26";
8836
+ const release = baseAgent.version ?? "cc2ab9f972b0945800468710b76d4809a3c6faa1a595c85f117a934b62a37e90";
8457
8837
  const workspaces = options.workspaces;
8458
8838
  const schedulerError = (name, error, properties = {}) => options.error?.(name, error, properties);
8459
8839
  const statusComment = !!verifiedHostIdentity && presetOptions.status?.comment !== false;
@@ -8569,6 +8949,44 @@ function createBabysitterRuntime(options) {
8569
8949
  const { provider } = await forge(path.split("/").slice(1, 3).join("/"), signal);
8570
8950
  return (await retryTransient(() => provider.request("GET", `/${path}`, { signal }), signal)).data;
8571
8951
  }
8952
+ const writerAnswers = /* @__PURE__ */ new Map();
8953
+ /**
8954
+ * The reviewers that approval counts as maintainers: those whose association claims write access and
8955
+ * whose repository permission confirms it. An organization member with read access is `MEMBER` too.
8956
+ * Each answer stays for ten minutes.
8957
+ */
8958
+ async function verifiedWriters(snapshot, signal) {
8959
+ const repository = snapshot.repository.toLowerCase();
8960
+ const writers = /* @__PURE__ */ new Set();
8961
+ for (const login of approvalReviewers(snapshot)) {
8962
+ const key = `${repository}:${login}`;
8963
+ let answer = writerAnswers.get(key);
8964
+ if (!answer || answer.at < Date.now() - 6e5) {
8965
+ const permission = await readOnePage(`repos/${repository}/collaborators/${encodeURIComponent(login)}/permission`, signal).catch((error) => {
8966
+ if (forgeErrorStatus(error) === 404) return void 0;
8967
+ throw error;
8968
+ });
8969
+ answer = {
8970
+ writer: isRuntimeRecord(permission) && [
8971
+ "admin",
8972
+ "maintain",
8973
+ "write"
8974
+ ].includes(String(permission.permission)),
8975
+ at: Date.now()
8976
+ };
8977
+ if (writerAnswers.size > 1e3) writerAnswers.clear();
8978
+ writerAnswers.set(key, answer);
8979
+ }
8980
+ if (answer.writer) writers.add(login);
8981
+ }
8982
+ return writers;
8983
+ }
8984
+ /** `eligible()` with the approval evidence that admits a PR through `lifecycle.approval`. */
8985
+ async function eligibleNow(repository, pr, snapshot, signal) {
8986
+ if (pullRequestInbox.eligible(repository, pr)) return true;
8987
+ if (!approvalAdmission || !snapshot) return false;
8988
+ return pullRequestInbox.eligible(repository, pr, snapshot, await verifiedWriters(snapshot, signal));
8989
+ }
8572
8990
  const freshnessReader = {
8573
8991
  rest: (path, signal, key) => readRest(path, key ? `.${key}[]` : ".[]", signal),
8574
8992
  page: readOnePage
@@ -8603,12 +9021,15 @@ function createBabysitterRuntime(options) {
8603
9021
  }
8604
9022
  };
8605
9023
  }
8606
- async function checkMainRepairs(repositories, track) {
9024
+ async function checkMainRepairs(repositories, track, signal) {
8607
9025
  if (!mainRepair || !mainRepairPrefix) return;
8608
9026
  for (const repository of repositories) {
9027
+ signal.throwIfAborted();
8609
9028
  if (!mainRepairWatches(repository) || mainRepairRunning.has(repository)) continue;
8610
9029
  if ((await pullRequestInbox.metaNumber(mainRepairKey(repository)) ?? 0) > Date.now()) continue;
8611
- await pullRequestInbox.setMeta(mainRepairKey(repository), Date.now() + mainRepairIntervalMs);
9030
+ signal.throwIfAborted();
9031
+ await pullRequestInbox.setMeta(mainRepairKey(repository), Date.now() + mainRepairIntervalMs, signal);
9032
+ signal.throwIfAborted();
8612
9033
  mainRepairRunning.add(repository);
8613
9034
  track(repairBaseBranch(mainRepairGitHub(repository, AbortSignal.timeout(3e5)), {
8614
9035
  repository,
@@ -8676,7 +9097,9 @@ function createBabysitterRuntime(options) {
8676
9097
  * Merges the base into the PR branch through GitHub, without a model pass. False when GitHub refuses.
8677
9098
  * `pr` is the live or snapshot PR; its branches allow the merges API fallback.
8678
9099
  */
8679
- async function updateBranch(owner, repository, number, head, signal, pr) {
9100
+ async function updateBranch(owner, repository, number, head, signal, pr, { reopenFork = true } = {}) {
9101
+ if (reopenFork && isForkHead(pr, repository)) return await reopenForkPullRequest(owner, repository, number, head, signal);
9102
+ if (approvalAdmission) await pullRequestInbox.registerHostUpdate(repository, number, head);
8680
9103
  try {
8681
9104
  const { provider } = await forge(repository, signal);
8682
9105
  await provider.request("PUT", `/repos/${repository}/pulls/${number}/update-branch`, {
@@ -8704,14 +9127,16 @@ function createBabysitterRuntime(options) {
8704
9127
  });
8705
9128
  return false;
8706
9129
  }
8707
- await provider.request("POST", `/repos/${repository}/merges`, {
9130
+ const merged = (await provider.request("POST", `/repos/${repository}/merges`, {
8708
9131
  body: {
8709
9132
  base: branches.head,
8710
9133
  head: branches.base,
8711
9134
  commit_message: `Merge ${branches.base} into ${branches.head}`
8712
9135
  },
8713
9136
  signal
8714
- });
9137
+ })).data;
9138
+ const parent = isRuntimeRecord(merged) && Array.isArray(merged.parents) && isRuntimeRecord(merged.parents[0]) ? merged.parents[0].sha : void 0;
9139
+ if (approvalAdmission && parent === head && isRuntimeRecord(merged) && hasRuntimeType(merged.sha, "string") && /^[a-f\d]{40}$/i.test(merged.sha)) await pullRequestInbox.registerHostUpdate(repository, number, head, merged.sha);
8715
9140
  return true;
8716
9141
  } catch (fallback) {
8717
9142
  await noteForgeQuota(fallback, "merge-base-into-head");
@@ -8724,6 +9149,110 @@ function createBabysitterRuntime(options) {
8724
9149
  }
8725
9150
  }
8726
9151
  /**
9152
+ * Closes and reopens a fork PR, so its `pull_request` workflows run again on the merge with the current
9153
+ * base. The host cannot update a fork branch: GitHub refuses App pushes to forks. At most hourly per PR.
9154
+ * The host records the close before it sends it, so `recoverForkReopens` reopens a PR that a restart
9155
+ * or a GitHub error left closed.
9156
+ */
9157
+ async function reopenForkPullRequest(owner, repository, number, head, signal) {
9158
+ if (!hostIdentity) return false;
9159
+ const key = forkReopenKey(repository, number);
9160
+ const previous = await pullRequestInbox.meta(key);
9161
+ if (isRuntimeRecord(previous) && (previous.closing === true || Number(previous.at) > Date.now() - 36e5)) return false;
9162
+ const { provider } = await forge(repository, signal);
9163
+ try {
9164
+ const live = (await provider.request("GET", `/repos/${repository}/pulls/${number}`, { signal })).data;
9165
+ if (!isRuntimeRecord(live) || live.state !== "open" || !isRuntimeRecord(live.head) || live.head.sha !== head) {
9166
+ schedulerEvent("babysitter.fork_checks.reopen_skipped", {
9167
+ ...owner,
9168
+ reason: "head changed"
9169
+ });
9170
+ return false;
9171
+ }
9172
+ } catch (error) {
9173
+ await noteForgeQuota(error, "fork-reopen");
9174
+ return false;
9175
+ }
9176
+ await pullRequestInbox.setMeta(key, {
9177
+ at: Date.now(),
9178
+ head,
9179
+ closing: true,
9180
+ login: hostIdentity.toLowerCase()
9181
+ });
9182
+ try {
9183
+ await provider.request("PATCH", `/repos/${repository}/pulls/${number}`, {
9184
+ body: { state: "closed" },
9185
+ signal
9186
+ });
9187
+ await reopenPullRequest(repository, number);
9188
+ } catch (error) {
9189
+ await noteForgeQuota(error, "fork-reopen");
9190
+ schedulerEvent("babysitter.fork_checks.reopen_failed", {
9191
+ ...owner,
9192
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
9193
+ });
9194
+ return false;
9195
+ }
9196
+ await pullRequestInbox.setMeta(key, {
9197
+ at: Date.now(),
9198
+ head,
9199
+ closing: false
9200
+ });
9201
+ schedulerEvent("babysitter.fork_checks.reopened", {
9202
+ ...owner,
9203
+ head_sha: head
9204
+ });
9205
+ return true;
9206
+ }
9207
+ async function reopenPullRequest(repository, number) {
9208
+ const { provider } = await forge(repository, new AbortController().signal);
9209
+ await provider.request("PATCH", `/repos/${repository}/pulls/${number}`, { body: { state: "open" } });
9210
+ }
9211
+ const closeClockMarginMs = 6e4;
9212
+ const forkReopenKey = (repository, number) => `fork-reopen:${repository}#${number}`;
9213
+ /**
9214
+ * Finishes a close and reopen that a restart or a GitHub error interrupted. A PR that is still closed
9215
+ * is reopened only when this host's identity closed it while the close was in flight.
9216
+ */
9217
+ async function recoverForkReopens(signal) {
9218
+ for (const [key, value] of await pullRequestInbox.metaEntries("fork-reopen:")) {
9219
+ signal.throwIfAborted();
9220
+ const match = /^fork-reopen:(.+)#(\d+)$/.exec(key);
9221
+ if (!match || !isRuntimeRecord(value) || value.closing !== true || Number(value.at) > Date.now() - 12e4) continue;
9222
+ const [, repository, number] = match;
9223
+ const owner = {
9224
+ repository,
9225
+ pullRequest: Number(number)
9226
+ };
9227
+ try {
9228
+ const { provider } = await forge(repository, signal);
9229
+ const issue = (await provider.request("GET", `/repos/${repository}/issues/${number}`, { signal })).data;
9230
+ if (!isRuntimeRecord(issue)) continue;
9231
+ const closedBy = isRuntimeRecord(issue.closed_by) ? issue.closed_by : void 0;
9232
+ const ours = issue.state === "closed" && typeof value.login === "string" && String(closedBy?.login).toLowerCase() === value.login && Date.parse(String(issue.closed_at)) >= Number(value.at) - closeClockMarginMs;
9233
+ const merged = isRuntimeRecord(issue.pull_request) && issue.pull_request.merged_at != null;
9234
+ if (ours && !merged) {
9235
+ await reopenPullRequest(repository, Number(number));
9236
+ schedulerEvent("babysitter.fork_checks.reopen_recovered", owner);
9237
+ } else if (issue.state === "closed") schedulerEvent("babysitter.fork_checks.reopen_abandoned", {
9238
+ ...owner,
9239
+ reason: merged ? "merged" : "closed by someone else"
9240
+ });
9241
+ await pullRequestInbox.setMeta(key, {
9242
+ ...value,
9243
+ closing: false
9244
+ }, signal);
9245
+ } catch (error) {
9246
+ signal.throwIfAborted();
9247
+ await noteForgeQuota(error, "fork-reopen-recover");
9248
+ schedulerEvent("babysitter.fork_checks.reopen_failed", {
9249
+ ...owner,
9250
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
9251
+ });
9252
+ }
9253
+ }
9254
+ }
9255
+ /**
8727
9256
  * Failed checks that ran on an older base get one retest on the current base before a model pass,
8728
9257
  * when the base tip has no failing check. One retest per PR every six hours.
8729
9258
  */
@@ -8748,8 +9277,8 @@ function createBabysitterRuntime(options) {
8748
9277
  const conflicted = (snapshot) => snapshot.pr?.mergeable === false || snapshot.pr?.mergeable_state === "dirty";
8749
9278
  /**
8750
9279
  * 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.
9280
+ * per head and base and at most hourly per PR. Without it, a PR waits for hours on a transient error,
9281
+ * such as a 504 from a setup action, that nothing retries.
8753
9282
  */
8754
9283
  async function retestInfrastructureFailure(snapshot, owner, signal) {
8755
9284
  const { repository, number } = snapshot;
@@ -8772,8 +9301,216 @@ function createBabysitterRuntime(options) {
8772
9301
  return true;
8773
9302
  }
8774
9303
  /**
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.
9304
+ * Pushes a fork PR's head to its `merge.forkHeadBranches` branch, so required checks that run only on
9305
+ * pushes to the repository report on it. A push runs the workflow files of the pushed commit with the
9306
+ * repository's permissions, so the host pushes only a head that GitHub reports, now, as:
9307
+ * - approved at that exact SHA by a reviewer with write access, with no change request standing;
9308
+ * - carrying no local action and no workflow that a push to that branch starts, unless the base branch has
9309
+ * the same file now.
9310
+ * It moves only a branch it created itself. Once per head; a refused or failed push is tried again after an hour.
9311
+ */
9312
+ async function pushForkHead(snapshot, owner, missing, signal) {
9313
+ const { repository, number } = snapshot;
9314
+ const head = snapshot.pr?.head?.sha;
9315
+ const baseRef = snapshot.pr?.base?.ref;
9316
+ const template = merge.mode === "direct" ? merge.forkHeadBranches?.get(repository.toLowerCase()) : void 0;
9317
+ if (!template || !head || !baseRef || !isForkHead(snapshot.pr, repository)) return false;
9318
+ const key = forkHeadKey(repository, number);
9319
+ const previous = await pullRequestInbox.meta(key);
9320
+ const record = isRuntimeRecord(previous) ? previous : {};
9321
+ if (record.head === head && (record.pushed === true || Number(record.at) > Date.now() - 36e5)) return false;
9322
+ const branch = template.replaceAll("{number}", String(number));
9323
+ const settle = async (pushed, fields) => {
9324
+ await pullRequestInbox.setMeta(key, {
9325
+ ...record,
9326
+ head,
9327
+ at: Date.now(),
9328
+ pushed,
9329
+ ...fields
9330
+ });
9331
+ };
9332
+ try {
9333
+ const { provider } = await forge(repository, signal);
9334
+ const read = async (path) => (await retryTransient(() => provider.request("GET", path, { signal }), signal)).data;
9335
+ const refusal = await forkHeadRefusal(repository, number, head, baseRef, branch, read);
9336
+ if (refusal) {
9337
+ await settle(false, {});
9338
+ schedulerEvent("babysitter.fork_head.skipped", {
9339
+ ...owner,
9340
+ missing,
9341
+ branch,
9342
+ reason: refusal
9343
+ });
9344
+ return false;
9345
+ }
9346
+ const ref = await read(`/repos/${repository}/git/ref/heads/${branch}`).catch((error) => {
9347
+ if (forgeErrorStatus(error) === 404) return void 0;
9348
+ throw error;
9349
+ });
9350
+ const tip = isRuntimeRecord(ref) && isRuntimeRecord(ref.object) ? ref.object.sha : void 0;
9351
+ if (tip === head) {
9352
+ await settle(true, {
9353
+ branch,
9354
+ sha: head
9355
+ });
9356
+ return false;
9357
+ }
9358
+ if (ref !== void 0 && !(record.branch === branch && tip === record.sha)) {
9359
+ await settle(false, {});
9360
+ schedulerEvent("babysitter.fork_head.skipped", {
9361
+ ...owner,
9362
+ missing,
9363
+ branch,
9364
+ reason: "branch exists and the host did not create it"
9365
+ });
9366
+ return false;
9367
+ }
9368
+ if (ref !== void 0) await provider.request("PATCH", `/repos/${repository}/git/refs/heads/${branch}`, {
9369
+ body: {
9370
+ sha: head,
9371
+ force: true
9372
+ },
9373
+ signal
9374
+ });
9375
+ else await provider.request("POST", `/repos/${repository}/git/refs`, {
9376
+ body: {
9377
+ ref: `refs/heads/${branch}`,
9378
+ sha: head
9379
+ },
9380
+ signal
9381
+ });
9382
+ } catch (error) {
9383
+ await noteForgeQuota(error, "fork-head-push");
9384
+ await settle(false, {});
9385
+ schedulerEvent("babysitter.fork_head.push_failed", {
9386
+ ...owner,
9387
+ missing,
9388
+ branch,
9389
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
9390
+ });
9391
+ return false;
9392
+ }
9393
+ await settle(true, {
9394
+ branch,
9395
+ sha: head
9396
+ });
9397
+ schedulerEvent("babysitter.fork_head.pushed", {
9398
+ ...owner,
9399
+ missing,
9400
+ branch,
9401
+ head_sha: head
9402
+ });
9403
+ return true;
9404
+ }
9405
+ /** Why GitHub's current state does not allow pushing a fork head, or undefined when it does. */
9406
+ async function forkHeadRefusal(repository, number, head, baseRef, branch, read) {
9407
+ const pr = await read(`/repos/${repository}/pulls/${number}`);
9408
+ if (!isRuntimeRecord(pr) || pr.state !== "open" || !isRuntimeRecord(pr.head) || pr.head.sha !== head) return "head changed";
9409
+ const latest = /* @__PURE__ */ new Map();
9410
+ const reviews = await readRest(`repos/${repository}/pulls/${number}/reviews?per_page=100`, ".[]");
9411
+ for (const review of reviews) {
9412
+ if (!isRuntimeRecord(review) || !isRuntimeRecord(review.user) || !hasRuntimeType(review.user.login, "string")) continue;
9413
+ const state = String(review.state ?? "").toUpperCase();
9414
+ if (state === "APPROVED" || state === "CHANGES_REQUESTED" || state === "DISMISSED") latest.set(review.user.login.toLowerCase(), {
9415
+ state,
9416
+ commit: review.commit_id
9417
+ });
9418
+ }
9419
+ if ([...latest.values()].some((review) => review.state === "CHANGES_REQUESTED")) return "changes requested";
9420
+ let approved = false;
9421
+ for (const [login, review] of latest) {
9422
+ if (review.state !== "APPROVED" || review.commit !== head) continue;
9423
+ const permission = await read(`/repos/${repository}/collaborators/${encodeURIComponent(login)}/permission`);
9424
+ if (isRuntimeRecord(permission) && [
9425
+ "admin",
9426
+ "maintain",
9427
+ "write"
9428
+ ].includes(String(permission.permission))) approved = true;
9429
+ }
9430
+ if (!approved) return `no approval of ${head.slice(0, 7)} by a reviewer with write access`;
9431
+ const entries = async (treeish) => {
9432
+ const tree = await read(`/repos/${repository}/git/trees/${encodeURIComponent(treeish)}`);
9433
+ const list = isRuntimeRecord(tree) && Array.isArray(tree.tree) ? tree.tree : [];
9434
+ return new Map(list.flatMap((item) => isRuntimeRecord(item) && hasRuntimeType(item.path, "string") && hasRuntimeType(item.sha, "string") ? [[item.path, {
9435
+ sha: item.sha,
9436
+ type: item.type
9437
+ }]] : []));
9438
+ };
9439
+ const child = async (tree, name) => {
9440
+ const entry = tree.get(name);
9441
+ return entry?.type === "tree" ? {
9442
+ sha: entry.sha,
9443
+ entries: await entries(entry.sha)
9444
+ } : void 0;
9445
+ };
9446
+ const [headRoot, baseRoot] = await Promise.all([entries(head), entries(baseRef)]);
9447
+ if (headRoot.get(".github")?.sha === baseRoot.get(".github")?.sha) return void 0;
9448
+ const [headGithub, baseGithub] = await Promise.all([child(headRoot, ".github"), child(baseRoot, ".github")]);
9449
+ if (!headGithub) return void 0;
9450
+ if (headGithub.entries.has("actions") && headGithub.entries.get("actions")?.sha !== baseGithub?.entries.get("actions")?.sha) return `the PR's .github/actions differs from ${baseRef}`;
9451
+ const [headFlows, baseFlows] = await Promise.all([child(headGithub.entries, "workflows"), baseGithub && child(baseGithub.entries, "workflows")]);
9452
+ if (!headFlows || headFlows.sha === baseFlows?.sha) return void 0;
9453
+ for (const [name, entry] of headFlows.entries) {
9454
+ if (baseFlows?.entries.get(name)?.sha === entry.sha) continue;
9455
+ const blob = await read(`/repos/${repository}/git/blobs/${entry.sha}`);
9456
+ const text = isRuntimeRecord(blob) && hasRuntimeType(blob.content, "string") ? Buffer.from(blob.content, "base64").toString("utf8") : void 0;
9457
+ if (text === void 0 || runsOnPush(text, branch)) return `.github/workflows/${name} can run on push and differs from ${baseRef}`;
9458
+ }
9459
+ }
9460
+ const forkHeadKey = (repository, number) => `fork-head-push:${repository}#${number}`;
9461
+ /**
9462
+ * Deletes the `merge.forkHeadBranches` branches of PRs that are no longer open, at most every ten minutes.
9463
+ * A branch is deleted only while it still points at the SHA the host pushed.
9464
+ */
9465
+ async function sweepForkHeadBranches(signal) {
9466
+ if (merge.mode !== "direct" || !merge.forkHeadBranches?.size) return;
9467
+ if ((await pullRequestInbox.metaNumber("fork-head-sweep-next") ?? 0) > Date.now()) return;
9468
+ signal.throwIfAborted();
9469
+ await pullRequestInbox.setMeta("fork-head-sweep-next", Date.now() + 6e5, signal);
9470
+ signal.throwIfAborted();
9471
+ for (const [key, value] of await pullRequestInbox.metaEntries("fork-head-push:")) {
9472
+ signal.throwIfAborted();
9473
+ const match = /^fork-head-push:(.+)#(\d+)$/.exec(key);
9474
+ if (!match || !isRuntimeRecord(value) || !hasRuntimeType(value.branch, "string") || !hasRuntimeType(value.sha, "string")) continue;
9475
+ const [, repository, number] = match;
9476
+ if ((await pullRequestInbox.get(repository, Number(number)))?.status !== "terminal") continue;
9477
+ const reopen = await pullRequestInbox.meta(forkReopenKey(repository, Number(number)));
9478
+ if (isRuntimeRecord(reopen) && reopen.closing === true) continue;
9479
+ try {
9480
+ signal.throwIfAborted();
9481
+ const { provider } = await forge(repository, signal);
9482
+ signal.throwIfAborted();
9483
+ const ref = await provider.request("GET", `/repos/${repository}/git/ref/heads/${value.branch}`, { signal }).then((response) => response.data, (error) => {
9484
+ if (forgeErrorStatus(error) === 404) return void 0;
9485
+ throw error;
9486
+ });
9487
+ signal.throwIfAborted();
9488
+ if (isRuntimeRecord(ref) && isRuntimeRecord(ref.object) && ref.object.sha === value.sha) {
9489
+ await provider.request("DELETE", `/repos/${repository}/git/refs/heads/${value.branch}`, { signal });
9490
+ signal.throwIfAborted();
9491
+ schedulerEvent("babysitter.fork_head.deleted", {
9492
+ repository,
9493
+ pullRequest: Number(number),
9494
+ branch: value.branch
9495
+ });
9496
+ }
9497
+ await pullRequestInbox.deleteMeta(key, signal);
9498
+ } catch (error) {
9499
+ signal.throwIfAborted();
9500
+ await noteForgeQuota(error, "fork-head-delete");
9501
+ schedulerEvent("babysitter.fork_head.delete_failed", {
9502
+ repository,
9503
+ pullRequest: Number(number),
9504
+ branch: value.branch,
9505
+ reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
9506
+ });
9507
+ }
9508
+ }
9509
+ }
9510
+ /**
9511
+ * A required check that never reported gets a fresh run: an approved fork head is pushed to its
9512
+ * `merge.forkHeadBranches` branch, a branch behind its base is updated, and a current one has its
9513
+ * head's Actions runs rerun. Once per head every six hours.
8777
9514
  */
8778
9515
  async function retestMissingRequiredChecks(snapshot, owner, signal) {
8779
9516
  const { repository, number } = snapshot;
@@ -8783,6 +9520,7 @@ function createBabysitterRuntime(options) {
8783
9520
  if (!head || !baseRef || pr.draft || conflicted(snapshot)) return false;
8784
9521
  const missing = missingRequiredChecks(snapshot, await requiredCheckEvaluation(snapshot, signal));
8785
9522
  if (!missing.length) return false;
9523
+ if (await pushForkHead(snapshot, owner, missing, signal)) return true;
8786
9524
  const key = `missing-check-retest:${repository}#${number}`;
8787
9525
  const previous = await pullRequestInbox.meta(key);
8788
9526
  if (isRuntimeRecord(previous) && previous.head === head && Number(previous.at) > Date.now() - 216e5) return false;
@@ -8791,7 +9529,7 @@ function createBabysitterRuntime(options) {
8791
9529
  at: Date.now()
8792
9530
  });
8793
9531
  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)) {
9532
+ if (isRuntimeRecord(compare) && Number(compare.ahead_by) > 0 && await updateBranch(owner, repository, number, head, signal, pr, { reopenFork: false })) {
8795
9533
  schedulerEvent("babysitter.required_check.retest", {
8796
9534
  ...owner,
8797
9535
  missing,
@@ -8863,62 +9601,53 @@ function createBabysitterRuntime(options) {
8863
9601
  }
8864
9602
  return newest;
8865
9603
  }
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) {
9604
+ async function liveBaseTip(repository, base, signal) {
9605
+ const tip = await readOnePage(`repos/${repository}/git/ref/heads/${encodeURIComponent(base)}`, signal);
9606
+ const sha = isRuntimeRecord(tip) && isRuntimeRecord(tip.object) ? tip.object.sha : void 0;
9607
+ return hasRuntimeType(sha, "string") && /^[a-f\d]{40}$/i.test(sha) ? sha : void 0;
9608
+ }
9609
+ /** Current-head Actions checks that repeat the same job failure on the live base tip. */
9610
+ async function readInheritedBaseFailures(snapshot, signal, verificationBaseSha) {
8873
9611
  const { repository } = snapshot;
8874
9612
  const head = snapshot.pr?.head?.sha;
8875
9613
  const baseRef = snapshot.pr?.base?.ref;
8876
9614
  if (!head || !baseRef || conflicted(snapshot) || checksStillRunning(snapshot)) return [];
8877
9615
  const failing = currentActionRuns(snapshot, waitPolicy.pendingReviewChecks).filter((check) => failedConclusions.has(String(check.conclusion)));
8878
9616
  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
- }
9617
+ const tip = verificationBaseSha ?? await liveBaseTip(repository, baseRef, signal);
9618
+ if (!tip) return [];
9619
+ const key = JSON.stringify([
9620
+ repository.toLowerCase(),
9621
+ tip,
9622
+ head,
9623
+ failureKeys(snapshot)
9624
+ ]);
9625
+ const cached = inheritedFailures.get(key);
9626
+ if (!verificationBaseSha && cached && cached.expiresAt > Date.now()) return cached.ids;
9627
+ const runs = await baseActionRuns(repository, tip, signal);
8887
9628
  const ids = [];
8888
9629
  for (const check of failing) {
8889
- const base = inherited.get(String(check.name));
8890
- if (!base) continue;
9630
+ const base = runs.get(String(check.name));
9631
+ if (!base || base.status !== "completed" || !failedConclusions.has(String(base.conclusion))) continue;
8891
9632
  const [own, tested] = await Promise.all([jobFailure(repository, check, signal), jobFailure(repository, base, signal)]);
8892
9633
  if (sameActionFailure(own?.output, tested?.output)) ids.push(Number(check.id));
8893
9634
  }
9635
+ if (inheritedFailures.size >= 128) inheritedFailures.delete(inheritedFailures.keys().next().value);
9636
+ inheritedFailures.set(key, {
9637
+ ids,
9638
+ expiresAt: Date.now() + 3e5
9639
+ });
8894
9640
  return ids;
8895
9641
  }
8896
9642
  const inheritedFailures = /* @__PURE__ */ new Map();
8897
- /** `readInheritedBaseFailures()` for the base branch, cached for five minutes per head, base and failures. */
8898
9643
  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
9644
  try {
8910
- ids = await readInheritedBaseFailures(snapshot, signal);
9645
+ return await readInheritedBaseFailures(snapshot, signal);
8911
9646
  } catch (error) {
8912
9647
  if (isAbortError(error)) throw error;
8913
9648
  await noteForgeQuota(error, "inherited-failures");
8914
9649
  return [];
8915
9650
  }
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
9651
  }
8923
9652
  /** Why each failing current-head check outside the review checks fails. A cause the host cannot prove is `pr`. */
8924
9653
  async function failureCauses(snapshot, signal) {
@@ -8984,7 +9713,7 @@ function createBabysitterRuntime(options) {
8984
9713
  }
8985
9714
  function cancelWhenPullRequestStops(claim, controller, providerDirectory, pushedHead) {
8986
9715
  let stopped = false, polling = false;
8987
- const check = createClaimStopCheck(claim, () => pullRequestInbox.get(claim.snapshot.repository, claim.snapshot.number), createProviderHeadReader(providerDirectory, pushedHead));
9716
+ const check = createClaimStopCheck(claim, () => pullRequestInbox.get(claim.snapshot.repository, claim.snapshot.number), createProviderHeadReader(providerDirectory, pushedHead), () => pullRequestInbox.now());
8988
9717
  const poll = async () => {
8989
9718
  if (stopped || polling || controller.signal.aborted) return;
8990
9719
  polling = true;
@@ -9114,9 +9843,9 @@ function createBabysitterRuntime(options) {
9114
9843
  });
9115
9844
  return "blocked";
9116
9845
  }
9117
- const age = Date.now() - pending.startedAt;
9846
+ const age = pullRequestInbox.now() - pending.startedAt;
9118
9847
  if (pending.asynchronous && age >= pendingMergeDeadlineMs) {
9119
- const until = Date.now() + stoppedMergeRetryMs;
9848
+ const until = pullRequestInbox.now() + stoppedMergeRetryMs;
9120
9849
  const reason = `Stopped waiting for the GitHub merge of ${pending.head}: it was still pending after ${Math.floor(age / 6e4)} minutes. The Babysitter requests it again at ${new Date(until).toISOString()}.`;
9121
9850
  await pullRequestInbox.setMeta(stoppedKey, {
9122
9851
  head: pending.head,
@@ -9169,12 +9898,14 @@ function createBabysitterRuntime(options) {
9169
9898
  if (decision.ready && merge.ready) {
9170
9899
  const callback = merge.ready;
9171
9900
  const head = decision.head;
9901
+ const writers = await verifiedWriters(snapshot, signal);
9172
9902
  const ready = await boundedMergeReady(() => callback({
9173
9903
  repository,
9174
9904
  number,
9175
9905
  head,
9176
9906
  snapshot: structuredClone(snapshot),
9177
- requiredChecks: evaluation.state
9907
+ requiredChecks: evaluation.state,
9908
+ writers
9178
9909
  }), signal);
9179
9910
  if (signal.aborted) return "blocked";
9180
9911
  if (ready !== true) decision = {
@@ -9190,7 +9921,7 @@ function createBabysitterRuntime(options) {
9190
9921
  return pending?.asynchronous ? await parkMerge(`Unconfirmed merge is waiting for ${decision.reason}.`) : "not-ready";
9191
9922
  }
9192
9923
  const stopped = pending ? void 0 : await pullRequestInbox.meta(stoppedKey);
9193
- if (isRuntimeRecord(stopped) && stopped.head === decision.head && hasRuntimeType(stopped.until, "number") && stopped.until > Date.now()) return await parkMerge(hasRuntimeType(stopped.reason, "string") ? stopped.reason : "Stopped waiting for a pending GitHub merge.", stopped.until);
9924
+ if (isRuntimeRecord(stopped) && stopped.head === decision.head && hasRuntimeType(stopped.until, "number") && stopped.until > pullRequestInbox.now()) return await parkMerge(hasRuntimeType(stopped.reason, "string") ? stopped.reason : "Stopped waiting for a pending GitHub merge.", stopped.until);
9194
9925
  const folding = pending ? void 0 : await pullRequestInbox.foldingChild(repository, number);
9195
9926
  if (folding !== void 0) return await parkMerge(`Waiting for the merge of stacked pull request #${folding} into this branch.`);
9196
9927
  let mergeStarted = false;
@@ -9227,7 +9958,7 @@ function createBabysitterRuntime(options) {
9227
9958
  reason: current.reason
9228
9959
  });
9229
9960
  if (!pending && current.reason === "mergeable_state behind") {
9230
- if (!await updateBranch(owner, repository, number, decision.head, signal, live)) return "not-ready";
9961
+ if (!await updateBranch(owner, repository, number, decision.head, signal, live, { reopenFork: false })) return "not-ready";
9231
9962
  schedulerEvent("babysitter.branch.updated", {
9232
9963
  ...owner,
9233
9964
  reason: "behind"
@@ -9408,7 +10139,7 @@ function createBabysitterRuntime(options) {
9408
10139
  /**
9409
10140
  * Proves from fresh GitHub reads that a bypass merge only skips inherited failures. The failures must
9410
10141
  * 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.
10142
+ * CI runs. Every other branch rule must be known and satisfied. Returns why it cannot.
9412
10143
  */
9413
10144
  async function verifyInheritedMerge(snapshot, live, signal) {
9414
10145
  const { repository, number } = snapshot;
@@ -9416,9 +10147,8 @@ function createBabysitterRuntime(options) {
9416
10147
  const prBase = isRuntimeRecord(live.base) ? live.base : {};
9417
10148
  const base = prBase.ref;
9418
10149
  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." };
10150
+ const baseSha = await liveBaseTip(repository, base, signal);
10151
+ if (!baseSha) return { refused: "Inherited-check bypass base tip unavailable." };
9422
10152
  const [owner, name] = repository.split("/");
9423
10153
  const [protection, rules, review, threads] = await Promise.all([
9424
10154
  readOnePage(`repos/${repository}/branches/${encodeURIComponent(base)}/protection`, signal).catch(() => void 0),
@@ -9606,6 +10336,10 @@ function createBabysitterRuntime(options) {
9606
10336
  async function requiredCheckState(snapshot, signal, fold = false) {
9607
10337
  return (await requiredCheckEvaluation(snapshot, signal, fold))?.state ?? "unknown";
9608
10338
  }
10339
+ async function hasRepairableActionsFailure(snapshot, signal) {
10340
+ if (!failedOwnActions(snapshot, waitPolicy.pendingReviewChecks).length || await requiredCheckState(snapshot, signal) !== "failed") return false;
10341
+ return !unrelatedFailureWait(await failureCauses(snapshot, signal), snapshot.pr?.base?.ref ?? "the base");
10342
+ }
9609
10343
  /** Times of the PR's repair pushes in the last 24 hours, kept while `dailyPushBudget` is set. */
9610
10344
  async function repairPushTimes(snapshot) {
9611
10345
  const pushes = await pullRequestInbox.meta(`repair-pushes:${snapshot.repository}#${snapshot.number}`);
@@ -9717,12 +10451,14 @@ function createBabysitterRuntime(options) {
9717
10451
  if (!head) return false;
9718
10452
  const callback = merge.ready;
9719
10453
  try {
10454
+ const writers = await verifiedWriters(snapshot);
9720
10455
  return await boundedMergeReady(() => callback({
9721
10456
  repository: snapshot.repository,
9722
10457
  number: snapshot.number,
9723
10458
  head,
9724
10459
  snapshot: structuredClone(snapshot),
9725
- requiredChecks
10460
+ requiredChecks,
10461
+ writers
9726
10462
  })) === true;
9727
10463
  } catch (error) {
9728
10464
  schedulerEvent("babysitter.direct_merge.skipped", {
@@ -9734,9 +10470,9 @@ function createBabysitterRuntime(options) {
9734
10470
  }
9735
10471
  }
9736
10472
  const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
9737
- async function dependencyEvidence(wake) {
10473
+ async function dependencyEvidence(wake, signal) {
9738
10474
  if (wake.kind === "pull-request") {
9739
- const pr = await readPull(wake.repository, wake.number);
10475
+ const pr = await readPull(wake.repository, wake.number, signal);
9740
10476
  if (!isRuntimeRecord(pr)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_EXTERNAL_STATE_MISSING();
9741
10477
  return digest({
9742
10478
  state: pr.state,
@@ -9744,14 +10480,14 @@ function createBabysitterRuntime(options) {
9744
10480
  head: isRuntimeRecord(pr.head) ? pr.head.sha : void 0
9745
10481
  });
9746
10482
  }
9747
- const { provider, repo } = await forge(wake.repository);
9748
- return checksDependencyEvidence(await provider.checks.list(repo, wake.headSha));
10483
+ const { provider, repo } = await forge(wake.repository, signal);
10484
+ signal?.throwIfAborted();
10485
+ return checksDependencyEvidence(await provider.checks.list(repo, wake.headSha, { signal }));
9749
10486
  }
9750
10487
  /**
9751
10488
  * 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
10489
+ * blocker gets a fresh pass after two hours: the blocker may be fixed already, such as an install
10490
+ * 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
10491
  * new worker release fixes it, and that release wakes the wait.
9756
10492
  */
9757
10493
  async function externalWait(observed, wake, reason) {
@@ -9786,16 +10522,22 @@ function createBabysitterRuntime(options) {
9786
10522
  ...otherPullRequest ? {} : { retryAt }
9787
10523
  };
9788
10524
  }
9789
- async function recoverFailedCiWaits() {
10525
+ async function recoverFailedCiWaits(step, signal) {
9790
10526
  for (const snapshot of await pullRequestInbox.waitsToEvaluate(false, true)) {
10527
+ step("ci-recovery", `${snapshot.repository}#${snapshot.number}`);
9791
10528
  if (snapshot.generation > snapshot.handled || isWorkerBlocker(snapshot) || !hasFailedActions(snapshot)) continue;
9792
10529
  const head = snapshot.pr?.head?.sha;
9793
10530
  if (!head) continue;
9794
10531
  if (snapshot.progressBudget?.exhausted && snapshot.progressBudget.head === head && (snapshot.wait?.retryAt ?? 0) > Date.now()) continue;
9795
10532
  const recoveryKey = `ci-recovery-next:${snapshot.repository}#${snapshot.number}:${head}`;
9796
10533
  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", {
10534
+ signal.throwIfAborted();
10535
+ await pullRequestInbox.setMeta(recoveryKey, Date.now() + 6e5, signal);
10536
+ signal.throwIfAborted();
10537
+ if (await pullRequestInbox.wake(snapshot, `ci-recovery:${head}`, {
10538
+ recovery: true,
10539
+ signal
10540
+ })) schedulerEvent("babysitter.ci.recovery.woken", {
9799
10541
  repository: snapshot.repository,
9800
10542
  pull_request: snapshot.number,
9801
10543
  head_sha: head
@@ -9804,22 +10546,24 @@ function createBabysitterRuntime(options) {
9804
10546
  }
9805
10547
  /**
9806
10548
  * 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.
10549
+ * ten minutes. Otherwise a child stays parked on its parent's branch after the parent merged.
9808
10550
  */
9809
- async function stackParentMerged(snapshot) {
10551
+ async function stackParentMerged(snapshot, signal) {
9810
10552
  const target = snapshot.pr && !snapshot.wait?.wake ? nonDefaultBase(snapshot.pr) : void 0;
9811
10553
  if (!snapshot.pr || !target) return false;
9812
10554
  const nextReadKey = `stack-parent-next:${snapshot.repository}#${snapshot.number}`;
9813
10555
  if ((await pullRequestInbox.metaNumber(nextReadKey) ?? 0) > Date.now()) return false;
9814
- await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e5);
10556
+ signal.throwIfAborted();
10557
+ await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e5, signal);
9815
10558
  try {
9816
10559
  const parents = await readPulls(snapshot.repository, {
9817
10560
  state: "all",
9818
10561
  head: `${target.owner}:${target.base}`,
9819
10562
  limit: 10
9820
- });
10563
+ }, signal);
9821
10564
  return stackRetargetBase(snapshot.pr, parents) !== void 0;
9822
10565
  } catch (error) {
10566
+ signal.throwIfAborted();
9823
10567
  await noteForgeQuota(error, "stack-parent");
9824
10568
  return false;
9825
10569
  }
@@ -9831,41 +10575,54 @@ function createBabysitterRuntime(options) {
9831
10575
  return new Set(snapshot.threads.filter((thread) => thread.isResolved !== true).map((thread) => String(thread.node_id ?? thread.id)).filter((id) => held.has(id)));
9832
10576
  }
9833
10577
  /** Wakes a parked PR only when its new events need a model pass or a direct merge. */
9834
- async function evaluateWaits() {
10578
+ async function evaluateWaits(step, signal) {
10579
+ signal.throwIfAborted();
9835
10580
  for (const snapshot of await pullRequestInbox.waitsToEvaluate(true, true)) {
9836
- const parentMerged = await stackParentMerged(snapshot);
10581
+ step("waits", `${snapshot.repository}#${snapshot.number}`);
10582
+ const parentMerged = await stackParentMerged(snapshot, signal);
10583
+ signal.throwIfAborted();
9837
10584
  if (!parentMerged && snapshot.generation <= snapshot.handled && (snapshot.wait?.retryAt ?? Infinity) > Date.now() && !snapshot.wait?.wake) continue;
9838
- const checks = await requiredCheckState(snapshot);
10585
+ const checkSignal = AbortSignal.any([signal, AbortSignal.timeout(12e4)]);
10586
+ const checks = await requiredCheckState(snapshot, checkSignal);
10587
+ signal.throwIfAborted();
9839
10588
  let reasons = wakeReasons(snapshot, checks, {
9840
10589
  ...waitPolicy,
9841
10590
  heldThreads: await heldOpenThreads(snapshot)
9842
10591
  });
10592
+ signal.throwIfAborted();
9843
10593
  if (parentMerged) reasons.push("stack-parent-merged");
9844
10594
  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";
10595
+ const foldWake = foldStacks && snapshot.wait?.reason === "stack-parent" && snapshot.generation > snapshot.handled && !reasons.includes("ready-to-merge") && await requiredCheckState(snapshot, checkSignal, true) === "passed";
10596
+ signal.throwIfAborted();
9846
10597
  if (foldWake) reasons.push("ready-to-merge");
9847
10598
  if (reasons.includes("ready-to-merge") && !await directMergeWakeAllowed(snapshot, foldWake ? "passed" : checks)) reasons = reasons.filter((reason) => reason !== "ready-to-merge");
10599
+ signal.throwIfAborted();
9848
10600
  if (snapshot.wait?.retryAt !== void 0 && snapshot.wait.retryAt <= Date.now()) reasons.push("merge-retry");
9849
10601
  if (snapshot.wait?.wake) {
9850
10602
  const dependencyKey = `dependency:${snapshot.repository}#${snapshot.number}`;
9851
10603
  const nextReadKey = `dependency-next:${snapshot.repository}#${snapshot.number}`;
9852
10604
  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");
10605
+ signal.throwIfAborted();
10606
+ await pullRequestInbox.setMeta(nextReadKey, Date.now() + 6e4, signal);
10607
+ signal.throwIfAborted();
10608
+ const next = await dependencyEvidence(snapshot.wait.wake, signal);
10609
+ signal.throwIfAborted();
10610
+ if (next !== await pullRequestInbox.meta(dependencyKey)) reasons.push("external-dependency-changed");
9855
10611
  }
9856
10612
  }
10613
+ signal.throwIfAborted();
9857
10614
  const owner = {
9858
10615
  pullRequest: snapshot.number,
9859
10616
  repository: snapshot.repository
9860
10617
  };
9861
10618
  if (!reasons.length) {
9862
- await pullRequestInbox.acknowledgeWait(snapshot);
10619
+ await pullRequestInbox.acknowledgeWait(snapshot, signal);
9863
10620
  schedulerEvent("babysitter.wait.kept", {
9864
10621
  ...owner,
9865
10622
  head_sha: snapshot.pr?.head?.sha,
9866
10623
  avoided_invocation: true
9867
10624
  });
9868
- } else if (await pullRequestInbox.wake(snapshot, `evaluated:${snapshot.generation}:${snapshot.revision ?? 0}`)) schedulerEvent("babysitter.wait.woken", {
10625
+ } else if (await pullRequestInbox.wake(snapshot, `evaluated:${snapshot.generation}:${snapshot.revision ?? 0}`, { signal })) schedulerEvent("babysitter.wait.woken", {
9869
10626
  ...owner,
9870
10627
  head_sha: snapshot.pr?.head?.sha,
9871
10628
  reasons
@@ -9944,7 +10701,117 @@ function createBabysitterRuntime(options) {
9944
10701
  }
9945
10702
  const hostOnlyChecked = /* @__PURE__ */ new Map();
9946
10703
  const hostOnlyStamp = (s) => `${s.generation}:${s.revision ?? 0}`;
9947
- async function reconcile(reason, { track }, isAccepting = () => true) {
10704
+ const createdAt = Date.now();
10705
+ let runningTick;
10706
+ let lastFinishedAt;
10707
+ let lastStall;
10708
+ let stallsInRow = 0;
10709
+ function scheduler(accepting = true) {
10710
+ const now = Date.now();
10711
+ const iso = (time) => new Date(time).toISOString();
10712
+ const silent = accepting && now - (lastFinishedAt ?? createdAt) > stallMs + 6e4;
10713
+ return {
10714
+ status: stallsInRow ? "stalled" : silent ? "silent" : "ok",
10715
+ ...runningTick ? { running: {
10716
+ reason: runningTick.reason,
10717
+ step: runningTick.step,
10718
+ ...runningTick.subject ? { subject: runningTick.subject } : {},
10719
+ startedAt: iso(runningTick.startedAt),
10720
+ stepAt: iso(runningTick.stepAt)
10721
+ } } : {},
10722
+ ...lastFinishedAt ? { lastFinishedAt: iso(lastFinishedAt) } : {},
10723
+ ...lastStall ? { lastStall: {
10724
+ at: iso(lastStall.at),
10725
+ step: lastStall.step,
10726
+ ...lastStall.subject ? { subject: lastStall.subject } : {},
10727
+ count: lastStall.count
10728
+ } } : {}
10729
+ };
10730
+ }
10731
+ async function stallSnapshot(tick) {
10732
+ const now = Date.now();
10733
+ const snapshot = {
10734
+ reason: tick.reason,
10735
+ step: tick.step,
10736
+ ...tick.subject ? { subject: tick.subject } : {},
10737
+ step_ms: now - tick.stepAt,
10738
+ tick_ms: now - tick.startedAt,
10739
+ active_owners: [...active],
10740
+ model_passes: activeModelPasses,
10741
+ executing_model_passes: executingModelPasses,
10742
+ waiting_model_owners: [...waitingModelOwners],
10743
+ host_preparations: activeHostPreparations,
10744
+ main_repairs: [...mainRepairRunning]
10745
+ };
10746
+ let timer;
10747
+ const queue = await Promise.race([Promise.resolve().then(() => pullRequestInbox.summary()).then((items) => babysitterQueueHealth(items, now)), new Promise((resolve) => {
10748
+ timer = setTimeout(() => resolve(void 0), 5e3);
10749
+ timer.unref?.();
10750
+ })]).catch(() => void 0).finally(() => clearTimeout(timer));
10751
+ return {
10752
+ ...snapshot,
10753
+ ...queue ? {
10754
+ ready: queue.ready,
10755
+ working: queue.working,
10756
+ waiting: queue.waiting
10757
+ } : { queue: "unreadable" }
10758
+ };
10759
+ }
10760
+ /**
10761
+ * Runs one reconcile, and stops it when it waits longer than `stallMs`. The stall event names the step
10762
+ * that did not settle. A stopped reconcile ends at its next step, so it never claims next to the one
10763
+ * that replaced it.
10764
+ */
10765
+ async function reconcile(reason, context, isAccepting = () => true) {
10766
+ const startedAt = Date.now();
10767
+ const tick = {
10768
+ reason,
10769
+ startedAt,
10770
+ step: "start",
10771
+ stepAt: startedAt
10772
+ };
10773
+ const controller = new AbortController();
10774
+ const { signal } = controller;
10775
+ const step = (name, subject) => {
10776
+ signal.throwIfAborted();
10777
+ tick.step = name;
10778
+ tick.subject = subject;
10779
+ tick.stepAt = Date.now();
10780
+ };
10781
+ let timer;
10782
+ const stalled = new Promise((_resolve, reject) => {
10783
+ timer = setTimeout(() => {
10784
+ stallsInRow += 1;
10785
+ lastStall = {
10786
+ at: Date.now(),
10787
+ step: tick.step,
10788
+ ...tick.subject ? { subject: tick.subject } : {},
10789
+ count: stallsInRow
10790
+ };
10791
+ if (runningTick === tick) runningTick = void 0;
10792
+ const error = presetsErrorDiagnostics.PRESETS_BABYSITTER_RECONCILE_STALLED({
10793
+ step: tick.subject ? `${tick.step} (${tick.subject})` : tick.step,
10794
+ minutes: Math.round((Date.now() - startedAt) / 6e4)
10795
+ });
10796
+ reject(error);
10797
+ controller.abort(error);
10798
+ stallSnapshot(tick).then((snapshot) => schedulerEvent("babysitter.reconcile.stalled", snapshot)).catch(() => {});
10799
+ }, stallMs);
10800
+ timer.unref?.();
10801
+ });
10802
+ runningTick = tick;
10803
+ try {
10804
+ await Promise.race([reconcileTick(reason, context, isAccepting, step, signal), stalled]);
10805
+ } finally {
10806
+ clearTimeout(timer);
10807
+ if (!signal.aborted) {
10808
+ lastFinishedAt = Date.now();
10809
+ stallsInRow = 0;
10810
+ if (runningTick === tick) runningTick = void 0;
10811
+ }
10812
+ }
10813
+ }
10814
+ async function reconcileTick(reason, { track }, isAccepting, step, signal) {
9948
10815
  const startedAt = /* @__PURE__ */ new Date();
9949
10816
  const schedule = {
9950
10817
  id: "babysitter-demand",
@@ -9953,7 +10820,9 @@ function createBabysitterRuntime(options) {
9953
10820
  };
9954
10821
  const { publicUrl } = options;
9955
10822
  if (!isAccepting()) return;
10823
+ step("forge-quota");
9956
10824
  const forgeBlockedUntil = await forgeQuota.blockedUntil();
10825
+ signal.throwIfAborted();
9957
10826
  if (forgeBlockedUntil > Date.now()) {
9958
10827
  schedulerEvent("babysitter.forge.quota.waiting", {
9959
10828
  reason,
@@ -9961,18 +10830,23 @@ function createBabysitterRuntime(options) {
9961
10830
  });
9962
10831
  return;
9963
10832
  }
9964
- await statusRecovery.recover();
10833
+ step("status-recovery");
10834
+ await statusRecovery.recover(signal);
10835
+ signal.throwIfAborted();
9965
10836
  track(statusRecovery.flush().catch((failure) => schedulerError("babysitter.status.flush.failed", failure)));
9966
10837
  let modelAdmission = true;
9967
10838
  let hostAdmission = true;
9968
10839
  let modelRetryAt;
9969
10840
  if (options.admission) {
9970
- const admission = await options.admission();
10841
+ step("admission");
10842
+ const admission = await options.admission(signal);
10843
+ signal.throwIfAborted();
9971
10844
  if (!admission.accepting) {
9972
10845
  modelAdmission = false;
9973
10846
  hostAdmission = admission.reason === "token-budget-hourly" || admission.reason === "token-budget-daily";
9974
10847
  modelRetryAt = admission.retryAt ?? Date.now() + 6e4;
9975
10848
  const previous = await pullRequestInbox.meta("admission-skipped");
10849
+ signal.throwIfAborted();
9976
10850
  if (previous?.reason !== admission.reason || Date.now() - (previous?.at ?? 0) >= 9e5) {
9977
10851
  const skipped = {
9978
10852
  at: Date.now(),
@@ -9981,7 +10855,8 @@ function createBabysitterRuntime(options) {
9981
10855
  retryAt: admission.retryAt,
9982
10856
  active_owners: active.size
9983
10857
  };
9984
- await pullRequestInbox.setMeta("admission-skipped", skipped);
10858
+ await pullRequestInbox.setMeta("admission-skipped", skipped, signal);
10859
+ signal.throwIfAborted();
9985
10860
  schedulerEvent("babysitter.admission.skipped", {
9986
10861
  trigger: reason,
9987
10862
  ...skipped
@@ -9991,7 +10866,9 @@ function createBabysitterRuntime(options) {
9991
10866
  }
9992
10867
  }
9993
10868
  const ownerLimit = options.concurrency;
9994
- const repositories = await repositorySource.current().catch(async (error) => {
10869
+ step("repositories");
10870
+ const repositories = await repositorySource.current(signal).catch(async (error) => {
10871
+ signal.throwIfAborted();
9995
10872
  await noteForgeQuota(error, "repositories");
9996
10873
  schedulerError("babysitter.repositories.failed", error, { source: repositorySource.source });
9997
10874
  return repositorySource.known();
@@ -9999,61 +10876,94 @@ function createBabysitterRuntime(options) {
9999
10876
  const eventScopedBootstrap = Boolean(filter.actor || filter.action);
10000
10877
  for (const repository of repositories) {
10001
10878
  if (eventScopedBootstrap) continue;
10879
+ step("bootstrap", repository);
10002
10880
  const key = `bootstrap-rest-v1:${repository}`;
10003
10881
  const previous = await pullRequestInbox.meta(key);
10882
+ signal.throwIfAborted();
10004
10883
  if (previous && Date.now() - Date.parse(previous.at) < 18e5) continue;
10005
10884
  const nextKey = `${key}:next`;
10006
10885
  if ((await pullRequestInbox.meta(nextKey) ?? 0) > Date.now()) continue;
10007
- await pullRequestInbox.setMeta(nextKey, Date.now() + 12e4);
10886
+ signal.throwIfAborted();
10887
+ await pullRequestInbox.setMeta(nextKey, Date.now() + 12e4, signal);
10008
10888
  try {
10009
10889
  const prs = await readPulls(repository, {
10010
10890
  state: "open",
10011
10891
  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() });
10892
+ }, signal);
10893
+ for (const pr of prs) {
10894
+ signal.throwIfAborted();
10895
+ await pullRequestInbox.seed(repository, normalizePullRequest(pr), signal);
10896
+ }
10897
+ signal.throwIfAborted();
10898
+ await pullRequestInbox.setMeta(key, { at: (/* @__PURE__ */ new Date()).toISOString() }, signal);
10015
10899
  } catch (error) {
10900
+ signal.throwIfAborted();
10016
10901
  await noteForgeQuota(error, "bootstrap");
10017
10902
  schedulerError("babysitter.bootstrap.failed", error, { repository });
10018
10903
  }
10019
10904
  }
10020
- await checkMainRepairs(repositories, track);
10905
+ step("main-repair");
10906
+ await checkMainRepairs(repositories, track, signal);
10907
+ step("fork-head-sweep");
10908
+ await sweepForkHeadBranches(signal).catch((error) => {
10909
+ signal.throwIfAborted();
10910
+ schedulerError("babysitter.fork_head.sweep_failed", error);
10911
+ });
10912
+ await recoverForkReopens(signal).catch((error) => {
10913
+ signal.throwIfAborted();
10914
+ schedulerError("babysitter.fork_checks.recover_failed", error);
10915
+ });
10916
+ step("snapshot-detect");
10021
10917
  try {
10022
- await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository), repositories, Date.now(), !eventScopedBootstrap, (repository, error) => {
10918
+ await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository, signal), repositories, pullRequestInbox.now(), !eventScopedBootstrap, (repository, error) => {
10023
10919
  noteForgeQuota(error, "snapshot-detect");
10024
10920
  schedulerEvent("babysitter.snapshot.detect.failed", {
10025
10921
  repository,
10026
10922
  error: (error instanceof Error ? error.message : String(error)).slice(0, 300)
10027
10923
  });
10028
- });
10924
+ }, signal);
10029
10925
  } catch (error) {
10926
+ signal.throwIfAborted();
10030
10927
  await noteForgeQuota(error, "snapshot-detect");
10031
10928
  schedulerError("babysitter.snapshot.detect.failed", error);
10032
10929
  }
10930
+ step("snapshot-probe");
10033
10931
  try {
10034
- await probeChangedSnapshots(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors);
10035
- await reconcileOneSnapshot(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors);
10932
+ await probeChangedSnapshots(pullRequestInbox, readRest, pullRequestInbox.now(), readThreads, activityAuthors, void 0, void 0, signal);
10933
+ step("snapshot-sweep");
10934
+ await reconcileOneSnapshot(pullRequestInbox, readRest, pullRequestInbox.now(), readThreads, activityAuthors, signal);
10036
10935
  } catch (error) {
10936
+ signal.throwIfAborted();
10037
10937
  await noteForgeQuota(error, "snapshot-reconcile");
10038
10938
  schedulerError("babysitter.snapshot.reconcile.failed", error);
10039
10939
  }
10040
- await pullRequestInbox.recoverLeases();
10940
+ step("lease-recovery");
10941
+ await pullRequestInbox.recoverLeases(signal);
10942
+ step("waits");
10041
10943
  try {
10042
10944
  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();
10945
+ signal.throwIfAborted();
10946
+ await pullRequestInbox.setMeta("idle-wait-sweep-next", Date.now() + 6e5, signal);
10947
+ signal.throwIfAborted();
10948
+ await recoverFailedCiWaits(step, signal);
10045
10949
  }
10046
- await evaluateWaits();
10950
+ await evaluateWaits(step, signal);
10047
10951
  } catch (error) {
10952
+ signal.throwIfAborted();
10048
10953
  await noteForgeQuota(error, "wait-evaluate");
10049
10954
  schedulerError("babysitter.wait.evaluate.failed", error);
10050
10955
  }
10956
+ step("delivery-prune");
10051
10957
  if ((await pullRequestInbox.metaNumber("deliveries-prune-next") ?? 0) <= Date.now()) {
10052
- await pullRequestInbox.setMeta("deliveries-prune-next", Date.now() + 36e5);
10053
- await pullRequestInbox.pruneDeliveries();
10958
+ signal.throwIfAborted();
10959
+ await pullRequestInbox.setMeta("deliveries-prune-next", Date.now() + 36e5, signal);
10960
+ signal.throwIfAborted();
10961
+ await pullRequestInbox.pruneDeliveries({ signal });
10054
10962
  }
10055
10963
  if (!isAccepting()) return;
10964
+ step("forge-quota");
10056
10965
  const forgeBlockedAfterReconcile = await forgeQuota.blockedUntil();
10966
+ signal.throwIfAborted();
10057
10967
  if (forgeBlockedAfterReconcile > Date.now()) {
10058
10968
  schedulerEvent("babysitter.forge.quota.waiting", {
10059
10969
  reason,
@@ -10061,7 +10971,9 @@ function createBabysitterRuntime(options) {
10061
10971
  });
10062
10972
  return;
10063
10973
  }
10974
+ step("provider-quota");
10064
10975
  const providerBlockedUntil = await providerQuota.blockedUntil();
10976
+ signal.throwIfAborted();
10065
10977
  if (providerBlockedUntil > Date.now() && modelAdmission) {
10066
10978
  modelAdmission = false;
10067
10979
  modelRetryAt = providerBlockedUntil;
@@ -10071,26 +10983,38 @@ function createBabysitterRuntime(options) {
10071
10983
  });
10072
10984
  }
10073
10985
  const claimLimit = ownerLimit;
10986
+ step("placement");
10074
10987
  const hostActive = active.size;
10075
- const placementAdmitted = presetOptions.placement?.admitted ? await presetOptions.placement.admitted() : Number.POSITIVE_INFINITY;
10988
+ const placementAdmitted = presetOptions.placement?.admitted ? await presetOptions.placement.admitted(signal) : Number.POSITIVE_INFINITY;
10076
10989
  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
- ];
10990
+ step("claim");
10991
+ const jobs = [];
10992
+ const skip = (snapshot) => !modelAdmission && hostOnlyChecked.get(`${snapshot.repository}#${snapshot.number}`) === hostOnlyStamp(snapshot);
10993
+ try {
10994
+ jobs.push(...await pullRequestInbox.claim(Math.min(5, remainingCapacity), {
10995
+ only: (snapshot) => Boolean(snapshot.recoveryHead && snapshot.recoveryHead === snapshot.pr?.head?.sha),
10996
+ includeBlocked: true,
10997
+ skip,
10998
+ signal
10999
+ }));
11000
+ signal.throwIfAborted();
11001
+ jobs.push(...await pullRequestInbox.claim(remainingCapacity - jobs.length, {
11002
+ skip,
11003
+ signal
11004
+ }));
11005
+ signal.throwIfAborted();
11006
+ jobs.push(...await pullRequestInbox.claim(remainingCapacity - jobs.length, {
11007
+ includeBlocked: true,
11008
+ skip,
11009
+ signal,
11010
+ only: (snapshot) => snapshot.progressBudget?.exhausted === true && snapshot.progressBudget.head === snapshot.pr?.head?.sha
11011
+ }));
11012
+ signal.throwIfAborted();
11013
+ } catch (error) {
11014
+ const releases = await Promise.allSettled(jobs.map((claim) => pullRequestInbox.release(claim)));
11015
+ for (const release of releases) if (release.status === "rejected") schedulerError("babysitter.claim.release.failed", release.reason);
11016
+ throw error;
11017
+ }
10094
11018
  if (!jobs.length) return;
10095
11019
  for (const claim of jobs) active.add(`${claim.snapshot.repository}#${claim.snapshot.number}`);
10096
11020
  schedulerEvent("babysitter.queue.selected", {
@@ -10401,7 +11325,7 @@ function createBabysitterRuntime(options) {
10401
11325
  await pullRequestInbox.release(inboxClaim);
10402
11326
  return;
10403
11327
  }
10404
- if (!pullRequestInbox.eligible(repository, inboxClaim.snapshot.pr)) {
11328
+ if (!await eligibleNow(repository, inboxClaim.snapshot.pr, inboxClaim.snapshot, passSignal)) {
10405
11329
  await pullRequestInbox.finish(inboxClaim, {
10406
11330
  text: "PR closed or outside the configured filter.",
10407
11331
  terminal: true
@@ -10443,7 +11367,7 @@ function createBabysitterRuntime(options) {
10443
11367
  const held = await heldOpenThreads(inboxClaim.snapshot);
10444
11368
  let reviewedRetryAt = Date.now() + 12e4;
10445
11369
  let pushWindowRetry = false;
10446
- if (dailyPushBudget !== false && await requiredCheckState(inboxClaim.snapshot) === "failed") {
11370
+ if (isRuntimeRecord(assessment) && (dailyPushBudget !== false && await requiredCheckState(inboxClaim.snapshot) === "failed" || await hasRepairableActionsFailure(inboxClaim.snapshot, passSignal))) {
10447
11371
  const window = await repairPushWindow(inboxClaim.snapshot, "failed", false);
10448
11372
  reviewedRetryAt = window && !window.allowed ? window.nextAt + 6e4 : void 0;
10449
11373
  pushWindowRetry = reviewedRetryAt !== void 0;
@@ -10693,6 +11617,7 @@ function createBabysitterRuntime(options) {
10693
11617
  workspaceRun.head = pullRequest.headRefOid;
10694
11618
  workspaceRun.base = pullRequest.baseRefOid;
10695
11619
  await github.withPullRequestCheckout({
11620
+ baseRef: pullRequest.baseRefName,
10696
11621
  headRef: pullRequest.headRefName,
10697
11622
  headRepository: pullRequest.headRepository?.nameWithOwner,
10698
11623
  headSha: pullRequest.headRefOid,
@@ -10764,7 +11689,7 @@ function createBabysitterRuntime(options) {
10764
11689
  const assertLeaseHeld = async () => {
10765
11690
  abortSignal.throwIfAborted();
10766
11691
  const current = await pullRequestInbox.get(repository, number);
10767
- if (current?.lease !== inboxClaim.token || current.leaseUntil <= Date.now()) throw new DOMException("Pull request lease lost.", "AbortError");
11692
+ if (current?.lease !== inboxClaim.token || current.leaseUntil <= pullRequestInbox.now()) throw new DOMException("Pull request lease lost.", "AbortError");
10768
11693
  return current;
10769
11694
  };
10770
11695
  const assertLease = async () => {
@@ -10773,7 +11698,7 @@ function createBabysitterRuntime(options) {
10773
11698
  for (const [id, reopens] of ownedResolutions) if ((current.threadReopens?.[id] ?? 0) !== reopens) throw new DOMException("An addressed review thread was reopened.", "AbortError");
10774
11699
  const observedHead = current.pr?.head?.sha;
10775
11700
  if (current.sourcePushOverflow || current.sourcePushHeads?.some((head) => !verifiedPushHeads.has(head)) || current.sourcePushHead !== inboxClaim.snapshot.sourcePushHead && !verifiedPushHeads.has(current.sourcePushHead ?? "")) throw new DOMException("Pull request source branch changed before synchronize.", "AbortError");
10776
- const stopped = claimStopReason(inboxClaim, current, observedHead && pendingInboxHeads.has(observedHead) ? observedHead : pushedHead);
11701
+ const stopped = claimStopReason(inboxClaim, current, observedHead && pendingInboxHeads.has(observedHead) ? observedHead : pushedHead, pullRequestInbox.now());
10777
11702
  if (stopped) throw new DOMException(stopped, "AbortError");
10778
11703
  if (pushedHead && observedHead === pushedHead) {
10779
11704
  pendingInboxHeads.clear();
@@ -10902,7 +11827,7 @@ function createBabysitterRuntime(options) {
10902
11827
  commentPrefix: "<!-- vitehub-babysitter-repair:repair -->\n",
10903
11828
  signal: abortSignal,
10904
11829
  autoMerge: merge.mode === "auto" && stackParent === void 0,
10905
- eligible: (current) => pullRequestInbox.eligible(repository, normalizePullRequest(current)),
11830
+ eligible: async (current) => await eligibleNow(repository, normalizePullRequest(current), await pullRequestInbox.get(repository, number), abortSignal),
10906
11831
  checkDependencies: async () => {
10907
11832
  await assertLease();
10908
11833
  if (presetOptions.install === false) return {
@@ -10951,7 +11876,7 @@ function createBabysitterRuntime(options) {
10951
11876
  ...inboxClaim,
10952
11877
  generation: current.generation,
10953
11878
  snapshot: current
10954
- }, Date.now() + 72e5)) return;
11879
+ }, pullRequestInbox.now() + 72e5)) return;
10955
11880
  const latest = await assertLease();
10956
11881
  if (latest.generation === current.generation) throw new DOMException("Pull request lease renewal failed.", "AbortError");
10957
11882
  current = latest;
@@ -10979,7 +11904,7 @@ function createBabysitterRuntime(options) {
10979
11904
  try {
10980
11905
  const result = await prepared.push(providerDirectory, {
10981
11906
  signal: abortSignal,
10982
- beforePush: async (head) => {
11907
+ beforePush: async (head, lineage) => {
10983
11908
  const current = await assertLease();
10984
11909
  await assertRepairBase();
10985
11910
  const window = await repairPushWindow(current, await requiredCheckState(current), current.pr?.mergeable === false);
@@ -10991,7 +11916,7 @@ function createBabysitterRuntime(options) {
10991
11916
  ...inboxClaim,
10992
11917
  generation: current.generation,
10993
11918
  snapshot: current
10994
- }, head)) throw new DOMException("Publication candidate lease changed.", "AbortError");
11919
+ }, head, lineage)) throw new DOMException("Publication candidate lease changed.", "AbortError");
10995
11920
  observePendingPush = head ? (current) => {
10996
11921
  if (current.sourcePushHeads?.includes(head)) recordPush(head);
10997
11922
  } : void 0;
@@ -11186,7 +12111,11 @@ function createBabysitterRuntime(options) {
11186
12111
  authorAssociation: void 0,
11187
12112
  actor: void 0
11188
12113
  },
11189
- when: (context) => matchesBabysitterPullRequestFilter(context, filter),
12114
+ when: (context) => matchesBabysitterPullRequestFilter(context, approvalAdmission ? {
12115
+ ...filter,
12116
+ author: void 0,
12117
+ authorAssociation: void 0
12118
+ } : filter),
11190
12119
  workspace: false
11191
12120
  }
11192
12121
  }));
@@ -11291,7 +12220,9 @@ function createBabysitterRuntime(options) {
11291
12220
  const reviewPushes = inboxClaim.snapshot.reviewPushBudget?.count ?? 0;
11292
12221
  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
12222
  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}`;
12223
+ 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>` : "";
12224
+ const inheritedIds = await inheritedBaseFailures(inboxClaim.snapshot, passSignal);
12225
+ 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
12226
  assertPromptFits(userMessage);
11296
12227
  schedulerEvent("babysitter.context.prepared", {
11297
12228
  repository,
@@ -11357,7 +12288,7 @@ function createBabysitterRuntime(options) {
11357
12288
  }, abortSignal, () => {
11358
12289
  providerLimited = true;
11359
12290
  }).catch(async (error) => {
11360
- if (recordedPass && isProviderFailure(error) && Date.now() - recordedPass.at < providerFailureReleaseMs && await pullRequestInbox.releaseModelPass(inboxClaim, recordedPass.at, recordedPass.exemption)) schedulerEvent("babysitter.daily_pass_budget.released", {
12291
+ if (recordedPass && isProviderFailure(error) && pullRequestInbox.now() - recordedPass.at < providerFailureReleaseMs && await pullRequestInbox.releaseModelPass(inboxClaim, recordedPass.at, recordedPass.exemption)) schedulerEvent("babysitter.daily_pass_budget.released", {
11361
12292
  ...owner,
11362
12293
  head_sha: pullRequest.headRefOid,
11363
12294
  ...recordedPass.exemption ? { exemption: recordedPass.exemption } : {},
@@ -11384,7 +12315,9 @@ function createBabysitterRuntime(options) {
11384
12315
  workspaceRun.ok = true;
11385
12316
  if (modelWorkParked) return;
11386
12317
  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);
12318
+ 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);
12319
+ const rejectedAssessment = reportedAssessment && await hasRepairableActionsFailure(current, passSignal);
12320
+ const assessed = reportedAssessment && !rejectedAssessment;
11388
12321
  if (assessed) await recordAssessment(inboxClaim.snapshot, {
11389
12322
  head: pullRequest.headRefOid,
11390
12323
  evidenceKey: mergeReviewEvidenceKey(inboxClaim.snapshot, waitPolicy)
@@ -11406,7 +12339,7 @@ function createBabysitterRuntime(options) {
11406
12339
  progress: { kind: "no-progress" },
11407
12340
  wait: await externalWait(inboxClaim.snapshot, passResult.wait.wake, passResult.wait.reason)
11408
12341
  });
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))) {
12342
+ } 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
12343
  outcome = "waiting";
11411
12344
  recorded = await pullRequestInbox.finish(inboxClaim, {
11412
12345
  text: resultText,
@@ -11608,6 +12541,7 @@ function createBabysitterRuntime(options) {
11608
12541
  inbox: pullRequestInbox,
11609
12542
  repositories: repositorySource,
11610
12543
  reconcile,
12544
+ scheduler,
11611
12545
  workload,
11612
12546
  observeMainRepair
11613
12547
  };
@@ -11634,4 +12568,4 @@ function withoutCapacity(driver) {
11634
12568
  return rest;
11635
12569
  }
11636
12570
  //#endregion
11637
- export { pullRequestThreadId as a, budgetParks as i, isProviderRateLimit as n, createGitHubAppCredentials as o, pendingMergeRetryAt as r, createGitHubHost as s, createBabysitterRuntime as t };
12571
+ 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 };