@vite-hub/presets 0.5.1 → 0.6.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.
package/README.md CHANGED
@@ -132,7 +132,7 @@ symlink resolution. Trusted GitHub release archives use the HTTPS archive path.
132
132
  Workers call `commitRepair` with a message and explicit repair paths, then
133
133
  `pushRepair`. The host commits because the provider sandbox protects Git metadata. For a
134
134
  conflicting PR, the host first prepares a merge against the exact base commit.
135
- Installation runs after merge preparation. The worker resolves dependency conflicts and calls `refreshDependencies` before validation, then commits through the same tool. Changing dependency inputs requires another refresh and validation before committing. `commitRepair` rejects a base merge whose result undoes changes the base made since the PR branched: lines the base added that the result lacks, or lines the base removed that it brings back. Lockfiles are exempt because the host regenerates them. When the PR deliberately replaces such a change, the worker passes the file in `baseOverrides` with a reason, and the merge commit message lists it.
135
+ Installation runs after merge preparation. The worker resolves dependency conflicts and calls `refreshDependencies` before validation, then commits through the same tool. Changing dependency inputs requires another refresh and validation before committing. `commitRepair` rejects a base merge whose result undoes changes the base made since the PR branched: lines the base added that the result lacks, or lines the base removed that it brings back. Lockfiles are exempt because the host regenerates them. When the PR deliberately replaces such a change, the worker passes the file in `baseOverrides` with a reason, and the merge commit message lists it. The same check runs for the PR's side: a result that lacks lines the PR added, or brings back lines the PR removed, is rejected unless the worker passes the file in `prOverrides` with a reason. The PR-side check skips a host resolution only if its staged entry is unchanged.
136
136
  Unattended Codex runs preauthorize only the assigned host tools. Capability checks
137
137
  still run on the host, and the native shell keeps its edit sandbox.
138
138
 
@@ -151,7 +151,8 @@ GitHub request results re-enter the current head's normal merge gates. An enqueu
151
151
  | `{ strategy: "direct", method, ready, trustedAuthors, markDraftsReady, bypassInheritedChecks, foldStacks }` | Direct merge with `"squash"`, `"merge"`, or `"rebase"`, an optional `ready` hook, optional trusted authors, optional draft authors, optional required checks to merge past when they only repeat the base's failure, and stack folding (default `true`). |
152
152
 
153
153
  A direct merge needs passing required checks, completed and successful
154
- current-head checks and statuses, loaded and resolved review threads, a
154
+ current-head checks and statuses (a head without any check waits up to one
155
+ minute for its first one when the branch requires none), loaded and resolved review threads, a
155
156
  non-draft PR, and GitHub's live `mergeable_state: "clean"` on the default
156
157
  branch. The merge request pins the head SHA, so a concurrent push makes GitHub
157
158
  reject it. `ready({ repository, number, head, snapshot, requiredChecks })` can
