@vite-hub/presets 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,6 +79,15 @@ The same rules apply during discovery and to `opened`, `labeled`, and
79
79
  resume work. Use `lifecycle.labels` for lifecycle control and `filter.labels`
80
80
  for selection, rather than configuring both on one Babysitter.
81
81
 
82
+ `lifecycle.approval: true` also selects a pull request that the author allow
83
+ lists leave out, such as an outside contributor's, once a reviewer with write
84
+ access approves its current head. Approving is then the only step: the
85
+ Babysitter repairs the PR and merges it. The approval carries over to heads the
86
+ Babysitter builds on the approved commit, so its own repairs need no new
87
+ review. A push by anyone else drops the PR until the next approval. The
88
+ Babysitter pushes to a fork's branch with its base repository's App
89
+ installation, which GitHub allows when the author lets maintainers edit the PR.
90
+
82
91
  With only `filter.repository.allow`, the Babysitter serves pull requests whose
83
92
  author is an owner, member, or collaborator, skips those labelled
84
93
  `babysitter:skip`, and merges ready ones directly. A direct merge holds a pull
@@ -149,7 +158,8 @@ reject it. `ready({ repository, number, head, snapshot, requiredChecks })` can
149
158
  add a policy, such as a required approval check; return `true` or a reason. Any
150
159
  other result runs a normal repair pass. `ready: "approved-if-outside"` merges a
151
160
  PR from an author without write access only after a reviewer with write access
152
- approves its current head and no such reviewer's latest review requests changes.
161
+ approves its current head, or a head that the Babysitter built on the approved
162
+ commit, and no such reviewer's latest review requests changes.
153
163
  `trustedAuthors`, such as `["renovate[bot]"]`, lets those authors through that
154
164
  gate without an approval. A bot entry needs its `[bot]` suffix and matches only a
155
165
  bot account.
@@ -320,7 +330,9 @@ health and queue. SIGUSR2 starts a drain. The build fails with `AGENT_B0022` on
320
330
  hosts that cannot keep a process running, and with `AGENT_B0023` without SQL
321
331
  Agent State. Hosts start in production builds, or in development only with
322
332
  `VITEHUB_AGENT_PROCESS_HOSTS=1`, so a development server does not repair real
323
- PRs by accident.
333
+ PRs by accident. With a ViteHub Database, one server at a time runs the host,
334
+ and another server takes over about 30 seconds after it stops. PR leases in the
335
+ inbox end on the clock of the Agent State database, not on the server clock.
324
336
 
325
337
  The host reads the GitHub App from `env.server.github` or `VITEHUB_GITHUB_APP_ID`,
326
338
  `VITEHUB_GITHUB_PRIVATE_KEY` (or `VITEHUB_GITHUB_PRIVATE_KEY_PATH`), and
@@ -412,7 +424,7 @@ still revoke further repair operations.
412
424
 
413
425
  ## Babysitter GitHub host
414
426
 
415
- `createGitHubHost()` from `@vite-hub/presets/babysitter/server` is the GitHub host that `createBabysitterRuntime()` takes. Use it to resolve GitHub App or fallback credentials, call GitHub through `@vite-hub/forge`, and run against an exact pull-request head in a temporary checkout. `withPullRequestCheckout()` uses Git over HTTPS, fetches the source branch directly, verifies the requested head, and removes the checkout contents after success, failure, cancellation, or timeout. Cleanup is best effort and preserves the callback result or error if filesystem discovery or deletion fails. Cleanup retains an empty temporary directory because removing its pathname could delete a concurrent replacement. Checkout and push operations need Git but do not need the GitHub CLI. Include `headRepository` and `headRef` to make an ordinary `git push` target the pull request's source branch. The callback keeps base repository access for reads from `origin`; use its `push()` after long-running work so the host resolves fresh source repository credentials before pushing. Push checks that the repair descends from the last verified head and uses a lease to reject a changed source branch. It returns the pushed SHA and advances the lease for later pushes in the same callback. Pass the Agent Invocation's abort signal and use the callback signal for work inside the checkout:
427
+ `createGitHubHost()` from `@vite-hub/presets/babysitter/server` is the GitHub host that `createBabysitterRuntime()` takes. Use it to resolve GitHub App or fallback credentials, call GitHub through `@vite-hub/forge`, and run against an exact pull-request head in a temporary checkout. With App credentials, the host commits and comments as the App's bot, such as `my-app[bot]` with its noreply email. The host resolves the identity from the credentials it uses for that repository. Set `identity: { login, email, appId }` only for a token without an App. `withPullRequestCheckout()` uses Git over HTTPS, fetches the source branch directly, verifies the requested head, and removes the checkout contents after success, failure, cancellation, or timeout. Cleanup is best effort and preserves the callback result or error if filesystem discovery or deletion fails. Cleanup retains an empty temporary directory because removing its pathname could delete a concurrent replacement. Checkout and push operations need Git but do not need the GitHub CLI. Include `headRepository` and `headRef` to make an ordinary `git push` target the pull request's source branch. The callback keeps base repository access for reads from `origin`; use its `push()` after long-running work so the host resolves fresh source repository credentials before pushing. Push checks that the repair descends from the last verified head and uses a lease to reject a changed source branch. It returns the pushed SHA and advances the lease for later pushes in the same callback. Pass the Agent Invocation's abort signal and use the callback signal for work inside the checkout:
416
428
 
