@vite-hub/presets 0.6.1 → 0.8.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,4 +1,4 @@
1
- import { C as createGitHubAppCredentials, S as GitHubHostSecret, _ as GitHubHostCredentials, a as BabysitterAdmissionResult, b as GitHubHostPullRequest, c as PullRequestInboxStorage, d as GitHubHost, f as GitHubHostAccess, g as GitHubHostCredentialContext, h as GitHubHostCheckoutOptions, m as GitHubHostCheckout, n as PullRequestWorkspaces, o as PullRequestInbox, p as GitHubHostAccessOptions, u as GitHubAppEnvironment, v as GitHubHostForgeOptions, w as createGitHubHost, x as GitHubHostRateLimit, y as GitHubHostOptions } from "../pr-workspaces-BGAsF7fH.js";
1
+ import { C as createGitHubAppCredentials, S as GitHubHostSecret, _ as GitHubHostCredentials, a as BabysitterAdmissionResult, b as GitHubHostPullRequest, c as PullRequestInboxStorage, d as GitHubHost, f as GitHubHostAccess, g as GitHubHostCredentialContext, h as GitHubHostCheckoutOptions, m as GitHubHostCheckout, n as PullRequestWorkspaces, o as PullRequestInbox, p as GitHubHostAccessOptions, u as GitHubAppEnvironment, v as GitHubHostForgeOptions, w as createGitHubHost, x as GitHubHostRateLimit, y as GitHubHostOptions } from "../pr-workspaces-CbTDCpFn.js";
2
2
  import { AgentInput } from "@vite-hub/agent";
3
3
  import { GitHubAppRepository } from "@vite-hub/forge";
4
4
  import { ProcessReconcilerRunContext } from "@vite-hub/runtime/internal/node";
@@ -17,6 +17,7 @@ interface BabysitterRepositories {
17
17
  */
18
18
  observe(event: string, payload: unknown): boolean;
19
19
  }
