@vite-hub/presets 0.4.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
1
  import { a as isRuntimeString, i as isRuntimeRecord, n as hasRuntimeType, r as isRuntimeNumber, t as presetsErrorDiagnostics } from "./error-diagnostics-o3pHscWs.js";
2
- import { A as matchesBabysitterPullRequestFilter, C as isReviewThreadOutcome, D as invariant, E as reviewerLabeledSevere, F as createBabysitterCheckRuns, I as isBabysitterCheckRun, L as createBabysitterPassResultSchema, M as failed$1, N as hydrateFailedCiEvidence, O as invariantError, P as newestCheckRun, S as createGitHubPullRequestOperations, T as reviewThreadOutcomes, _ as liveMergeReadiness, a as isBabysitterPlacementCapacityError, b as resolveBabysitterMerge, c as workspaceDecision, g as isAutomatedFeedback, h as hasHumanComment, j as actionLocation, k as hasGitHubLogin, l as babysitterModelAdmission, m as feedbackFingerprints, p as directMergeReadiness, r as resolveBabysitterLifecycleFilter, s as providerSessionDecision, v as matchesMergeReviewEvidence, w as normalizeGitHubMentionAllowlist, x as snapshotCheckEvidence, y as mergeReviewEvidenceKey } from "./babysitter-DQeA81N0.js";
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,10 +3702,25 @@ var PullRequestInbox = class {
3603
3702
  });
3604
3703
  await this.ready;