417
429
  ```ts fragment
418
430
  await github.withPullRequestCheckout(pullRequest, async ({ env, path, push, signal }) => {
@@ -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-CMdQ9U15.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-QjQyRB6g.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";
@@ -79,6 +79,30 @@ export interface BabysitterRuntimeOptions {
79
79
  export declare function pendingMergeRetryAt(startedAt: number, now: number): number;
80
80
  /** Provider quota and rate-limit failures. Cancellation is never a rate limit. */
81
81
  export declare function isProviderRateLimit(error: unknown): boolean;
82
+ /**
83
+ * Whether the reconcile loop still makes progress, for the health route. `stalled`: the last reconcile
84
+ * waited longer than `stallMs` and was stopped. `silent`: no reconcile finished for `stallMs` plus one
85
+ * minute while the host accepts work.
86
+ */
87
+ export interface BabysitterSchedulerHealth {
88
+ status: "ok" | "stalled" | "silent";
89
+ /** The reconcile that runs now and the step it waits on. */
90
+ running?: {
91
+ reason: string;
92
+ step: string;
93
+ subject?: string;
94
+ startedAt: string;
95
+ stepAt: string;
96
+ };
97
+ lastFinishedAt?: string;
98
+ /** The last stopped reconcile, and how many reconciles in a row were stopped. */
99
+ lastStall?: {
100
+ at: string;
101
+ step: string;
102
+ subject?: string;
103
+ count: number;
104
+ };
105
+ }
82
106
  /** Own one durable PR inbox and its repair passes inside a process host. */
83
107
  export interface BabysitterRuntime {
84
108
  inbox: PullRequestInbox;
@@ -88,6 +112,8 @@ export interface BabysitterRuntime {
88
112
  workload(): {
89
113
  running: number;
90
114
  };
115
+ /** Reconcile liveness. Pass `accepting: false` while the host drains, so a quiet loop is not reported as silent. */
116
+ scheduler(accepting?: boolean): BabysitterSchedulerHealth;
91
117
  /**
92
118
  * Makes the next reconcile check the default branch of the delivery's repository when the delivery
93
119
  * is a failed push run of a watched workflow there. Returns whether it did.
@@ -1,2 +1,2 @@
1
- import { c as createGitHubHost, n as isProviderRateLimit, r as pendingMergeRetryAt, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "../server-ILDJE5V7.js";
1
+ import { c as createGitHubHost, n as isProviderRateLimit, r as pendingMergeRetryAt, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "../server-Bj5_Uf_Y.js";
2
2
  export { createBabysitterRuntime, createGitHubAppCredentials, createGitHubHost, isProviderRateLimit, pendingMergeRetryAt };
@@ -273,10 +273,14 @@ const maxRangeLines = 1e3;
273
273
  function compactCiLog(log, limit = compactLimit) {
274
274
  const compact = log.replace(/(?:\x1b|\^\[)\[[0-9;?]*[ -/]*[@-~]/g, "").split("\n").filter((line) => !/\s\* \[new (?:branch|tag)\]\s/.test(line)).join("\n");
275
275
  if (compact.length <= limit) return compact;
276
- const start = compact.indexOf("\n", compact.length - limit) + 1;
276
+ const cutoff = compact.length - limit;
277
+ const nextLine = compact.indexOf("\n", cutoff - 1) + 1;
278
+ let start = nextLine && compact.slice(nextLine).trim() ? nextLine : cutoff;
279
+ if ((compact.codePointAt(start - 1) ?? 0) > 65535) start++;
277
280
  let omitted = 0;
278
281
  for (let n = compact.indexOf("\n"); n !== -1 && n < start; n = compact.indexOf("\n", n + 1)) omitted++;
279
- return `[${omitted} earlier log lines omitted]\n${compact.slice(start)}`;
282
+ const partial = compact[start - 1] !== "\n" && start < compact.length;
283
+ return `[${omitted} earlier log lines omitted]\n${partial ? "…" : ""}${compact.slice(start)}`;
280
284
  }
281
285
  /** Bound log context explicitly; the full fetched log remains in the local cache. */
282
286
  function diagnosticExcerpt(log, limit = 16e3, failedSteps = []) {
@@ -1279,6 +1283,62 @@ function createGitHubPullRequestOperations(github, options) {
1279
1283
  };
1280
1284
  }
1281
1285
  //#endregion
1286
+ //#region src/babysitter/approval.ts
1287
+ /** Author and reviewer associations that GitHub gives to people with write access to the repository. */
1288
+ const writeAccess = /* @__PURE__ */ new Set([
1289
+ "OWNER",
1290
+ "MEMBER",
1291
+ "COLLABORATOR"
1292
+ ]);
1293
+ const hasWriteAccess = (association) => writeAccess.has(String(association ?? "").toUpperCase());
1294
+ const reviewer = (review) => String(review.user?.login ?? review.author?.login ?? "").toLowerCase();
1295
+ /** Each reviewer's latest APPROVED or CHANGES_REQUESTED review whose association claims write access, by lowercase login. */
1296
+ function decisiveReviews(snapshot) {
1297
+ const latest = /* @__PURE__ */ new Map();
1298
+ const decisive = Object.values(snapshot.reviews).filter((review) => !review.deleted && hasWriteAccess(review.author_association ?? review.authorAssociation) && ["APPROVED", "CHANGES_REQUESTED"].includes(String(review.state ?? "").toUpperCase())).sort((a, b) => String(a.submitted_at ?? a.submittedAt ?? "").localeCompare(String(b.submitted_at ?? b.submittedAt ?? "")));
1299
+ for (const review of decisive) {
1300
+ const login = reviewer(review);
1301
+ if (login) latest.set(login, review);
1302
+ }
1303
+ return latest;
1304
+ }
1305
+ /**
1306
+ * The reviewers whose permission decides `maintainerApproval()`. Their association only claims write
1307
+ * access: an organization member with read access is `MEMBER` too.
1308
+ */
1309
+ const approvalReviewers = (snapshot) => [...decisiveReviews(snapshot).keys()];
1310
+ /**
1311
+ * The approval state of `head` from reviewers with write access. Each reviewer's latest APPROVED or
1312
+ * CHANGES_REQUESTED review counts; comments, pending and dismissed reviews leave it standing. An
1313
+ * approval of commit A also covers a head that the host built on A, and any head the host built on
1314
+ * that one, as `hostHeads` records them. A push by anyone else starts a head that no approval covers.
1315
+ * `writers` holds the lowercase logins whose write permission the host verified; without it, the
1316
+ * review's association stands in for that permission.
1317
+ */
1318
+ function maintainerApproval(snapshot, head, writers) {
1319
+ const latest = decisiveReviews(snapshot);
1320
+ if (writers) {
1321
+ for (const login of latest.keys()) if (!writers.has(login)) latest.delete(login);
1322
+ }
1323
+ const changesRequested = [...latest].filter(([, review]) => String(review.state).toUpperCase() === "CHANGES_REQUESTED").map(([login]) => login);
1324
+ const approvedCommits = new Set([...latest.values()].filter((review) => String(review.state).toUpperCase() === "APPROVED").map((review) => review.commit_id ?? review.commit?.oid).filter((commit) => typeof commit === "string"));
1325
+ const parents = new Map((snapshot.hostHeads ?? []).map((entry) => [entry.head, entry.parent]));
1326
+ let current = head;
1327
+ const seen = /* @__PURE__ */ new Set();
1328
+ while (current !== void 0 && !seen.has(current)) {
1329
+ if (approvedCommits.has(current)) return {
1330
+ approved: true,
1331
+ changesRequested
1332
+ };
1333
+ seen.add(current);
1334
+ current = parents.get(current);
1335
+ }
1336
+ return {
1337
+ approved: false,
1338
+ changesRequested
1339
+ };
1340
+ }
1341
+ //#endregion
1282
1342
  //#region src/babysitter/merge.ts
1283
1343
  const failing = /* @__PURE__ */ new Set([
1284
1344
  "failure",
@@ -1419,16 +1479,11 @@ function feedbackFingerprints(snapshot, policy = {}, legacy = false) {
1419
1479
  value.state
1420
1480
  ])).digest("hex").slice(0, 32)));
1421
1481
  }
1422
- /** Author and reviewer associations that GitHub gives to people with write access to the repository. */
1423
- const writeAccess = /* @__PURE__ */ new Set([
1424
- "OWNER",
1425
- "MEMBER",
1426
- "COLLABORATOR"
1427
- ]);
1428
- const hasWriteAccess = (association) => writeAccess.has(String(association ?? "").toUpperCase());
1429
1482
  /**
1430
1483
  * The `"approved-if-outside"` merge gate. Each write-access reviewer's latest APPROVED or
1431
- * CHANGES_REQUESTED review counts; comments, pending and dismissed reviews leave it standing.
1484
+ * CHANGES_REQUESTED review counts; comments, pending and dismissed reviews leave it standing. An
1485
+ * approval carries over to heads the host built on the approved commit, so its own repairs need no
1486
+ * new approval. A push by anyone else does.
1432
1487
  */
1433
1488
  function approvedIfOutside(input) {
1434
1489
  return approvedIfOutsideGate(input, /* @__PURE__ */ new Set());
@@ -1439,20 +1494,15 @@ function accountLogin(user) {
1439
1494
  if (!login) return "";
1440
1495
  return (login.endsWith("[bot]") || String(user?.type ?? user?.__typename ?? "").toLowerCase() === "bot") && !login.endsWith("[bot]") ? `${login}[bot]` : login;
1441
1496
  }
1442
- function approvedIfOutsideGate({ head, snapshot }, trustedAuthors) {
1497
+ function approvedIfOutsideGate({ head, snapshot, writers }, trustedAuthors) {
1443
1498
  const pr = snapshot.pr;
1499
+ const author = accountLogin(pr?.user ?? pr?.author);
1444
1500
  if (hasWriteAccess(pr?.author_association ?? pr?.authorAssociation)) return true;
1445
- if (trustedAuthors.has(accountLogin(pr?.user ?? pr?.author))) return true;
1446
- const latest = /* @__PURE__ */ new Map();
1447
- const decisive = Object.values(snapshot.reviews).filter((review) => !review.deleted && hasWriteAccess(review.author_association ?? review.authorAssociation) && ["APPROVED", "CHANGES_REQUESTED"].includes(String(review.state ?? "").toUpperCase())).sort((a, b) => String(a.submitted_at ?? a.submittedAt ?? "").localeCompare(String(b.submitted_at ?? b.submittedAt ?? "")));
1448
- for (const review of decisive) {
1449
- const reviewer = feedbackAuthor(review);
1450
- if (reviewer) latest.set(reviewer, review);
1451
- }
1501
+ if (trustedAuthors.has(author)) return true;
1502
+ const approval = maintainerApproval(snapshot, head, writers);
1452
1503
  const short = head.slice(0, 7);
1453
- const blocking = [...latest].filter(([, review]) => String(review.state).toUpperCase() === "CHANGES_REQUESTED").map(([reviewer]) => reviewer);
1454
- if (blocking.length) return `a maintainer's approval of ${short}: ${blocking.join(", ")} requested changes`;
1455
- return [...latest.values()].some((review) => (review.commit_id ?? review.commit?.oid) === head) || `a maintainer's approval of ${short}`;
1504
+ if (approval.changesRequested.length) return `a maintainer's approval of ${short}: ${approval.changesRequested.join(", ")} requested changes`;
1505
+ return approval.approved || `a maintainer's approval of ${short}`;
1456
1506
  }
