@vite-hub/presets 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
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";
1
+ import { a as isRuntimeString, i as isRuntimeRecord, n as hasRuntimeType, r as isRuntimeNumber, t as presetsErrorDiagnostics } from "./error-diagnostics-FZJIIO9X.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-BvKD88Nz.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,9 +15,11 @@ 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
- //#region src/github/checkout.ts
20
+ import { resolveRuntimeValue } from "@vite-hub/runtime/internal/context";
21
+ import { resolveRegisteredWorkspaceDefinition } from "@vite-hub/workspace/runtime";
22
+ // 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. */
23
25
  async function sanitizeProviderGitConfig(git, destination) {
@@ -353,8 +355,7 @@ async function preparePersistentGitHubPullRequestWorkspace(checkout, target, opt
353
355
  reason: reason ?? "warm"
354
356
  };
355
357
  }
356
- //#endregion
357
- //#region src/github/base-reverts.ts
358
+ // src/github/base-reverts.ts
358
359
  const lockfile = /(?:^|\/)(?:pnpm-lock\.yaml|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|bun\.lockb?)$/;
359
360
  /**
360
361
  * Find base changes that a staged merge of `base` into the PR `head` undoes.
@@ -433,8 +434,7 @@ async function blob(git, spec) {
433
434
  return await git("cat-file", "-e", spec).then(() => git("cat-file", "blob", spec), () => "");
434
435
  }
435
436
  const names = (output) => output.split("\0").filter(Boolean);
436
- //#endregion
437
- //#region src/github/install-inputs.ts
437
+ // src/github/install-inputs.ts
438
438
  const inputNames = /* @__PURE__ */ new Set([
439
439
  ".npmrc",
440
440
  ".yarnrc.yml",
@@ -835,8 +835,7 @@ const publishOutputScript = `
835
835
  if (present[index]) await rename(join(source, name), name);
836
836
  }
837
837
  `;
838
- //#endregion
839
- //#region src/github/install-snapshot.ts
838
+ // src/github/install-snapshot.ts
840
839
  const exec$5 = promisify(execFile);
841
840
  const yarnOutputs = /* @__PURE__ */ new Set([
842
841
  "cache",
@@ -965,8 +964,7 @@ async function publishGitHubInstallSnapshot(snapshot, signal) {
965
964
  });
966
965
  }
967
966
  }
968
- //#endregion
969
- //#region src/github/install.ts
967
+ // src/github/install.ts
970
968
  const exec$4 = promisify(execFile);
971
969
  const manifest = v.object({ packageManager: v.optional(v.string()) });
972
970
  const systemError = v.object({ errno: v.pipe(v.number(), v.integer(), v.maxValue(-1)) });
@@ -1403,8 +1401,7 @@ async function hasCurrentGitHubDependencies(target, inputs = target) {
1403
1401
  return false;
1404
1402
  }
1405
1403
  }
1406
- //#endregion
1407
- //#region src/github/conflicts.ts
1404
+ // src/github/conflicts.ts
1408
1405
  /**
1409
1406
  * Resolve conflicts of a prepared merge that need no judgment, and stage each resolution.
1410
1407
  * Ours is the PR head and theirs is the base. Anything the rules cannot prove stays conflicted.
@@ -1760,8 +1757,7 @@ function lockfileResolutions(text) {
1760
1757
  for (const [key, versions] of edgeVersions) resolutions.set(key, [...new Set(versions)].sort().join(" "));
1761
1758
  return resolutions;
1762
1759
  }
1763
- //#endregion
1764
- //#region src/github/repair.ts
1760
+ // src/github/repair.ts
1765
1761
  const exec$3 = promisify(execFile);
1766
1762
  /** Git metadata is protected by provider sandboxes. Only the host stages repairs. */
1767
1763
  async function commitGitHubPullRequestWorkspace(target, input, options) {
@@ -1916,8 +1912,7 @@ async function prepareGitHubRepairBase(target, options) {
1916
1912
  }));
1917
1913
  return conflicts;
1918
1914
  }
1919
- //#endregion
1920
- //#region src/github/host.ts
1915
+ // src/github/host.ts
1921
1916
  const exec$2 = promisify(execFile);
1922
1917
  const rateLimitLimit = 256;
1923
1918
  function secret(value) {
@@ -1940,7 +1935,6 @@ function createGitHubAppCredentials(app) {
1940
1935
  installations: Object.fromEntries(Object.entries(app.installations ?? {}).map(([name, id]) => [name.toLowerCase(), id]))
1941
1936
  };
1942
1937
  const installations = /* @__PURE__ */ new Map();
1943
- let identity;
1944
1938
  const client = githubAppCredentials(app);
1945
1939
  const installation = async (repository, signal) => {
1946
1940
  signal?.throwIfAborted();
@@ -1972,36 +1966,35 @@ function createGitHubAppCredentials(app) {
1972
1966
  redeliver: (id, signal) => client.redeliver(id, signal),
1973
1967
  /** The App bot's login and noreply email, used as the commit author. */
1974
1968
  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;
1969
+ return await appIdentity(client);
1999
1970
  }
2000
1971
  };
2001
1972
  }
2002
1973
  function tokenKey(token) {
2003
1974
  return `token:${createHash("sha256").update(token).digest("base64url")}`;
2004
1975
  }