3605
3704
  }
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
+ }
3606
3719
  async transaction(run, signal) {
3607
3720
  await this.init();
3608
3721
  return await this.storage.transaction(async (tx) => {
3609
3722
  signal?.throwIfAborted();
3723
+ await this.syncClock(tx);
3610
3724
  const result = await run(tx);
3611
3725
  signal?.throwIfAborted();
3612
3726
  return result;
@@ -3614,6 +3728,7 @@ var PullRequestInbox = class {
3614
3728
  }
3615
3729
  async read(statement, args = []) {
3616
3730
  await this.init();
3731
+ await this.syncClock(this.storage);
3617
3732
  return await this.storage.execute(statement, args);
3618
3733
  }
3619
3734
  /** Parses one stored row. An invalid row is reported once and skipped by queue-wide reads. */
@@ -3772,6 +3887,7 @@ var PullRequestInbox = class {
3772
3887
  s.wait?.headSha ?? null,
3773
3888
  leaseHeads ? JSON.stringify(leaseHeads) : null
3774
3889
  ]);
3890
+ if (s.pr?.state === "closed") await this.retireFoldIn(tx, s.repository, s.number);
3775
3891
  if (this.activityAuthors.size && (s.status === "terminal" || reopened || resumed || readySuperseded)) {
3776
3892
  const target = statusTargetKey(s);
3777
3893
  const pending = v.safeParse(statusDeliverySchema, await this.metaIn(tx, `${statusOutboxPrefix}${target}`));
@@ -3814,6 +3930,11 @@ var PullRequestInbox = class {
3814
3930
  key,
3815
3931
  JSON.stringify(value)
3816
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
+ ]);
3817
3938
  }
3818
3939
  async meta(key) {
3819
3940
  await this.init();
@@ -4208,6 +4329,19 @@ var PullRequestInbox = class {
4208
4329
  const attempt = await this.metaIn(tx, this.directMergeKey(repository, fold.child));
4209
4330
  return isRuntimeRecord(attempt) && attempt.token === fold.token && attempt.foldInto === parent ? fold.child : void 0;
4210
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
+ }
4211
4345
  async foldingChild(repository, parent) {
4212
4346
  await this.init();
4213
4347
  return await this.foldingChildIn({ execute: (statement, args) => this.storage.execute(statement, args) }, repository, parent);
@@ -4427,8 +4561,26 @@ var PullRequestInbox = class {
4427
4561
  isMainRepair(pr) {
4428
4562
  return this.mainRepairBranchPrefix !== void 0 && Boolean(pr?.head?.ref?.startsWith(this.mainRepairBranchPrefix));
4429
4563
  }
4430
- eligible(repository, pr) {
4431
- 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;
4432
4584
  }
4433
4585
  async seed(repository, value, signal) {
4434
4586
  repository = repository.toLowerCase();
@@ -4437,7 +4589,7 @@ var PullRequestInbox = class {
4437
4589
  return await this.transaction(async (tx) => {
4438
4590
  const s = await this.getIn(tx, repository, pr.number) ?? this.empty(repository, pr.number);
4439
4591
  if (this.updatePr(s, pr)) this.dirty(s, "bootstrap");
4440
- if (!this.eligible(repository, s.pr)) {
4592
+ if (!this.eligible(repository, s.pr, s)) {
4441
4593
  delete s.wait;
4442
4594
  s.status = "terminal";
4443
4595
  s.handled = s.generation;
@@ -4569,6 +4721,7 @@ var PullRequestInbox = class {
4569
4721
  if (sha && s.pr?.head?.sha && s.pr.head.sha !== sha && !pushRefMatch && !pendingHead) continue;
4570
4722
  let changed = false;
4571
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);
4572
4725
  const upsert = (map, value, itemKey) => {
4573
4726
  if (!value) return;
4574
4727
  const key = itemKey ?? String(value.id);
@@ -4696,7 +4849,7 @@ var PullRequestInbox = class {
4696
4849
  else if (changed) s.revision = (s.revision ?? 0) + 1;
4697
4850
  if (changed && human && feedbackEvent) s.humanFeedbackGeneration = s.generation;
4698
4851
  const exhausted = s.progressBudget?.exhausted && s.progressBudget.head === s.pr?.head?.sha;
4699
- const eligible = this.eligible(repository, s.pr);
4852
+ const eligible = this.eligible(repository, s.pr, s);
4700
4853
  if (s.pr && !eligible) {
4701
4854
  delete s.wait;
4702
4855
  s.status = "terminal";
@@ -4755,7 +4908,7 @@ var PullRequestInbox = class {
4755
4908
  const s = await this.getRowIn(tx, candidate);
4756
4909
  options.signal?.throwIfAborted();
4757
4910
  if (!s) continue;
4758
- if (s.pr && !this.eligible(s.repository, s.pr)) continue;
4911
+ if (s.pr && !this.eligible(s.repository, s.pr, s)) continue;
4759
4912
  if (options.only && !options.only(s)) continue;
4760
4913
  if (options.skip && options.skip(s)) continue;
4761
4914
  s.lease = randomUUID();
@@ -4790,7 +4943,7 @@ var PullRequestInbox = class {
4790
4943
  Object.assign(s, patch);
4791
4944
  this.cleanSnapshot(s);
4792
4945
  if (patch.pr && before && before.head?.sha === s.pr?.head?.sha && conflicted$1(s.pr) && !conflicted$1(before)) this.grantProgress(s, "conflict");
4793
- 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";
4794
4947
  await this.put(tx, s);
4795
4948
  Object.assign(claim.snapshot, patch, {
4796
4949
  comments: s.comments,
@@ -4855,8 +5008,12 @@ var PullRequestInbox = class {
4855
5008
  return true;
4856
5009
  });
4857
5010
  }
4858
- /** Retain CI for an exact candidate before its source-push webhook arrives. This is not a publication receipt. */
4859
- 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) {
4860
5017
  invariant(/^[a-f\d]{40}$/i.test(head), "the runtime registers the full commit SHA that the host push returned");
4861
5018
  return await this.transaction(async (tx) => {
4862
5019
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
@@ -4870,11 +5027,47 @@ var PullRequestInbox = class {
4870
5027
  token: claim.token,
4871
5028
  heads
4872
5029
  };
5030
+ if (lineage?.hostOnly && /^[a-f\d]{40}$/i.test(lineage.parent)) this.addHostHead(s, head, lineage.parent);
4873
5031
  s.revision = (s.revision ?? 0) + 1;
4874
5032
  await this.put(tx, s);
4875
5033
  return true;
4876
5034
  });
4877
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
+ }
4878
5071
  async release(claim) {
4879
5072
  return await this.transaction(async (tx) => {
4880
5073
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
@@ -5313,13 +5506,33 @@ var PullRequestInbox = class {
5313
5506
  const now = this.clock();
5314
5507
  await this.transaction(async (tx) => {
5315
5508
  signal?.throwIfAborted();
5316
- await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key>='ci-evidence:v1:' AND key<'ci-evidence:v1;'
5317
- AND CASE WHEN NOT json_valid(value) THEN 1 WHEN json_type(value)<>'object' THEN 1
5318
- WHEN coalesce(json_type(value, '$.fetchedAt'), '') NOT IN ('integer', 'real') THEN 1 ELSE json_extract(value, '$.fetchedAt')<? END`, [this.scope, now - payloadMs]);
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]);
5319
5524
  signal?.throwIfAborted();
5320
5525
  await tx.execute(`DELETE FROM ${this.tables.deliveries} WHERE scope=? AND received<?`, [this.scope, now - idMs]);
5321
5526
  signal?.throwIfAborted();
5322
- await tx.execute(`UPDATE ${this.tables.deliveries} SET payload=NULL WHERE scope=? AND received<? AND payload IS NOT NULL`, [this.scope, now - payloadMs]);
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);
5323
5536
  signal?.throwIfAborted();
5324
5537
  });
5325
5538
  }
@@ -5549,28 +5762,29 @@ function snapshotPullRequest(snapshot) {
5549
5762
  labels: (pr.labels ?? []).map((label) => hasRuntimeType(label, "string") ? { name: label } : label)
5550
5763
  };
5551
5764
  }
5552
- function claimStopReason(claim, current, acceptedSelfHead) {
5553
- 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.";
5554
5768
  if (current.status === "terminal" || current.pr?.state === "closed") return "Pull request is no longer open.";
5555
5769
  const expectedHead = claim.snapshot.pr?.head?.sha;
5556
5770
  if (current.pr?.head?.sha !== (acceptedSelfHead ?? expectedHead)) return "Pull request head changed.";
5557
5771
  }
5558
5772
  /** A new remote head may be our repair; prove it against the actual provider Git HEAD. */
5559
- function createClaimStopCheck(claim, readCurrent, readProviderHead) {
5773
+ function createClaimStopCheck(claim, readCurrent, readProviderHead, now = Date.now) {
5560
5774
  let acceptedSelfHead;
5561
5775
  return async () => {
5562
5776
  const observed = await readCurrent();
5563
- const reason = claimStopReason(claim, observed, acceptedSelfHead);
5777
+ const reason = claimStopReason(claim, observed, acceptedSelfHead, now());
5564
5778
  if (reason !== "Pull request head changed.") return reason;
5565
5779
  if (acceptedSelfHead && observed?.pr?.head?.sha === claim.snapshot.pr?.head?.sha) return reason;
5566
5780
  let providerHead;
5567
5781
  try {
5568
5782
  providerHead = await readProviderHead();
5569
5783
  } catch {
5570
- return claimStopReason(claim, await readCurrent(), acceptedSelfHead);
5784
+ return claimStopReason(claim, await readCurrent(), acceptedSelfHead, now());
5571
5785
  }
5572
5786
  const current = await readCurrent();
5573
- const latestReason = claimStopReason(claim, current, acceptedSelfHead);
5787
+ const latestReason = claimStopReason(claim, current, acceptedSelfHead, now());
5574
5788
  if (latestReason !== "Pull request head changed.") return latestReason;
5575
5789
  if (!providerHead || current?.pr?.head?.sha !== providerHead) return latestReason;
5576
5790
  acceptedSelfHead = providerHead;
@@ -5858,6 +6072,7 @@ const openPullRequestSchema = v.object({
5858
6072
  latestReviews: nodes,
5859
6073
  reviewThreads: nodes
5860
6074
  });
6075
+ const approvedReview = v.object({ state: v.literal("APPROVED") });
5861
6076
  const openPullRequestsSchema = v.object({ repository: v.object({ pullRequests: v.object({
5862
6077
  nodes: v.array(openPullRequestSchema),
5863
6078
  pageInfo: v.object({
@@ -5963,7 +6178,7 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5963
6178
  }
5964
6179
  signal?.throwIfAborted();
5965
6180
  if (!allowSeed) continue;
5966
- await inbox.seed(repository, {
6181
+ const seeded = await inbox.seed(repository, {
5967
6182
  number,
5968
6183
  title: pr.title,
5969
6184
  state: "open",
@@ -5984,7 +6199,8 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5984
6199
  }
5985
6200
  }, signal);
5986
6201
  signal?.throwIfAborted();
5987
- await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint, signal);
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);
5988
6204
  }
5989
6205
  for (const item of tracked) if (item.repository === repository && item.status !== "terminal" && !open.has(item.number)) await mark(item.number, "closed", true);
5990
6206
  } catch (error) {
@@ -8385,11 +8601,17 @@ async function repairBaseBranch(github, options) {
8385
8601
  head
8386
8602
  };
8387
8603
  }
8388
- const open = v.parse(pullsSchema, await github.read(`repos/${repository}/pulls`, {
8389
- state: "open",
8390
- base,
8391
- per_page: 100
8392
- })).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
+ }
8393
8615
  if (open) {
8394
8616
  event("repair_open", {
8395
8617
  head,
@@ -8525,6 +8747,7 @@ function createBabysitterRuntime(options) {
8525
8747
  assertBabysitterAgent(baseAgent);
8526
8748
  const presetOptions = baseAgent.options;
8527
8749
  const filter = resolveBabysitterLifecycleFilter(presetOptions.filter, presetOptions.lifecycle);
8750
+ const approvalAdmission = presetOptions.lifecycle?.approval === true;
8528
8751
  const merge = resolveBabysitterMerge(presetOptions.merge);
8529
8752
  const github = options.github;
8530
8753
  const hostIdentity = github.identity()?.trim();
@@ -8547,6 +8770,7 @@ function createBabysitterRuntime(options) {
8547
8770
  } : { path: options.inboxPath },
8548
8771
  repositories: () => repositorySource.known(),
8549
8772
  filter,
8773
+ admitApproved: approvalAdmission,
8550
8774
  activityAuthors,
8551
8775
  activityAppId: verifiedHostIdentity ? github.appId?.() : void 0,
8552
8776
  budgets: {
@@ -8609,7 +8833,7 @@ function createBabysitterRuntime(options) {
8609
8833
  ignoreAssessedBotThreads: presetOptions.ignoreAssessedBotThreads === true
8610
8834
  };
8611
8835
  const schedulerEvent = (name, properties = {}) => options.event?.(name, properties);
8612
- const release = baseAgent.version ?? "91ca93f60843c0df231a3f438cf1c2ef1587bfc67b8791323ef4f38cc44ca863";
8836
+ const release = baseAgent.version ?? "cc2ab9f972b0945800468710b76d4809a3c6faa1a595c85f117a934b62a37e90";
8613
8837
  const workspaces = options.workspaces;
8614
8838
  const schedulerError = (name, error, properties = {}) => options.error?.(name, error, properties);
8615
8839
  const statusComment = !!verifiedHostIdentity && presetOptions.status?.comment !== false;
@@ -8725,6 +8949,44 @@ function createBabysitterRuntime(options) {
8725
8949
  const { provider } = await forge(path.split("/").slice(1, 3).join("/"), signal);
8726
8950
  return (await retryTransient(() => provider.request("GET", `/${path}`, { signal }), signal)).data;
8727
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
+ }
8728
8990
  const freshnessReader = {
8729
8991
  rest: (path, signal, key) => readRest(path, key ? `.${key}[]` : ".[]", signal),
8730
8992
  page: readOnePage
@@ -8837,6 +9099,7 @@ function createBabysitterRuntime(options) {
8837
9099
  */
8838
9100
  async function updateBranch(owner, repository, number, head, signal, pr, { reopenFork = true } = {}) {
8839
9101
  if (reopenFork && isForkHead(pr, repository)) return await reopenForkPullRequest(owner, repository, number, head, signal);
9102
+ if (approvalAdmission) await pullRequestInbox.registerHostUpdate(repository, number, head);
8840
9103
  try {
8841
9104
  const { provider } = await forge(repository, signal);
8842
9105
  await provider.request("PUT", `/repos/${repository}/pulls/${number}/update-branch`, {
@@ -8864,14 +9127,16 @@ function createBabysitterRuntime(options) {
8864
9127
  });
8865
9128
  return false;
8866
9129
  }
8867
- await provider.request("POST", `/repos/${repository}/merges`, {
9130
+ const merged = (await provider.request("POST", `/repos/${repository}/merges`, {
8868
9131
  body: {
8869
9132
  base: branches.head,
8870
9133
  head: branches.base,
8871
9134
  commit_message: `Merge ${branches.base} into ${branches.head}`
8872
9135
  },
8873
9136
  signal
8874
- });
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);
8875
9140
  return true;
8876
9141
  } catch (fallback) {
8877
9142
  await noteForgeQuota(fallback, "merge-base-into-head");
@@ -8943,6 +9208,7 @@ function createBabysitterRuntime(options) {
8943
9208
  const { provider } = await forge(repository, new AbortController().signal);
8944
9209
  await provider.request("PATCH", `/repos/${repository}/pulls/${number}`, { body: { state: "open" } });
8945
9210
  }
9211
+ const closeClockMarginMs = 6e4;
8946
9212
  const forkReopenKey = (repository, number) => `fork-reopen:${repository}#${number}`;
8947
9213
  /**
8948
9214
  * Finishes a close and reopen that a restart or a GitHub error interrupted. A PR that is still closed
@@ -8963,7 +9229,7 @@ function createBabysitterRuntime(options) {
8963
9229
  const issue = (await provider.request("GET", `/repos/${repository}/issues/${number}`, { signal })).data;
8964
9230
  if (!isRuntimeRecord(issue)) continue;
8965
9231
  const closedBy = isRuntimeRecord(issue.closed_by) ? issue.closed_by : void 0;
8966
- const ours = issue.state === "closed" && typeof value.login === "string" && String(closedBy?.login).toLowerCase() === value.login && Date.parse(String(issue.closed_at)) >= Math.floor(Number(value.at) / 1e3) * 1e3;
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;
8967
9233
  const merged = isRuntimeRecord(issue.pull_request) && issue.pull_request.merged_at != null;
8968
9234
  if (ours && !merged) {
8969
9235
  await reopenPullRequest(repository, Number(number));
@@ -9447,7 +9713,7 @@ function createBabysitterRuntime(options) {
9447
9713
  }
9448
9714
  function cancelWhenPullRequestStops(claim, controller, providerDirectory, pushedHead) {
9449
9715
  let stopped = false, polling = false;
9450
- 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());
9451
9717
  const poll = async () => {
9452
9718
  if (stopped || polling || controller.signal.aborted) return;
9453
9719
  polling = true;
@@ -9577,9 +9843,9 @@ function createBabysitterRuntime(options) {
9577
9843
  });
9578
9844
  return "blocked";
9579
9845
  }
9580
- const age = Date.now() - pending.startedAt;
9846
+ const age = pullRequestInbox.now() - pending.startedAt;
9581
9847
  if (pending.asynchronous && age >= pendingMergeDeadlineMs) {
9582
- const until = Date.now() + stoppedMergeRetryMs;
9848
+ const until = pullRequestInbox.now() + stoppedMergeRetryMs;
9583
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()}.`;
9584
9850
  await pullRequestInbox.setMeta(stoppedKey, {
9585
9851
  head: pending.head,
@@ -9632,12 +9898,14 @@ function createBabysitterRuntime(options) {
9632
9898
  if (decision.ready && merge.ready) {
9633
9899
  const callback = merge.ready;
9634
9900
  const head = decision.head;
9901
+ const writers = await verifiedWriters(snapshot, signal);
9635
9902
  const ready = await boundedMergeReady(() => callback({
9636
9903
  repository,
9637
9904
  number,
9638
9905
  head,
9639
9906
  snapshot: structuredClone(snapshot),
9640
- requiredChecks: evaluation.state
9907
+ requiredChecks: evaluation.state,
9908
+ writers
9641
9909
  }), signal);
9642
9910
  if (signal.aborted) return "blocked";
9643
9911
  if (ready !== true) decision = {
@@ -9653,7 +9921,7 @@ function createBabysitterRuntime(options) {
9653
9921
  return pending?.asynchronous ? await parkMerge(`Unconfirmed merge is waiting for ${decision.reason}.`) : "not-ready";
9654
9922
  }
9655
9923
  const stopped = pending ? void 0 : await pullRequestInbox.meta(stoppedKey);
9656
- 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);
9657
9925
  const folding = pending ? void 0 : await pullRequestInbox.foldingChild(repository, number);
9658
9926
  if (folding !== void 0) return await parkMerge(`Waiting for the merge of stacked pull request #${folding} into this branch.`);
9659
9927
  let mergeStarted = false;
@@ -10183,12 +10451,14 @@ function createBabysitterRuntime(options) {
10183
10451
  if (!head) return false;
10184
10452
  const callback = merge.ready;
10185
10453
  try {
10454
+ const writers = await verifiedWriters(snapshot);
10186
10455
  return await boundedMergeReady(() => callback({
10187
10456
  repository: snapshot.repository,
10188
10457
  number: snapshot.number,
10189
10458
  head,
10190
10459
  snapshot: structuredClone(snapshot),
10191
- requiredChecks
10460
+ requiredChecks,
10461
+ writers
10192
10462
  })) === true;
10193
10463
  } catch (error) {
10194
10464
  schedulerEvent("babysitter.direct_merge.skipped", {
@@ -10431,6 +10701,33 @@ function createBabysitterRuntime(options) {
10431
10701
  }
10432
10702
  const hostOnlyChecked = /* @__PURE__ */ new Map();
10433
10703
  const hostOnlyStamp = (s) => `${s.generation}:${s.revision ?? 0}`;
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
+ }
10434
10731
  async function stallSnapshot(tick) {
10435
10732
  const now = Date.now();
10436
10733
  const snapshot = {
@@ -10484,6 +10781,14 @@ function createBabysitterRuntime(options) {
10484
10781
  let timer;
10485
10782
  const stalled = new Promise((_resolve, reject) => {
10486
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;
10487
10792
  const error = presetsErrorDiagnostics.PRESETS_BABYSITTER_RECONCILE_STALLED({
10488
10793
  step: tick.subject ? `${tick.step} (${tick.subject})` : tick.step,
10489
10794
  minutes: Math.round((Date.now() - startedAt) / 6e4)
@@ -10494,10 +10799,16 @@ function createBabysitterRuntime(options) {
10494
10799
  }, stallMs);
10495
10800
  timer.unref?.();
10496
10801
  });
10802
+ runningTick = tick;
10497
10803
  try {
10498
10804
  await Promise.race([reconcileTick(reason, context, isAccepting, step, signal), stalled]);
10499
10805
  } finally {
10500
10806
  clearTimeout(timer);
10807
+ if (!signal.aborted) {
10808
+ lastFinishedAt = Date.now();
10809
+ stallsInRow = 0;
10810
+ if (runningTick === tick) runningTick = void 0;
10811
+ }
10501
10812
  }
10502
10813
  }
10503
10814
  async function reconcileTick(reason, { track }, isAccepting, step, signal) {
@@ -10604,7 +10915,7 @@ function createBabysitterRuntime(options) {
10604
10915
  });
10605
10916
  step("snapshot-detect");
10606
10917
  try {
10607
- await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository, signal), repositories, Date.now(), !eventScopedBootstrap, (repository, error) => {
10918
+ await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository, signal), repositories, pullRequestInbox.now(), !eventScopedBootstrap, (repository, error) => {
10608
10919
  noteForgeQuota(error, "snapshot-detect");
10609
10920
  schedulerEvent("babysitter.snapshot.detect.failed", {
10610
10921
  repository,
@@ -10618,9 +10929,9 @@ function createBabysitterRuntime(options) {
10618
10929
  }
10619
10930
  step("snapshot-probe");
10620
10931
  try {
10621
- await probeChangedSnapshots(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors, void 0, void 0, signal);
10932
+ await probeChangedSnapshots(pullRequestInbox, readRest, pullRequestInbox.now(), readThreads, activityAuthors, void 0, void 0, signal);
10622
10933
  step("snapshot-sweep");
10623
- await reconcileOneSnapshot(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors, signal);
10934
+ await reconcileOneSnapshot(pullRequestInbox, readRest, pullRequestInbox.now(), readThreads, activityAuthors, signal);
10624
10935
  } catch (error) {
10625
10936
  signal.throwIfAborted();
10626
10937
  await noteForgeQuota(error, "snapshot-reconcile");
@@ -11014,7 +11325,7 @@ function createBabysitterRuntime(options) {
11014
11325
  await pullRequestInbox.release(inboxClaim);
11015
11326
  return;
11016
11327
  }
11017
- if (!pullRequestInbox.eligible(repository, inboxClaim.snapshot.pr)) {
11328
+ if (!await eligibleNow(repository, inboxClaim.snapshot.pr, inboxClaim.snapshot, passSignal)) {
11018
11329
  await pullRequestInbox.finish(inboxClaim, {
11019
11330
  text: "PR closed or outside the configured filter.",
11020
11331
  terminal: true
@@ -11306,6 +11617,7 @@ function createBabysitterRuntime(options) {
11306
11617
  workspaceRun.head = pullRequest.headRefOid;
11307
11618
  workspaceRun.base = pullRequest.baseRefOid;
11308
11619
  await github.withPullRequestCheckout({
11620
+ baseRef: pullRequest.baseRefName,
11309
11621
  headRef: pullRequest.headRefName,
11310
11622
  headRepository: pullRequest.headRepository?.nameWithOwner,
11311
11623
  headSha: pullRequest.headRefOid,
@@ -11377,7 +11689,7 @@ function createBabysitterRuntime(options) {
11377
11689
  const assertLeaseHeld = async () => {
11378
11690
  abortSignal.throwIfAborted();
11379
11691
  const current = await pullRequestInbox.get(repository, number);
11380
- 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");
11381
11693
  return current;
11382
11694
  };
11383
11695
  const assertLease = async () => {
@@ -11386,7 +11698,7 @@ function createBabysitterRuntime(options) {
11386
11698
  for (const [id, reopens] of ownedResolutions) if ((current.threadReopens?.[id] ?? 0) !== reopens) throw new DOMException("An addressed review thread was reopened.", "AbortError");
11387
11699
  const observedHead = current.pr?.head?.sha;
11388
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");
11389
- 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());
11390
11702
  if (stopped) throw new DOMException(stopped, "AbortError");
11391
11703
  if (pushedHead && observedHead === pushedHead) {
11392
11704
  pendingInboxHeads.clear();
@@ -11515,7 +11827,7 @@ function createBabysitterRuntime(options) {
11515
11827
  commentPrefix: "<!-- vitehub-babysitter-repair:repair -->\n",
11516
11828
  signal: abortSignal,
11517
11829
  autoMerge: merge.mode === "auto" && stackParent === void 0,
11518
- eligible: (current) => pullRequestInbox.eligible(repository, normalizePullRequest(current)),
11830
+ eligible: async (current) => await eligibleNow(repository, normalizePullRequest(current), await pullRequestInbox.get(repository, number), abortSignal),
11519
11831
  checkDependencies: async () => {
11520
11832
  await assertLease();
11521
11833
  if (presetOptions.install === false) return {
@@ -11564,7 +11876,7 @@ function createBabysitterRuntime(options) {
11564
11876
  ...inboxClaim,
11565
11877
  generation: current.generation,
11566
11878
  snapshot: current
11567
- }, Date.now() + 72e5)) return;
11879
+ }, pullRequestInbox.now() + 72e5)) return;
11568
11880
  const latest = await assertLease();
11569
11881
  if (latest.generation === current.generation) throw new DOMException("Pull request lease renewal failed.", "AbortError");
11570
11882
  current = latest;
@@ -11592,7 +11904,7 @@ function createBabysitterRuntime(options) {
11592
11904
  try {
11593
11905
  const result = await prepared.push(providerDirectory, {
11594
11906
  signal: abortSignal,
11595
- beforePush: async (head) => {
11907
+ beforePush: async (head, lineage) => {
11596
11908
  const current = await assertLease();
11597
11909
  await assertRepairBase();
11598
11910
  const window = await repairPushWindow(current, await requiredCheckState(current), current.pr?.mergeable === false);
@@ -11604,7 +11916,7 @@ function createBabysitterRuntime(options) {
11604
11916
  ...inboxClaim,
11605
11917
  generation: current.generation,
11606
11918
  snapshot: current
11607
- }, head)) throw new DOMException("Publication candidate lease changed.", "AbortError");
11919
+ }, head, lineage)) throw new DOMException("Publication candidate lease changed.", "AbortError");
11608
11920
  observePendingPush = head ? (current) => {
11609
11921
  if (current.sourcePushHeads?.includes(head)) recordPush(head);
11610
11922
  } : void 0;
@@ -11799,7 +12111,11 @@ function createBabysitterRuntime(options) {
11799
12111
  authorAssociation: void 0,
11800
12112
  actor: void 0
11801
12113
  },
11802
- when: (context) => matchesBabysitterPullRequestFilter(context, filter),
12114
+ when: (context) => matchesBabysitterPullRequestFilter(context, approvalAdmission ? {
12115
+ ...filter,
12116
+ author: void 0,
12117
+ authorAssociation: void 0
12118
+ } : filter),
11803
12119
  workspace: false
11804
12120
  }
11805
12121
  }));
@@ -11972,7 +12288,7 @@ function createBabysitterRuntime(options) {
11972
12288
  }, abortSignal, () => {
11973
12289
  providerLimited = true;
11974
12290
  }).catch(async (error) => {
11975
- 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", {
11976
12292
  ...owner,
11977
12293
  head_sha: pullRequest.headRefOid,
11978
12294
  ...recordedPass.exemption ? { exemption: recordedPass.exemption } : {},
@@ -12225,6 +12541,7 @@ function createBabysitterRuntime(options) {
12225
12541
  inbox: pullRequestInbox,
12226
12542
  repositories: repositorySource,
12227
12543
  reconcile,
12544
+ scheduler,
12228
12545
  workload,
12229
12546
  observeMainRepair
12230
12547
  };