1457
1507
  function resolveBabysitterMerge(merge) {
1458
1508
  if (merge === false) return { mode: "off" };
@@ -2268,7 +2318,7 @@ function validMainRepair(mainRepair) {
2268
2318
  return names(workflows, /\S/) && (repositories === void 0 || names(repositories, /^[\w.-]+\/[\w.-]+$/)) && (stuckJobMinutes === void 0 || stuckJobMinutes === false || Number.isSafeInteger(stuckJobMinutes) && Number(stuckJobMinutes) >= 1);
2269
2319
  }
2270
2320
  const babysitterHost = { async create(context) {
2271
- const { createBabysitterProcessHost } = await import("./host-DH0o7xSq.js");
2321
+ const { createBabysitterProcessHost } = await import("./host-gF2JTvw8.js");
2272
2322
  return await createBabysitterProcessHost(context);
2273
2323
  } };
2274
2324
  function plainSecret(value) {
@@ -2365,6 +2415,10 @@ function resolveBabysitterLifecycleFilter(configured, lifecycle) {
2365
2415
  option: "lifecycle",
2366
2416
  expected: "an object"
2367
2417
  });
2418
+ if (lifecycle?.approval !== void 0 && typeof lifecycle.approval !== "boolean") throw presetsErrorDiagnostics.PRESETS_BABYSITTER_OPTION_INVALID({
2419
+ option: "lifecycle.approval",
2420
+ expected: "a boolean"
2421
+ });
2368
2422
  const labels = lifecycle?.labels;
2369
2423
  if (labels === void 0) return filter.labels ? filter : {
2370
2424
  ...filter,
@@ -2538,4 +2592,4 @@ const babysitter = defineAgent({
2538
2592
  }
2539
2593
  });
2540
2594
  //#endregion
2541
- export { matchesBabysitterPullRequestFilter as A, isReviewThreadOutcome as C, invariant as D, reviewerLabeledSevere as E, createBabysitterCheckRuns as F, isBabysitterCheckRun as I, createBabysitterPassResultSchema as L, failed as M, hydrateFailedCiEvidence as N, invariantError as O, newestCheckRun as P, createGitHubPullRequestOperations as S, reviewThreadOutcomes 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, actionLocation as j, hasGitHubLogin 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, normalizeGitHubMentionAllowlist as w, snapshotCheckEvidence as x, mergeReviewEvidenceKey as y };
2595
+ 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 };
@@ -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-CMdQ9U15.js";
1
+ import { T as AutomatedReviewClass, i as BabysitterAdmissionPause, l as GitHubRequiredCheckState, r as BabysitterAdmissionOptions, s as Snapshot, t as BabysitterWarmWorkspaces } from "./pr-workspaces-QjQyRB6g.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";
@@ -35,6 +35,11 @@ interface BabysitterMergeReadinessInput {
35
35
  head: string;
36
36
  snapshot: Snapshot;
37
37
  requiredChecks: GitHubRequiredCheckState;
38
+ /**
39
+ * Lowercase logins of the reviewers whose write permission the host verified. The built-in gate
40
+ * counts only their approvals; without it, each review's author association stands in.
41
+ */
42
+ writers?: ReadonlySet<string>;
38
43
  }