1976
+ async function appIdentity(client, signal) {
1977
+ const { id: appId, login, email } = await client.app(signal).catch((error) => {
1978
+ if (signal?.aborted) throw abortError(signal.reason);
1979
+ const status = forgeErrorStatus(error);
1980
+ if (status !== void 0) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_REQUEST_FAILED({
1981
+ status,
1982
+ cause: error
1983
+ });
1984
+ if (isForgeResponseError(error)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_RESPONSE_INVALID({ cause: error });
1985
+ throw error;
1986
+ });
1987
+ return {
1988
+ appId,
1989
+ login,
1990
+ email
1991
+ };
1992
+ }
1993
+ /** The App lookup or token request for a repository answered 404: the App is not installed there. */
1994
+ function notInstalled(error) {
1995
+ for (let cause = error, depth = 0; cause instanceof Error && depth < 4; cause = cause.cause, depth++) if (forgeErrorStatus(cause) === 404) return true;
1996
+ return false;
1997
+ }
2005
1998
  function owner(repository) {
2006
1999
  return repository.split("/", 1)[0].toLowerCase();
2007
2000
  }
@@ -2041,7 +2034,7 @@ async function waitForCaller(promise, options) {
2041
2034
  function createGitHubHost(options) {
2042
2035
  const checkoutScope = new AsyncLocalStorage();
2043
2036
  const maxBuffer = options.maxBuffer ?? 16777216;
2044
- const identity = options.identity ?? {};
2037
+ let appBot;
2045
2038
  const rateLimits = /* @__PURE__ */ new Map();
2046
2039
  /** Record the rate limit headers of each Forge response, keyed by credential and resource. */
2047
2040
  function observe(credentialKey) {
@@ -2083,14 +2076,23 @@ function createGitHubHost(options) {
2083
2076
  operation.close();
2084
2077
  }
2085
2078
  }
2079
+ async function appBotIdentity(appId, privateKey, signal) {
2080
+ appBot = await appIdentity(githubAppCredentials({
2081
+ appId,
2082
+ privateKey,
2083
+ userAgent: options.userAgent
2084
+ }), signal);
2085
+ return appBot;
2086
+ }
2086
2087
  function fallbackToken(config) {
2087
2088
  const configured = secret(config.token)?.trim();
2088
2089
  if (!configured) throw presetsErrorDiagnostics.PRESETS_GITHUB_AUTH_MISSING();
2089
2090
  return configured;
2090
2091
  }
2091
- async function scopedAccess(input) {
2092
+ async function scopedAccess(input, commits = true) {
2093
+ const installationRepository = input.installationRepository ?? input.repository;
2092
2094
  const config = await credentials({
2093
- repository: input.repository,
2095
+ repository: installationRepository,
2094
2096
  signal: input.signal
2095
2097
  });
2096
2098
  const appId = String(config.appId || "").trim();
@@ -2102,9 +2104,10 @@ function createGitHubHost(options) {
2102
2104
  installationId,
2103
2105
  privateKey
2104
2106
  ];
2105
- const repositoryOwner = input.repository ? owner(input.repository) : void 0;
2107
+ const repositoryOwner = installationRepository ? owner(installationRepository) : void 0;
2106
2108
  let token;
2107
2109
  let credentialKey;
2110
+ let identity = options.identity ?? {};
2108
2111
  if (appValues.some(Boolean)) {
2109
2112
  if (!appValues.every(Boolean)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_CREDENTIALS_INCOMPLETE();
2110
2113
  if (!appOwner) throw presetsErrorDiagnostics.PRESETS_GITHUB_HOST_APP_OWNER_MISSING();
@@ -2135,6 +2138,7 @@ function createGitHubHost(options) {
2135
2138
  if (isForgeResponseError(error)) throw presetsErrorDiagnostics.PRESETS_GITHUB_APP_TOKEN_MISSING({ cause: error });
2136
2139
  throw error;
2137
2140
  }
2141
+ if (commits && !options.identity) identity = await appBotIdentity(numericAppId, privateKey, input.signal);
2138
2142
  }
2139
2143
  } else {
2140
2144
  token = fallbackToken(config);
@@ -2170,32 +2174,52 @@ function createGitHubHost(options) {
2170
2174
  return {
2171
2175
  env,
2172
2176
  credentialKey,
2173
- token
2177
+ token,
2178
+ identity
2174
2179
  };
2175
2180
  }
2176
- async function access(input = {}) {
2181
+ async function commitAccess(input) {
2177
2182
  const operation = controlledOperation(input);
2178
2183
  try {
2179
- const { env, token } = await scopedAccess({
2184
+ return await scopedAccess({
2180
2185
  ...input,
2181
2186
  signal: operation.signal,
2182
2187
  timeout: void 0
2183
2188
  });
2184
- return {
2185
- env,
2186
- token
2187
- };
2188
2189
  } finally {
2189
2190
  operation.close();
2190
2191
  }
2191
2192
  }
2193
+ async function access(input = {}) {
2194
+ const { env, token } = await commitAccess(input);
2195
+ return {
2196
+ env,
2197
+ token
2198
+ };
2199
+ }
2200
+ /**
2201
+ * Access to a fork head: the fork's own App installation, or the base repository's when the App is not
2202
+ * installed on the fork. The base's token pushes to the fork only while its author allows edits by maintainers.
2203
+ */
2204
+ async function headAccess(input, base) {
2205
+ if (!input.repository || input.repository === base) return await access(input);
2206
+ try {
2207
+ return await access(input);
2208
+ } catch (error) {
2209
+ if (input.signal?.aborted || !notInstalled(error)) throw error;
2210
+ return await access({
2211
+ ...input,
2212
+ installationRepository: base
2213
+ });
2214
+ }
2215
+ }
2192
2216
  async function forge(input = {}) {
2193
2217
  const operation = controlledOperation(input);
2194
2218
  try {
2195
2219
  const auth = await scopedAccess({
2196
2220
  repository: input.repository,
2197
2221
  signal: operation.signal
2198
- });
2222
+ }, false);
2199
2223
  return await forgeProvider({
2200
2224
  forge: "github",
2201
2225
  token: auth.token,
@@ -2316,11 +2340,11 @@ function createGitHubHost(options) {
2316
2340
  }
2317
2341
  if (pullRequest.headRef) {
2318
2342
  const sourceRepository = pullRequest.headRepository ?? pullRequest.repository;
2319
- const sourceAuth = sourceRepository === pullRequest.repository ? baseAuth : await access({
2343
+ const sourceAuth = sourceRepository === pullRequest.repository ? baseAuth : await headAccess({
2320
2344
  refresh: true,
2321
2345
  repository: sourceRepository,
2322
2346
  signal: operation.signal
2323
- });
2347
+ }, pullRequest.repository);
2324
2348
  await exec$2("git", [
2325
2349
  "-C",
2326
2350
  checkout,
@@ -2429,12 +2453,57 @@ function createGitHubHost(options) {
2429
2453
  signal: operation.signal
2430
2454
  });
2431
2455
  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
- });
2456
+ const hostCommits = /* @__PURE__ */ new Set();
2457
+ const commitRepair = async (target, input, commitOptions) => {
2458
+ const before = (await exec$2("git", [
2459
+ "-C",
2460
+ target,
2461
+ "rev-parse",
2462
+ "HEAD"
2463
+ ], commandOptions)).stdout.trim();
2464
+ const head = await commitGitHubPullRequestWorkspace(target, input, {
2465
+ expectedHead: pushHead,
2466
+ signal: operation.signal,
2467
+ identity: env,
2468
+ verifyDependencies: commitOptions?.verifyDependencies
2469
+ });
2470
+ if (head !== before) hostCommits.add(head);
2471
+ return head;
2472
+ };
2473
+ const hostOnly = async (head, parent, signal) => {
2474
+ if (!hostCommits.size) return false;
2475
+ let base = [];
2476
+ if (pullRequest.baseRef) try {
2477
+ await exec$2("git", [
2478
+ "-C",
2479
+ checkout,
2480
+ ...fetchConfig,
2481
+ "fetch",
2482
+ "--no-tags",
2483
+ "--",
2484
+ "origin",
2485
+ `refs/heads/${pullRequest.baseRef}`
2486
+ ], {
2487
+ ...commandOptions,
2488
+ signal
2489
+ });
2490
+ base = ["^FETCH_HEAD"];
2491
+ } catch {
2492
+ if (signal.aborted) throw abortError(signal.reason);
2493
+ }
2494
+ const added = (await exec$2("git", [
2495
+ "-C",
2496
+ checkout,
2497
+ "rev-list",
2498
+ head,
2499
+ `^${parent}`,
2500
+ ...base
2501
+ ], {
2502
+ ...commandOptions,
2503
+ signal
2504
+ })).stdout.split("\n").filter(Boolean);
2505
+ return added.length > 0 && added.every((commit) => hostCommits.has(commit));
2506
+ };
2438
2507
  const push = async (target = checkout, options = {}) => {
2439
2508
  const signal = options.signal ? AbortSignal.any([operation.signal, options.signal]) : operation.signal;
2440
2509
  signal.throwIfAborted();
@@ -2493,13 +2562,16 @@ function createGitHubHost(options) {
2493
2562
  ...commandOptions,
2494
2563
  signal
2495
2564
  });
2496
- const refreshed = await access({
2565
+ const refreshed = await headAccess({
2497
2566
  refresh: true,
2498
2567
  repository: pullRequest.headRepository,
2499
2568
  signal
2500
- });
2569
+ }, pullRequest.repository);
2501
2570
  signal.throwIfAborted();
2502
- await options.beforePush?.(head);
2571
+ await options.beforePush?.(head, {
2572
+ parent: expectedHead,
2573
+ hostOnly: await hostOnly(head, expectedHead, signal)
2574
+ });
2503
2575
  await exec$2("git", [
2504
2576
  "-C",
2505
2577
  checkout,
@@ -2540,25 +2612,28 @@ function createGitHubHost(options) {
2540
2612
  if (!persistent) await cleanupCheckout().catch(() => void 0);
2541
2613
  }
2542
2614
  }
2543
- const host = {
2615
+ return {
2544
2616
  identity() {
2545
- return identity.login?.trim() || void 0;
2617
+ return (options.identity ?? appBot)?.login?.trim() || void 0;
2546
2618
  },
2547
2619
  appId() {
2548
- return identity.appId;
2620
+ return (options.identity ?? appBot)?.appId;
2549
2621
  },
2550
2622
  channel(channelOptions = {}) {
2551
- const login = host.identity();
2552
2623
  return github({
2553
2624
  ...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
- }
2625
+ app: { token: async (_context, scope) => {
2626
+ const { token, identity: { login, appId, email } } = await commitAccess(scope);
2627
+ const name = login?.trim();
2628
+ return {
2629
+ token,
2630
+ identity: name ? {
2631
+ login: name,
2632
+ appId,
2633
+ email
2634
+ } : void 0
2635
+ };
2636
+ } }
2562
2637
  });
2563
2638
  },
2564
2639
  async environment() {
@@ -2575,10 +2650,8 @@ function createGitHubHost(options) {
2575
2650
  rateLimit,
2576
2651
  withPullRequestCheckout
2577
2652
  };
2578
- return host;
2579
2653
  }
2580
- //#endregion
2581
- //#region src/github/pull-requests.ts
2654
+ // src/github/pull-requests.ts
2582
2655
  const rollupSchema = v.object({ nodes: v.array(v.object({ commit: v.object({ statusCheckRollup: v.nullable(v.object({ contexts: v.object({ nodes: v.array(v.unknown()) }) })) }) })) });
2583
2656
  v.pipe(v.object({
2584
2657
  baseRefOid: v.string(),
@@ -2633,8 +2706,7 @@ async function createGitHubPullRequestRun(repository, pullRequest, options) {
2633
2706
  }
2634
2707
  };
2635
2708
  }
2636
- //#endregion
2637
- //#region src/github/required-checks.ts
2709
+ // src/github/required-checks.ts
2638
2710
  /** Cache authoritative policy, including explicit unknown results; never infer CI requirements from names. */
2639
2711
  function createGitHubRequiredCheckPolicyReader(read, options = {}) {
2640
2712
  const clock = options.clock ?? Date.now;
@@ -2785,8 +2857,7 @@ function combine(states) {
2785
2857
  if (!states.length || states.includes("unknown")) return "unknown";
2786
2858
  return states.includes("pending") ? "pending" : "passed";
2787
2859
  }
2788
- //#endregion
2789
- //#region src/babysitter/inbox/budgets.ts
2860
+ // src/babysitter/inbox/budgets.ts
2790
2861
  const count = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER - 1));
2791
2862
  const providerBudgetSchema = v.object({
2792
2863
  generation: v.string(),
@@ -2935,8 +3006,7 @@ function validateBudgets(budgets) {
2935
3006
  function requireEvidence(evidence) {
2936
3007
  invariant(evidence.trim(), "the inbox passes evidence that the runtime builds, such as push:<sha>, or a fixed reset reason");
2937
3008
  }
2938
- //#endregion
2939
- //#region src/babysitter/inbox/wait-state.ts
3009
+ // src/babysitter/inbox/wait-state.ts
2940
3010
  const nonempty = v.pipe(v.string(), v.minLength(1));
2941
3011
  const repository = v.pipe(v.string(), v.regex(/^[\w.-]+\/[\w.-]+$/));
2942
3012
  const commitSha = v.pipe(v.string(), v.regex(/^[a-f0-9]{40,64}$/));
@@ -2961,8 +3031,7 @@ const waitSchema = v.object({
2961
3031
  wake: v.optional(wakeSchema)
2962
3032
  });
2963
3033
  const parseWait = (value) => v.parse(waitSchema, value);
2964
- //#endregion
2965
- //#region src/babysitter/inbox/storage.ts
3034
+ // src/babysitter/inbox/storage.ts
2966
3035
  function isBusy(error) {
2967
3036
  return error instanceof Error && ("errcode" in error && (error.errcode === 5 || error.errcode === 6) || /database is (?:locked|busy)/i.test(error.message));
2968
3037
  }
@@ -3035,8 +3104,7 @@ function createNodeSqliteInboxStorage(path) {
3035
3104
  }
3036
3105
  };
3037
3106
  }
3038
- //#endregion
3039
- //#region src/babysitter/inbox/status-delivery.ts
3107
+ // src/babysitter/inbox/status-delivery.ts
3040
3108
  const statusOutboxPrefix = "status-outbox:v1:";
3041
3109
  const statusWriterPrefix = "status-writers:v1:";
3042
3110
  const statusSentPrefix = "status-sent:v1:";
@@ -3104,8 +3172,7 @@ function isStatusDeliveryCurrent(pending, snapshot) {
3104
3172
  const terminalResult = snapshot.status === "terminal" && pending.activity.status === "completed";
3105
3173
  return snapshot.lastResult === pending.text && (snapshot.generation === pending.generation || Boolean(repairHeadObserved) || terminalResult);
3106
3174
  }
3107
- //#endregion
3108
- //#region src/babysitter/inbox/types.ts
3175
+ // src/babysitter/inbox/types.ts
3109
3176
  const actor = v.nullish(v.object({
3110
3177
  login: v.optional(v.string()),
3111
3178
  type: v.optional(v.string()),
@@ -3267,8 +3334,7 @@ const deliverySchema = v.looseObject({
3267
3334
  state: v.optional(v.string())
3268
3335
  });
3269
3336
  const parseDelivery = (value) => v.parse(deliverySchema, value);
3270
- //#endregion
3271
- //#region src/babysitter/inbox/store.ts
3337
+ // src/babysitter/inbox/store.ts
3272
3338
  const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
3273
3339
  const statusContentKey = (snapshot, head = snapshot.wait?.headSha ?? snapshot.pr?.head?.sha) => digest([
3274
3340
  head,
@@ -3327,6 +3393,11 @@ function parseSnapshot(value) {
3327
3393
  token: v.string(),
3328
3394
  heads: v.array(v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i)))
3329
3395
  }), input.prospectivePush);
3396
+ if (input.hostUpdates !== void 0) v.parse(v.array(v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i))), input.hostUpdates);
3397
+ if (input.hostHeads !== void 0) v.parse(v.array(v.object({
3398
+ head: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i)),
3399
+ parent: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i))
3400
+ })), input.hostHeads);
3330
3401
  if (input.threadReopens !== void 0) v.parse(v.record(v.string(), v.pipe(v.number(), v.integer(), v.minValue(0))), input.threadReopens);
3331
3402
  if (input.sourcePushHeads !== void 0) v.parse(v.array(v.string()), input.sourcePushHeads);
3332
3403
  if (input.sourcePushOverflow !== void 0) v.parse(v.boolean(), input.sourcePushOverflow);
@@ -3370,6 +3441,10 @@ function pullRequestFilterContext(repository, pr) {
3370
3441
  };
3371
3442
  }
3372
3443
  const stringValue = (value) => isRuntimeString(value) ? value : String(value);
3444
+ const databaseNow = "CAST(ROUND((julianday('now') - 2440587.5) * 86400000) AS INTEGER)";
3445
+ const clockSampleIntervalMs = 3e4;
3446
+ const ciEvidencePrefix = "ci-evidence:v1:";
3447
+ const ciEvidenceAtPrefix = "ci-evidence-at:v1:";
3373
3448
  const legacyRecordSchema = v.record(v.string(), v.unknown());
3374
3449
  const legacyWaitSchema = v.object({
3375
3450
  headSha: v.pipe(v.string(), v.minLength(1)),
@@ -3520,7 +3595,11 @@ var PullRequestInbox = class {
3520
3595
  tables;
3521
3596
  repositoryList;
3522
3597
  clock;
3598
+ usesDatabaseClock;
3599
+ clockSample;
3523
3600
  filter;
3601
+ /** Whether a maintainer's approval admits an author the filter leaves out. */
3602
+ admitApproved;
3524
3603
  activityAuthors;
3525
3604
  activityAppId;
3526
3605
  budgets;
@@ -3529,7 +3608,7 @@ var PullRequestInbox = class {
3529
3608
  claimStackChildren;
3530
3609
  invalidRow;
3531
3610
  reportedRows = /* @__PURE__ */ new Set();
3532
- constructor({ path, storage, scope = "", repositories, filter, clock = Date.now, budgets = {}, activityAuthors = [], activityAppId, priorityLabels = [], mainRepairBranchPrefix, claimStackChildren = false, invalidRow }) {
3611
+ constructor({ path, storage, scope = "", repositories, filter, admitApproved = false, clock, budgets = {}, activityAuthors = [], activityAppId, priorityLabels = [], mainRepairBranchPrefix, claimStackChildren = false, invalidRow }) {
3533
3612
  validateBudgets(budgets);
3534
3613
  if (path === void 0 === (storage === void 0)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_INBOX_STORAGE_MISSING();
3535
3614
  this.budgets = { ...budgets };
@@ -3542,8 +3621,13 @@ var PullRequestInbox = class {
3542
3621
  const fixed = repositories.map((repository) => repository.toLowerCase());
3543
3622
  this.repositoryList = () => fixed;
3544
3623
  }
3545
- this.clock = clock;
3624
+ this.usesDatabaseClock = clock === void 0 && storage !== void 0;
3625
+ this.clock = clock ?? (!this.usesDatabaseClock ? () => Date.now() : () => {
3626
+ const sample = this.clockSample;
3627
+ return sample ? sample.time + Math.floor(performance.now() - sample.sampledAt) : Date.now();
3628
+ });
3546
3629
  this.filter = filter;
3630
+ this.admitApproved = admitApproved;
3547
3631
  this.activityAuthors = new Set(activityAuthors.map((author) => author.trim().toLowerCase()));
3548
3632
  this.activityAppId = activityAppId === void 0 ? void 0 : v.parse(v.pipe(v.number(), v.integer(), v.minValue(1)), activityAppId);
3549
3633
  this.storage = storage ?? createNodeSqliteInboxStorage(path);
@@ -3603,10 +3687,25 @@ var PullRequestInbox = class {
3603
3687
  });
3604
3688
  await this.ready;
3605
3689
  }
3690
+ /** The current time on the inbox clock. Compare lease ends from the inbox with it, not with `Date.now()`. */
3691
+ now() {
3692
+ return this.clock();
3693
+ }
3694
+ async syncClock(tx) {
3695
+ if (!this.usesDatabaseClock || this.clockSample && performance.now() - this.clockSample.sampledAt < clockSampleIntervalMs) return;
3696
+ const [row] = await tx.execute(`SELECT ${databaseNow} AS now`);
3697
+ const now = Number(row?.now);
3698
+ if (!Number.isFinite(now)) return;
3699
+ this.clockSample = {
3700
+ time: now,
3701
+ sampledAt: performance.now()
3702
+ };
3703
+ }
3606
3704
  async transaction(run, signal) {
3607
3705
  await this.init();
3608
3706
  return await this.storage.transaction(async (tx) => {
3609
3707
  signal?.throwIfAborted();
3708
+ await this.syncClock(tx);
3610
3709
  const result = await run(tx);
3611
3710
  signal?.throwIfAborted();
3612
3711
  return result;
@@ -3614,6 +3713,7 @@ var PullRequestInbox = class {
3614
3713
  }
3615
3714
  async read(statement, args = []) {
3616
3715
  await this.init();
3716
+ await this.syncClock(this.storage);
3617
3717
  return await this.storage.execute(statement, args);
3618
3718
  }
3619
3719
  /** Parses one stored row. An invalid row is reported once and skipped by queue-wide reads. */
@@ -3772,6 +3872,7 @@ var PullRequestInbox = class {
3772
3872
  s.wait?.headSha ?? null,
3773
3873
  leaseHeads ? JSON.stringify(leaseHeads) : null
3774
3874
  ]);
3875
+ if (s.pr?.state === "closed") await this.retireFoldIn(tx, s.repository, s.number);
3775
3876
  if (this.activityAuthors.size && (s.status === "terminal" || reopened || resumed || readySuperseded)) {
3776
3877
  const target = statusTargetKey(s);
3777
3878
  const pending = v.safeParse(statusDeliverySchema, await this.metaIn(tx, `${statusOutboxPrefix}${target}`));
@@ -3814,6 +3915,11 @@ var PullRequestInbox = class {
3814
3915
  key,
3815
3916
  JSON.stringify(value)
3816
3917
  ]);
3918
+ if (key.startsWith(ciEvidencePrefix) && isRuntimeRecord(value) && isRuntimeNumber(value.fetchedAt)) await tx.execute(`INSERT OR REPLACE INTO ${this.tables.meta} (scope, key, value) VALUES (?,?,?)`, [
3919
+ this.scope,
3920
+ ciEvidenceAtPrefix + key.slice(15),
3921
+ JSON.stringify(value.fetchedAt)
3922
+ ]);
3817
3923
  }
3818
3924
  async meta(key) {
3819
3925
  await this.init();
@@ -4208,6 +4314,19 @@ var PullRequestInbox = class {
4208
4314
  const attempt = await this.metaIn(tx, this.directMergeKey(repository, fold.child));
4209
4315
  return isRuntimeRecord(attempt) && attempt.token === fold.token && attempt.foldInto === parent ? fold.child : void 0;
4210
4316
  }
4317
+ /**
4318
+ * A closed child's fold has a known outcome, and its pending-merge path never runs again to clear it.
4319
+ * Retire the attempt with the parent's slot, so a reopened child must win the slot again before it folds.
4320
+ */
4321
+ async retireFoldIn(tx, repository, child) {
4322
+ const key = this.directMergeKey(repository, child);
4323
+ const attempt = await this.metaIn(tx, key);
4324
+ if (!isRuntimeRecord(attempt) || !isRuntimeNumber(attempt.foldInto)) return;
4325
+ await tx.execute(`DELETE FROM ${this.tables.meta} WHERE scope=? AND key=?`, [this.scope, key]);
4326
+ const foldKey = this.stackFoldKey(repository, attempt.foldInto);
4327
+ const fold = await this.metaIn(tx, foldKey);
4328
+ 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]);
4329
+ }
4211
4330
  async foldingChild(repository, parent) {
4212
4331
  await this.init();
4213
4332
  return await this.foldingChildIn({ execute: (statement, args) => this.storage.execute(statement, args) }, repository, parent);
@@ -4427,8 +4546,26 @@ var PullRequestInbox = class {
4427
4546
  isMainRepair(pr) {
4428
4547
  return this.mainRepairBranchPrefix !== void 0 && Boolean(pr?.head?.ref?.startsWith(this.mainRepairBranchPrefix));
4429
4548
  }
4430
- eligible(repository, pr) {
4431
- return Boolean(pr && pr.state === "open" && matchesBabysitterPullRequestFilter(pullRequestFilterContext(repository, pr), this.filter, "pull-request"));
4549
+ /**
4550
+ * Whether the runtime acts on `pr`. With `admitApproved`, a maintainer's approval of the head in
4551
+ * `snapshot` admits an author the filter leaves out. `writers` holds the reviewers whose write
4552
+ * permission the caller verified; without it, the review's association stands in, which only the
4553
+ * inbox's own bookkeeping relies on before a pass checks again.
4554
+ */
4555
+ eligible(repository, pr, snapshot, writers) {
4556
+ if (!pr || pr.state !== "open") return false;
4557
+ const context = pullRequestFilterContext(repository, pr);
4558
+ if (matchesBabysitterPullRequestFilter(context, this.filter, "pull-request")) return true;
4559
+ if (!this.admitApproved || !snapshot || !pr.head?.sha) return false;
4560
+ const { author, authorAssociation } = this.filter ?? {};
4561
+ const denyOnly = {
4562
+ ...this.filter,
4563
+ author: author?.deny ? { deny: author.deny } : void 0,
4564
+ authorAssociation: authorAssociation?.deny ? { deny: authorAssociation.deny } : void 0
4565
+ };
4566
+ if (!matchesBabysitterPullRequestFilter(context, denyOnly, "pull-request")) return false;
4567
+ const approval = maintainerApproval(snapshot, pr.head.sha, writers);
4568
+ return approval.approved && !approval.changesRequested.length;
4432
4569
  }
4433
4570
  async seed(repository, value, signal) {
4434
4571
  repository = repository.toLowerCase();
@@ -4437,7 +4574,7 @@ var PullRequestInbox = class {
4437
4574
  return await this.transaction(async (tx) => {
4438
4575
  const s = await this.getIn(tx, repository, pr.number) ?? this.empty(repository, pr.number);
4439
4576
  if (this.updatePr(s, pr)) this.dirty(s, "bootstrap");
4440
- if (!this.eligible(repository, s.pr)) {
4577
+ if (!this.eligible(repository, s.pr, s)) {
4441
4578
  delete s.wait;
4442
4579
  s.status = "terminal";
4443
4580
  s.handled = s.generation;
@@ -4569,6 +4706,7 @@ var PullRequestInbox = class {
4569
4706
  if (sha && s.pr?.head?.sha && s.pr.head.sha !== sha && !pushRefMatch && !pendingHead) continue;
4570
4707
  let changed = false;
4571
4708
  if (payload.pull_request) changed = this.updatePr(s, payload.pull_request);
4709
+ if (event === "pull_request" && payload.action === "synchronize" && s.hostUpdates?.length) this.settleHostUpdate(s, payload);
4572
4710
  const upsert = (map, value, itemKey) => {
4573
4711
  if (!value) return;
4574
4712
  const key = itemKey ?? String(value.id);
@@ -4696,7 +4834,7 @@ var PullRequestInbox = class {
4696
4834
  else if (changed) s.revision = (s.revision ?? 0) + 1;
4697
4835
  if (changed && human && feedbackEvent) s.humanFeedbackGeneration = s.generation;
4698
4836
  const exhausted = s.progressBudget?.exhausted && s.progressBudget.head === s.pr?.head?.sha;
4699
- const eligible = this.eligible(repository, s.pr);
4837
+ const eligible = this.eligible(repository, s.pr, s);
4700
4838
  if (s.pr && !eligible) {
4701
4839
  delete s.wait;
4702
4840
  s.status = "terminal";
@@ -4755,7 +4893,7 @@ var PullRequestInbox = class {
4755
4893
  const s = await this.getRowIn(tx, candidate);
4756
4894
  options.signal?.throwIfAborted();
4757
4895
  if (!s) continue;
4758
- if (s.pr && !this.eligible(s.repository, s.pr)) continue;
4896
+ if (s.pr && !this.eligible(s.repository, s.pr, s)) continue;
4759
4897
  if (options.only && !options.only(s)) continue;
4760
4898
  if (options.skip && options.skip(s)) continue;
4761
4899
  s.lease = randomUUID();
@@ -4790,7 +4928,7 @@ var PullRequestInbox = class {
4790
4928
  Object.assign(s, patch);
4791
4929
  this.cleanSnapshot(s);
4792
4930
  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";
4931
+ if (s.pr && !this.eligible(s.repository, s.pr, s)) s.status = "terminal";
4794
4932
  await this.put(tx, s);
4795
4933
  Object.assign(claim.snapshot, patch, {
4796
4934
  comments: s.comments,
@@ -4855,8 +4993,12 @@ var PullRequestInbox = class {
4855
4993
  return true;
4856
4994
  });
4857
4995
  }
4858
- /** Retain CI for an exact candidate before its source-push webhook arrives. This is not a publication receipt. */
4859
- async registerProspectivePush(claim, head) {
4996
+ /**
4997
+ * Retain CI for an exact candidate before its source-push webhook arrives. This is not a publication receipt.
4998
+ * With `lineage.hostOnly`, it also records the head as the host's own work on `lineage.parent`, so an
4999
+ * approval of that parent carries over to it.
5000
+ */
5001
+ async registerProspectivePush(claim, head, lineage) {
4860
5002
  invariant(/^[a-f\d]{40}$/i.test(head), "the runtime registers the full commit SHA that the host push returned");
4861
5003
  return await this.transaction(async (tx) => {
4862
5004
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
@@ -4870,11 +5012,47 @@ var PullRequestInbox = class {
4870
5012
  token: claim.token,
4871
5013
  heads
4872
5014
  };
5015
+ if (lineage?.hostOnly && /^[a-f\d]{40}$/i.test(lineage.parent)) this.addHostHead(s, head, lineage.parent);
4873
5016
  s.revision = (s.revision ?? 0) + 1;
4874
5017
  await this.put(tx, s);
4875
5018
  return true;
4876
5019
  });
4877
5020
  }
5021
+ /**
5022
+ * Records that the host asks GitHub to update the PR's branch from `from` with its base, before it sends
5023
+ * the request. GitHub writes the merge commit and the response carries no SHA, so the `synchronize`
5024
+ * delivery that the host's own identity sends from `from` records the new head as the host's work. A
5025
+ * merges API call returns the commit: pass it as `head` to record it at once. Anything but a full commit
5026
+ * SHA records nothing, so the approval does not carry over.
5027
+ */
5028
+ async registerHostUpdate(repository, number, from, head) {
5029
+ if (!/^[a-f\d]{40}$/i.test(from) || head !== void 0 && !/^[a-f\d]{40}$/i.test(head)) return;
5030
+ await this.transaction(async (tx) => {
5031
+ const s = await this.getIn(tx, repository.toLowerCase(), number);
5032
+ if (!s) return;
5033
+ if (head) this.addHostHead(s, head, from);
5034
+ else s.hostUpdates = [...(s.hostUpdates ?? []).filter((entry) => entry !== from), from].slice(-8);
5035
+ await this.put(tx, s);
5036
+ });
5037
+ }
5038
+ addHostHead(s, head, parent) {
5039
+ if (s.hostHeads?.some((entry) => entry.head === head)) return;
5040
+ s.hostHeads = [...s.hostHeads ?? [], {
5041
+ head,
5042
+ parent
5043
+ }].slice(-64);
5044
+ }
5045
+ /**
5046
+ * A webhook head move ends every pending update. Only the host's own move from a registered head carries an
5047
+ * approval. A probe's synthetic `synchronize` has no `before` and leaves the updates for the webhook.
5048
+ */
5049
+ settleHostUpdate(s, payload) {
5050
+ const before = payload.before, after = payload.after ?? payload.pull_request?.head?.sha;
5051
+ if (typeof before !== "string") return;
5052
+ const sender = payload.sender;
5053
+ 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);
5054
+ delete s.hostUpdates;
5055
+ }
4878
5056
  async release(claim) {
4879
5057
  return await this.transaction(async (tx) => {
4880
5058
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
@@ -5313,19 +5491,38 @@ var PullRequestInbox = class {
5313
5491
  const now = this.clock();
5314
5492
  await this.transaction(async (tx) => {
5315
5493
  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]);
5494
+ const meta = this.tables.meta;
5495
+ const unindexed = `scope=? AND ${`key>='${ciEvidencePrefix}' AND key<'ci-evidence:v1;'`} AND NOT EXISTS (SELECT 1 FROM ${meta} WHERE scope=evidence.scope
5496
+ AND key='${ciEvidenceAtPrefix}' || substr(evidence.key, 16))`;
5497
+ await tx.execute(`INSERT INTO ${meta} (scope, key, value) SELECT scope, '${ciEvidenceAtPrefix}' || substr(key, 16),
5498
+ json_extract(value, '$.fetchedAt') FROM ${meta} AS evidence WHERE ${unindexed} AND json_valid(value) AND json_type(value)='object'
5499
+ AND json_type(value, '$.fetchedAt') IN ('integer', 'real')`, [this.scope]);
5500
+ await tx.execute(`DELETE FROM ${meta} AS evidence WHERE ${unindexed}`, [this.scope]);
5501
+ const expiredAt = `key>='${ciEvidenceAtPrefix}' AND key<'ci-evidence-at:v1;' AND CAST(value AS REAL)<?`;
5502
+ await tx.execute(`DELETE FROM ${meta} WHERE scope=? AND key IN (SELECT '${ciEvidencePrefix}' || substr(key, 19)
5503
+ FROM ${meta} WHERE scope=? AND ${expiredAt})`, [
5504
+ this.scope,
5505
+ this.scope,
5506
+ now - payloadMs
5507
+ ]);
5508
+ await tx.execute(`DELETE FROM ${meta} WHERE scope=? AND ${expiredAt}`, [this.scope, now - payloadMs]);
5319
5509
  signal?.throwIfAborted();
5320
5510
  await tx.execute(`DELETE FROM ${this.tables.deliveries} WHERE scope=? AND received<?`, [this.scope, now - idMs]);
5321
5511
  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]);
5512
+ const cutoff = now - payloadMs;
5513
+ const prunedBefore = await this.metaIn(tx, "deliveries-payload-pruned-before");
5514
+ const from = isRuntimeNumber(prunedBefore) && prunedBefore <= cutoff ? prunedBefore : 0;
5515
+ await tx.execute(`UPDATE ${this.tables.deliveries} SET payload=NULL WHERE scope=? AND received>=? AND received<? AND payload IS NOT NULL`, [
5516
+ this.scope,
5517
+ from,
5518
+ cutoff
5519
+ ]);
5520
+ await this.setMetaIn(tx, "deliveries-payload-pruned-before", cutoff);
5323
5521
  signal?.throwIfAborted();
5324
5522
  });
5325
5523
  }
5326
5524
  };
5327
- //#endregion
5328
- //#region src/babysitter/inbox/snapshot-prompt.ts
5525
+ // src/babysitter/inbox/snapshot-prompt.ts
5329
5526
  const author = (value) => ({
5330
5527
  login: value.user?.login ?? value.author?.login ?? null,
5331
5528
  type: value.user?.type ?? value.author?.__typename ?? "unknown"
@@ -5518,8 +5715,7 @@ function assertPromptFits(message, limit = 95e4) {
5518
5715
  limit
5519
5716
  });
5520
5717
  }
5521
- //#endregion
5522
- //#region src/babysitter/inbox/claim-state.ts
5718
+ // src/babysitter/inbox/claim-state.ts
5523
5719
  /** REST fields are authoritative; older persisted GraphQL aliases may be stale. */
5524
5720
  function snapshotPullRequest(snapshot) {
5525
5721
  const pr = snapshot.pr;
@@ -5549,35 +5745,35 @@ function snapshotPullRequest(snapshot) {
5549
5745
  labels: (pr.labels ?? []).map((label) => hasRuntimeType(label, "string") ? { name: label } : label)
5550
5746
  };
5551
5747
  }
5552
- function claimStopReason(claim, current, acceptedSelfHead) {
5553
- if (!current || current.lease !== claim.token || current.leaseUntil <= Date.now()) return "Pull request lease lost.";
5748
+ /** `now` comes from the inbox clock (`PullRequestInbox.now()`), the clock that wrote `leaseUntil`. */
5749
+ function claimStopReason(claim, current, acceptedSelfHead, now = Date.now()) {
5750
+ if (!current || current.lease !== claim.token || current.leaseUntil <= now) return "Pull request lease lost.";
5554
5751
  if (current.status === "terminal" || current.pr?.state === "closed") return "Pull request is no longer open.";
5555
5752
  const expectedHead = claim.snapshot.pr?.head?.sha;
5556
5753
  if (current.pr?.head?.sha !== (acceptedSelfHead ?? expectedHead)) return "Pull request head changed.";
5557
5754
  }
5558
5755
  /** A new remote head may be our repair; prove it against the actual provider Git HEAD. */
5559
- function createClaimStopCheck(claim, readCurrent, readProviderHead) {
5756
+ function createClaimStopCheck(claim, readCurrent, readProviderHead, now = Date.now) {
5560
5757
  let acceptedSelfHead;
5561
5758
  return async () => {
5562
5759
  const observed = await readCurrent();
5563
- const reason = claimStopReason(claim, observed, acceptedSelfHead);
5760
+ const reason = claimStopReason(claim, observed, acceptedSelfHead, now());
5564
5761
  if (reason !== "Pull request head changed.") return reason;
5565
5762
  if (acceptedSelfHead && observed?.pr?.head?.sha === claim.snapshot.pr?.head?.sha) return reason;
5566
5763
  let providerHead;
5567
5764
  try {
5568
5765
  providerHead = await readProviderHead();
5569
5766
  } catch {
5570
- return claimStopReason(claim, await readCurrent(), acceptedSelfHead);
5767
+ return claimStopReason(claim, await readCurrent(), acceptedSelfHead, now());
5571
5768
  }
5572
5769
  const current = await readCurrent();
5573
- const latestReason = claimStopReason(claim, current, acceptedSelfHead);
5770
+ const latestReason = claimStopReason(claim, current, acceptedSelfHead, now());
5574
5771
  if (latestReason !== "Pull request head changed.") return latestReason;
5575
5772
  if (!providerHead || current?.pr?.head?.sha !== providerHead) return latestReason;
5576
5773
  acceptedSelfHead = providerHead;
5577
5774
  };
5578
5775
  }
5579
- //#endregion
5580
- //#region src/babysitter/inbox/snapshot-sync.ts
5776
+ // src/babysitter/inbox/snapshot-sync.ts
5581
5777
  /** Read review conversations through forges `threads.reviewThreads()`. */
5582
5778
  async function readForgePullRequestThreads(provider, repository, number, signal) {
5583
5779
  const repo = repoRef(provider, repository);
@@ -5858,6 +6054,7 @@ const openPullRequestSchema = v.object({
5858
6054
  latestReviews: nodes,
5859
6055
  reviewThreads: nodes
5860
6056
  });
6057
+ const approvedReview = v.object({ state: v.literal("APPROVED") });
5861
6058
  const openPullRequestsSchema = v.object({ repository: v.object({ pullRequests: v.object({
5862
6059
  nodes: v.array(openPullRequestSchema),
5863
6060
  pageInfo: v.object({
@@ -5963,7 +6160,7 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5963
6160
  }
5964
6161
  signal?.throwIfAborted();
5965
6162
  if (!allowSeed) continue;
5966
- await inbox.seed(repository, {
6163
+ const seeded = await inbox.seed(repository, {
5967
6164
  number,
5968
6165
  title: pr.title,
5969
6166
  state: "open",
@@ -5984,7 +6181,8 @@ async function detectChangedPullRequests(inbox, graphql, repositories, now = Dat
5984
6181
  }
5985
6182
  }, signal);
5986
6183
  signal?.throwIfAborted();
5987
- await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint, signal);
6184
+ if (seeded.status === "terminal" && inbox.admitApproved && pr.latestReviews.nodes.some((review) => v.is(approvedReview, review))) await mark(number, fingerprint, openPullRequestChecksSettled(pr));
6185
+ else await inbox.setMeta(`change-fingerprint:${repository}:${number}`, fingerprint, signal);
5988
6186
  }
5989
6187
  for (const item of tracked) if (item.repository === repository && item.status !== "terminal" && !open.has(item.number)) await mark(item.number, "closed", true);
5990
6188
  } catch (error) {
@@ -6043,8 +6241,7 @@ async function probeChangedSnapshots(inbox, read, now = Date.now(), readThreads,
6043
6241
  }
6044
6242
  return probed;
6045
6243
  }
6046
- //#endregion
6047
- //#region src/babysitter/box-commit.ts
6244
+ // src/babysitter/box-commit.ts
6048
6245
  /** Import committed Sandbox work before the host publishes it with host-owned credentials. */
6049
6246
  async function importSandboxCommit(session, checkout, base, signal) {
6050
6247
  const git = async (args) => {
@@ -6138,8 +6335,7 @@ async function importSandboxCommit(session, checkout, base, signal) {
6138
6335
  await session.files.remove(remoteBundle, { signal }).catch(() => {});
6139
6336
  }
6140
6337
  }
6141
- //#endregion
6142
- //#region src/babysitter/checkout-watch.ts
6338
+ // src/babysitter/checkout-watch.ts
6143
6339
  const exec$1 = promisify(execFile);
6144
6340
  /** Read host checkout proof when a synchronize event changes the claimed head. */
6145
6341
  function createProviderHeadReader(providerDirectory, pushedHead) {
@@ -6158,8 +6354,7 @@ function createProviderHeadReader(providerDirectory, pushedHead) {
6158
6354
  })).stdout.trim();
6159
6355
  };
6160
6356
  }
6161
- //#endregion
6162
- //#region src/babysitter/box-repair.ts
6357
+ // src/babysitter/box-repair.ts
6163
6358
  const exec = promisify(execFile);
6164
6359
  const inside = (root, path) => {
6165
6360
  const part = relative(root, path);
@@ -6315,8 +6510,7 @@ async function publishSandboxDependencies(session, checkout, signal) {
6315
6510
  await session.files.remove(remote, { signal }).catch(() => {});
6316
6511
  }
6317
6512
  }
6318
- //#endregion
6319
- //#region src/babysitter/feedback.ts
6513
+ // src/babysitter/feedback.ts
6320
6514
  const feedbackInputSchema = v.strictObject({
6321
6515
  kind: v.picklist([
6322
6516
  "comment",
@@ -6379,8 +6573,7 @@ function readBabysitterFeedback(snapshot, input) {
6379
6573
  }
6380
6574
  };
6381
6575
  }
6382
- //#endregion
6383
- //#region src/babysitter/repair.ts
6576
+ // src/babysitter/repair.ts
6384
6577
  const noArguments = {
6385
6578
  type: "object",
6386
6579
  properties: {},
@@ -6721,8 +6914,7 @@ function repairEnvironment(environment = {}, githubConfigDirectory, identity = {
6721
6914
  GIT_TERMINAL_PROMPT: "0"
6722
6915
  };
6723
6916
  }
6724
- //#endregion
6725
- //#region src/babysitter/wait.ts
6917
+ // src/babysitter/wait.ts
6726
6918
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
6727
6919
  const pending = /* @__PURE__ */ new Set([
6728
6920
  "queued",
@@ -7059,8 +7251,7 @@ function checksDependencyEvidence(checks) {
7059
7251
  ])).sort()
7060
7252
  });
7061
7253
  }
7062
- //#endregion
7063
- //#region src/babysitter/provider-quota.ts
7254
+ // src/babysitter/provider-quota.ts
7064
7255
  const providerBlockedKey = "provider-quota-blocked-until";
7065
7256
  const providerStrikesKey = "provider-quota-strikes";
7066
7257
  const forgeBlockedKey = "forge-quota-blocked-until";
@@ -7124,8 +7315,7 @@ function createForgeQuota(store, now = Date.now) {
7124
7315
  }
7125
7316
  };
7126
7317
  }
7127
- //#endregion
7128
- //#region src/babysitter/base-freshness.ts
7318
+ // src/babysitter/base-freshness.ts
7129
7319
  /** Files the comparison may list before it counts as truncated. GitHub caps this at 300. */
7130
7320
  const compareFileLimit = 300;
7131
7321
  /** Pushes this close to the run start may not be in the run's checkout. */
@@ -7238,8 +7428,7 @@ async function baseFixedSinceFailure(reader, snapshot, failed, signal) {
7238
7428
  for (const value of baseStatuses) if (isRuntimeRecord(value) && hasRuntimeType(value.context, "string") && hasRuntimeType(value.state, "string") && !latestStatuses.has(value.context)) latestStatuses.set(value.context, value.state);
7239
7429
  return baseChecks.some((check) => isRuntimeRecord(check) && !isBabysitterCheckRun(check) && failing.has(String(check.name)) && hasRuntimeType(check.conclusion, "string") && failedSet.has(check.conclusion.toLowerCase())) || [...latestStatuses].some(([context, value]) => failing.has(context) && failedSet.has(value.toLowerCase())) ? void 0 : compare.ahead_by;
7240
7430
  }
7241
- //#endregion
7242
- //#region src/babysitter/ci-attribution.ts
7431
+ // src/babysitter/ci-attribution.ts
7243
7432
  const strip = (line) => stripVTControlCharacters(line.replace(/^\S+Z /, ""));
7244
7433
  /** Undefined when no step exited with an error code. */
7245
7434
  function parseFailedActionOutput(log) {
@@ -7440,8 +7629,7 @@ function inheritedBypassSafety({ protection, rules, reviewDecision, threadsResol
7440
7629
  if (strict && !upToDate) return "branch must be up to date";
7441
7630
  return true;
7442
7631
  }
7443
- //#endregion
7444
- //#region src/babysitter/stack.ts
7632
+ // src/babysitter/stack.ts
7445
7633
  const field = (value, ...path) => {
7446
7634
  let current = value;
7447
7635
  for (const key of path) current = isRuntimeRecord(current) ? current[key] : void 0;
@@ -7578,8 +7766,7 @@ function branchFilter(pattern) {
7578
7766
  }
7579
7767
  return new RegExp(`^${source}$`);
7580
7768
  }
7581
- //#endregion
7582
- //#region src/babysitter/merge-ready.ts
7769
+ // src/babysitter/merge-ready.ts
7583
7770
  /** Fence application callbacks so stalled or rejected readiness never retains a scheduler slot. */
7584
7771
  async function boundedMergeReady(ready, signal, timeoutMs = 5e3) {
7585
7772
  if (signal?.aborted) return "merge readiness cancelled";
@@ -7595,8 +7782,7 @@ async function boundedMergeReady(ready, signal, timeoutMs = 5e3) {
7595
7782
  Promise.resolve().then(ready).then((result) => finish(result === true ? true : hasRuntimeType(result, "string") ? result : "merge readiness declined"), () => finish("merge readiness check failed"));
7596
7783
  });
7597
7784
  }
7598
- //#endregion
7599
- //#region src/babysitter/install.ts
7785
+ // src/babysitter/install.ts
7600
7786
  const execFileAsync = promisify(execFile);
7601
7787
  const environmentNames = /^(?:PATH|HOME|USER|LOGNAME|LANG|LC_[A-Z]+|TMPDIR|TERM|SHELL|COREPACK_[A-Z_]+|npm_config_[a-z_]+|PNPM_HOME)$/;
7602
7788
  const exists = (path) => access(path).then(() => true, () => false);
@@ -7923,8 +8109,7 @@ function createBabysitterInstaller(install, env = process.env, repository) {
7923
8109
  };
7924
8110
  };
7925
8111
  }
7926
- //#endregion
7927
- //#region src/babysitter/ci-recovery.ts
8112
+ // src/babysitter/ci-recovery.ts
7928
8113
  function hasFailedActions(snapshot) {
7929
8114
  const head = snapshot.pr?.head?.sha;
7930
8115
  return Boolean(head && Object.values(snapshot.checks).some((check) => failed$1(check) && check.head_sha === head && actionLocation(snapshot.repository, check)?.runId));
@@ -8061,8 +8246,7 @@ async function rerunFailedActions(inbox, claim, forge, now = Date.now(), signal)
8061
8246
  reason: blocked.map((run) => `Actions run ${run.runId}: ${run.reason}`).join("; ")
8062
8247
  };
8063
8248
  }
8064
- //#endregion
8065
- //#region src/babysitter/status-recovery.ts
8249
+ // src/babysitter/status-recovery.ts
8066
8250
  function isWorkerBlocker(snapshot) {
8067
8251
  if (snapshot.wait?.kind !== "external" || snapshot.wait.wake || snapshot.wait.retryAt !== void 0) return false;
8068
8252
  const text = `${snapshot.wait.reason}\n${snapshot.lastResult ?? ""}`;
@@ -8175,8 +8359,7 @@ function createBabysitterStatusRecovery(options) {
8175
8359
  }
8176
8360
  };
8177
8361
  }
8178
- //#endregion
8179
- //#region src/babysitter/transient.ts
8362
+ // src/babysitter/transient.ts
8180
8363
  const transientStatuses = /* @__PURE__ */ new Set([
8181
8364
  502,
8182
8365
  503,
@@ -8212,8 +8395,7 @@ async function retryTransient(read, signal) {
8212
8395
  }
8213
8396
  }
8214
8397
  }
8215
- //#endregion
8216
- //#region src/babysitter/queue-health.ts
8398
+ // src/babysitter/queue-health.ts
8217
8399
  /** Derive bounded operational counters from the durable queue, including scheduled retries. */
8218
8400
  function babysitterQueueHealth(items, now = Date.now()) {
8219
8401
  const mergedTerminal = (result) => result?.startsWith("Merged ") || result === "Asynchronous merge confirmed by GitHub." || result === "Direct merge outcome reconciled: GitHub reports the pull request merged.";
@@ -8237,8 +8419,7 @@ function babysitterQueueHealth(items, now = Date.now()) {
8237
8419
  }
8238
8420
  };
8239
8421
  }
8240
- //#endregion
8241
- //#region src/babysitter/main-repair.ts
8422
+ // src/babysitter/main-repair.ts
8242
8423
  const defaultStuckJobMinutes = 90;
8243
8424
  const branchSchema = v.looseObject({
8244
8425
  name: v.string(),
@@ -8268,6 +8449,8 @@ const jobsSchema = v.looseObject({ jobs: v.array(v.looseObject({
8268
8449
  const pullsSchema = v.array(v.looseObject({
8269
8450
  number: v.number(),
8270
8451
  merged_at: v.nullish(v.string()),
8452
+ title: v.optional(v.string()),
8453
+ user: v.nullish(v.looseObject({ login: v.string() })),
8271
8454
  head: v.looseObject({
8272
8455
  ref: v.string(),
8273
8456
  repo: v.nullish(v.looseObject({ full_name: v.string() }))
@@ -8314,6 +8497,12 @@ async function repairBaseBranch(github, options) {
8314
8497
  const base = v.parse(repositorySchema, await github.read(`repos/${repository}`)).default_branch;
8315
8498
  const tip = v.parse(branchSchema, await github.read(`repos/${repository}/branches/${encodeURIComponent(base)}`));
8316
8499
  const head = tip.commit.sha;
8500
+ const repairTitle = (shortSha) => `fix: repair ${base} after ${shortSha}`;
8501
+ const repairAuthor = options.repairAuthor?.toLowerCase();
8502
+ const ownedRepairPull = (pull) => {
8503
+ const shortSha = pull.head.ref.slice(branchPrefix.length);
8504
+ return repairAuthor !== void 0 && pull.user?.login.toLowerCase() === repairAuthor && /^[0-9a-f]{8}$/.test(shortSha) && pull.title === repairTitle(shortSha);
8505
+ };
8317
8506
  const stuckJobMinutes = mainRepair.stuckJobMinutes ?? defaultStuckJobMinutes;
8318
8507
  if (stuckJobMinutes !== false) {
8319
8508
  const running = v.parse(runsSchema, await github.read(`repos/${repository}/actions/runs`, {
@@ -8367,6 +8556,18 @@ async function repairBaseBranch(github, options) {
8367
8556
  })).workflow_runs.filter((run) => watched(run) && !["cancelled", "skipped"].includes(run.conclusion ?? "") && Date.parse(run.created_at) > repairedAt);
8368
8557
  failed = mainRepair.workflows.flatMap((name) => finished.find((run) => run.name === name) ?? []).find((run) => run.conclusion === "failure");
8369
8558
  }
8559
+ async function* openRepairs() {
8560
+ for (let page = 1;; page++) {
8561
+ const pulls = v.parse(pullsSchema, await github.read(`repos/${repository}/pulls`, {
8562
+ state: "open",
8563
+ base,
8564
+ per_page: 100,
8565
+ page
8566
+ }));
8567
+ yield* pulls.filter(repairPull);
8568
+ if (pulls.length < 100) return;
8569
+ }
8570
+ }
8370
8571
  if (!failed) {
8371
8572
  if (!runs.length || runs.some((run) => run.status !== "completed")) {
8372
8573
  event("waiting", {
@@ -8379,18 +8580,30 @@ async function repairBaseBranch(github, options) {
8379
8580
  reason: runs.length ? "ci-running" : "no-ci-run"
8380
8581
  };
8381
8582
  }
8382
- event("green", { head });
8383
- return {
8583
+ const tipPassed = runs.every((run) => run.conclusion === "success") && mainRepair.workflows.every((name) => runs.some((run) => run.name === name));
8584
+ const stale = [];
8585
+ if (tipPassed && repairAuthor) {
8586
+ for await (const pull of openRepairs()) if (ownedRepairPull(pull)) stale.push(pull);
8587
+ }
8588
+ for (const pull of stale) {
8589
+ await github.write(`repos/${repository}/issues/${pull.number}/comments`, { body: `${base} is green at ${head}, so this repair is no longer needed. Closed by the Babysitter.` });
8590
+ await github.write(`repos/${repository}/pulls/${pull.number}`, { state: "closed" }, "PATCH");
8591
+ }
8592
+ const closed = stale.map((pull) => pull.number);
8593
+ event("green", {
8594
+ head,
8595
+ ...closed.length ? { closed } : {}
8596
+ });
8597
+ return closed.length ? {
8598
+ state: "green",
8599
+ head,
8600
+ closed
8601
+ } : {
8384
8602
  state: "green",
8385
8603
  head
8386
8604
  };
8387
8605
  }
8388
- const open = v.parse(pullsSchema, await github.read(`repos/${repository}/pulls`, {
8389
- state: "open",
8390
- base,
8391
- per_page: 100
8392
- })).find(repairPull);
8393
- if (open) {
8606
+ for await (const open of openRepairs()) {
8394
8607
  event("repair_open", {
8395
8608
  head,
8396
8609
  pull_request: open.number
@@ -8445,7 +8658,7 @@ Opened automatically by the Babysitter.`;
8445
8658
  });
8446
8659
  }
8447
8660
  const pull = v.parse(pullSchema, await github.write(`repos/${repository}/pulls`, {
8448
- title: `fix: repair ${base} after ${red.slice(0, 8)}`,
8661
+ title: repairTitle(red.slice(0, 8)),
8449
8662
  head: branch,
8450
8663
  base,
8451
8664
  body
@@ -8466,8 +8679,7 @@ Opened automatically by the Babysitter.`;
8466
8679
  jobs: jobs.map((job) => job.name)
8467
8680
  };
8468
8681
  }
8469
- //#endregion
8470
- //#region src/babysitter/server.ts
8682
+ // src/babysitter/server.ts
8471
8683
  /** The first and the longest wait before a reviewed head's merge gates are checked again. */
8472
8684
  const mergeRetryMinMs = 12e4;
8473
8685
  const mergeRetryMaxMs = 18e5;
@@ -8525,6 +8737,7 @@ function createBabysitterRuntime(options) {
8525
8737
  assertBabysitterAgent(baseAgent);
8526
8738
  const presetOptions = baseAgent.options;
8527
8739
  const filter = resolveBabysitterLifecycleFilter(presetOptions.filter, presetOptions.lifecycle);
8740
+ const approvalAdmission = presetOptions.lifecycle?.approval === true;
8528
8741
  const merge = resolveBabysitterMerge(presetOptions.merge);
8529
8742
  const github = options.github;
8530
8743
  const hostIdentity = github.identity()?.trim();
@@ -8547,6 +8760,7 @@ function createBabysitterRuntime(options) {
8547
8760
  } : { path: options.inboxPath },
8548
8761
  repositories: () => repositorySource.known(),
8549
8762
  filter,
8763
+ admitApproved: approvalAdmission,
8550
8764
  activityAuthors,
8551
8765
  activityAppId: verifiedHostIdentity ? github.appId?.() : void 0,
8552
8766
  budgets: {
@@ -8609,7 +8823,7 @@ function createBabysitterRuntime(options) {
8609
8823
  ignoreAssessedBotThreads: presetOptions.ignoreAssessedBotThreads === true
8610
8824
  };
8611
8825
  const schedulerEvent = (name, properties = {}) => options.event?.(name, properties);
8612
- const release = baseAgent.version ?? "91ca93f60843c0df231a3f438cf1c2ef1587bfc67b8791323ef4f38cc44ca863";
8826
+ const release = baseAgent.version ?? "fe995c180e0431214d6624fa86644133bbb7a46e97d1011eaee87cde7a1d063f";
8613
8827
  const workspaces = options.workspaces;
8614
8828
  const schedulerError = (name, error, properties = {}) => options.error?.(name, error, properties);
8615
8829
  const statusComment = !!verifiedHostIdentity && presetOptions.status?.comment !== false;
@@ -8725,6 +8939,44 @@ function createBabysitterRuntime(options) {
8725
8939
  const { provider } = await forge(path.split("/").slice(1, 3).join("/"), signal);
8726
8940
  return (await retryTransient(() => provider.request("GET", `/${path}`, { signal }), signal)).data;
8727
8941
  }
8942
+ const writerAnswers = /* @__PURE__ */ new Map();
8943
+ /**
8944
+ * The reviewers that approval counts as maintainers: those whose association claims write access and
8945
+ * whose repository permission confirms it. An organization member with read access is `MEMBER` too.
8946
+ * Each answer stays for ten minutes.
8947
+ */
8948
+ async function verifiedWriters(snapshot, signal) {
8949
+ const repository = snapshot.repository.toLowerCase();
8950
+ const writers = /* @__PURE__ */ new Set();
8951
+ for (const login of approvalReviewers(snapshot)) {
8952
+ const key = `${repository}:${login}`;
8953
+ let answer = writerAnswers.get(key);
8954
+ if (!answer || answer.at < Date.now() - 6e5) {
8955
+ const permission = await readOnePage(`repos/${repository}/collaborators/${encodeURIComponent(login)}/permission`, signal).catch((error) => {
8956
+ if (forgeErrorStatus(error) === 404) return void 0;
8957
+ throw error;
8958
+ });
8959
+ answer = {
8960
+ writer: isRuntimeRecord(permission) && [
8961
+ "admin",
8962
+ "maintain",
8963
+ "write"
8964
+ ].includes(String(permission.permission)),
8965
+ at: Date.now()
8966
+ };
8967
+ if (writerAnswers.size > 1e3) writerAnswers.clear();
8968
+ writerAnswers.set(key, answer);
8969
+ }
8970
+ if (answer.writer) writers.add(login);
8971
+ }
8972
+ return writers;
8973
+ }
8974
+ /** `eligible()` with the approval evidence that admits a PR through `lifecycle.approval`. */
8975
+ async function eligibleNow(repository, pr, snapshot, signal) {
8976
+ if (pullRequestInbox.eligible(repository, pr)) return true;
8977
+ if (!approvalAdmission || !snapshot) return false;
8978
+ return pullRequestInbox.eligible(repository, pr, snapshot, await verifiedWriters(snapshot, signal));
8979
+ }
8728
8980
  const freshnessReader = {
8729
8981
  rest: (path, signal, key) => readRest(path, key ? `.${key}[]` : ".[]", signal),
8730
8982
  page: readOnePage
@@ -8750,9 +9002,9 @@ function createBabysitterRuntime(options) {
8750
9002
  throw error;
8751
9003
  }
8752
9004
  },
8753
- async write(path, body) {
9005
+ async write(path, body, method = "POST") {
8754
9006
  const { provider } = await forge(repository, signal);
8755
- return (await provider.request("POST", `/${path}`, {
9007
+ return (await provider.request(method, `/${path}`, {
8756
9008
  body,
8757
9009
  signal
8758
9010
  })).data;
@@ -8772,6 +9024,7 @@ function createBabysitterRuntime(options) {
8772
9024
  track(repairBaseBranch(mainRepairGitHub(repository, AbortSignal.timeout(3e5)), {
8773
9025
  repository,
8774
9026
  branchPrefix: mainRepairPrefix,
9027
+ repairAuthor: verifiedHostIdentity,
8775
9028
  mainRepair,
8776
9029
  event: schedulerEvent
8777
9030
  }).catch(async (error) => {
@@ -8837,6 +9090,7 @@ function createBabysitterRuntime(options) {
8837
9090
  */
8838
9091
  async function updateBranch(owner, repository, number, head, signal, pr, { reopenFork = true } = {}) {
8839
9092
  if (reopenFork && isForkHead(pr, repository)) return await reopenForkPullRequest(owner, repository, number, head, signal);
9093
+ if (approvalAdmission) await pullRequestInbox.registerHostUpdate(repository, number, head);
8840
9094
  try {
8841
9095
  const { provider } = await forge(repository, signal);
8842
9096
  await provider.request("PUT", `/repos/${repository}/pulls/${number}/update-branch`, {
@@ -8864,14 +9118,16 @@ function createBabysitterRuntime(options) {
8864
9118
  });
8865
9119
  return false;
8866
9120
  }
8867
- await provider.request("POST", `/repos/${repository}/merges`, {
9121
+ const merged = (await provider.request("POST", `/repos/${repository}/merges`, {
8868
9122
  body: {
8869
9123
  base: branches.head,
8870
9124
  head: branches.base,
8871
9125
  commit_message: `Merge ${branches.base} into ${branches.head}`
8872
9126
  },
8873
9127
  signal
8874
- });
9128
+ })).data;
9129
+ const parent = isRuntimeRecord(merged) && Array.isArray(merged.parents) && isRuntimeRecord(merged.parents[0]) ? merged.parents[0].sha : void 0;
9130
+ 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
9131
  return true;
8876
9132
  } catch (fallback) {
8877
9133
  await noteForgeQuota(fallback, "merge-base-into-head");
@@ -8943,6 +9199,7 @@ function createBabysitterRuntime(options) {
8943
9199
  const { provider } = await forge(repository, new AbortController().signal);
8944
9200
  await provider.request("PATCH", `/repos/${repository}/pulls/${number}`, { body: { state: "open" } });
8945
9201
  }
9202
+ const closeClockMarginMs = 6e4;
8946
9203
  const forkReopenKey = (repository, number) => `fork-reopen:${repository}#${number}`;
8947
9204
  /**
8948
9205
  * Finishes a close and reopen that a restart or a GitHub error interrupted. A PR that is still closed
@@ -8963,7 +9220,7 @@ function createBabysitterRuntime(options) {
8963
9220
  const issue = (await provider.request("GET", `/repos/${repository}/issues/${number}`, { signal })).data;
8964
9221
  if (!isRuntimeRecord(issue)) continue;
8965
9222
  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;
9223
+ 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
9224
  const merged = isRuntimeRecord(issue.pull_request) && issue.pull_request.merged_at != null;
8968
9225
  if (ours && !merged) {
8969
9226
  await reopenPullRequest(repository, Number(number));
@@ -9447,7 +9704,7 @@ function createBabysitterRuntime(options) {
9447
9704
  }
9448
9705
  function cancelWhenPullRequestStops(claim, controller, providerDirectory, pushedHead) {
9449
9706
  let stopped = false, polling = false;
9450
- const check = createClaimStopCheck(claim, () => pullRequestInbox.get(claim.snapshot.repository, claim.snapshot.number), createProviderHeadReader(providerDirectory, pushedHead));
9707
+ const check = createClaimStopCheck(claim, () => pullRequestInbox.get(claim.snapshot.repository, claim.snapshot.number), createProviderHeadReader(providerDirectory, pushedHead), () => pullRequestInbox.now());
9451
9708
  const poll = async () => {
9452
9709
  if (stopped || polling || controller.signal.aborted) return;
9453
9710
  polling = true;
@@ -9577,9 +9834,9 @@ function createBabysitterRuntime(options) {
9577
9834
  });
9578
9835
  return "blocked";
9579
9836
  }
9580
- const age = Date.now() - pending.startedAt;
9837
+ const age = pullRequestInbox.now() - pending.startedAt;
9581
9838
  if (pending.asynchronous && age >= pendingMergeDeadlineMs) {
9582
- const until = Date.now() + stoppedMergeRetryMs;
9839
+ const until = pullRequestInbox.now() + stoppedMergeRetryMs;
9583
9840
  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
9841
  await pullRequestInbox.setMeta(stoppedKey, {
9585
9842
  head: pending.head,
@@ -9632,12 +9889,14 @@ function createBabysitterRuntime(options) {
9632
9889
  if (decision.ready && merge.ready) {
9633
9890
  const callback = merge.ready;
9634
9891
  const head = decision.head;
9892
+ const writers = await verifiedWriters(snapshot, signal);
9635
9893
  const ready = await boundedMergeReady(() => callback({
9636
9894
  repository,
9637
9895
  number,
9638
9896
  head,
9639
9897
  snapshot: structuredClone(snapshot),
9640
- requiredChecks: evaluation.state
9898
+ requiredChecks: evaluation.state,
9899
+ writers
9641
9900
  }), signal);
9642
9901
  if (signal.aborted) return "blocked";
9643
9902
  if (ready !== true) decision = {
@@ -9653,7 +9912,7 @@ function createBabysitterRuntime(options) {
9653
9912
  return pending?.asynchronous ? await parkMerge(`Unconfirmed merge is waiting for ${decision.reason}.`) : "not-ready";
9654
9913
  }
9655
9914
  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);
9915
+ 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
9916
  const folding = pending ? void 0 : await pullRequestInbox.foldingChild(repository, number);
9658
9917
  if (folding !== void 0) return await parkMerge(`Waiting for the merge of stacked pull request #${folding} into this branch.`);
9659
9918
  let mergeStarted = false;
@@ -10183,12 +10442,14 @@ function createBabysitterRuntime(options) {
10183
10442
  if (!head) return false;
10184
10443
  const callback = merge.ready;
10185
10444
  try {
10445
+ const writers = await verifiedWriters(snapshot);
10186
10446
  return await boundedMergeReady(() => callback({
10187
10447
  repository: snapshot.repository,
10188
10448
  number: snapshot.number,
10189
10449
  head,
10190
10450
  snapshot: structuredClone(snapshot),
10191
- requiredChecks
10451
+ requiredChecks,
10452
+ writers
10192
10453
  })) === true;
10193
10454
  } catch (error) {
10194
10455
  schedulerEvent("babysitter.direct_merge.skipped", {
@@ -10431,6 +10692,33 @@ function createBabysitterRuntime(options) {
10431
10692
  }
10432
10693
  const hostOnlyChecked = /* @__PURE__ */ new Map();
10433
10694
  const hostOnlyStamp = (s) => `${s.generation}:${s.revision ?? 0}`;
10695
+ const createdAt = Date.now();
10696
+ let runningTick;
10697
+ let lastFinishedAt;
10698
+ let lastStall;
10699
+ let stallsInRow = 0;
10700
+ function scheduler(accepting = true) {
10701
+ const now = Date.now();
10702
+ const iso = (time) => new Date(time).toISOString();
10703
+ const silent = accepting && now - (lastFinishedAt ?? createdAt) > stallMs + 6e4;
10704
+ return {
10705
+ status: stallsInRow ? "stalled" : silent ? "silent" : "ok",
10706
+ ...runningTick ? { running: {
10707
+ reason: runningTick.reason,
10708
+ step: runningTick.step,
10709
+ ...runningTick.subject ? { subject: runningTick.subject } : {},
10710
+ startedAt: iso(runningTick.startedAt),
10711
+ stepAt: iso(runningTick.stepAt)
10712
+ } } : {},
10713
+ ...lastFinishedAt ? { lastFinishedAt: iso(lastFinishedAt) } : {},
10714
+ ...lastStall ? { lastStall: {
10715
+ at: iso(lastStall.at),
10716
+ step: lastStall.step,
10717
+ ...lastStall.subject ? { subject: lastStall.subject } : {},
10718
+ count: lastStall.count
10719
+ } } : {}
10720
+ };
10721
+ }
10434
10722
  async function stallSnapshot(tick) {
10435
10723
  const now = Date.now();
10436
10724
  const snapshot = {
@@ -10484,6 +10772,14 @@ function createBabysitterRuntime(options) {
10484
10772
  let timer;
10485
10773
  const stalled = new Promise((_resolve, reject) => {
10486
10774
  timer = setTimeout(() => {
10775
+ stallsInRow += 1;
10776
+ lastStall = {
10777
+ at: Date.now(),
10778
+ step: tick.step,
10779
+ ...tick.subject ? { subject: tick.subject } : {},
10780
+ count: stallsInRow
10781
+ };
10782
+ if (runningTick === tick) runningTick = void 0;
10487
10783
  const error = presetsErrorDiagnostics.PRESETS_BABYSITTER_RECONCILE_STALLED({
10488
10784
  step: tick.subject ? `${tick.step} (${tick.subject})` : tick.step,
10489
10785
  minutes: Math.round((Date.now() - startedAt) / 6e4)
@@ -10494,10 +10790,16 @@ function createBabysitterRuntime(options) {
10494
10790
  }, stallMs);
10495
10791
  timer.unref?.();
10496
10792
  });
10793
+ runningTick = tick;
10497
10794
  try {
10498
10795
  await Promise.race([reconcileTick(reason, context, isAccepting, step, signal), stalled]);
10499
10796
  } finally {
10500
10797
  clearTimeout(timer);
10798
+ if (!signal.aborted) {
10799
+ lastFinishedAt = Date.now();
10800
+ stallsInRow = 0;
10801
+ if (runningTick === tick) runningTick = void 0;
10802
+ }
10501
10803
  }
10502
10804
  }
10503
10805
  async function reconcileTick(reason, { track }, isAccepting, step, signal) {
@@ -10604,7 +10906,7 @@ function createBabysitterRuntime(options) {
10604
10906
  });
10605
10907
  step("snapshot-detect");
10606
10908
  try {
10607
- await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository, signal), repositories, Date.now(), !eventScopedBootstrap, (repository, error) => {
10909
+ await detectChangedPullRequests(pullRequestInbox, (repository) => readGraphql(repository, signal), repositories, pullRequestInbox.now(), !eventScopedBootstrap, (repository, error) => {
10608
10910
  noteForgeQuota(error, "snapshot-detect");
10609
10911
  schedulerEvent("babysitter.snapshot.detect.failed", {
10610
10912
  repository,
@@ -10618,9 +10920,9 @@ function createBabysitterRuntime(options) {
10618
10920
  }
10619
10921
  step("snapshot-probe");
10620
10922
  try {
10621
- await probeChangedSnapshots(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors, void 0, void 0, signal);
10923
+ await probeChangedSnapshots(pullRequestInbox, readRest, pullRequestInbox.now(), readThreads, activityAuthors, void 0, void 0, signal);
10622
10924
  step("snapshot-sweep");
10623
- await reconcileOneSnapshot(pullRequestInbox, readRest, Date.now(), readThreads, activityAuthors, signal);
10925
+ await reconcileOneSnapshot(pullRequestInbox, readRest, pullRequestInbox.now(), readThreads, activityAuthors, signal);
10624
10926
  } catch (error) {
10625
10927
  signal.throwIfAborted();
10626
10928
  await noteForgeQuota(error, "snapshot-reconcile");
@@ -11014,7 +11316,7 @@ function createBabysitterRuntime(options) {
11014
11316
  await pullRequestInbox.release(inboxClaim);
11015
11317
  return;
11016
11318
  }
11017
- if (!pullRequestInbox.eligible(repository, inboxClaim.snapshot.pr)) {
11319
+ if (!await eligibleNow(repository, inboxClaim.snapshot.pr, inboxClaim.snapshot, passSignal)) {
11018
11320
  await pullRequestInbox.finish(inboxClaim, {
11019
11321
  text: "PR closed or outside the configured filter.",
11020
11322
  terminal: true
@@ -11306,6 +11608,7 @@ function createBabysitterRuntime(options) {
11306
11608
  workspaceRun.head = pullRequest.headRefOid;
11307
11609
  workspaceRun.base = pullRequest.baseRefOid;
11308
11610
  await github.withPullRequestCheckout({
11611
+ baseRef: pullRequest.baseRefName,
11309
11612
  headRef: pullRequest.headRefName,
11310
11613
  headRepository: pullRequest.headRepository?.nameWithOwner,
11311
11614
  headSha: pullRequest.headRefOid,
@@ -11377,7 +11680,7 @@ function createBabysitterRuntime(options) {
11377
11680
  const assertLeaseHeld = async () => {
11378
11681
  abortSignal.throwIfAborted();
11379
11682
  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");
11683
+ if (current?.lease !== inboxClaim.token || current.leaseUntil <= pullRequestInbox.now()) throw new DOMException("Pull request lease lost.", "AbortError");
11381
11684
  return current;
11382
11685
  };
11383
11686
  const assertLease = async () => {
@@ -11386,7 +11689,7 @@ function createBabysitterRuntime(options) {
11386
11689
  for (const [id, reopens] of ownedResolutions) if ((current.threadReopens?.[id] ?? 0) !== reopens) throw new DOMException("An addressed review thread was reopened.", "AbortError");
11387
11690
  const observedHead = current.pr?.head?.sha;
11388
11691
  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);
11692
+ const stopped = claimStopReason(inboxClaim, current, observedHead && pendingInboxHeads.has(observedHead) ? observedHead : pushedHead, pullRequestInbox.now());
11390
11693
  if (stopped) throw new DOMException(stopped, "AbortError");
11391
11694
  if (pushedHead && observedHead === pushedHead) {
11392
11695
  pendingInboxHeads.clear();
@@ -11515,7 +11818,7 @@ function createBabysitterRuntime(options) {
11515
11818
  commentPrefix: "<!-- vitehub-babysitter-repair:repair -->\n",
11516
11819
  signal: abortSignal,
11517
11820
  autoMerge: merge.mode === "auto" && stackParent === void 0,
11518
- eligible: (current) => pullRequestInbox.eligible(repository, normalizePullRequest(current)),
11821
+ eligible: async (current) => await eligibleNow(repository, normalizePullRequest(current), await pullRequestInbox.get(repository, number), abortSignal),
11519
11822
  checkDependencies: async () => {
11520
11823
  await assertLease();
11521
11824
  if (presetOptions.install === false) return {
@@ -11564,7 +11867,7 @@ function createBabysitterRuntime(options) {
11564
11867
  ...inboxClaim,
11565
11868
  generation: current.generation,
11566
11869
  snapshot: current
11567
- }, Date.now() + 72e5)) return;
11870
+ }, pullRequestInbox.now() + 72e5)) return;
11568
11871
  const latest = await assertLease();
11569
11872
  if (latest.generation === current.generation) throw new DOMException("Pull request lease renewal failed.", "AbortError");
11570
11873
  current = latest;
@@ -11592,7 +11895,7 @@ function createBabysitterRuntime(options) {
11592
11895
  try {
11593
11896
  const result = await prepared.push(providerDirectory, {
11594
11897
  signal: abortSignal,
11595
- beforePush: async (head) => {
11898
+ beforePush: async (head, lineage) => {
11596
11899
  const current = await assertLease();
11597
11900
  await assertRepairBase();
11598
11901
  const window = await repairPushWindow(current, await requiredCheckState(current), current.pr?.mergeable === false);
@@ -11604,7 +11907,7 @@ function createBabysitterRuntime(options) {
11604
11907
  ...inboxClaim,
11605
11908
  generation: current.generation,
11606
11909
  snapshot: current
11607
- }, head)) throw new DOMException("Publication candidate lease changed.", "AbortError");
11910
+ }, head, lineage)) throw new DOMException("Publication candidate lease changed.", "AbortError");
11608
11911
  observePendingPush = head ? (current) => {
11609
11912
  if (current.sourcePushHeads?.includes(head)) recordPush(head);
11610
11913
  } : void 0;
@@ -11799,7 +12102,11 @@ function createBabysitterRuntime(options) {
11799
12102
  authorAssociation: void 0,
11800
12103
  actor: void 0
11801
12104
  },
11802
- when: (context) => matchesBabysitterPullRequestFilter(context, filter),
12105
+ when: (context) => matchesBabysitterPullRequestFilter(context, approvalAdmission ? {
12106
+ ...filter,
12107
+ author: void 0,
12108
+ authorAssociation: void 0
12109
+ } : filter),
11803
12110
  workspace: false
11804
12111
  }
11805
12112
  }));
@@ -11972,7 +12279,7 @@ function createBabysitterRuntime(options) {
11972
12279
  }, abortSignal, () => {
11973
12280
  providerLimited = true;
11974
12281
  }).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", {
12282
+ if (recordedPass && isProviderFailure(error) && pullRequestInbox.now() - recordedPass.at < providerFailureReleaseMs && await pullRequestInbox.releaseModelPass(inboxClaim, recordedPass.at, recordedPass.exemption)) schedulerEvent("babysitter.daily_pass_budget.released", {
11976
12283
  ...owner,
11977
12284
  head_sha: pullRequest.headRefOid,
11978
12285
  ...recordedPass.exemption ? { exemption: recordedPass.exemption } : {},
@@ -12225,6 +12532,7 @@ function createBabysitterRuntime(options) {
12225
12532
  inbox: pullRequestInbox,
12226
12533
  repositories: repositorySource,
12227
12534
  reconcile,
12535
+ scheduler,
12228
12536
  workload,
12229
12537
  observeMainRepair
12230
12538
  };
@@ -12250,5 +12558,4 @@ function withoutCapacity(driver) {
12250
12558
  const { capacity: _capacity, ...rest } = driver;
12251
12559
  return rest;
12252
12560
  }
12253
- //#endregion
12254
12561
  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 };