@@ -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-CscUp4ts.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-BGAsF7fH.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";
@@ -47,6 +47,11 @@ export interface BabysitterRuntimeOptions {
47
47
  providerRetryDelayMs?: number;
48
48
  /** Delay between live reads while GitHub computes mergeability before a direct merge. Defaults to 3 seconds. */
49
49
  mergeabilityRetryDelayMs?: number;
50
+ /**
51
+ * How long a head without required checks waits for GitHub to report its first check before a
52
+ * direct merge. GitHub creates the checks of a push some seconds after the push. Defaults to 60 seconds.
53
+ */
54
+ firstCheckWaitMs?: number;
50
55
  admission?: (signal?: AbortSignal) => Promise<Pick<BabysitterAdmissionResult, "accepting" | "hostOnly" | "reason" | "retryAt" | "detail">>;
51
56
  /**
52
57
  * Samples memory and pressure for work that runs like a worker before the model starts, such as the
@@ -1 +1 @@
1
- export { t as createBabysitterRuntime, s as createGitHubAppCredentials, c as createGitHubHost, n as isProviderRateLimit, r as pendingMergeRetryAt } from "../server-CpOkw38n.js";
1
+ export { t as createBabysitterRuntime, s as createGitHubAppCredentials, c as createGitHubHost, n as isProviderRateLimit, r as pendingMergeRetryAt } from "../server-BAwiKpEK.js";
@@ -1,4 +1,4 @@
1
- import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-FZJIIO9X.js";
1
+ import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-BqwPfmNx.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";
@@ -113,7 +113,7 @@ Build a repair list from the requested behavior, unresolved feedback, body-only
113
113
 
114
114
  Use preloaded ciEvidence first. It contains job identity, failed steps, bounded diagnostic excerpts, omitted line ranges and availability status. An unavailable log is an API read failure, not proof of an additional CI failure. When an excerpt cannot answer the diagnosis, call readCheckLogs, then pass tailLines or startLine/endLine to read the lines its excerpt omitted. Use readBaseCheckEvidence and readBaseCheckLogs for exact-base CI evidence; GitHub credentials stay on the host. Separate setup failures from code failures. Reproduce the original failure or nearest useful focused case. Prove a claimed base regression on the exact base SHA with the same command; if that CI dependency is pending, record a structured wake for that base SHA rather than the PR HEAD. Do not repeatedly rerun a failure without inspecting its cause. A completed pass without a pushed repair, merge, or concrete durable wait is not progress.
115
115
 
116
- Use previousPass as a starting point and verify its diagnosis. Fix the requested behavior, conflicts, failing checks and valid review findings. Keep the repair scoped to this PR. Before local validation, call checkDependencies. If current is false, read changedInputs and the reason, call refreshDependencies, then check again. A failed refresh keeps your source edits and can be retried. Run focused local tests and the repository lint command when one exists, then review the final diff. Use hosted CI for full typechecks, builds and broad validation. Run a local full check only when a current maintainer explicitly requires it or a focused reproduction needs it; use the worker budget, and stop after a memory-limit failure instead of retrying the same command. Call commitRepair with a commit message and explicit intentional repair file paths, then call pushRepair. Git metadata is protected by the provider sandbox; staging and commits belong to the host. For a conflicting PR, the host has prepared the exact-base merge. The host already resolved and staged conflicts that need no judgment; .git/vitehub-merge.json lists them under conflicts.resolved with the rule used (package-json merges independent key changes, pnpm-lockfile regenerates the base lockfile for the merged manifests, markdown-union keeps lines both sides added). Review those files instead of redoing them; commitRepair accepts their paths unchanged. If the host install then failed on a regenerated lockfile, repair it like any lockfile defect. Resolve the remaining file conflict markers, call refreshDependencies before validation (also after editing dependency manifests or lockfiles), and include every resolved file in commitRepair; do not start another merge or rebase. Before you resolve a file, read what the base changed in it since the PR branched (\`git log -p HEAD..MERGE_HEAD -- <file>\`) and apply the PR's intent on top of the base version. Never keep the PR's older copy of a file: that reverts work that already landed. When the base already does what a hunk wants, keep the base version and drop the hunk. commitRepair rejects a merge that undoes base changes; pass a file in baseOverrides only when this PR deliberately replaces that base change. Do not commit generated provider instruction files or injected skills. A push records every supplied finding as handled, so fix or explicitly reject each one before pushing. GitHub writes go through the supplied tools, which are bound to this PR. Do not use shell credentials, direct API calls, branch deletion, PR closure, or direct merging.
116
+ Use previousPass as a starting point and verify its diagnosis. Fix the requested behavior, conflicts, failing checks and valid review findings. Keep the repair scoped to this PR. Before local validation, call checkDependencies. If current is false, read changedInputs and the reason, call refreshDependencies, then check again. A failed refresh keeps your source edits and can be retried. Run focused local tests and the repository lint command when one exists, then review the final diff. Use hosted CI for full typechecks, builds and broad validation. Run a local full check only when a current maintainer explicitly requires it or a focused reproduction needs it; use the worker budget, and stop after a memory-limit failure instead of retrying the same command. Call commitRepair with a commit message and explicit intentional repair file paths, then call pushRepair. Git metadata is protected by the provider sandbox; staging and commits belong to the host. For a conflicting PR, the host has prepared the exact-base merge. The host already resolved and staged conflicts that need no judgment; .git/vitehub-merge.json lists them under conflicts.resolved with the rule used (package-json merges independent key changes, pnpm-lockfile regenerates the base lockfile for the merged manifests, markdown-union keeps lines both sides added). Review those files instead of redoing them; commitRepair accepts their paths unchanged. If the host install then failed on a regenerated lockfile, repair it like any lockfile defect. Resolve the remaining file conflict markers, call refreshDependencies before validation (also after editing dependency manifests or lockfiles), and include every resolved file in commitRepair; do not start another merge or rebase. Before you resolve a file, read what the base changed in it since the PR branched (\`git log -p HEAD..MERGE_HEAD -- <file>\`) and what this PR changed in it (\`git diff MERGE_HEAD...HEAD -- <file>\`), and apply the PR's intent on top of the base version. The result keeps the work of both sides. Never keep the PR's older copy of a file: that reverts work that already landed. Never take the base's copy of a hunk this PR changed: that drops this PR's work. commitRepair rejects a merge that undoes changes of either side. Pass a file in baseOverrides only when this PR deliberately replaces that base change. Pass a file in prOverrides only when the base already does what this PR's hunk wants or deliberately replaces it. Do not commit generated provider instruction files or injected skills. A push records every supplied finding as handled, so fix or explicitly reject each one before pushing. GitHub writes go through the supplied tools, which are bound to this PR. Do not use shell credentials, direct API calls, branch deletion, PR closure, or direct merging.
117
117
 
118
118
  Answer every review thread you address through resolveReviewThread with its outcome; every outcome other than fixed carries a one-sentence reason, which is posted on the thread. The managed activity comment carries each session's final answer. Use commentOnPullRequest only for an actionable finding, a necessary explanation of a verified fix, or a reproduced blocker that humans need to act on. Do not post clean reviews, routine status updates, or duplicate the final answer in a separate comment. Preserve unrelated body content when updating metadata. Before reporting an external blocker, reproduce it now; previous generated blocker notes are not proof. Explain the exact external action needed without repeating an existing unchanged comment. Use mentionOnPullRequest only when a verified blocker needs action from one login in the configured allowlist. Never put a second mention in its body and never mention someone merely to provide status.
119
119
 
@@ -1607,6 +1607,11 @@ function snapshotCheckEvidence(snapshot) {
1607
1607
  statuses
1608
1608
  };
1609
1609
  }
1610
+ /** Whether the snapshot holds no check run and no commit status for the PR's head. */
1611
+ function headChecksUnreported(snapshot) {
1612
+ const evidence = snapshotCheckEvidence(snapshot);
1613
+ return !evidence.checkRuns.length && !evidence.statuses.length;
1614
+ }
1610
1615
  /**
1611
1616
  * Decides from inbox evidence whether a PR needs only a merge. Any doubt returns a reason,
1612
1617
  * and the PR gets a normal pass. The live check in `liveMergeReadiness` still runs before merging.
@@ -2304,7 +2309,7 @@ function validMainRepair(mainRepair) {
2304
2309
  return names(workflows, /\S/) && (repositories === void 0 || names(repositories, /^[\w.-]+\/[\w.-]+$/)) && (stuckJobMinutes === void 0 || stuckJobMinutes === false || Number.isSafeInteger(stuckJobMinutes) && Number(stuckJobMinutes) >= 1);
2305
2310
  }
2306
2311
  const babysitterHost = { async create(context) {
2307
- const { createBabysitterProcessHost } = await import("./host-CJAPkRoP.js");
2312
+ const { createBabysitterProcessHost } = await import("./host-DkX1bQwj.js");
2308
2313
  return await createBabysitterProcessHost(context);
2309
2314
  } };
2310
2315
  function plainSecret(value) {
@@ -2577,4 +2582,4 @@ const babysitter = defineAgent({
2577
2582
  }), babysitterHost);
2578
2583
  }
2579
2584
  });
2580
- export { invariantError as A, maintainerApproval as C, reviewThreadOutcomes as D, normalizeGitHubMentionAllowlist as E, hydrateFailedCiEvidence as F, newestCheckRun as I, createBabysitterCheckRuns as L, matchesBabysitterPullRequestFilter as M, actionLocation as N, reviewerLabeledSevere as O, failed as P, isBabysitterCheckRun as R, approvalReviewers as S, isReviewThreadOutcome as T, liveMergeReadiness as _, isBabysitterPlacementCapacityError as a, resolveBabysitterMerge as b, workspaceDecision as c, resolveBabysitterAdmissionLimits as d, sharedBabysitterRead as f, isAutomatedFeedback as g, hasHumanComment as h, BabysitterPlacementCapacityError as i, hasGitHubLogin as j, invariant as k, babysitterModelAdmission as l, feedbackFingerprints as m, babysitterPassResultSchema as n, createPullRequestWorkspaces as o, directMergeReadiness as p, resolveBabysitterLifecycleFilter as r, providerSessionDecision as s, babysitter as t, createBabysitterAdmission as u, matchesMergeReviewEvidence as v, createGitHubPullRequestOperations as w, snapshotCheckEvidence as x, mergeReviewEvidenceKey as y, createBabysitterPassResultSchema as z };
2585
+ export { invariant as A, createBabysitterPassResultSchema as B, approvalReviewers as C, normalizeGitHubMentionAllowlist as D, isReviewThreadOutcome as E, failed as F, hydrateFailedCiEvidence as I, newestCheckRun as L, hasGitHubLogin as M, matchesBabysitterPullRequestFilter as N, reviewThreadOutcomes as O, actionLocation as P, createBabysitterCheckRuns as R, snapshotCheckEvidence as S, createGitHubPullRequestOperations as T, isAutomatedFeedback as _, isBabysitterPlacementCapacityError as a, mergeReviewEvidenceKey as b, workspaceDecision as c, resolveBabysitterAdmissionLimits as d, sharedBabysitterRead as f, headChecksUnreported as g, hasHumanComment as h, BabysitterPlacementCapacityError as i, invariantError as j, reviewerLabeledSevere as k, babysitterModelAdmission as l, feedbackFingerprints as m, babysitterPassResultSchema as n, createPullRequestWorkspaces as o, directMergeReadiness as p, resolveBabysitterLifecycleFilter as r, providerSessionDecision as s, babysitter as t, createBabysitterAdmission as u, liveMergeReadiness as v, maintainerApproval as w, resolveBabysitterMerge as x, matchesMergeReviewEvidence as y, isBabysitterCheckRun as z };
@@ -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-CscUp4ts.js";
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";
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-BvKD88Nz.js";
1
+ export { i as BabysitterPlacementCapacityError, t as babysitter, n as babysitterPassResultSchema, r as resolveBabysitterLifecycleFilter } from "./babysitter-YDTdao5H.js";
@@ -278,6 +278,10 @@ const presetsErrorDiagnostics = /*#__PURE__*/ defineErrors({
278
278
  why: "Repair paths must name files inside the assigned checkout.",
279
279
  fix: "Pass paths relative to the checkout root, such as src/index.ts, without .., .git, or a leading slash."
280
280
  },
281
+ PRESETS_REPAIR_PR_REVERTED: {
282
+ why: ({ files }) => `The merge result undoes changes of this PR:\n${files}`,
283
+ fix: "Read what this PR changed in each listed file (git diff MERGE_HEAD...HEAD -- <file>) and put that change back on top of the base version. When the base already does what the change wanted, or deliberately replaces it, pass the file in commitRepair prOverrides with a one-sentence reason."
284
+ },
281
285
  PRESETS_REPAIR_STAGED_CHANGES: {
282
286
  why: "Repair checkout contains unrelated staged changes.",
283
287
  fix: "Do not stage files with git add. Pass the files to commit in commitRepair paths; commitRepair stages them."
@@ -1,6 +1,6 @@
1
- import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-FZJIIO9X.js";
2
- import { a as budgetParks, c as createGitHubHost, i as babysitterQueueHealth, o as pullRequestThreadId, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "./server-CpOkw38n.js";
3
- import { d as resolveBabysitterAdmissionLimits, f as sharedBabysitterRead, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-BvKD88Nz.js";
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-BAwiKpEK.js";
3
+ import { d as resolveBabysitterAdmissionLimits, f as sharedBabysitterRead, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-YDTdao5H.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 = "fe995c180e0431214d6624fa86644133bbb7a46e97d1011eaee87cde7a1d063f";
511
+ const buildRevision = "e84ed17cf4cb5d201e05886cccf8b5601be874adf9b44800cd7ea43f162f41b5";
512
512
  const admission = createBabysitterAdmission({
513
513
  invocations: host.invocations,
514
514
  limits: resolveBabysitterAdmissionLimits(agent.options.admission),
package/dist/labeller.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-FZJIIO9X.js";
1
+ import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-BqwPfmNx.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";
@@ -84,6 +84,11 @@ interface GitHubRepairCommit {
84
84
  path: string;
85
85
  reason: string;
86
86
  }>;
87
+ /** Files where a base merge intentionally keeps the base's version over a change of the PR, each with the reason. */
88
+ prOverrides?: Array<{
89
+ path: string;
90
+ reason: string;
91
+ }>;
87
92
  }
88
93
  type GitHubHostSecret = string | {
89
94
  unseal: () => string;
@@ -1,5 +1,5 @@
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";
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-YDTdao5H.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";
@@ -392,7 +392,69 @@ async function findGitHubBaseReverts(git, options) {
392
392
  }
393
393
  return reverts;
394
394
  }
395
- /** Compare one file's merge base, base, PR head and merge result. */
395
+ /**
396
+ * Find changes of the PR `head` that a staged merge of `base` undoes.
397
+ *
398
+ * A resolution that takes the base's copy of a conflicted hunk silently drops the PR's own work. This is
399
+ * `findGitHubBaseReverts` with the sides swapped: the result must keep every line the PR added unless
400
+ * the base removed it, and must not bring back a line the PR removed unless the base added it.
401
+ * Follow renames on both sides. `skip` names unchanged host resolutions in the staged result.
402
+ */
403
+ async function findGitHubHeadReverts(git, options) {
404
+ const origin = (await git("merge-base", options.head, options.base)).trim();
405
+ const skipped = new Set(options.skip);
406
+ const [headChanges, baseChanges, stagedChanges] = await Promise.all([
407
+ changedPaths(git, origin, options.head),
408
+ changedPaths(git, origin, options.base),
409
+ changedPaths(git, "--cached", options.head)
410
+ ]);
411
+ const differs = /* @__PURE__ */ new Set([...stagedChanges.keys(), ...stagedChanges.values()]);
412
+ const reverts = [];
413
+ for (const [original, path] of headChanges) {
414
+ const base = baseChanges.get(original) ?? original;
415
+ const staged = stagedChanges.get(path) ?? path;
416
+ if (!differs.has(path) && !differs.has(base)) continue;
417
+ const merged = staged === path && base !== path && !await isBlob(git, `:${path}`) ? base : staged;
418
+ if (skipped.has(merged) || [
419
+ original,
420
+ path,
421
+ base,
422
+ merged
423
+ ].some((name) => lockfile.test(name))) continue;
424
+ const [o, b, p, r] = await Promise.all([
425
+ `${origin}:${original}`,
426
+ `${options.base}:${base}`,
427
+ `${options.head}:${path}`,
428
+ `:${merged}`
429
+ ].map((spec) => blob(git, spec)));
430
+ if ([
431
+ o,
432
+ b,
433
+ p,
434
+ r
435
+ ].some((text) => text.includes("\0"))) continue;
436
+ const revert = revertedLines(o, p, b, r);
437
+ if (revert.dropped.length || revert.restored.length) reverts.push({
438
+ path,
439
+ ...revert
440
+ });
441
+ }
442
+ return reverts;
443
+ }
444
+ async function changedPaths(git, ...refs) {
445
+ const entries = names(await git("diff", "--name-status", "--find-renames", "-z", ...refs));
446
+ const paths = /* @__PURE__ */ new Map();
447
+ for (let index = 0; index < entries.length;) {
448
+ const status = entries[index++];
449
+ const path = entries[index++];
450
+ paths.set(path, status.startsWith("R") ? entries[index++] : path);
451
+ }
452
+ return paths;
453
+ }
454
+ /**
455
+ * Compare one file's merge base, base, PR head and merge result. Pass the PR head as `base` and the
456
+ * base as `head` to find what the result undoes of the PR.
457
+ */
396
458
  function revertedLines(origin, base, head, result) {
397
459
  const [o, b, p, r] = [
398
460
  origin,
@@ -430,8 +492,9 @@ function lineCounts(text) {
430
492
  }
431
493
  return counts;
432
494
  }
495
+ const isBlob = (git, spec) => git("cat-file", "-t", spec).then((type) => type.trim() === "blob", () => false);
433
496
  async function blob(git, spec) {
434
- return await git("cat-file", "-e", spec).then(() => git("cat-file", "blob", spec), () => "");
497
+ return await isBlob(git, spec) ? await git("cat-file", "blob", spec) : "";
435
498
  }
436
499
  const names = (output) => output.split("\0").filter(Boolean);
437
500
  // src/github/install-inputs.ts
@@ -1787,17 +1850,29 @@ async function commitGitHubPullRequestWorkspace(target, input, options) {
1787
1850
  if (skipped.length) await git("update-index", "--no-skip-worktree", "--", ...skipped);
1788
1851
  await git("add", "--sparse", "--", ...input.paths);
1789
1852
  if (mergeRecord) {
1853
+ const index = await git("ls-files", "--stage", "-z");
1790
1854
  await writeFile(recordPath, JSON.stringify({
1791
1855
  ...mergeRecord,
1792
- index: digest$1(await git("ls-files", "--stage", "-z"))
1856
+ index: digest$1(index)
1793
1857
  }));
1794
1858
  const unresolved = await git("diff", "--name-only", "--diff-filter=U");
1795
1859
  if (unresolved) throw presetsErrorDiagnostics.PRESETS_REPAIR_CONFLICTS_UNRESOLVED({ files: unresolved });
1796
1860
  const reasons = new Map(input.baseOverrides?.map(({ path, reason }) => [path, reason.trim()]));
1797
1861
  const reverts = await findGitHubBaseReverts(git.raw, mergeRecord);
1798
1862
  const unexplained = reverts.filter(({ path }) => !reasons.get(path));
1799
- if (unexplained.length) throw presetsErrorDiagnostics.PRESETS_REPAIR_BASE_REVERTED({ files: describeBaseReverts(unexplained) });
1863
+ if (unexplained.length) throw presetsErrorDiagnostics.PRESETS_REPAIR_BASE_REVERTED({ files: describeReverts(unexplained, "base line(s)", "the base") });
1864
+ const prReasons = new Map(input.prOverrides?.map(({ path, reason }) => [path, reason.trim()]));
1865
+ const staged = stagedEntries(index);
1866
+ const skip = mergeRecord.hostResolvedEntries?.filter(({ path, entry }) => staged.get(path) === entry).map(({ path }) => path);
1867
+ const prReverts = await findGitHubHeadReverts(git.raw, {
1868
+ head: mergeRecord.head,
1869
+ base: mergeRecord.base,
1870
+ skip
1871
+ });
1872
+ const unexplainedPr = prReverts.filter(({ path }) => !prReasons.get(path));
1873
+ if (unexplainedPr.length) throw presetsErrorDiagnostics.PRESETS_REPAIR_PR_REVERTED({ files: describeReverts(unexplainedPr, "line(s) of this PR", "this PR") });
1800
1874
  if (reverts.length) message += `\n\nKeeps this PR's version over base changes:\n${reverts.map(({ path }) => `- ${path}: ${reasons.get(path)}`).join("\n")}`;
1875
+ if (prReverts.length) message += `\n\nKeeps the base version over this PR's changes:\n${prReverts.map(({ path }) => `- ${path}: ${prReasons.get(path)}`).join("\n")}`;
1801
1876
  }
1802
1877
  if (options.verifyDependencies) {
1803
1878
  const directory = await mkdtemp(join(target, ".git", "vitehub-commit-snapshot-"));
@@ -1825,6 +1900,10 @@ const mergeRecordSchema = v.object({
1825
1900
  head: v.string(),
1826
1901
  base: v.string(),
1827
1902
  index: v.string(),
1903
+ hostResolvedEntries: v.optional(v.array(v.object({
1904
+ path: v.string(),
1905
+ entry: v.string()
1906
+ }))),
1828
1907
  conflicts: v.optional(v.object({
1829
1908
  conflicted: v.array(v.string()),
1830
1909
  resolved: v.array(v.object({
@@ -1839,16 +1918,25 @@ const mergeRecordSchema = v.object({
1839
1918
  lockfile: v.optional(v.string())
1840
1919
  }))
1841
1920
  });
1842
- function describeBaseReverts(reverts) {
1921
+ function describeReverts(reverts, added, remover) {
1843
1922
  const quote = (line) => JSON.stringify(line.length > 100 ? `${line.slice(0, 100)}…` : line);
1844
1923
  return reverts.slice(0, 10).map(({ path, dropped, restored }) => [
1845
1924
  `${path}:`,
1846
- dropped.length ? ` drops ${dropped.length} base line(s) such as ${dropped.slice(0, 2).map(quote).join(", ")}` : "",
1925
+ dropped.length ? ` drops ${dropped.length} ${added} such as ${dropped.slice(0, 2).map(quote).join(", ")}` : "",
1847
1926
  dropped.length && restored.length ? ";" : "",
1848
- restored.length ? ` restores ${restored.length} line(s) the base removed, such as ${restored.slice(0, 2).map(quote).join(", ")}` : ""
1927
+ restored.length ? ` restores ${restored.length} line(s) ${remover} removed, such as ${restored.slice(0, 2).map(quote).join(", ")}` : ""
1849
1928
  ].join("")).join("\n") + (reverts.length > 10 ? `\nand ${reverts.length - 10} more files` : "");
1850
1929
  }
1851
1930
  const digest$1 = (index) => createHash("sha256").update(index).digest("hex");
1931
+ function stagedEntries(index) {
1932
+ const entries = /* @__PURE__ */ new Map();
1933
+ for (const record of index.split("\0")) {
1934
+ const tab = record.indexOf(" ");
1935
+ const entry = record.slice(0, tab);
1936
+ if (tab !== -1 && entry.endsWith(" 0")) entries.set(record.slice(tab + 1), entry);
1937
+ }
1938
+ return entries;
1939
+ }
1852
1940
  function repairGit(target, options) {
1853
1941
  const env = {
1854
1942
  PATH: process.env.PATH,
@@ -1904,11 +1992,21 @@ async function prepareGitHubRepairBase(target, options) {
1904
1992
  ...options.conflicts,
1905
1993
  signal: options.signal
1906
1994
  });
1995
+ const index = await git("ls-files", "--stage", "-z");
1996
+ const staged = stagedEntries(index);
1997
+ const hostResolvedEntries = conflicts?.resolved.flatMap(({ path }) => {
1998
+ const entry = staged.get(path);
1999
+ return entry === void 0 ? [] : [{
2000
+ path,
2001
+ entry
2002
+ }];
2003
+ });
1907
2004
  await writeFile(join(target, ".git", "vitehub-merge.json"), JSON.stringify({
1908
2005
  head: options.expectedHead,
1909
2006
  base: options.base,
1910
- index: digest$1(await git("ls-files", "--stage", "-z")),
1911
- conflicts
2007
+ index: digest$1(index),
2008
+ conflicts,
2009
+ hostResolvedEntries
1912
2010
  }));
1913
2011
  return conflicts;
1914
2012
  }
@@ -5862,6 +5960,26 @@ async function readThreadComments(request, id) {
5862
5960
  } while (after);
5863
5961
  return comments;
5864
5962
  }
5963
+ /** The check runs and commit statuses that GitHub reports for one commit now. */
5964
+ async function readHeadChecks(read, repository, head, signal) {
5965
+ const readAll = async (path, projection) => {
5966
+ const items = [];
5967
+ for (let page = 1;; page++) {
5968
+ const batch = await read(`${path}&page=${page}`, projection, signal);
5969
+ signal?.throwIfAborted();
5970
+ items.push(...batch);
5971
+ if (batch.length < 100) return items;
5972
+ }
5973
+ };
5974
+ const [checks, statuses] = await Promise.all([readAll(`repos/${repository}/commits/${head}/check-runs?per_page=100`, ".check_runs[]"), readAll(`repos/${repository}/commits/${head}/statuses?per_page=100`)]);
5975
+ return {
5976
+ checks: Object.fromEntries(checks.map(parseEvidence).filter((c) => !isBabysitterCheckRun(c)).map((c) => [`check_run:${c.id}`, c])),
5977
+ statuses: Object.fromEntries(statuses.map(parseEvidence).reverse().map((s) => [s.context, {
5978
+ ...s,
5979
+ sha: head
5980
+ }]))
5981
+ };
5982
+ }
5865
5983
  /** REST snapshots fill webhook gaps without asking an LLM to poll GitHub. */
5866
5984
  async function readSnapshot(read, repository, number, readThreads, activityAuthors = [], signal) {
5867
5985
  const prefix = `repos/${repository}`;
@@ -5880,12 +5998,11 @@ async function readSnapshot(read, repository, number, readThreads, activityAutho
5880
5998
  if (batch.length < 100) return items;
5881
5999
  }
5882
6000
  };
5883
- const [comments, reviews, reviewComments, checks, statuses, threads] = await Promise.all([
6001
+ const [comments, reviews, reviewComments, headChecks, threads] = await Promise.all([
5884
6002
  readAll(`${prefix}/issues/${number}/comments?per_page=100`),
5885
6003
  readAll(`${prefix}/pulls/${number}/reviews?per_page=100`),
5886
6004
  readAll(`${prefix}/pulls/${number}/comments?per_page=100`),
5887
- readAll(`${prefix}/commits/${pr.head.sha}/check-runs?per_page=100`, ".check_runs[]"),
5888
- readAll(`${prefix}/commits/${pr.head.sha}/statuses?per_page=100`),
6005
+ readHeadChecks(read, repository, pr.head.sha, signal),
5889
6006
  readThreads?.(repository, number, signal)
5890
6007
  ]);
5891
6008
  const normalizedActivityAuthors = new Set(activityAuthors.map((author) => author.trim().toLowerCase()));
@@ -5894,8 +6011,7 @@ async function readSnapshot(read, repository, number, readThreads, activityAutho
5894
6011
  comments: index(comments.map(parseEvidence).filter((comment) => !(normalizedActivityAuthors.has(String(comment.user?.login ?? comment.author?.login ?? "").trim().toLowerCase()) && String(comment.body ?? "").startsWith("<!-- vitehub-agent-activity:")))),
5895
6012
  reviews: index(reviews.map(parseEvidence)),
5896
6013
  reviewComments: index(reviewComments.map(parseEvidence)),
5897
- checks: Object.fromEntries(checks.map(parseEvidence).filter((c) => !isBabysitterCheckRun(c)).map((c) => [`check_run:${c.id}`, c])),
5898
- statuses: Object.fromEntries(statuses.map(parseEvidence).reverse().map((s) => [s.context, s])),
6014
+ ...headChecks,
5899
6015
  hydrated: true
5900
6016
  };
5901
6017
  if (threads) Object.assign(snapshot, {
@@ -6728,7 +6844,7 @@ function repairCapability(operations, autoMerge, mentionAllowlist = [], beforePu
6728
6844
  },
6729
6845
  commitRepair: {
6730
6846
  name: "commitRepair",
6731
- description: "Stage the named repair files and commit them on the host. Git metadata is read-only in the provider sandbox. A base merge is rejected when it undoes base changes, unless baseOverrides names each such file with a reason. Call pushRepair after validation and this commit.",
6847
+ description: "Stage the named repair files and commit them on the host. Git metadata is read-only in the provider sandbox. A base merge is rejected when it undoes changes of the base or of this PR, unless baseOverrides or prOverrides names each such file with a reason. Call pushRepair after validation and this commit.",
6732
6848
  inputSchema: {
6733
6849
  type: "object",
6734
6850
  properties: {
@@ -6762,6 +6878,25 @@ function repairCapability(operations, autoMerge, mentionAllowlist = [], beforePu
6762
6878
  required: ["path", "reason"],
6763
6879
  additionalProperties: false
6764
6880
  }
6881
+ },
6882
+ prOverrides: {
6883
+ type: "array",
6884
+ description: "Files where the base version deliberately replaces a change this PR made, each with a one-sentence reason.",
6885
+ items: {
6886
+ type: "object",
6887
+ properties: {
6888
+ path: {
6889
+ type: "string",
6890
+ minLength: 1
6891
+ },
6892
+ reason: {
6893
+ type: "string",
6894
+ minLength: 1
6895
+ }
6896
+ },
6897
+ required: ["path", "reason"],
6898
+ additionalProperties: false
6899
+ }
6765
6900
  }
6766
6901
  },
6767
6902
  required: ["message", "paths"],
@@ -6770,18 +6905,25 @@ function repairCapability(operations, autoMerge, mentionAllowlist = [], beforePu
6770
6905
  execute: (input) => withinRepair(async () => {
6771
6906
  if (!isRuntimeRecord(input) || !Array.isArray(input.paths) || !input.paths.every((path) => hasRuntimeType(path, "string"))) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_TOOL_PATHS_MISSING();
6772
6907
  await workspace?.beforeRepair(context.context, input.paths);
6773
- if (input.baseOverrides !== void 0 && !Array.isArray(input.baseOverrides)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_TOOL_FIELD_INVALID({
6774
- key: "baseOverrides",
6775
- expected: "an array"
6776
- });
6777
- const baseOverrides = input.baseOverrides?.map((entry) => ({
6778
- path: stringField(entry, "path"),
6779
- reason: stringField(entry, "reason")
6780
- }));
6908
+ const overrides = (key) => {
6909
+ const entries = input[key];
6910
+ if (entries === void 0) return void 0;
6911
+ if (!Array.isArray(entries)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_TOOL_FIELD_INVALID({
6912
+ key,
6913
+ expected: "an array"
6914
+ });
6915
+ return entries.map((entry) => ({
6916
+ path: stringField(entry, "path"),
6917
+ reason: stringField(entry, "reason")
6918
+ }));
6919
+ };
6920
+ const baseOverrides = overrides("baseOverrides");
6921
+ const prOverrides = overrides("prOverrides");
6781
6922
  return { head: await operations.commitRepair({
6782
6923
  message: stringField(input, "message"),
6783
6924
  paths: input.paths,
6784
- ...baseOverrides && { baseOverrides }
6925
+ ...baseOverrides && { baseOverrides },
6926
+ ...prOverrides && { prOverrides }
6785
6927
  }) };
6786
6928
  })
6787
6929
  },
@@ -7697,18 +7839,30 @@ function directMergeBranchSafety(repository, pr, openChildren) {
7697
7839
  if (!hasRuntimeType(branch, "string")) return "pull request source branch unavailable";
7698
7840
  return openChildren.some((child) => String(field(child, "state")).toLowerCase() === "open" && field(child, "base", "ref") === branch) ? stackChildBaseDeletion : true;
7699
7841
  }
7700
- /** Whether a PR's head branch lives in another repository than `repository`, such as a fork. */
7701
- function isForkHead(pr, repository) {
7842
+ /**
7843
+ * Whether a PR's head branch lives in its base repository. GitHub reports both under the repository's
7844
+ * current name, so this compares them with each other, by id when both carry one. `repository` is the
7845
+ * configured name, which goes stale when the repository is renamed; it only stands in for a missing base.
7846
+ */
7847
+ function headInBaseRepository(pr, repository) {
7848
+ const headId = field(pr, "head", "repo", "id");
7849
+ const baseId = field(pr, "base", "repo", "id");
7850
+ if (hasRuntimeType(headId, "number") && hasRuntimeType(baseId, "number")) return headId === baseId;
7702
7851
  const headRepository = field(pr, "head", "repo", "full_name");
7703
- return hasRuntimeType(headRepository, "string") && headRepository.toLowerCase() !== repository.toLowerCase();
7852
+ if (!hasRuntimeType(headRepository, "string")) return void 0;
7853
+ const baseRepository = field(pr, "base", "repo", "full_name");
7854
+ return headRepository.toLowerCase() === (hasRuntimeType(baseRepository, "string") ? baseRepository : repository).toLowerCase();
7855
+ }
7856
+ /** Whether a PR's head branch lives in another repository than its base, such as a fork. */
7857
+ function isForkHead(pr, repository) {
7858
+ return headInBaseRepository(pr, repository) === false;
7704
7859
  }
7705
- /** The head and base branch of a PR whose head branch lives in `repository`, which the host can push to. */
7860
+ /** The head and base branch of a PR whose head branch lives in its base repository, which the host can push to. */
7706
7861
  function sameRepositoryBranches(pr, repository) {
7707
7862
  const head = field(pr, "head", "ref");
7708
7863
  const base = field(pr, "base", "ref");
7709
- const headRepository = field(pr, "head", "repo", "full_name");
7710
- if (!hasRuntimeType(head, "string") || !hasRuntimeType(base, "string") || !hasRuntimeType(headRepository, "string")) return void 0;
7711
- return headRepository.toLowerCase() === repository.toLowerCase() ? {
7864
+ if (!hasRuntimeType(head, "string") || !hasRuntimeType(base, "string")) return void 0;
7865
+ return headInBaseRepository(pr, repository) === true ? {
7712
7866
  head,
7713
7867
  base
7714
7868
  } : void 0;
@@ -8823,7 +8977,7 @@ function createBabysitterRuntime(options) {
8823
8977
  ignoreAssessedBotThreads: presetOptions.ignoreAssessedBotThreads === true
8824
8978
  };
8825
8979
  const schedulerEvent = (name, properties = {}) => options.event?.(name, properties);
8826
- const release = baseAgent.version ?? "fe995c180e0431214d6624fa86644133bbb7a46e97d1011eaee87cde7a1d063f";
8980
+ const release = baseAgent.version ?? "e84ed17cf4cb5d201e05886cccf8b5601be874adf9b44800cd7ea43f162f41b5";
8827
8981
  const workspaces = options.workspaces;
8828
8982
  const schedulerError = (name, error, properties = {}) => options.error?.(name, error, properties);
8829
8983
  const statusComment = !!verifiedHostIdentity && presetOptions.status?.comment !== false;
@@ -9049,8 +9203,8 @@ function createBabysitterRuntime(options) {
9049
9203
  if (!authors) return false;
9050
9204
  const { repository, number } = snapshot;
9051
9205
  const allowed = (pr) => {
9052
- if (!isRuntimeRecord(pr) || pr.draft !== true || !isRuntimeRecord(pr.user) || !isRuntimeRecord(pr.head) || !isRuntimeRecord(pr.head.repo)) return false;
9053
- return pr.head.sha === snapshot.pr?.head?.sha && hasRuntimeType(pr.user.login, "string") && authors.has(pr.user.login.toLowerCase()) && String(pr.head.repo.full_name).toLowerCase() === repository.toLowerCase();
9206
+ if (!isRuntimeRecord(pr) || pr.draft !== true || !isRuntimeRecord(pr.user) || !isRuntimeRecord(pr.head)) return false;
9207
+ return pr.head.sha === snapshot.pr?.head?.sha && hasRuntimeType(pr.user.login, "string") && authors.has(pr.user.login.toLowerCase()) && headInBaseRepository(pr, repository) === true;
9054
9208
  };
9055
9209
  if (!allowed(snapshot.pr)) return false;
9056
9210
  let failure;
@@ -9149,7 +9303,13 @@ function createBabysitterRuntime(options) {
9149
9303
  if (!hostIdentity) return false;
9150
9304
  const key = forkReopenKey(repository, number);
9151
9305
  const previous = await pullRequestInbox.meta(key);
9152
- if (isRuntimeRecord(previous) && (previous.closing === true || Number(previous.at) > Date.now() - 36e5)) return false;
9306
+ if (isRuntimeRecord(previous) && (previous.closing === true || Number(previous.at) > Date.now() - 36e5)) {
9307
+ schedulerEvent("babysitter.fork_checks.reopen_skipped", {
9308
+ ...owner,
9309
+ reason: previous.closing === true ? "reopen in flight" : "reopened in the last hour"
9310
+ });
9311
+ return false;
9312
+ }
9153
9313
  const { provider } = await forge(repository, signal);
9154
9314
  try {
9155
9315
  const live = (await provider.request("GET", `/repos/${repository}/pulls/${number}`, { signal })).data;
@@ -9757,6 +9917,7 @@ function createBabysitterRuntime(options) {
9757
9917
  return "blocked";
9758
9918
  };
9759
9919
  const stoppedKey = `direct-merge-stopped:${repository}#${number}`;
9920
+ const firstCheckKey = `first-check-wait:${repository}#${number}`;
9760
9921
  if (pending) try {
9761
9922
  const live = await readPull(repository, number, signal);
9762
9923
  const state = isRuntimeRecord(live) && hasRuntimeType(live.state, "string") ? live.state : void 0;
@@ -9860,7 +10021,8 @@ function createBabysitterRuntime(options) {
9860
10021
  return await parkMerge("GitHub merge outcome could not be reconciled; retrying the provider read.");
9861
10022
  }
9862
10023
  if (signal.aborted) return "blocked";
9863
- const evaluation = await checkEvaluation(snapshot, await requiredCheckPolicy(snapshot, foldInto !== void 0), signal);
10024
+ const policy = await requiredCheckPolicy(snapshot, foldInto !== void 0);
10025
+ const evaluation = await checkEvaluation(snapshot, policy, signal);
9864
10026
  const savedAssessment = await pullRequestInbox.meta(`review-assessment:${repository}#${number}`);
9865
10027
  const assessment = isRuntimeRecord(savedAssessment) && savedAssessment.version === 2 ? savedAssessment : void 0;
9866
10028
  const reviewedEvidenceKey = isRuntimeRecord(assessment) && assessment.head === snapshot.pr?.head?.sha && hasRuntimeType(assessment.evidenceKey, "string") ? assessment.evidenceKey : void 0;
@@ -9911,6 +10073,23 @@ function createBabysitterRuntime(options) {
9911
10073
  });
9912
10074
  return pending?.asynchronous ? await parkMerge(`Unconfirmed merge is waiting for ${decision.reason}.`) : "not-ready";
9913
10075
  }
10076
+ const everyCheckGates = policy.status === "known" && !policy.required.length;
10077
+ if (!pending && everyCheckGates && firstCheckWaitMs > 0 && headChecksUnreported(snapshot)) {
10078
+ const saved = await pullRequestInbox.meta(firstCheckKey);
10079
+ const since = isRuntimeRecord(saved) && saved.head === decision.head && hasRuntimeType(saved.since, "number") ? saved.since : pullRequestInbox.now();
10080
+ if (!isRuntimeRecord(saved) || saved.head !== decision.head) await pullRequestInbox.setMeta(firstCheckKey, {
10081
+ head: decision.head,
10082
+ since
10083
+ });
10084
+ const until = since + firstCheckWaitMs;
10085
+ if (until > pullRequestInbox.now()) {
10086
+ schedulerEvent("babysitter.direct_merge.skipped", {
10087
+ ...owner,
10088
+ reason: "no check reported for the head yet"
10089
+ });
10090
+ return await parkMerge(`GitHub has reported no check for ${decision.head} yet; waiting until ${new Date(until).toISOString()} for its first check.`, until);
10091
+ }
10092
+ }
9914
10093
  const stopped = pending ? void 0 : await pullRequestInbox.meta(stoppedKey);
9915
10094
  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);
9916
10095
  const folding = pending ? void 0 : await pullRequestInbox.foldingChild(repository, number);
@@ -9969,7 +10148,21 @@ function createBabysitterRuntime(options) {
9969
10148
  ...owner,
9970
10149
  reason: `${base} changed files this PR touches after its checks ran: ${files}`
9971
10150
  });
9972
- if (!await updateBranch(owner, repository, number, decision.head, signal, live)) return "not-ready";
10151
+ if (!await updateBranch(owner, repository, number, decision.head, signal, live)) {
10152
+ const reopened = isForkHead(live, repository) ? await pullRequestInbox.meta(forkReopenKey(repository, number)) : void 0;
10153
+ const at = isRuntimeRecord(reopened) ? Number(reopened.at) : NaN;
10154
+ const reopening = Number.isFinite(at) && at > Date.now() - 36e5;
10155
+ if (!reopening && !reviewPushBudgetSpent(snapshot, waitPolicy)) return "not-ready";
10156
+ const retryAt = reopening ? Math.max(at + 36e5, Date.now() + 6e4) : Date.now() + 6e5;
10157
+ await pullRequestInbox.finish(claim, {
10158
+ text: `${base} changed ${files} after its checks ran, and the branch could not be refreshed yet. Waiting for fresh checks or a retry.`,
10159
+ wait: {
10160
+ ...createCheckWait(snapshot, waitPolicy),
10161
+ retryAt
10162
+ }
10163
+ });
10164
+ return "blocked";
10165
+ }
9973
10166
  schedulerEvent("babysitter.branch.updated", {
9974
10167
  ...owner,
9975
10168
  files: overlap.slice(0, 10)
@@ -10031,6 +10224,24 @@ function createBabysitterRuntime(options) {
10031
10224
  return pending?.asynchronous ? await parkMerge(`Unconfirmed fold is waiting: ${reason}.`) : "not-ready";
10032
10225
  }
10033
10226
  }
10227
+ if (everyCheckGates) {
10228
+ const reported = await readHeadChecks((path, projection) => readRest(path, projection, signal), repository, decision.head, signal);
10229
+ const fresh = {
10230
+ ...snapshot,
10231
+ ...reported
10232
+ };
10233
+ const freshEvaluation = await checkEvaluation(fresh, policy, signal);
10234
+ const freshDecision = readiness(fresh, freshEvaluation.state, freshEvaluation.inheritedCheckIds);
10235
+ if (!freshDecision.ready) {
10236
+ schedulerEvent("babysitter.direct_merge.skipped", {
10237
+ ...owner,
10238
+ reason: `GitHub reports checks the inbox lacks: ${freshDecision.reason}`
10239
+ });
10240
+ if (await pullRequestInbox.hydrate(claim, reported)) return pending ? await parkMerge(`Unconfirmed merge is waiting for ${freshDecision.reason}.`) : "not-ready";
10241
+ await pullRequestInbox.release(claim);
10242
+ return "blocked";
10243
+ }
10244
+ }
10034
10245
  if (!await pullRequestInbox.isClaimCurrent(claim)) {
10035
10246
  schedulerEvent("babysitter.direct_merge.skipped", {
10036
10247
  ...owner,
@@ -10102,6 +10313,7 @@ function createBabysitterRuntime(options) {
10102
10313
  return await parkMerge(`GitHub merge request failed: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`);
10103
10314
  }
10104
10315
  await pullRequestInbox.clearDirectMerge(repository, number, mergeToken);
10316
+ await pullRequestInbox.deleteMeta(firstCheckKey);
10105
10317
  if (foldInto !== void 0) {
10106
10318
  await pullRequestInbox.finish(claim, {
10107
10319
  text: `Merged ${decision.head} into ${base}, the branch of parent #${foldInto}: it lands with its parent.`,
@@ -10286,6 +10498,7 @@ function createBabysitterRuntime(options) {
10286
10498
  const providerRetryDelayMs = options.providerRetryDelayMs ?? 1e4;
10287
10499
  const providerRetries = presetOptions.providerRetries ?? 3;
10288
10500
  const mergeabilityRetryDelayMs = options.mergeabilityRetryDelayMs ?? 3e3;
10501
+ const firstCheckWaitMs = options.firstCheckWaitMs ?? 6e4;
10289
10502
  /** A GitHub rate limit stops every forge request until it resets. Returns whether the error was one. */
10290
10503
  async function noteForgeQuota(error, operation) {
10291
10504
  if (!(error instanceof RateLimitedError)) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/presets",
3
- "version": "0.5.1",
3
+ "version": "0.6.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.5.1",
62
- "@vite-hub/gateways": "0.5.1",
63
- "@vite-hub/runtime": "0.5.1",
64
- "@vite-hub/sandbox": "0.5.1",
65
- "@vite-hub/workspace": "0.5.1",
61
+ "@vite-hub/forge": "0.6.0",
62
+ "@vite-hub/gateways": "0.6.0",
63
+ "@vite-hub/runtime": "0.6.0",
64
+ "@vite-hub/sandbox": "0.6.0",
65
+ "@vite-hub/workspace": "0.6.0",
66
66
  "@yarnpkg/parsers": "3.1.0",
67
67
  "comark": "^0.9.2",
68
68
  "nostics": "1.4.0",
@@ -74,7 +74,7 @@
74
74
  "@modelcontextprotocol/sdk": "^1.32.2",
75
75
  "@t3tools/provider-runtime": "https://pkg.pr.new/vite-hub/t3code/@t3tools/provider-runtime@2a519db9ccb4227091f0d8a839d7121af9d6aed5",
76
76
  "@types/node": "^24.19.2",
77
- "@vite-hub/agent": "0.5.1",
77
+ "@vite-hub/agent": "0.6.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.5.1"
85
+ "@vite-hub/agent": "0.6.0"
86
86
  },
87
87
  "engines": {
88
88
  "node": ">=24.15.0"