39
44
  /** Return `true` to allow the merge, or a reason that sends the PR to a normal pass. */
40
45
  type BabysitterMergeReady = (input: BabysitterMergeReadinessInput) => true | string | Promise<true | string>;
@@ -123,6 +128,14 @@ export interface BabysitterLifecycleLabels {
123
128
  }
124
129
  export interface BabysitterLifecycleOptions {
125
130
  labels?: BabysitterLifecycleLabels;
131
+ /**
132
+ * Also select a PR that `filter`'s author allow lists leave out, such as one from an outside
133
+ * contributor, once a reviewer with write access approves its current head. The approval carries
134
+ * over to the heads the Babysitter builds on the approved commit, so it repairs and merges the PR
135
+ * without another review. A push by anyone else drops the PR until the next approval. Deny lists and
136
+ * every other rule still apply. Defaults to `false`.
137
+ */
138
+ approval?: boolean;
126
139
  }
127
140
  /** Where one pass runs. A pass without a Sandbox uses the host checkout and the configured `sandbox`. */
128
141
  export interface BabysitterPlacementLease {
@@ -1,2 +1,2 @@
1
- import { i as BabysitterPlacementCapacityError, n as babysitterPassResultSchema, r as resolveBabysitterLifecycleFilter, t as babysitter } from "./babysitter-DQeA81N0.js";
1
+ import { i as BabysitterPlacementCapacityError, n as babysitterPassResultSchema, r as resolveBabysitterLifecycleFilter, t as babysitter } from "./babysitter-B5C0KLRl.js";
2
2
  export { BabysitterPlacementCapacityError, babysitter, babysitterPassResultSchema, resolveBabysitterLifecycleFilter };
@@ -1,6 +1,6 @@
1
1
  import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-o3pHscWs.js";
2
- import { d as resolveBabysitterAdmissionLimits, f as sharedBabysitterRead, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-DQeA81N0.js";
3
- import { a as budgetParks, c as createGitHubHost, i as babysitterQueueHealth, o as pullRequestThreadId, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "./server-ILDJE5V7.js";
2
+ import { d as resolveBabysitterAdmissionLimits, f as sharedBabysitterRead, o as createPullRequestWorkspaces, r as resolveBabysitterLifecycleFilter, u as createBabysitterAdmission } from "./babysitter-B5C0KLRl.js";
3
+ import { a as budgetParks, c as createGitHubHost, i as babysitterQueueHealth, o as pullRequestThreadId, s as createGitHubAppCredentials, t as createBabysitterRuntime } from "./server-Bj5_Uf_Y.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";
@@ -512,13 +512,12 @@ async function createBabysitterProcessHost(context) {
512
512
  run: async (reason, run, accepting) => await runtime?.reconcile(reason, run, accepting)
513
513
  });
514
514
  const preflight = createBabysitterPreflight(agent.options.install ?? true);
515
- const buildRevision = "91ca93f60843c0df231a3f438cf1c2ef1587bfc67b8791323ef4f38cc44ca863";
515
+ const buildRevision = "cc2ab9f972b0945800468710b76d4809a3c6faa1a595c85f117a934b62a37e90";
516
516
  const admission = createBabysitterAdmission({
517
517
  invocations: host.invocations,
518
518
  limits: resolveBabysitterAdmissionLimits(agent.options.admission),
519
519
  check: async () => (await preflight()).pause ?? await agent.options.admission?.check?.()
520
520
  });
521
- let admissionPrerequisiteSample;
522
521
  const warmWorkspaces = agent.options.warmWorkspaces;
523
522
  const resumeThreads = typeof warmWorkspaces === "object" && warmWorkspaces.resumeThreads === true;
524
523
  const workspaces = warmWorkspaces ? createPullRequestWorkspaces({
@@ -566,6 +565,20 @@ async function createBabysitterProcessHost(context) {
566
565
  }
567
566
  });
568
567
  const inbox = runtime.inbox;
568
+ const schedulerHealth = runtime.scheduler;
569
+ const processHealth = boundedHealthRead(() => host.health());
570
+ const queueHealth = boundedHealthRead(() => inbox.summary());
571
+ const prerequisiteHealth = boundedHealthRead(preflight);
572
+ const skipHealth = boundedHealthRead(async () => ({ lastSkip: await inbox.meta("admission-skipped") }));
573
+ let admissionPrerequisiteSample;
574
+ const admissionHealth = boundedHealthRead(async () => {
575
+ const prerequisites = await preflight();
576
+ if (admissionPrerequisiteSample !== prerequisites.checkedAt) {
577
+ admissionPrerequisiteSample = prerequisites.checkedAt;
578
+ admission.invalidate();
579
+ }
580
+ return await admission.health();
581
+ });
569
582
  const swept = await sweepBabysitterWorkspaces();
570
583
  const workspaceStatus = async (repository, number) => {
571
584
  if (!repositories.known().includes(repository.toLowerCase())) return "unknown";
@@ -586,6 +599,8 @@ async function createBabysitterProcessHost(context) {
586
599
  error: host.error
587
600
  });
588
601
  let redeliverySweep;
602
+ let starting;
603
+ let closing = false;
589
604
  return {
590
605
  start() {
591
606
  registerAgentProcessHostIntake(context.agentName, async ({ deliveryId, event, payload }) => {
@@ -602,9 +617,10 @@ async function createBabysitterProcessHost(context) {
602
617
  if (result.updated.length || enrolled || mainRepair || event === "installation" || event === "installation_repositories") host.wake("webhook");
603
618
  return Response.json(result, { status: 202 });
604
619
  });
605
- inbox.importLegacyFile(".vitehub/pull-request-inbox.sqlite").catch((error) => host.error("babysitter.legacy-import.failed", error)).then(() => inbox.releaseLeases()).then((released) => {
620
+ starting = inbox.importLegacyFile(".vitehub/pull-request-inbox.sqlite").catch((error) => host.error("babysitter.legacy-import.failed", error)).then(() => closing ? 0 : inbox.releaseLeases()).then((released) => {
606
621
  if (released) host.event("babysitter.leases.released", { released });
607
622
  }, (error) => host.error("babysitter.leases.release-failed", error)).finally(() => {
623
+ if (closing) return;
608
624
  if (swept) host.event("babysitter.workspaces.swept", { removed: swept });
609
625
  host.start();
610
626
  redeliverySweep = setInterval(() => void redelivery.sweep().catch((error) => host.error("babysitter.webhook.redelivery_failed", error)), 3e5);
@@ -626,70 +642,111 @@ async function createBabysitterProcessHost(context) {
626
642
  }, (error) => host.error("babysitter.labels.failed", error));
627
643
  },
628
644
  async close() {
645
+ closing = true;
629
646
  clearInterval(workspaceSweep);
630
647
  clearInterval(redeliverySweep);
631
648
  registerAgentProcessHostIntake(context.agentName, void 0);
632
649
  await host.close();
650
+ await starting;
633
651
  await inbox.close();
634
652
  },
635
653
  wake: (reason) => host.wake(reason),
636
654
  status: () => host.status(),
637
655
  async health() {
638
- const health = await host.health();
639
- const queue = await inbox.summary();
640
- const prerequisites = await preflight();
641
- if (admissionPrerequisiteSample !== prerequisites.checkedAt) {
642
- admissionPrerequisiteSample = prerequisites.checkedAt;
643
- admission.invalidate();
644
- }
645
- const guard = await admission.health();
646
- const lastSkip = await inbox.meta("admission-skipped");
656
+ const [health, queue, prerequisites, guard, skip] = await Promise.all([
657
+ processHealth(),
658
+ queueHealth(),
659
+ prerequisiteHealth(),
660
+ admissionHealth(),
661
+ skipHealth()
662
+ ]);
663
+ const hostStatus = host.status();
664
+ const scheduler = schedulerHealth(hostStatus === "accepting" || hostStatus === "starting");
665
+ const stall = scheduler.status === "stalled" ? scheduler.lastStall : void 0;
666
+ const schedulerDiagnostics = scheduler.status === "ok" ? [] : [{
667
+ label: "Scheduler",
668
+ status: "warning",
669
+ value: stall ? `Stalled at ${stall.step}` : "No reconcile finished",
670
+ detail: stall ? `${stall.count} reconcile(s) in a row waited too long and were stopped${stall.subject ? `, the last on ${stall.subject}` : ""}.` : `The last reconcile finished at ${scheduler.lastFinishedAt ?? "never"}.`
671
+ }];
672
+ const unavailable = [
673
+ !health && "invocation state",
674
+ !queue && "queue",
675
+ !prerequisites && "prerequisites",
676
+ !guard && "admission",
677
+ !skip && "admission history"
678
+ ].filter(Boolean);
679
+ const readDiagnostics = unavailable.length ? [{
680
+ label: "Health data",
681
+ status: "warning",
682
+ value: "Unavailable",
683
+ detail: unavailable.join(", ")
684
+ }] : [];
685
+ const lastSkip = skip?.lastSkip;
647
686
  return {
648
687
  ...health,
649
- status: prerequisites.pause ? "degraded" : health.status,
650
- diagnostics: [...health.diagnostics, ...prerequisites.diagnostics],
688
+ status: health?.status === "healthy" && !prerequisites?.pause && !schedulerDiagnostics.length && !unavailable.length ? "healthy" : "degraded",
689
+ diagnostics: [
690
+ ...health?.diagnostics ?? [],
691
+ ...prerequisites?.diagnostics ?? [],
692
+ ...schedulerDiagnostics,
693
+ ...readDiagnostics
694
+ ],
695
+ scheduler,
651
696
  release: agent.version,
652
697
  framework: { buildRevision },
653
698
  concurrency: agent.options.concurrency,
654
699
  repositories: repositories.known(),
655
700
  repositorySource: repositories.source,
656
- queue: {
701
+ ...queue ? { queue: {
657
702
  ...babysitterQueueHealth(queue),
658
703
  parked: budgetParks(queue)
659
- },
660
- admission: {
661
- accepting: guard.accepting,
662
- hostOnly: guard.hostOnly,
663
- reason: guard.reason,
664
- retryAt: guard.retryAt,
665
- detail: guard.detail,
666
- lastSkip,
667
- history: { lastSkip }
668
- },
669
- budget: {
670
- accounting: guard.accounting,
671
- observedAt: new Date(guard.observedAt).toISOString(),
672
- hourly: {
673
- inputTokens: guard.state.hourlyInputTokens,
674
- limit: guard.limits.hourlyInputTokens,
675
- resetsAt: guard.state.windows.hourEnd
676
- },
677
- daily: {
678
- inputTokens: guard.state.dailyInputTokens,
679
- limit: guard.limits.dailyInputTokens,
680
- resetsAt: guard.state.windows.dayEnd
681
- },
682
- tmp: {
683
- dir: guard.state.tmpDir,
684
- freeBytes: guard.state.freeTmpBytes,
685
- minFreeBytes: guard.limits.minFreeTmpBytes
704
+ } } : {},
705
+ ...guard ? {
706
+ admission: {
707
+ accepting: guard.accepting,
708
+ hostOnly: guard.hostOnly,
709
+ reason: guard.reason,
710
+ retryAt: guard.retryAt,
711
+ detail: guard.detail,
712
+ lastSkip,
713
+ history: { lastSkip }
686
714
  },
687
- pause: guard.state.pause,
688
- errors: guard.state.errors
689
- }
715
+ budget: {
716
+ accounting: guard.accounting,
717
+ observedAt: new Date(guard.observedAt).toISOString(),
718
+ hourly: {
719
+ inputTokens: guard.state.hourlyInputTokens,
720
+ limit: guard.limits.hourlyInputTokens,
721
+ resetsAt: guard.state.windows.hourEnd
722
+ },
723
+ daily: {
724
+ inputTokens: guard.state.dailyInputTokens,
725
+ limit: guard.limits.dailyInputTokens,
726
+ resetsAt: guard.state.windows.dayEnd
727
+ },
728
+ tmp: {
729
+ dir: guard.state.tmpDir,
730
+ freeBytes: guard.state.freeTmpBytes,
731
+ minFreeBytes: guard.limits.minFreeTmpBytes
732
+ },
733
+ pause: guard.state.pause,
734
+ errors: guard.state.errors
735
+ }
736
+ } : {}
690
737
  };
691
738
  }
692
739
  };
693
740
  }
741
+ function boundedHealthRead(read) {
742
+ let pending;
743
+ return () => pending ??= new Promise((resolve) => {
744
+ const timer = setTimeout(() => resolve(void 0), 1e3);
745
+ Promise.resolve().then(read).then(resolve, () => resolve(void 0)).finally(() => {
746
+ clearTimeout(timer);
747
+ pending = void 0;
748
+ });
749
+ });
750
+ }
694
751
  //#endregion
695
752
  export { createBabysitterProcessHost };