20
+ export declare function isProviderRateLimit(error: unknown): boolean;
20
21
  export interface BabysitterRuntimeOptions {
21
22
  agent: AgentInput;
22
23
  /** Discovered Agent name for per-Agent public URLs. Defaults to the definition name. */
@@ -79,8 +80,6 @@ export interface BabysitterRuntimeOptions {
79
80
  * A fixed 30-second poll can run for hours on a request that GitHub never settles.
80
81
  */
81
82
  export declare function pendingMergeRetryAt(startedAt: number, now: number): number;
82
- /** Provider quota and rate-limit failures. Cancellation is never a rate limit. */
83
- export declare function isProviderRateLimit(error: unknown): boolean;
84
83
  /**
85
84
  * Whether the reconcile loop still makes progress, for the health route. `stalled`: the last reconcile
86
85
  * waited longer than `stallMs` and was stopped. `silent`: no reconcile finished for `stallMs` plus one
@@ -1 +1 @@
1
- export { t as createBabysitterRuntime, s as createGitHubAppCredentials, c as createGitHubHost, n as isProviderRateLimit, r as pendingMergeRetryAt } from "../server-9eUlfkBm.js";
1
+ export { t as createBabysitterRuntime, s as createGitHubAppCredentials, c as createGitHubHost, i as isProviderRateLimit, n as pendingMergeRetryAt } from "../server-CnBPeA2q.js";
@@ -1,4 +1,4 @@
1
- import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-BqwPfmNx.js";
1
+ import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-ba9TWgh5.js";
2
2
  import { claudeCodeDriver, codexDriver, defineAgent } from "@vite-hub/agent";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import * as v from "valibot";
@@ -1244,7 +1244,11 @@ function createGitHubPullRequestOperations(github, options) {
1244
1244
  if ((await snapshot()).pullRequest.body !== current.pullRequest.body) throw presetsErrorDiagnostics.PRESETS_PULL_REQUEST_BODY_CHANGED();
1245
1245
  }
1246
1246
  const { provider, pullRequest } = await forge();
1247
- await provider.threads.update(pullRequest, update, { signal });
1247
+ const send = async () => {
1248
+ await provider.threads.update(pullRequest, update, { signal });
1249
+ };
1250
+ if (options.sendMetadata) await options.sendMetadata(update, send);
1251
+ else await send();
1248
1252
  },
1249
1253
  async checkDependencies() {
1250
1254
  return await options.checkDependencies?.() ?? {
@@ -1411,6 +1415,9 @@ function mergeTarget(snapshot, legacy = false) {
1411
1415
  }
1412
1416
  /** Assessment is bound to full feedback bodies and failed check evidence, never prose heuristics. */
1413
1417
  function mergeReviewEvidenceKey(snapshot, policy = {}, legacy = false) {
1418
+ return reviewEvidenceKey(snapshot, policy, legacy, true);
1419
+ }
1420
+ function reviewEvidenceKey(snapshot, policy, legacy, includeThreadAuthors) {
1414
1421
  const head = snapshot.pr?.head?.sha;
1415
1422
  const failures = [...Object.values(snapshot.checks), ...Object.values(snapshot.statuses)].filter((value) => !value.deleted && (value.head_sha ?? value.sha) === head && !isBabysitterCheckRun(value) && failing.has(String(value.conclusion ?? value.state).toLowerCase())).map((value) => ({
1416
1423
  id: value.id ?? value.context,
@@ -1427,7 +1434,7 @@ function mergeReviewEvidenceKey(snapshot, policy = {}, legacy = false) {
1427
1434
  comments: (Array.isArray(thread.comments) ? thread.comments : thread.comments?.nodes ?? []).filter((comment) => !comment.deleted).map((comment) => ({
1428
1435
  id: comment.node_id ?? comment.id,
1429
1436
  body: comment.body,
1430
- user: comment.user ?? comment.author,
1437
+ user: includeThreadAuthors ? comment.user ?? comment.author : void 0,
1431
1438
  commit: comment.commit_id ?? comment.commit?.oid
1432
1439
  }))
1433
1440
  })).sort((left, right) => String(left.id).localeCompare(String(right.id)));
@@ -1446,9 +1453,9 @@ function mergeReviewEvidenceKey(snapshot, policy = {}, legacy = false) {
1446
1453
  failures
1447
1454
  })).digest("hex");
1448
1455
  }
1449
- /** Whether a stored evidence key covers this snapshot, including a key stored with the base commit. */
1456
+ /** Whether a stored evidence key covers this snapshot, including keys with the base commit or without thread authors. */
1450
1457
  function matchesMergeReviewEvidence(key, snapshot, policy = {}) {
1451
- return hasRuntimeType(key, "string") && (key === mergeReviewEvidenceKey(snapshot, policy) || key === mergeReviewEvidenceKey(snapshot, policy, true));
1458
+ return hasRuntimeType(key, "string") && (key === mergeReviewEvidenceKey(snapshot, policy) || key === mergeReviewEvidenceKey(snapshot, policy, true) || key === reviewEvidenceKey(snapshot, policy, false, false) || key === reviewEvidenceKey(snapshot, policy, true, false));
1452
1459
  }
1453
1460
  /**
1454
1461
  * Identities of the feedback items that need an assessment. An explicit assessment covers
@@ -2309,7 +2316,7 @@ function validMainRepair(mainRepair) {
2309
2316
  return names(workflows, /\S/) && (repositories === void 0 || names(repositories, /^[\w.-]+\/[\w.-]+$/)) && (stuckJobMinutes === void 0 || stuckJobMinutes === false || Number.isSafeInteger(stuckJobMinutes) && Number(stuckJobMinutes) >= 1);
2310
2317
  }
2311
2318
  const babysitterHost = { async create(context) {
2312
- const { createBabysitterProcessHost } = await import("./host-DHjNUmve.js");
2319
+ const { createBabysitterProcessHost } = await import("./host-Dq3z2dW8.js");
2313
2320
  return await createBabysitterProcessHost(context);
2314
2321
  } };
2315
2322
  function plainSecret(value) {
@@ -1,4 +1,4 @@
1
- import { T as AutomatedReviewClass, i as BabysitterAdmissionPause, l as GitHubRequiredCheckState, r as BabysitterAdmissionOptions, s as Snapshot, t as BabysitterWarmWorkspaces } from "./pr-workspaces-BGAsF7fH.js";
1
+ import { T as AutomatedReviewClass, i as BabysitterAdmissionPause, l as GitHubRequiredCheckState, r as BabysitterAdmissionOptions, s as Snapshot, t as BabysitterWarmWorkspaces } from "./pr-workspaces-CbTDCpFn.js";
2
2
  import { AgentDefinition, AgentInvocationContextValues, AgentInvoker, AgentRuntimeConfig, AgentSandboxDefinition, BuiltInAgentDriverName, ConfiguredAgentDefinition } from "@vite-hub/agent";
3
3
  import { GitHubPullRequestFilter } from "@vite-hub/agent/channels";
4
4
  import { Diagnostic } from "nostics";
@@ -1 +1 @@
1
- export { i as BabysitterPlacementCapacityError, t as babysitter, n as babysitterPassResultSchema, r as resolveBabysitterLifecycleFilter } from "./babysitter-Bc7fiKzx.js";
1
+ export { i as BabysitterPlacementCapacityError, t as babysitter, n as babysitterPassResultSchema, r as resolveBabysitterLifecycleFilter } from "./babysitter-C92vTLpo.js";
@@ -442,6 +442,10 @@ const presetsErrorDiagnostics = /*#__PURE__*/ defineErrors({
442
442
  why: "PullRequestInbox requires exactly one of path or storage.",
443
443
  fix: "Set inboxPath, a private node:sqlite file, or inboxStorage, such as agentState.extension(\"babysitter\"), in the createBabysitterRuntime() options."
444
444
  },
445
+ PRESETS_BABYSITTER_INBOX_STORAGE_NOT_SQLITE: {
446
+ why: "PullRequestInbox storage runs on Postgres Agent State. The inbox SQL is SQLite.",
447
+ fix: "Set inboxPath to a private node:sqlite file in the data directory of the server that holds the process host, as the Babysitter host does on Postgres Agent State."
448
+ },
445
449
  PRESETS_BABYSITTER_PROMPT_TOO_LARGE: {
446
450
  why: ({ characters, bytes, limit }) => `GitHubPullRequest prompt exceeds transport safety limit: ${characters} characters, ${bytes} UTF-8 bytes; limit ${limit}. All review/comment bodies were retained. No truncated prompt was sent.`,
447
451
  fix: "Shorten or hide the longest comments and review bodies on the pull request, or split it into smaller pull requests. The Babysitter does not cut feedback."
@@ -1,6 +1,6 @@
1
- import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-BqwPfmNx.js";
2
- import { a as budgetParks, c as createGitHubHost, i as babysitterQueueHealth, o as pullRequestThreadId, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "./server-9eUlfkBm.js";
3
- import { d as resolveBabysitterAdmissionLimits, f as sharedBabysitterRead, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-Bc7fiKzx.js";
1
+ import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-ba9TWgh5.js";
2
+ import { a as budgetParks, c as createGitHubHost, o as pullRequestThreadId, r as babysitterQueueHealth, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "./server-CnBPeA2q.js";
3
+ import { d as resolveBabysitterAdmissionLimits, f as sharedBabysitterRead, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-C92vTLpo.js";
4
4
  import { defineAgent } from "@vite-hub/agent";
5
5
  import { forgeErrorStatus, githubInstallationRouting } from "@vite-hub/forge";
6
6
  import { channelEnv } from "@vite-hub/agent/channels";
@@ -508,7 +508,7 @@ async function createBabysitterProcessHost(context) {
508
508
  run: async (reason, run, accepting) => await runtime?.reconcile(reason, run, accepting)
509
509
  });
510
510
  const preflight = createBabysitterPreflight(agent.options.install ?? true);
511
- const buildRevision = "756b06da1a98b116856ea2318509abcf6db920a1168e3f29c9dad2e604df4095";
511
+ const buildRevision = "7fd99b60ad33356545ce233e0675580c666313fbf3f50e93db479920a1ba9fad";
512
512
  const admission = createBabysitterAdmission({
513
513
  invocations: host.invocations,
514
514
  limits: resolveBabysitterAdmissionLimits(agent.options.admission),
@@ -529,12 +529,13 @@ async function createBabysitterProcessHost(context) {
529
529
  ...resumeThreads ? { sessionStorePath: host.providerSessionStorePath } : {}
530
530
  }
531
531
  });
532
+ const inboxStorage = context.state.extension("babysitter");
532
533
  runtime = createBabysitterRuntime({
533
534
  workspaces,
534
535
  agent: worker,
535
536
  agentName: context.agentName,
536
537
  github,
537
- inboxStorage: context.state.extension("babysitter"),
538
+ ...inboxStorage.dialect === "postgresql" ? { inboxPath: join(context.dataDir, "inbox.sqlite") } : { inboxStorage },
538
539
  inboxScope: context.agentName,
539
540
  repositories,
540
541
  concurrency: agent.options.concurrency,
@@ -50,6 +50,8 @@ export interface LabellerOptions {
50
50
  relabel: boolean;
51
51
  trashEnabled: boolean;
52
52
  client?: GmailClient;
53
+ /** Name of the Google Connection that the Gmail Channel calls Gmail through, as in `gmail({ connection })`. */
54
+ connection?: string;
53
55
  }
54
56
  export interface LabellerDecision {
55
57
  label: string;
package/dist/labeller.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-BqwPfmNx.js";
1
+ import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-ba9TWgh5.js";
2
2
  import { defineAgent } from "@vite-hub/agent";
3
3
  import { hasRuntimeType, isRuntimeObject } from "@vite-hub/runtime/internal/runtime-type";
4
4
  import * as v from "valibot";
@@ -172,7 +172,8 @@ const labeller = defineAgent({
172
172
  minConfidence: .6,
173
173
  relabel: false,
174
174
  trashEnabled: false,
175
- client: void 0
175
+ client: void 0,
176
+ connection: void 0
176
177
  },
177
178
  configure: (options) => {
178
179
  if (materializingTemplate) {
@@ -186,13 +187,14 @@ const labeller = defineAgent({
186
187
  });
187
188
  }
188
189
  validateOptions(options);
189
- const { labels, rules, actions, bodyLimit, hideUnmanagedLabels, maxAttempts, minConfidence, relabel, trashEnabled, client } = options;
190
+ const { labels, rules, actions, bodyLimit, hideUnmanagedLabels, maxAttempts, minConfidence, relabel, trashEnabled, client, connection } = options;
190
191
  const channelOptions = {
191
192
  labels,
192
193
  bodyLimit,
193
194
  client,
194
195
  hideUnmanagedLabels,
195
- ...maxAttempts === void 0 ? {} : { maxAttempts }
196
+ ...maxAttempts === void 0 ? {} : { maxAttempts },
197
+ ...connection === void 0 ? {} : { connection }
196
198
  };
197
199
  if (options.dryRun) channelOptions.dryRun = true;
198
200
  const channel = gmail(channelOptions);
@@ -431,9 +431,11 @@ type PullRequestWait = {
431
431
  };
432
432
  /**
433
433
  * SQL access for the PR inbox. `agentState.extension("babysitter")` from
434
- * `@vite-hub/agent/state` satisfies it and keeps the inbox in the Agent State database.
434
+ * `@vite-hub/agent/state` satisfies it on SQLite Agent State and keeps the inbox in the Agent State database.
435
+ * The inbox SQL is SQLite, so the inbox rejects an extension on Postgres Agent State.
435
436
  */
436
437
  interface PullRequestInboxStorage extends Pick<SqliteAgentStateExtension, "execute" | "tablePrefix" | "transaction"> {
438
+ readonly dialect?: SqliteAgentStateExtension["dialect"];
437
439
  close?: () => Promise<void>;
438
440
  }
439
441
  interface StatusDelivery {
@@ -469,6 +471,8 @@ interface StatusDelivery {
469
471
  interface HostHead {
470
472
  head: string;
471
473
  parent: string;
474
+ /** A pass pushed this head. A base update that the host asked GitHub for has no flag. */
475
+ repair?: true;
472
476
  }
473
477
  type Snapshot = {
474
478
  repository: string;
@@ -491,6 +495,10 @@ type Snapshot = {
491
495
  dailyPassBudget?: DailyPassBudget;
492
496
  /** Generation of the last human comment or review. A wait rejected before it stays free. */
493
497
  humanFeedbackGeneration?: number;
498
+ metadataEdits?: Partial<Record<"title" | "body", {
499
+ generation: number;
500
+ externalGeneration: number;
501
+ }>>;
494
502
  recoveryHead?: string;
495
503
  sourcePushHead?: string;
496
504
  sourcePushHeads?: string[];
@@ -781,6 +789,7 @@ declare class PullRequestInbox {
781
789
  * `budgets.dailyPasses`. It changes no evidence, so the claim stays current.
782
790
  */
783
791
  recordModelPass(claim: Claim, exemption?: string): Promise<number | false>;
792
+ recordModelPass(claim: Claim, exemption?: string, observed?: Pick<Snapshot, "generation" | "revision">): Promise<number | false | "changed">;
784
793
  /**
785
794
  * Gives back the pass that `recordModelPass` counted at `at`, and its exemption, when the provider
786
795
  * failed the pass before it did any work. It changes no evidence, so the claim stays current.
@@ -1,5 +1,5 @@
1
- import { a as isRuntimeString, i as isRuntimeRecord, n as hasRuntimeType, r as isRuntimeNumber, t as presetsErrorDiagnostics } from "./error-diagnostics-BqwPfmNx.js";
2
- import { A as invariant, B as createBabysitterPassResultSchema, C as approvalReviewers, D as normalizeGitHubMentionAllowlist, E as isReviewThreadOutcome, F as failed$1, I as hydrateFailedCiEvidence, L as newestCheckRun, M as hasGitHubLogin, N as matchesBabysitterPullRequestFilter, O as reviewThreadOutcomes, P as actionLocation, R as createBabysitterCheckRuns, S as snapshotCheckEvidence, T as createGitHubPullRequestOperations, _ as isAutomatedFeedback, a as isBabysitterPlacementCapacityError, b as mergeReviewEvidenceKey, c as workspaceDecision, g as headChecksUnreported, h as hasHumanComment, j as invariantError, k as reviewerLabeledSevere, l as babysitterModelAdmission, m as feedbackFingerprints, p as directMergeReadiness, r as resolveBabysitterLifecycleFilter, s as providerSessionDecision, v as liveMergeReadiness, w as maintainerApproval, x as resolveBabysitterMerge, y as matchesMergeReviewEvidence, z as isBabysitterCheckRun } from "./babysitter-Bc7fiKzx.js";
1
+ import { a as isRuntimeString, i as isRuntimeRecord, n as hasRuntimeType, r as isRuntimeNumber, t as presetsErrorDiagnostics } from "./error-diagnostics-ba9TWgh5.js";
2
+ import { A as invariant, B as createBabysitterPassResultSchema, C as approvalReviewers, D as normalizeGitHubMentionAllowlist, E as isReviewThreadOutcome, F as failed$1, I as hydrateFailedCiEvidence, L as newestCheckRun, M as hasGitHubLogin, N as matchesBabysitterPullRequestFilter, O as reviewThreadOutcomes, P as actionLocation, R as createBabysitterCheckRuns, S as snapshotCheckEvidence, T as createGitHubPullRequestOperations, _ as isAutomatedFeedback, a as isBabysitterPlacementCapacityError, b as mergeReviewEvidenceKey, c as workspaceDecision, g as headChecksUnreported, h as hasHumanComment, j as invariantError, k as reviewerLabeledSevere, l as babysitterModelAdmission, m as feedbackFingerprints, p as directMergeReadiness, r as resolveBabysitterLifecycleFilter, s as providerSessionDecision, v as liveMergeReadiness, w as maintainerApproval, x as resolveBabysitterMerge, y as matchesMergeReviewEvidence, z as isBabysitterCheckRun } from "./babysitter-C92vTLpo.js";
3
3
  import { activeProviderSandbox, agentInvocationId, agentSettings, createMessage, defineAgent, defineCapability, publishAgentActivity, recordProviderCheckout, runAgent, withoutForgeAccess } from "@vite-hub/agent";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { resolvePublicUrl } from "@vite-hub/runtime";
@@ -1027,13 +1027,21 @@ async function publishGitHubInstallSnapshot(snapshot, signal) {
1027
1027
  });
1028
1028
  }
1029
1029
  }
1030
+ // ../internal/src/object.ts
1031
+ /** A non-null object that is not an array. Functions do not pass. */
1032
+ function isRecord(value) {
1033
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1034
+ }
1035
+ /** A non-null object. Arrays pass. Functions do not. */
1036
+ function isObject(value) {
1037
+ return typeof value === "object" && value !== null;
1038
+ }
1030
1039
  // src/github/install.ts
1031
1040
  const exec$4 = promisify(execFile);
1032
1041
  const manifest = v.object({ packageManager: v.optional(v.string()) });
1033
1042
  const systemError = v.object({ errno: v.pipe(v.number(), v.integer(), v.maxValue(-1)) });
1034
1043
  const exists$1 = async (path) => await access(path).then(() => true, () => false);
1035
1044
  const isSystemError = (error) => v.safeParse(systemError, error).success;
1036
- const isRecord = (value) => typeof value === "object" && value !== null;
1037
1045
  function githubWorkspaceInstallError(cause, retryable = true, kind = "command") {
1038
1046
  return Object.assign(presetsErrorDiagnostics.PRESETS_GITHUB_INSTALL_FAILED({
1039
1047
  cause,
@@ -1057,9 +1065,9 @@ function isGitHubLockfileDefect(error) {
1057
1065
  const collect = (value) => {
1058
1066
  if (value === null || value === void 0 || seen.has(value)) return;
1059
1067
  if (typeof value === "object" || typeof value === "function") seen.add(value);
1060
- parts.push(value instanceof Error ? value.message : isRecord(value) && typeof value.message === "string" ? value.message : String(value));
1068
+ parts.push(value instanceof Error ? value.message : isObject(value) && typeof value.message === "string" ? value.message : String(value));
1061
1069
  if (value instanceof Error) collect(value.cause);
1062
- if (isRecord(value)) {
1070
+ if (isObject(value)) {
1063
1071
  collect(value.cause);
1064
1072
  collect(value.stderr);
1065
1073
  }
@@ -1435,12 +1443,12 @@ async function readGitHubDependencyStatus(target) {
1435
1443
  };
1436
1444
  }
1437
1445
  const record = await readFile(join(target, ".git", "vitehub-install.json"), "utf8").then(JSON.parse, () => ({}));
1438
- const installed = isRecord(record) ? record : {};
1446
+ const installed = isObject(record) ? record : {};
1439
1447
  if (installed.status === "installed" && installed.fingerprint === fingerprint) return {
1440
1448
  current: true,
1441
1449
  changedInputs: []
1442
1450
  };
1443
- const previous = isRecord(installed.inputs) ? installed.inputs : {};
1451
+ const previous = isObject(installed.inputs) ? installed.inputs : {};
1444
1452
  const changedInputs = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(inputs)])].filter((path) => previous[path] !== inputs[path]).sort();
1445
1453
  return {
1446
1454
  current: false,
@@ -1724,7 +1732,7 @@ function mergePackageJson(base, ours, theirs) {
1724
1732
  }
1725
1733
  });
1726
1734
  const styles = texts.map(jsonStyle);
1727
- if (parsed.some((value, index) => !isObject(value) || !styles[index] || serialize(value, styles[index]) !== texts[index])) return void 0;
1735
+ if (parsed.some((value, index) => !isRecord(value) || !styles[index] || serialize(value, styles[index]) !== texts[index])) return void 0;
1728
1736
  const merged = mergeValue(parsed[0], parsed[1], parsed[2], false);
1729
1737
  if (merged === conflict || merged === absent) return void 0;
1730
1738
  return serialize(merged, styles[1]);
@@ -1733,7 +1741,7 @@ function mergeValue(base, ours, theirs, atomic) {
1733
1741
  if (same(ours, theirs)) return ours;
1734
1742
  if (same(base, ours)) return theirs;
1735
1743
  if (same(base, theirs)) return ours;
1736
- if (atomic || !isObject(base) || !isObject(ours) || !isObject(theirs)) return conflict;
1744
+ if (atomic || !isRecord(base) || !isRecord(ours) || !isRecord(theirs)) return conflict;
1737
1745
  const order = (value) => Object.keys(value).filter((key) => Object.hasOwn(base, key) && Object.hasOwn(ours, key) && Object.hasOwn(theirs, key)).join("\0");
1738
1746
  if (order(ours) !== order(base) && order(theirs) !== order(base)) return conflict;
1739
1747
  const keys = keyOrder(order(ours) !== order(base) ? ours : theirs, order(ours) !== order(base) ? theirs : ours);
@@ -1757,7 +1765,6 @@ function keyOrder(primary, other) {
1757
1765
  }
1758
1766
  const read = (value, key) => Object.hasOwn(value, key) ? value[key] : absent;
1759
1767
  const same = (left, right) => left === absent || right === absent ? left === right : JSON.stringify(left) === JSON.stringify(right);
1760
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1761
1768
  function jsonStyle(text) {
1762
1769
  const indent = /^\{\r?\n([ \t]+)"/.exec(text)?.[1];
1763
1770
  if (indent === void 0) return text.trim() === "{}" ? {
@@ -2928,12 +2935,15 @@ function evaluateGitHubRequiredChecks(policy, evidence) {
2928
2935
  const runs = evidence.checkRuns.filter((value) => value.head_sha === evidence.headSha && value.name === required.context && (required.appId === null || value.app?.id === required.appId)).sort((a, b) => b.id - a.id);
2929
2936
  const status = evidence.statuses.filter((value) => value.sha === evidence.headSha && value.context === required.context).sort((a, b) => b.id - a.id)[0];
2930
2937
  const states = [];
2931
- if (runs[0]) states.push(stateOfCheck(runs[0]));
2938
+ const run = runs[0];
2939
+ const runState = run && stateOfCheck(run);
2940
+ if (runState) states.push(runState);
2932
2941
  if (status) states.push(status.state === "pending" ? "pending" : ["failure", "error"].includes(status.state) ? "failed" : status.state === "success" && required.appId === null ? "passed" : "unknown");
2933
2942
  if (!states.length) missing.push(required.context);
2934
2943
  return {
2935
2944
  ...required,
2936
- state: states.length ? combine(states) : "pending"
2945
+ state: states.length ? combine(states) : "pending",
2946
+ ...runState === "failed" && run?.conclusion?.toLowerCase() === "cancelled" ? { cancelled: true } : {}
2937
2947
  };
2938
2948
  });
2939
2949
  const newest = /* @__PURE__ */ new Map();
@@ -3416,6 +3426,10 @@ const deliverySchema = v.looseObject({
3416
3426
  action: v.optional(v.string()),
3417
3427
  sender: actor,
3418
3428
  pull_request: v.optional(pullRequestSchema),
3429
+ changes: v.optional(v.object({
3430
+ title: v.optional(v.unknown()),
3431
+ body: v.optional(v.unknown())
3432
+ })),
3419
3433
  issue: v.optional(v.object({
3420
3434
  number: v.pipe(v.number(), v.integer(), v.minValue(1)),
3421
3435
  pull_request: v.optional(v.unknown())
@@ -3494,7 +3508,8 @@ function parseSnapshot(value) {
3494
3508
  if (input.hostUpdates !== void 0) v.parse(v.array(v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i))), input.hostUpdates);
3495
3509
  if (input.hostHeads !== void 0) v.parse(v.array(v.object({
3496
3510
  head: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i)),
3497
- parent: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i))
3511
+ parent: v.pipe(v.string(), v.regex(/^[a-f\d]{40}$/i)),
3512
+ repair: v.optional(v.literal(true))
3498
3513
  })), input.hostHeads);
3499
3514
  if (input.threadReopens !== void 0) v.parse(v.record(v.string(), v.pipe(v.number(), v.integer(), v.minValue(0))), input.threadReopens);
3500
3515
  if (input.sourcePushHeads !== void 0) v.parse(v.array(v.string()), input.sourcePushHeads);
@@ -3502,6 +3517,16 @@ function parseSnapshot(value) {
3502
3517
  if (input.sourcePushHead !== void 0) v.parse(v.string(), input.sourcePushHead);
3503
3518
  if (input.recoveryHead !== void 0) v.parse(v.string(), input.recoveryHead);
3504
3519
  if (input.humanFeedbackGeneration !== void 0) v.parse(v.pipe(v.number(), v.integer(), v.minValue(0)), input.humanFeedbackGeneration);
3520
+ if (input.metadataEdits !== void 0) {
3521
+ const edit = v.optional(v.object({
3522
+ generation: v.number(),
3523
+ externalGeneration: v.number()
3524
+ }));
3525
+ v.parse(v.object({
3526
+ title: edit,
3527
+ body: edit
3528
+ }), input.metadataEdits);
3529
+ }
3505
3530
  if (input.ciEvidence !== void 0) v.parse(v.array(v.record(v.string(), v.unknown())), input.ciEvidence);
3506
3531
  if (input.ownedReviewCommentIds !== void 0) v.parse(v.array(v.string()), input.ownedReviewCommentIds);
3507
3532
  if (input.wait !== void 0) parseWait(input.wait);
@@ -3709,6 +3734,7 @@ var PullRequestInbox = class {
3709
3734
  constructor({ path, storage, scope = "", repositories, filter, admitApproved = false, clock, budgets = {}, activityAuthors = [], activityAppId, priorityLabels = [], mainRepairBranchPrefix, claimStackChildren = false, invalidRow }) {
3710
3735
  validateBudgets(budgets);
3711
3736
  if (path === void 0 === (storage === void 0)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_INBOX_STORAGE_MISSING();
3737
+ if (storage?.dialect === "postgresql") throw presetsErrorDiagnostics.PRESETS_BABYSITTER_INBOX_STORAGE_NOT_SQLITE();
3712
3738
  this.budgets = { ...budgets };
3713
3739
  this.priorityLabels = [...new Set(priorityLabels.map((label) => label.trim().toLowerCase()).filter(Boolean))];
3714
3740
  this.mainRepairBranchPrefix = mainRepairBranchPrefix || void 0;
@@ -4586,7 +4612,7 @@ var PullRequestInbox = class {
4586
4612
  if (!s.lease) s.status = s.wait ? "waiting" : "ready";
4587
4613
  s.reasons = [.../* @__PURE__ */ new Set([...s.reasons, reason])];
4588
4614
  }
4589
- updatePr(s, pr) {
4615
+ updatePr(s, pr, ownChanges) {
4590
4616
  pr = normalizePullRequest(pr);
4591
4617
  if (s.pr && stamp(pr) < stamp(s.pr)) return false;
4592
4618
  const previous = s.pr;
@@ -4614,6 +4640,15 @@ var PullRequestInbox = class {
4614
4640
  }
4615
4641
  if (pr.state === "closed") delete s.prospectivePush;
4616
4642
  if (newHead && pr.head?.sha !== s.wait?.headSha || pr.state === "closed") delete s.wait;
4643
+ for (const field of ["title", "body"]) {
4644
+ if (pr[field] === void 0 || pr[field] === previous?.[field]) continue;
4645
+ const edits = s.metadataEdits ??= {};
4646
+ const generation = s.generation + 1;
4647
+ edits[field] = {
4648
+ generation,
4649
+ externalGeneration: ownChanges?.[field] ? edits[field]?.externalGeneration ?? 0 : generation
4650
+ };
4651
+ }
4617
4652
  s.pr = {
4618
4653
  ...previous,
4619
4654
  ...pr
@@ -4803,7 +4838,10 @@ var PullRequestInbox = class {
4803
4838
  const pendingHead = sha && (check || event === "status") && (s.wait?.headSha === sha || s.lease && s.leaseUntil > this.clock() && (s.sourcePushHeads?.includes(sha) || s.prospectivePush?.token === s.lease && s.prospectivePush.heads.includes(sha)));
4804
4839
  if (sha && s.pr?.head?.sha && s.pr.head.sha !== sha && !pushRefMatch && !pendingHead) continue;
4805
4840
  let changed = false;
4806
- if (payload.pull_request) changed = this.updatePr(s, payload.pull_request);
4841
+ if (payload.pull_request) {
4842
+ const ownEdit = event === "pull_request" && payload.action === "edited" && payload.sender?.type?.toLowerCase() === "bot" && this.activityAuthors.has(payload.sender.login?.toLowerCase() ?? "");
4843
+ changed = this.updatePr(s, payload.pull_request, ownEdit ? payload.changes : void 0);
4844
+ }
4807
4845
  if (event === "pull_request" && payload.action === "synchronize" && s.hostUpdates?.length) this.settleHostUpdate(s, payload);
4808
4846
  const upsert = (map, value, itemKey) => {
4809
4847
  if (!value) return;
@@ -5054,7 +5092,7 @@ var PullRequestInbox = class {
5054
5092
  id: thread.node_id ?? thread.id,
5055
5093
  isResolved: thread.isResolved,
5056
5094
  isOutdated: thread.isOutdated,
5057
- comments: (Array.isArray(thread.comments) ? thread.comments : thread.comments?.nodes ?? []).map((comment) => String(comment.node_id ?? comment.id)).sort()
5095
+ comments: (Array.isArray(thread.comments) ? thread.comments : thread.comments?.nodes ?? []).map((comment) => `${String(comment.node_id ?? comment.id)}:${String((comment.user ?? comment.author)?.login ?? "")}`).sort()
5058
5096
  })).sort((a, b) => String(a.id).localeCompare(String(b.id)));
5059
5097
  const changed = digest(semantic(s.threads)) !== digest(semantic(threads));
5060
5098
  s.threads = threads;
@@ -5110,7 +5148,7 @@ var PullRequestInbox = class {
5110
5148
  token: claim.token,
5111
5149
  heads
5112
5150
  };
5113
- if (lineage?.hostOnly && /^[a-f\d]{40}$/i.test(lineage.parent)) this.addHostHead(s, head, lineage.parent);
5151
+ if (lineage?.hostOnly && /^[a-f\d]{40}$/i.test(lineage.parent)) this.addHostHead(s, head, lineage.parent, true);
5114
5152
  s.revision = (s.revision ?? 0) + 1;
5115
5153
  await this.put(tx, s);
5116
5154
  return true;
@@ -5133,11 +5171,12 @@ var PullRequestInbox = class {
5133
5171
  await this.put(tx, s);
5134
5172
  });
5135
5173
  }
5136
- addHostHead(s, head, parent) {
5174
+ addHostHead(s, head, parent, repair = false) {
5137
5175
  if (s.hostHeads?.some((entry) => entry.head === head)) return;
5138
5176
  s.hostHeads = [...s.hostHeads ?? [], {
5139
5177
  head,
5140
- parent
5178
+ parent,
5179
+ ...repair && { repair: true }
5141
5180
  }].slice(-64);
5142
5181
  }
5143
5182
  /**
@@ -5171,16 +5210,13 @@ var PullRequestInbox = class {
5171
5210
  return true;
5172
5211
  });
5173
5212
  }
5174
- /**
5175
- * Records that a claimed pass started the model, with the exemption that let it run past
5176
- * `budgets.dailyPasses`. It changes no evidence, so the claim stays current.
5177
- */
5178
- async recordModelPass(claim, exemption) {
5213
+ async recordModelPass(claim, exemption, observed) {
5179
5214
  if (this.budgets.dailyPasses === void 0) return false;
5180
5215
  return await this.transaction(async (tx) => {
5181
5216
  const s = await this.getIn(tx, claim.snapshot.repository, claim.snapshot.number);
5182
5217
  const at = this.clock();
5183
5218
  if (!s || s.lease !== claim.token || s.leaseUntil <= at) return false;
5219
+ if (observed && (s.generation !== observed.generation || (s.revision ?? 0) !== (observed.revision ?? 0))) return "changed";
5184
5220
  s.dailyPassBudget = nextDailyPassBudget(s.dailyPassBudget, at, s.humanFeedbackGeneration, exemption);
5185
5221
  s.revision = (s.revision ?? 0) + 1;
5186
5222
  await this.put(tx, s);
@@ -5896,7 +5932,10 @@ async function readForgePullRequestThreads(provider, repository, number, signal)
5896
5932
  },
5897
5933
  signal
5898
5934
  })).data);
5899
- }, thread.id) : thread.comments.flatMap((comment) => comment.ref ? [{ id: comment.ref.id }] : []);
5935
+ }, thread.id) : thread.comments.flatMap((comment) => comment.ref ? [{
5936
+ id: comment.ref.id,
5937
+ ...commentAuthor(comment.author)
5938
+ }] : []);
5900
5939
  threads.push({
5901
5940
  id: thread.id,
5902
5941
  node_id: thread.id,
@@ -5911,6 +5950,12 @@ async function readForgePullRequestThreads(provider, repository, number, signal)
5911
5950
  }
5912
5951
  return threads;
5913
5952
  }
5953
+ function commentAuthor(author) {
5954
+ return author ? { user: {
5955
+ login: author.login,
5956
+ type: author.isBotHint ? "Bot" : author.typeRaw ?? "User"
5957
+ } } : {};
5958
+ }
5914
5959
  const index = (items) => Object.fromEntries(items.map((item) => [String(item.id), item]));
5915
5960
  const pageInfo = v.object({
5916
5961
  hasNextPage: v.boolean(),
@@ -5919,7 +5964,11 @@ const pageInfo = v.object({
5919
5964
  const commentConnection = v.object({
5920
5965
  nodes: v.array(v.object({
5921
5966
  id: v.string(),
5922
- databaseId: v.nullish(v.number())
5967
+ databaseId: v.nullish(v.number()),
5968
+ author: v.nullish(v.object({
5969
+ login: v.string(),
5970
+ __typename: v.optional(v.string())
5971
+ }))
5923
5972
  })),
5924
5973
  pageInfo
5925
5974
  });
@@ -5949,14 +5998,17 @@ async function readThreadComments(request, id) {
5949
5998
  do {
5950
5999
  const more = v.parse(v.object({ node: v.object({ comments: commentConnection }) }), await request(`query GitHubPullRequestThreadComments($id:ID!,$after:String) {
5951
6000
  node(id:$id) { ... on PullRequestReviewThread { comments(first:100,after:$after) {
5952
- nodes { id databaseId } pageInfo { hasNextPage endCursor }
6001
+ nodes { id databaseId author { login __typename } } pageInfo { hasNextPage endCursor }
5953
6002
  } } }
5954
6003
  }`, {
5955
6004
  id,
5956
6005
  after
5957
6006
  }));
5958
6007
  after = nextCursor(more.node.comments, pages);
5959
- comments.push(...more.node.comments.nodes);
6008
+ comments.push(...more.node.comments.nodes.map(({ author, ...comment }) => author ? {
6009
+ ...comment,
6010
+ author
6011
+ } : comment));
5960
6012
  } while (after);
5961
6013
  return comments;
5962
6014
  }
@@ -7056,6 +7108,30 @@ function repairEnvironment(environment = {}, githubConfigDirectory, identity = {
7056
7108
  GIT_TERMINAL_PROMPT: "0"
7057
7109
  };
7058
7110
  }
7111
+ // src/babysitter/repair-evidence.ts
7112
+ function changedEvidence(before, after) {
7113
+ const changes = [];
7114
+ if (before.pr?.head?.sha !== after.pr?.head?.sha) changes.push("head");
7115
+ if (before.pr?.base?.ref !== after.pr?.base?.ref) changes.push("base");
7116
+ for (const field of [
7117
+ "title",
7118
+ "body",
7119
+ "draft"
7120
+ ]) if (before.pr?.[field] !== after.pr?.[field]) changes.push(`pr.${field}`);
7121
+ for (const field of [
7122
+ "comments",
7123
+ "reviews",
7124
+ "reviewComments",
7125
+ "checks",
7126
+ "statuses"
7127
+ ]) for (const [key, value] of Object.entries(after[field])) if (JSON.stringify(before[field][key]) !== JSON.stringify(value)) changes.push(`${field}:${key}`);
7128
+ const threads = new Map(before.threads.map((thread) => [String(thread.node_id ?? thread.id), JSON.stringify(thread)]));
7129
+ for (const thread of after.threads) {
7130
+ const id = String(thread.node_id ?? thread.id);
7131
+ if (threads.get(id) !== JSON.stringify(thread)) changes.push(`threads:${id}`);
7132
+ }
7133
+ return changes.length > 20 ? [...changes.slice(0, 20), `+${changes.length - 20} more`] : changes;
7134
+ }
7059
7135
  // src/babysitter/wait.ts
7060
7136
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
7061
7137
  const pending = /* @__PURE__ */ new Set([
@@ -7341,13 +7417,14 @@ function createCheckWait(observed, policy) {
7341
7417
  };
7342
7418
  }
7343
7419
  /** Why a parked PR needs a model pass or a direct merge. Empty means it keeps waiting. */
7344
- function wakeReasons(s, requiredChecks, policy) {
7420
+ function wakeReasons(s, requiredChecks, policy, repairOwnPush = false) {
7345
7421
  const wait = s.wait;
7346
7422
  if (!wait) return ["no-wait"];
7347
7423
  if (s.pr?.state !== "open") return ["not-open"];
7348
7424
  if (wait.headSha !== s.pr.head?.sha) return [];
7349
7425
  const known = new Set(wait.knownFailures ?? []);
7350
7426
  if (wait.defer === "checks") {
7427
+ if (repairOwnPush) return ["new-failure"];
7351
7428
  const conflict = s.pr.mergeable === false || s.pr.mergeable_state === "dirty";
7352
7429
  if (!conflict && checksStillRunning(s, Date.now(), policy)) return [];
7353
7430
  const failure = actionableFailureKeys(s, policy).some((key) => !known.has(key));
@@ -7428,6 +7505,15 @@ function createProviderQuota(store, cooldownMs, now = Date.now) {
7428
7505
  }
7429
7506
  };
7430
7507
  }
7508
+ function isProviderRateLimit(error) {
7509
+ if (error instanceof Error && error.name === "AbortError") return false;
7510
+ if (error instanceof RateLimitedError) return true;
7511
+ return [error, error instanceof Error ? error.cause : void 0].some((candidate) => isRuntimeRecord(candidate) && candidate.code === "AGENT_R0726" && hasRuntimeType(candidate.message, "string") && /\b429\b|too many requests|rate limit|\busage limit\b/i.test(candidate.message));
7512
+ }
7513
+ function isProviderFailure(error) {
7514
+ if (error instanceof Error && error.name === "AbortError") return false;
7515
+ return isProviderRateLimit(error) || [error, error instanceof Error ? error.cause : void 0].some((candidate) => isRuntimeRecord(candidate) && hasRuntimeType(candidate.message, "string") && /stream disconnected before completion|stream closed before response\.completed/i.test(candidate.message));
7516
+ }
7431
7517
  const forgeStrikesKey = "forge-quota-strikes";
7432
7518
  const forgeLastBlockKey = "forge-quota-last-block";
7433
7519
  const firstForgeCooldownMs = 3e5;
@@ -8864,17 +8950,6 @@ function mergeResultStatus(error) {
8864
8950
  return;
8865
8951
  }
8866
8952
  }
8867
- /** Provider quota and rate-limit failures. Cancellation is never a rate limit. */
8868
- function isProviderRateLimit(error) {
8869
- if (error instanceof Error && error.name === "AbortError") return false;
8870
- if (error instanceof RateLimitedError) return true;
8871
- return [error, error instanceof Error ? error.cause : void 0].some((candidate) => isRuntimeRecord(candidate) && candidate.code === "AGENT_R0726" && hasRuntimeType(candidate.message, "string") && /\b429\b|too many requests|rate limit|\busage limit\b/i.test(candidate.message));
8872
- }
8873
- /** A provider failure that says nothing about the PR: a rate limit or a stream the provider dropped. */
8874
- function isProviderFailure(error) {
8875
- if (error instanceof Error && error.name === "AbortError") return false;
8876
- return isProviderRateLimit(error) || [error, error instanceof Error ? error.cause : void 0].some((candidate) => isRuntimeRecord(candidate) && hasRuntimeType(candidate.message, "string") && /stream disconnected before completion|stream closed before response\.completed/i.test(candidate.message));
8877
- }
8878
8953
  /** A provider failure this soon after dispatch gives the daily pass back. A longer pass did real work. */
8879
8954
  const providerFailureReleaseMs = 6e5;
8880
8955
  function createBabysitterRuntime(options) {
@@ -8977,7 +9052,7 @@ function createBabysitterRuntime(options) {
8977
9052
  ignoreAssessedBotThreads: presetOptions.ignoreAssessedBotThreads === true
8978
9053
  };
8979
9054
  const schedulerEvent = (name, properties = {}) => options.event?.(name, properties);
8980
- const release = baseAgent.version ?? "756b06da1a98b116856ea2318509abcf6db920a1168e3f29c9dad2e604df4095";
9055
+ const release = baseAgent.version ?? "7fd99b60ad33356545ce233e0675580c666313fbf3f50e93db479920a1ba9fad";
8981
9056
  const workspaces = options.workspaces;
8982
9057
  const schedulerError = (name, error, properties = {}) => options.error?.(name, error, properties);
8983
9058
  const statusComment = !!verifiedHostIdentity && presetOptions.status?.comment !== false;
@@ -9405,20 +9480,24 @@ function createBabysitterRuntime(options) {
9405
9480
  }
9406
9481
  /**
9407
9482
  * Failed checks that ran on an older base get one retest on the current base before a model pass,
9408
- * when the base tip has no failing check. One retest per PR every six hours.
9483
+ * when the base tip has no failing check. It does not wait for the head's other checks: they run on
9484
+ * the same old base. Two retests per PR every six hours, so a retest that lands on a base that is
9485
+ * still broken gets one more after the base is fixed.
9409
9486
  */
9410
9487
  async function retestOnCurrentBase(snapshot, owner, signal) {
9411
9488
  const { repository, number } = snapshot;
9412
9489
  const pr = snapshot.pr;
9413
9490
  const head = pr?.head?.sha;
9414
9491
  if (!head || !pr?.base?.ref || pr.draft || pr.mergeable === false || pr.mergeable_state === "dirty") return false;
9415
- if (!failureKeys(snapshot).length || checksStillRunning(snapshot)) return false;
9416
- const key = `base-retest:${repository}#${number}`;
9417
- if ((await pullRequestInbox.metaNumber(key) ?? 0) > Date.now() - 216e5) return false;
9492
+ if (!failureKeys(snapshot).length) return false;
9493
+ const key = `base-retests:${repository}#${number}`;
9494
+ const saved = await pullRequestInbox.meta(key);
9495
+ const recent = (Array.isArray(saved) ? saved : []).filter((at) => hasRuntimeType(at, "number") && at > Date.now() - 216e5);
9496
+ if (recent.length >= 2) return false;
9418
9497
  const ahead = await baseFixedSinceFailure(freshnessReader, snapshot, failedConclusions, signal);
9419
9498
  if (!ahead) return false;
9420
9499
  if (!await updateBranch(owner, repository, number, head, signal, pr)) return false;
9421
- await pullRequestInbox.setMeta(key, Date.now());
9500
+ await pullRequestInbox.setMeta(key, [...recent, Date.now()]);
9422
9501
  schedulerEvent("babysitter.branch.retest", {
9423
9502
  ...owner,
9424
9503
  base_ahead: ahead
@@ -9429,9 +9508,10 @@ function createBabysitterRuntime(options) {
9429
9508
  /**
9430
9509
  * A job that a runner or network error stopped gets a fresh CI run: the host updates the branch, once
9431
9510
  * per head and base and at most hourly per PR. Without it, a PR waits for hours on a transient error,
9432
- * such as a 504 from a setup action, that nothing retries.
9511
+ * such as a 504 from a setup action, that nothing retries. A cancelled required check gets the same
9512
+ * retest: a cancel or a job timeout has no code cause for a pass to repair.
9433
9513
  */
9434
- async function retestInfrastructureFailure(snapshot, owner, signal) {
9514
+ async function retestInfrastructureFailure(snapshot, owner, signal, cause = "infrastructure") {
9435
9515
  const { repository, number } = snapshot;
9436
9516
  const pr = snapshot.pr;
9437
9517
  const head = pr?.head?.sha;
@@ -9447,7 +9527,7 @@ function createBabysitterRuntime(options) {
9447
9527
  if (!await updateBranch(owner, repository, number, head, signal, pr)) return false;
9448
9528
  schedulerEvent("babysitter.branch.retest", {
9449
9529
  ...owner,
9450
- cause: "infrastructure"
9530
+ cause
9451
9531
  });
9452
9532
  return true;
9453
9533
  }
@@ -9758,11 +9838,11 @@ function createBabysitterRuntime(options) {
9758
9838
  return hasRuntimeType(sha, "string") && /^[a-f\d]{40}$/i.test(sha) ? sha : void 0;
9759
9839
  }
9760
9840
  /** Current-head Actions checks that repeat the same job failure on the live base tip. */
9761
- async function readInheritedBaseFailures(snapshot, signal, verificationBaseSha) {
9841
+ async function readInheritedBaseFailures(snapshot, signal, verificationBaseSha, whileRunning = false) {
9762
9842
  const { repository } = snapshot;
9763
9843
  const head = snapshot.pr?.head?.sha;
9764
9844
  const baseRef = snapshot.pr?.base?.ref;
9765
- if (!head || !baseRef || conflicted(snapshot) || checksStillRunning(snapshot)) return [];
9845
+ if (!head || !baseRef || conflicted(snapshot) || !whileRunning && checksStillRunning(snapshot)) return [];
9766
9846
  const failing = currentActionRuns(snapshot, waitPolicy.pendingReviewChecks).filter((check) => failedConclusions.has(String(check.conclusion)));
9767
9847
  if (!failing.length) return [];
9768
9848
  const tip = verificationBaseSha ?? await liveBaseTip(repository, baseRef, signal);
@@ -9791,20 +9871,22 @@ function createBabysitterRuntime(options) {
9791
9871
  return ids;
9792
9872
  }
9793
9873
  const inheritedFailures = /* @__PURE__ */ new Map();
9794
- async function inheritedBaseFailures(snapshot, signal) {
9874
+ async function inheritedBaseFailures(snapshot, signal, whileRunning = false) {
9795
9875
  try {
9796
- return await readInheritedBaseFailures(snapshot, signal);
9876
+ return await readInheritedBaseFailures(snapshot, signal, void 0, whileRunning);
9797
9877
  } catch (error) {
9798
9878
  if (isAbortError(error)) throw error;
9799
9879
  await noteForgeQuota(error, "inherited-failures");
9800
9880
  return [];
9801
9881
  }
9802
9882
  }
9883
+ function failedSignals(snapshot) {
9884
+ return latestCheckSignals(snapshot).filter((check) => failedConclusions.has(String(check.conclusion ?? check.state)) && !waitPolicy.pendingReviewChecks.has(String(check.name ?? check.context).toLowerCase()));
9885
+ }
9803
9886
  /** Why each failing current-head check outside the review checks fails. A cause the host cannot prove is `pr`. */
9804
- async function failureCauses(snapshot, signal) {
9805
- const failing = latestCheckSignals(snapshot).filter((check) => failedConclusions.has(String(check.conclusion ?? check.state)) && !waitPolicy.pendingReviewChecks.has(String(check.name ?? check.context).toLowerCase()));
9887
+ async function failureCauses(snapshot, signal, failing = failedSignals(snapshot), whileRunning = false) {
9806
9888
  if (!failing.length) return [];
9807
- const inherited = new Set(await inheritedBaseFailures(snapshot, signal));
9889
+ const inherited = new Set(await inheritedBaseFailures(snapshot, signal, whileRunning));
9808
9890
  const causes = [];
9809
9891
  for (const check of failing) {
9810
9892
  const name = String(check.name ?? check.context);
@@ -9890,6 +9972,7 @@ function createBabysitterRuntime(options) {
9890
9972
  const { provider, repo } = await forge(repository);
9891
9973
  return await forgeBranchRules(provider, repo, branch);
9892
9974
  });
9975
+ const mergeBlockers = /* @__PURE__ */ new WeakMap();
9893
9976
  /**
9894
9977
  * Merges a PR that inbox evidence, the merge policy, and GitHub's live state all report ready.
9895
9978
  * Returns `not-ready` for a normal pass, and `blocked` while a merge outcome is unknown.
@@ -9898,6 +9981,14 @@ function createBabysitterRuntime(options) {
9898
9981
  if (merge.mode !== "direct") return "not-ready";
9899
9982
  const { snapshot } = claim;
9900
9983
  const { repository, number } = snapshot;
9984
+ mergeBlockers.delete(claim);
9985
+ const mergeSkipped = (reason) => {
9986
+ mergeBlockers.set(claim, reason);
9987
+ schedulerEvent("babysitter.direct_merge.skipped", {
9988
+ ...owner,
9989
+ reason
9990
+ });
9991
+ };
9901
9992
  const base = snapshot.pr?.base?.ref;
9902
9993
  if (!base) return "not-ready";
9903
9994
  const pending = await pullRequestInbox.directMergeAttempt(repository, number);
@@ -10014,10 +10105,7 @@ function createBabysitterRuntime(options) {
10014
10105
  }
10015
10106
  } catch (error) {
10016
10107
  await noteForgeQuota(error, "merge-reconcile");
10017
- schedulerEvent("babysitter.direct_merge.skipped", {
10018
- ...owner,
10019
- reason: `merge outcome unknown: ${(error instanceof Error ? error.message : String(error)).slice(0, 160)}`
10020
- });
10108
+ mergeSkipped(`merge outcome unknown: ${(error instanceof Error ? error.message : String(error)).slice(0, 160)}`);
10021
10109
  return await parkMerge("GitHub merge outcome could not be reconciled; retrying the provider read.");
10022
10110
  }
10023
10111
  if (signal.aborted) return "blocked";
@@ -10067,10 +10155,7 @@ function createBabysitterRuntime(options) {
10067
10155
  };
10068
10156
  }
10069
10157
  if (!decision.ready) {
10070
- schedulerEvent("babysitter.direct_merge.skipped", {
10071
- ...owner,
10072
- reason: decision.reason
10073
- });
10158
+ mergeSkipped(decision.reason);
10074
10159
  return pending?.asynchronous ? await parkMerge(`Unconfirmed merge is waiting for ${decision.reason}.`) : "not-ready";
10075
10160
  }
10076
10161
  const everyCheckGates = policy.status === "known" && !policy.required.length;
@@ -10083,10 +10168,7 @@ function createBabysitterRuntime(options) {
10083
10168
  });
10084
10169
  const until = since + firstCheckWaitMs;
10085
10170
  if (until > pullRequestInbox.now()) {
10086
- schedulerEvent("babysitter.direct_merge.skipped", {
10087
- ...owner,
10088
- reason: "no check reported for the head yet"
10089
- });
10171
+ mergeSkipped("no check reported for the head yet");
10090
10172
  return await parkMerge(`GitHub has reported no check for ${decision.head} yet; waiting until ${new Date(until).toISOString()} for its first check.`, until);
10091
10173
  }
10092
10174
  }
@@ -10097,10 +10179,7 @@ function createBabysitterRuntime(options) {
10097
10179
  let mergeStarted = false;
10098
10180
  const bypass = evaluation.bypassedRequiredChecks.length > 0;
10099
10181
  if (foldInto !== void 0 && bypass) {
10100
- schedulerEvent("babysitter.direct_merge.skipped", {
10101
- ...owner,
10102
- reason: "a fold never merges past failing required checks"
10103
- });
10182
+ mergeSkipped("a fold never merges past failing required checks");
10104
10183
  return pending?.asynchronous ? await parkMerge("Unconfirmed fold is waiting for passing required checks.") : "not-ready";
10105
10184
  }
10106
10185
  let inheritedProof;
@@ -10123,10 +10202,7 @@ function createBabysitterRuntime(options) {
10123
10202
  ...foldInto === void 0 ? {} : { foldInto: base }
10124
10203
  });
10125
10204
  if (!current.ready) {
10126
- schedulerEvent("babysitter.direct_merge.skipped", {
10127
- ...owner,
10128
- reason: current.reason
10129
- });
10205
+ mergeSkipped(current.reason);
10130
10206
  if (!pending && current.reason === "mergeable_state behind") {
10131
10207
  if (!await updateBranch(owner, repository, number, decision.head, signal, live, { reopenFork: false })) return "not-ready";
10132
10208
  schedulerEvent("babysitter.branch.updated", {
@@ -10144,10 +10220,7 @@ function createBabysitterRuntime(options) {
10144
10220
  }, signal, bypass ? /* @__PURE__ */ new Set(["success", ...failedConclusions]) : void 0);
10145
10221
  if (overlap.length) {
10146
10222
  const files = overlap.slice(0, 3).join(", ") + (overlap.length > 3 ? ` and ${overlap.length - 3} more` : "");
10147
- schedulerEvent("babysitter.direct_merge.skipped", {
10148
- ...owner,
10149
- reason: `${base} changed files this PR touches after its checks ran: ${files}`
10150
- });
10223
+ mergeSkipped(`${base} changed files this PR touches after its checks ran: ${files}`);
10151
10224
  if (!await updateBranch(owner, repository, number, decision.head, signal, live)) {
10152
10225
  const reopened = isForkHead(live, repository) ? await pullRequestInbox.meta(forkReopenKey(repository, number)) : void 0;
10153
10226
  const at = isRuntimeRecord(reopened) ? Number(reopened.at) : NaN;
@@ -10203,10 +10276,7 @@ function createBabysitterRuntime(options) {
10203
10276
  });
10204
10277
  }
10205
10278
  if (branchSafety !== true) {
10206
- schedulerEvent("babysitter.direct_merge.skipped", {
10207
- ...owner,
10208
- reason: branchSafety
10209
- });
10279
+ mergeSkipped(branchSafety);
10210
10280
  return pending?.asynchronous ? await parkMerge(`Unconfirmed merge is waiting for ${branchSafety}.`) : "not-ready";
10211
10281
  }
10212
10282
  if (foldInto !== void 0) {
@@ -10217,10 +10287,7 @@ function createBabysitterRuntime(options) {
10217
10287
  }, signal);
10218
10288
  const reason = foldParent(live, owners)?.number !== foldInto ? `parent #${foldInto} no longer owns ${base}` : await pullRequestInbox.directMergeAttempt(repository, foldInto) ? `parent #${foldInto} has a merge in flight` : void 0;
10219
10289
  if (reason) {
10220
- schedulerEvent("babysitter.direct_merge.skipped", {
10221
- ...owner,
10222
- reason
10223
- });
10290
+ mergeSkipped(reason);
10224
10291
  return pending?.asynchronous ? await parkMerge(`Unconfirmed fold is waiting: ${reason}.`) : "not-ready";
10225
10292
  }
10226
10293
  }
@@ -10233,29 +10300,20 @@ function createBabysitterRuntime(options) {
10233
10300
  const freshEvaluation = await checkEvaluation(fresh, policy, signal);
10234
10301
  const freshDecision = readiness(fresh, freshEvaluation.state, freshEvaluation.inheritedCheckIds);
10235
10302
  if (!freshDecision.ready) {
10236
- schedulerEvent("babysitter.direct_merge.skipped", {
10237
- ...owner,
10238
- reason: `GitHub reports checks the inbox lacks: ${freshDecision.reason}`
10239
- });
10303
+ mergeSkipped(`GitHub reports checks the inbox lacks: ${freshDecision.reason}`);
10240
10304
  if (await pullRequestInbox.hydrate(claim, reported)) return pending ? await parkMerge(`Unconfirmed merge is waiting for ${freshDecision.reason}.`) : "not-ready";
10241
10305
  await pullRequestInbox.release(claim);
10242
10306
  return "blocked";
10243
10307
  }
10244
10308
  }
10245
10309
  if (!await pullRequestInbox.isClaimCurrent(claim)) {
10246
- schedulerEvent("babysitter.direct_merge.skipped", {
10247
- ...owner,
10248
- reason: "claim changed before merge"
10249
- });
10310
+ mergeSkipped("claim changed before merge");
10250
10311
  return "not-ready";
10251
10312
  }
10252
10313
  if (bypass && isRuntimeRecord(live)) {
10253
10314
  const proof = await verifyInheritedMerge(snapshot, live, signal);
10254
10315
  if ("refused" in proof) {
10255
- schedulerEvent("babysitter.direct_merge.skipped", {
10256
- ...owner,
10257
- reason: proof.refused
10258
- });
10316
+ mergeSkipped(proof.refused);
10259
10317
  return pending?.asynchronous ? await parkMerge("Unconfirmed merge is waiting for inherited-check verification.") : "not-ready";
10260
10318
  }
10261
10319
  inheritedProof = proof;
@@ -10264,10 +10322,7 @@ function createBabysitterRuntime(options) {
10264
10322
  }
10265
10323
  signal.throwIfAborted();
10266
10324
  if (!pending && !await pullRequestInbox.beginDirectMerge(claim, decision.head, true, foldInto)) {
10267
- schedulerEvent("babysitter.direct_merge.skipped", {
10268
- ...owner,
10269
- reason: "merge attempt already in flight or claim changed"
10270
- });
10325
+ mergeSkipped("merge attempt already in flight or claim changed");
10271
10326
  return "blocked";
10272
10327
  }
10273
10328
  if (inheritedProof) {
@@ -10304,10 +10359,7 @@ function createBabysitterRuntime(options) {
10304
10359
  }
10305
10360
  } catch (error) {
10306
10361
  await noteForgeQuota(error, "direct-merge");
10307
- schedulerEvent("babysitter.direct_merge.skipped", {
10308
- ...owner,
10309
- reason: (error instanceof Error ? error.message : String(error)).slice(0, 200)
10310
- });
10362
+ mergeSkipped((error instanceof Error ? error.message : String(error)).slice(0, 200));
10311
10363
  const rejectedStatus = forgeErrorStatus(error);
10312
10364
  if (mergeStarted && rejectedStatus !== void 0 && rejectedStatus >= 400 && rejectedStatus < 500 && rejectedStatus !== 409) await pullRequestInbox.clearDirectMerge(repository, number, mergeToken);
10313
10365
  return await parkMerge(`GitHub merge request failed: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`);
@@ -10329,7 +10381,7 @@ function createBabysitterRuntime(options) {
10329
10381
  return "merged";
10330
10382
  }
10331
10383
  await pullRequestInbox.finish(claim, {
10332
- text: inheritedProof ? `Merged ${decision.head} directly past ${inheritedProof.evaluation.bypassedRequiredChecks.join(", ")}, which fail the same way on base ${inheritedProof.baseSha}; every other merge rule was satisfied.` : `Merged ${decision.head} directly: required checks passed and review threads were resolved.`,
10384
+ text: inheritedProof ? `Merged ${decision.head} directly past ${inheritedProof.evaluation.bypassedRequiredChecks.join(", ")}, which fail the same way on base ${inheritedProof.baseSha}; every other merge rule was satisfied.` : `Merged ${decision.head} directly: required checks and review gates passed.`,
10333
10385
  terminal: true
10334
10386
  });
10335
10387
  schedulerEvent("babysitter.owner.merged", {
@@ -10540,6 +10592,19 @@ function createBabysitterRuntime(options) {
10540
10592
  async function requiredCheckState(snapshot, signal, fold = false) {
10541
10593
  return (await requiredCheckEvaluation(snapshot, signal, fold))?.state ?? "unknown";
10542
10594
  }
10595
+ async function cancelledRequiredCheck(snapshot, signal) {
10596
+ if (checksStillRunning(snapshot, Date.now(), waitPolicy)) return false;
10597
+ return (await requiredCheckEvaluation(snapshot, signal))?.checks.some((check) => check.cancelled) ?? false;
10598
+ }
10599
+ async function ownRepairFailed(snapshot, signal) {
10600
+ if (!snapshot.hostHeads?.some((entry) => entry.repair && entry.head === snapshot.pr?.head?.sha)) return false;
10601
+ const failures = failedSignals(snapshot);
10602
+ if (!failures.length) return false;
10603
+ const required = snapshot.pr?.base?.ref ? (await requiredCheckPolicy(snapshot)).required : [];
10604
+ const candidates = failures.filter((check) => actionLocation(snapshot.repository, check) || required.some((rule) => rule.context === check.name && (!check.app || rule.appId === null || check.app.id === rule.appId)));
10605
+ if (!candidates.length) return false;
10606
+ return !unrelatedFailureWait(await failureCauses(snapshot, signal, candidates, true), snapshot.pr?.base?.ref ?? "the base");
10607
+ }
10543
10608
  async function hasRepairableActionsFailure(snapshot, signal) {
10544
10609
  if (!failedOwnActions(snapshot, waitPolicy.pendingReviewChecks).length || await requiredCheckState(snapshot, signal) !== "failed") return false;
10545
10610
  return !unrelatedFailureWait(await failureCauses(snapshot, signal), snapshot.pr?.base?.ref ?? "the base");
@@ -10737,6 +10802,7 @@ function createBabysitterRuntime(options) {
10737
10802
  if ((await pullRequestInbox.metaNumber(recoveryKey) ?? 0) > Date.now()) continue;
10738
10803
  signal.throwIfAborted();
10739
10804
  await pullRequestInbox.setMeta(recoveryKey, Date.now() + 6e5, signal);
10805
+ if (await ownRepairFailed(snapshot, signal)) continue;
10740
10806
  signal.throwIfAborted();
10741
10807
  if (await pullRequestInbox.wake(snapshot, `ci-recovery:${head}`, {
10742
10808
  recovery: true,
@@ -10778,7 +10844,7 @@ function createBabysitterRuntime(options) {
10778
10844
  const held = new Set(Array.isArray(saved) ? saved.filter((item) => hasRuntimeType(item, "string")) : []);
10779
10845
  return new Set(snapshot.threads.filter((thread) => thread.isResolved !== true).map((thread) => String(thread.node_id ?? thread.id)).filter((id) => held.has(id)));
10780
10846
  }
10781
- /** Wakes a parked PR only when its new events need a model pass or a direct merge. */
10847
+ /** Retests deferred checks on a fixed base, or wakes a parked PR when its new events need work. */
10782
10848
  async function evaluateWaits(step, signal) {
10783
10849
  signal.throwIfAborted();
10784
10850
  for (const snapshot of await pullRequestInbox.waitsToEvaluate(true, true)) {
@@ -10789,10 +10855,11 @@ function createBabysitterRuntime(options) {
10789
10855
  const checkSignal = AbortSignal.any([signal, AbortSignal.timeout(12e4)]);
10790
10856
  const checks = await requiredCheckState(snapshot, checkSignal);
10791
10857
  signal.throwIfAborted();
10858
+ const repairOwnPush = snapshot.wait?.defer === "checks" && snapshot.wait.headSha === snapshot.pr?.head?.sha && await ownRepairFailed(snapshot, checkSignal);
10792
10859
  let reasons = wakeReasons(snapshot, checks, {
10793
10860
  ...waitPolicy,
10794
10861
  heldThreads: await heldOpenThreads(snapshot)
10795
- });
10862
+ }, repairOwnPush);
10796
10863
  signal.throwIfAborted();
10797
10864
  if (parentMerged) reasons.push("stack-parent-merged");
10798
10865
  if (snapshot.wait?.reason === "non-default-base" && snapshot.pr && !nonDefaultBase(snapshot.pr)) reasons.push("base-retargeted");
@@ -10820,11 +10887,13 @@ function createBabysitterRuntime(options) {
10820
10887
  repository: snapshot.repository
10821
10888
  };
10822
10889
  if (!reasons.length) {
10890
+ const retested = merge.mode === "direct" && !repairOwnPush && snapshot.wait?.defer === "checks" && snapshot.pr?.state === "open" && snapshot.wait.headSha === snapshot.pr.head?.sha && snapshot.generation > snapshot.handled && await retestOnCurrentBase(snapshot, owner, checkSignal);
10823
10891
  await pullRequestInbox.acknowledgeWait(snapshot, signal);
10824
10892
  schedulerEvent("babysitter.wait.kept", {
10825
10893
  ...owner,
10826
10894
  head_sha: snapshot.pr?.head?.sha,
10827
- avoided_invocation: true
10895
+ avoided_invocation: true,
10896
+ ...retested && { reason: "retest-on-current-base" }
10828
10897
  });
10829
10898
  } else if (await pullRequestInbox.wake(snapshot, `evaluated:${snapshot.generation}:${snapshot.revision ?? 0}`, { signal })) schedulerEvent("babysitter.wait.woken", {
10830
10899
  ...owner,
@@ -11267,6 +11336,7 @@ function createBabysitterRuntime(options) {
11267
11336
  });
11268
11337
  const passController = new AbortController();
11269
11338
  let evidenceChanged;
11339
+ let evidenceChanges;
11270
11340
  const passSignal = AbortSignal.any([AbortSignal.timeout(36e5), passController.signal]);
11271
11341
  let providerDirectory;
11272
11342
  let conflictWork;
@@ -11300,7 +11370,7 @@ function createBabysitterRuntime(options) {
11300
11370
  modelWorkParked = true;
11301
11371
  outcome = "waiting";
11302
11372
  await pullRequestInbox.finish(inboxClaim, {
11303
- text: providerBlocked ? `CI reconciliation completed; provider quota cooldown ends at ${new Date(providerBlockedUntil).toISOString()}.` : admitted ? "CI reconciliation completed; the same-head repair budget is exhausted." : "CI reconciliation completed; model work is waiting for host admission.",
11373
+ text: providerBlocked ? `CI reconciliation completed; provider quota cooldown ends at ${new Date(providerBlockedUntil).toISOString()}.` : admitted ? `CI reconciliation completed; the same-head repair budget is exhausted.${mergeBlockers.has(inboxClaim) ? ` It does not merge yet: ${mergeBlockers.get(inboxClaim)}.` : ""}` : "CI reconciliation completed; model work is waiting for host admission.",
11304
11374
  ...pushedHead ? {
11305
11375
  progress: pushProgress(pushedHead, reviewDrivenPush()),
11306
11376
  verifiedPushHeads: [...verifiedPushHeads]
@@ -11434,13 +11504,15 @@ function createBabysitterRuntime(options) {
11434
11504
  * Parks the claim before its first model dispatch when `dailyPassBudget` passes started in the
11435
11505
  * last 24 hours, until the oldest leaves the window. Exempt work still gets a pass.
11436
11506
  */
11437
- const parkSpentDailyPassBudget = async () => {
11507
+ const parkSpentDailyPassBudget = async (observed) => {
11438
11508
  if (modelDispatched || pushedHead || dailyPassBudget === false) return false;
11509
+ dailyPassExemptionUsed = void 0;
11510
+ const snapshot = observed ?? inboxClaim.snapshot;
11439
11511
  const now = Date.now();
11440
- const budget = (await pullRequestInbox.get(repository, number))?.dailyPassBudget;
11512
+ const budget = observed ? observed.dailyPassBudget : (await pullRequestInbox.get(repository, number))?.dailyPassBudget;
11441
11513
  const resumeAt = dailyPassResumeAt(budget, dailyPassBudget, now);
11442
11514
  if (resumeAt === void 0) return false;
11443
- if (pullRequestInbox.isPriority(inboxClaim.snapshot.pr)) {
11515
+ if (pullRequestInbox.isPriority(snapshot.pr)) {
11444
11516
  schedulerEvent("babysitter.daily_pass_budget.exempt", {
11445
11517
  ...owner,
11446
11518
  head_sha: inboxClaim.snapshot.pr?.head?.sha,
@@ -11448,9 +11520,8 @@ function createBabysitterRuntime(options) {
11448
11520
  });
11449
11521
  return false;
11450
11522
  }
11451
- const requiredChecks = await requiredCheckState(inboxClaim.snapshot);
11452
- const openPushWindow = (requiredChecks === "failed" ? await repairPushWindow(inboxClaim.snapshot, requiredChecks, false) : void 0)?.allowed ? Math.max(0, ...await repairPushTimes(inboxClaim.snapshot)) : void 0;
11453
- const exemption = dailyPassExemption(inboxClaim.snapshot, requiredChecks, budget, openPushWindow);
11523
+ const requiredChecks = await requiredCheckState(snapshot);
11524
+ const exemption = dailyPassExemption(snapshot, requiredChecks, budget, (requiredChecks === "failed" ? await repairPushWindow(snapshot, requiredChecks, false) : void 0)?.allowed ? Math.max(0, ...await repairPushTimes(snapshot)) : void 0);
11454
11525
  if (exemption) {
11455
11526
  dailyPassExemptionUsed = exemption;
11456
11527
  schedulerEvent("babysitter.daily_pass_budget.exempt", {
@@ -11463,10 +11534,14 @@ function createBabysitterRuntime(options) {
11463
11534
  modelWorkParked = true;
11464
11535
  outcome = "waiting";
11465
11536
  const passes = budget?.passes.filter((at) => at > now - 864e5).length ?? 0;
11466
- await pullRequestInbox.finish(inboxClaim, {
11537
+ await pullRequestInbox.finish({
11538
+ ...inboxClaim,
11539
+ snapshot,
11540
+ generation: snapshot.generation
11541
+ }, {
11467
11542
  text: `Daily pass budget spent: ${passes} model pass${passes === 1 ? "" : "es"} in the last 24 hours (dailyPassBudget ${dailyPassBudget}). The next pass can start at ${new Date(resumeAt).toISOString()}. A person's comment or review, the first failing required check on a head, a head whose required checks pass, or a merge conflict still starts a pass.`,
11468
11543
  wait: {
11469
- ...createCheckWait(inboxClaim.snapshot, waitPolicy),
11544
+ ...createCheckWait(snapshot, waitPolicy),
11470
11545
  reason: "daily-pass-budget",
11471
11546
  retryAt: resumeAt
11472
11547
  }
@@ -11629,7 +11704,8 @@ function createBabysitterRuntime(options) {
11629
11704
  return;
11630
11705
  }
11631
11706
  }
11632
- if (merge.mode === "direct" && await retestOnCurrentBase(inboxClaim.snapshot, owner, passSignal)) {
11707
+ const repairOwnPush = await ownRepairFailed(inboxClaim.snapshot, passSignal);
11708
+ if (merge.mode === "direct" && !repairOwnPush && await retestOnCurrentBase(inboxClaim.snapshot, owner, passSignal)) {
11633
11709
  outcome = "waiting";
11634
11710
  await pullRequestInbox.finish(inboxClaim, {
11635
11711
  text: inboxClaim.snapshot.lastResult || `Updated the branch with ${inboxClaim.snapshot.pr?.base?.ref} to retest its failed checks on the current base.`,
@@ -11643,7 +11719,21 @@ function createBabysitterRuntime(options) {
11643
11719
  });
11644
11720
  return;
11645
11721
  }
11646
- const deferral = await pendingGateDeferral(inboxClaim.snapshot);
11722
+ if (merge.mode === "direct" && !repairOwnPush && await cancelledRequiredCheck(inboxClaim.snapshot, passSignal) && await retestInfrastructureFailure(inboxClaim.snapshot, owner, passSignal, "cancelled")) {
11723
+ outcome = "waiting";
11724
+ await pullRequestInbox.finish(inboxClaim, {
11725
+ text: `A required check was cancelled. Updated the branch with ${inboxClaim.snapshot.pr?.base?.ref} for a fresh CI run.`,
11726
+ wait: createCheckWait(inboxClaim.snapshot, waitPolicy)
11727
+ });
11728
+ schedulerEvent("babysitter.wait.kept", {
11729
+ ...owner,
11730
+ head_sha: inboxClaim.snapshot.pr?.head?.sha,
11731
+ avoided_invocation: true,
11732
+ reason: "cancelled-check-retest"
11733
+ });
11734
+ return;
11735
+ }
11736
+ const deferral = repairOwnPush ? void 0 : await pendingGateDeferral(inboxClaim.snapshot);
11647
11737
  if (deferral) {
11648
11738
  await pullRequestInbox.finish(inboxClaim, {
11649
11739
  text: inboxClaim.snapshot.lastResult || `Waiting for ${deferral} before the next pass.`,
@@ -11689,7 +11779,7 @@ function createBabysitterRuntime(options) {
11689
11779
  await pullRequestInbox.release(inboxClaim);
11690
11780
  return;
11691
11781
  }
11692
- const ciRecovery = ciRecoveryEnabled ? await rerunFailedActions(pullRequestInbox, inboxClaim, (await forge(repository, passSignal)).provider, Date.now(), passSignal) : void 0;
11782
+ const ciRecovery = ciRecoveryEnabled && !repairOwnPush ? await rerunFailedActions(pullRequestInbox, inboxClaim, (await forge(repository, passSignal)).provider, Date.now(), passSignal) : void 0;
11693
11783
  if (inboxClaim.snapshot.recoveryHead && inboxClaim.snapshot.recoveryHead === inboxClaim.snapshot.pr?.head?.sha && !hasFailedActions(inboxClaim.snapshot)) {
11694
11784
  outcome = "waiting";
11695
11785
  const wait = createCheckWait(inboxClaim.snapshot, waitPolicy);
@@ -11847,6 +11937,13 @@ function createBabysitterRuntime(options) {
11847
11937
  const abortSignal = AbortSignal.any([prepared.signal, passSignal]);
11848
11938
  const repairOperation = new AsyncLocalStorage();
11849
11939
  const ownedResolutions = /* @__PURE__ */ new Map();
11940
+ const metadataFields = ["title", "body"];
11941
+ const metadataWrites = /* @__PURE__ */ new Map();
11942
+ const ownsMetadata = (snapshot, field) => {
11943
+ const write = metadataWrites.get(field);
11944
+ const edit = snapshot.metadataEdits?.[field];
11945
+ return write && edit && edit.generation > write.after && edit.generation !== edit.externalGeneration && snapshot.pr?.[field] === write.value;
11946
+ };
11850
11947
  const repairEvidenceKey = (snapshot, current = snapshot) => {
11851
11948
  const published = !!pushedHead && verifiedPushHeads.has(pushedHead);
11852
11949
  const original = published && snapshot === inboxClaim.snapshot;
@@ -11876,6 +11973,8 @@ function createBabysitterRuntime(options) {
11876
11973
  } : thread),
11877
11974
  pr: snapshot.pr && {
11878
11975
  ...snapshot.pr,
11976
+ title: ownsMetadata(snapshot, "title") ? inboxClaim.snapshot.pr?.title : snapshot.pr.title,
11977
+ body: ownsMetadata(snapshot, "body") ? inboxClaim.snapshot.pr?.body : snapshot.pr.body,
11879
11978
  head: snapshot.pr.head && {
11880
11979
  ...snapshot.pr.head,
11881
11980
  sha: published ? pullRequest.headRefOid : snapshot.pr.head.sha
@@ -11909,12 +12008,18 @@ function createBabysitterRuntime(options) {
11909
12008
  pendingInboxHeads.add(pushedHead);
11910
12009
  }
11911
12010
  const selfHead = observedHead !== pullRequest.headRefOid && verifiedPushHeads.has(observedHead ?? "");
11912
- if (current.generation !== inboxClaim.generation && !((selfHead || repairOperation.getStore()) && repairEvidenceKey(current) === repairEvidenceKey(inboxClaim.snapshot, current))) {
12011
+ const sameHead = observedHead === pullRequest.headRefOid;
12012
+ const externalMetadata = metadataFields.some((field) => (current.metadataEdits?.[field]?.externalGeneration ?? 0) > inboxClaim.generation);
12013
+ if (current.generation !== inboxClaim.generation && (externalMetadata || !((selfHead || sameHead || repairOperation.getStore()) && repairEvidenceKey(current) === repairEvidenceKey(inboxClaim.snapshot, current)))) {
11913
12014
  const changed = evidenceChanged ??= new DOMException("Pull request evidence changed.", "AbortError");
12015
+ evidenceChanges ??= changedEvidence(inboxClaim.snapshot, current);
11914
12016
  schedulerEvent("babysitter.pass.evidence_changed", {
11915
12017
  ...owner,
11916
12018
  head_sha: pullRequest.headRefOid,
11917
- observed_head: observedHead
12019
+ observed_head: observedHead,
12020
+ claim_generation: inboxClaim.generation,
12021
+ generation: current.generation,
12022
+ changes: evidenceChanges
11918
12023
  });
11919
12024
  setTimeout(() => passController.abort(changed), 0);
11920
12025
  throw changed;
@@ -12029,6 +12134,34 @@ function createBabysitterRuntime(options) {
12029
12134
  mentionAllowlist: presetOptions.mentionAllowlist,
12030
12135
  restrictCommentMentions: true,
12031
12136
  commentPrefix: "<!-- vitehub-babysitter-repair:repair -->\n",
12137
+ sendMetadata: async (update, send) => {
12138
+ const current = await assertLease();
12139
+ const previous = new Map(metadataWrites);
12140
+ const writes = metadataFields.flatMap((field) => {
12141
+ const value = update[field];
12142
+ if (value === void 0 || value === current.pr?.[field]) return [];
12143
+ const write = {
12144
+ value,
12145
+ after: current.generation
12146
+ };
12147
+ metadataWrites.set(field, write);
12148
+ return [{
12149
+ field,
12150
+ write
12151
+ }];
12152
+ });
12153
+ try {
12154
+ await send();
12155
+ } catch (error) {
12156
+ for (const { field, write } of writes) {
12157
+ if (metadataWrites.get(field) !== write) continue;
12158
+ const prior = previous.get(field);
12159
+ if (prior) metadataWrites.set(field, prior);
12160
+ else metadataWrites.delete(field);
12161
+ }
12162
+ throw error;
12163
+ }
12164
+ },
12032
12165
  signal: abortSignal,
12033
12166
  autoMerge: merge.mode === "auto" && stackParent === void 0,
12034
12167
  eligible: async (current) => await eligibleNow(repository, normalizePullRequest(current), await pullRequestInbox.get(repository, number), abortSignal),
@@ -12447,14 +12580,18 @@ function createBabysitterRuntime(options) {
12447
12580
  if (workerSettings.sandbox && await parkBlockedModelWork()) throw new DOMException("Provider dispatch is waiting for admission.", "AbortError");
12448
12581
  await acquireModelSlot(abortSignal, `${repository}#${number}`);
12449
12582
  try {
12450
- if (!modelDispatched && dailyPassBudget !== false) {
12583
+ while (!modelDispatched && dailyPassBudget !== false) {
12584
+ const observed = await assertLease();
12585
+ if (await parkSpentDailyPassBudget(observed)) throw new DOMException("Provider dispatch is waiting for its daily pass budget.", "AbortError");
12451
12586
  const exemption = dailyPassExemptionUsed === "human-feedback" ? void 0 : dailyPassExemptionUsed;
12452
- const recorded = await pullRequestInbox.recordModelPass(inboxClaim, exemption);
12453
- if (!recorded || !await pullRequestInbox.isClaimCurrent(inboxClaim)) throw new DOMException("Provider dispatch lost its inbox lease.", "AbortError");
12587
+ const recorded = await pullRequestInbox.recordModelPass(inboxClaim, exemption, observed);
12588
+ if (recorded === "changed") continue;
12589
+ if (!recorded) throw new DOMException("Provider dispatch lost its inbox lease.", "AbortError");
12454
12590
  recordedPass = {
12455
12591
  at: recorded,
12456
12592
  exemption
12457
12593
  };
12594
+ break;
12458
12595
  }
12459
12596
  await assertLease();
12460
12597
  modelDispatched = true;
@@ -12541,7 +12678,10 @@ function createBabysitterRuntime(options) {
12541
12678
  recorded = await pullRequestInbox.finish(inboxClaim, {
12542
12679
  text: resultText,
12543
12680
  progress: { kind: "no-progress" },
12544
- wait: await externalWait(inboxClaim.snapshot, passResult.wait.wake, passResult.wait.reason)
12681
+ wait: {
12682
+ ...await externalWait(inboxClaim.snapshot, passResult.wait.wake, passResult.wait.reason),
12683
+ headSha: pullRequest.headRefOid
12684
+ }
12545
12685
  });
12546
12686
  } else if (disposition === "park" && current?.pr?.head?.sha === pullRequest.headRefOid && (hasPendingChecks(inboxClaim.snapshot, waitPolicy) || !rejectedAssessment && (passResult?.wait?.kind === "checks" && passResult.wait.headSha === pullRequest.headRefOid || passResult?.waitForChecksHead === pullRequest.headRefOid))) {
12547
12687
  outcome = "waiting";
@@ -12640,6 +12780,8 @@ function createBabysitterRuntime(options) {
12640
12780
  });
12641
12781
  schedulerEvent("babysitter.owner.cancelled", {
12642
12782
  reason: "pull-request-state-changed-or-aborted",
12783
+ cause: (error instanceof Error ? error.message : String(error)).slice(0, 200),
12784
+ ...evidenceChanges ? { evidence_changes: evidenceChanges } : {},
12643
12785
  ...owner
12644
12786
  });
12645
12787
  } else if (error instanceof RateLimitedError) {
@@ -12771,4 +12913,4 @@ function withoutCapacity(driver) {
12771
12913
  const { capacity: _capacity, ...rest } = driver;
12772
12914
  return rest;
12773
12915
  }
12774
- 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 };
12916
+ export { budgetParks as a, createGitHubHost as c, isProviderRateLimit as i, pendingMergeRetryAt as n, pullRequestThreadId as o, babysitterQueueHealth as r, createGitHubAppCredentials as s, createBabysitterRuntime as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/presets",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "Ready-made Agents built from ViteHub primitives: Babysitter, Labeller, and the workspace preset.",
5
5
  "keywords": [
6
6
  "agent",
@@ -58,11 +58,11 @@
58
58
  }
59
59
  },
60
60
  "dependencies": {
61
- "@vite-hub/forge": "0.6.1",
62
- "@vite-hub/gateways": "0.6.1",
63
- "@vite-hub/runtime": "0.6.1",
64
- "@vite-hub/sandbox": "0.6.1",
65
- "@vite-hub/workspace": "0.6.1",
61
+ "@vite-hub/forge": "0.8.0",
62
+ "@vite-hub/gateways": "0.8.0",
63
+ "@vite-hub/runtime": "0.8.0",
64
+ "@vite-hub/sandbox": "0.8.0",
65
+ "@vite-hub/workspace": "0.8.0",
66
66
  "@yarnpkg/parsers": "3.1.0",
67
67
  "comark": "^0.9.2",
68
68
  "nostics": "1.4.0",
@@ -72,9 +72,9 @@
72
72
  "devDependencies": {
73
73
  "@libsql/client": "^0.18.0",
74
74
  "@modelcontextprotocol/sdk": "^1.32.2",
75
- "@t3tools/provider-runtime": "https://pkg.pr.new/vite-hub/t3code/@t3tools/provider-runtime@2a519db9ccb4227091f0d8a839d7121af9d6aed5",
75
+ "@t3tools/provider-runtime": "https://pkg.pr.new/vite-hub/t3code/@t3tools/provider-runtime@1ee7ef6",
76
76
  "@types/node": "^24.19.2",
77
- "@vite-hub/agent": "0.6.1",
77
+ "@vite-hub/agent": "0.8.0",
78
78
  "@vite-hub/internal": "0.0.1",
79
79
  "publint": "^0.3.25",
80
80
  "typescript": "^6.0.3",
@@ -82,7 +82,7 @@
82
82
  "vitest": "5.1.0"
83
83
  },
84
84
  "peerDependencies": {
85
- "@vite-hub/agent": "0.6.1"
85
+ "@vite-hub/agent": "0.8.0"
86
86
  },
87
87
  "engines": {
88
88
  "node": ">=24.15.0"