@vite-hub/presets 0.3.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
@@ -1,15 +1,15 @@
1
1
  # @vite-hub/presets
2
2
 
3
- [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fpresets&icon=npm)](https://npmx.dev/package/@vite-hub/presets)
4
- [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fpresets&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/presets)
5
- [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
- [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
3
+ [![npm version](https://img.shields.io/npm/v/@vite-hub/presets)](https://npmx.dev/package/@vite-hub/presets)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@vite-hub/presets)](https://npmx.dev/package/@vite-hub/presets)
5
+ [![license](https://img.shields.io/static/v1?label=license&message=Apache-2.0&color=blue)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://img.shields.io/static/v1?label=docs&message=vitehub.dev&color=blue)](https://vitehub.dev/docs)
7
7
 
8
8
  `@vite-hub/presets` contains ready-made Agents that are built from ViteHub
9
9
  primitives. Each preset is a subpath. The package depends on
10
10
  [`@vite-hub/agent`](../agent/README.md); the Agent package does not know these presets.
11
11
 
12
- Most applications use the `vite-hub/presets/*` imports of the `vite-hub` framework distribution.
12
+ Most applications use the `vite-hub/presets/*` imports of the `vite-hub` framework distribution. User docs: [Agent presets](https://vitehub.dev/docs/presets).
13
13
 
14
14
  | Import | Preset |
15
15
  | --- | --- |
@@ -35,7 +35,7 @@ Most applications use the `vite-hub/presets/*` imports of the `vite-hub` framewo
35
35
  import { labeller } from "@vite-hub/presets/labeller"
36
36
  ```
37
37
 
38
- See the [Labeller docs](https://vitehub.dev/docs/agents/labeller).
38
+ See the [Labeller docs](https://vitehub.dev/docs/presets/labeller).
39
39
 
40
40
  ## Workspace preset
41
41
 
@@ -43,7 +43,7 @@ See the [Labeller docs](https://vitehub.dev/docs/agents/labeller).
43
43
  import workspace from "@vite-hub/presets/workspace"
44
44
  ```
45
45
 
46
- See the [workspace preset docs](https://vitehub.dev/docs/agents/workspace-preset).
46
+ See the [workspace preset docs](https://vitehub.dev/docs/presets/workspace).
47
47
 
48
48
  ## Babysitter
49
49
 
@@ -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.
@@ -159,7 +169,14 @@ changed its files after its checks ran, gets a branch update instead of a merge
159
169
  or a model pass. A head that already contains the base tip needs no update. When
160
170
  GitHub refuses `update-branch`, as it does for some stacked PRs, the host merges
161
171
  the base into a same-repository head branch through `POST /repos/{owner}/{repo}/merges`
162
- after checking that the head did not move.
172
+ after checking that the head did not move. GitHub refuses App pushes to a fork,
173
+ so a fork PR whose base changed its files, or that needs a retest on the current
174
+ base, is closed and reopened instead, at most hourly. Its `pull_request` workflows
175
+ then run again on the merge with the current base. GitHub lists no pull request on
176
+ a fork's Actions runs, so the host matches the workflow run to the fork branch and
177
+ head, then uses base branch activity before the run was created. Push runs do not
178
+ count. The host records the close first and recovers an interrupted reopen only
179
+ when its own GitHub identity closed the PR.
163
180
 
164
181
  PRs whose head branch starts with `mainRepairBranchPrefix` still get a repair pass when their failure repeats the base.
165
182
 
@@ -178,6 +195,17 @@ branch rules. A required check that never reported, 10 minutes after the head's
178
195
  checks finished, gets a branch update or an Actions rerun once per head every
179
196
  six hours.
180
197
 
198
+ `forkHeadBranches` (off by default), such as
199
+ `{ "acme/app": "preview/pr-{number}" }`, is for required checks that run only on
200
+ pushes to the repository, like pkg.pr.new. Such a check never reports on a fork
201
+ PR's head. When it is missing, the host pushes the head to that branch, once per
202
+ head. A push runs the workflow files of the pushed commit with the repository's
203
+ permissions, so the host first rereads GitHub and pushes only when a reviewer with
204
+ write access approved that exact head, no change request stands, and any local
205
+ action, reusable workflow, or workflow triggered by pushing or creating that
206
+ branch still matches the live base. It moves and deletes only a
207
+ branch it created, and deletes it once the PR closes.
208
+
181
209
  `markDraftsReady` lists GitHub logins, such as maintainers and their bots, whose
182
210
  drafts should merge. Off by default. When a pass has reviewed a draft's head, no
183
211
  required check failed, and the head branch is in the repository itself, the host
@@ -295,14 +323,16 @@ installations can access, except archived ones and `filter.repository.deny`),
295
323
  claims, repair passes, and wake handling. Installing the App on a repository
296
324
  enrolls it; `installation` and `installation_repositories` webhooks update the
297
325
  list at once, and the host lists the installations again every 10 minutes. Signed
298
- GitHub deliveries to `/api/_vitehub/agents/<name>/webhooks/github` feed the
299
- inbox; they never start the Agent directly. `GET /api/_vitehub/host/drain`
300
- reports drain status, and `GET /api/_vitehub/host/health` reports each host's
326
+ GitHub deliveries to `/_vitehub/agents/<name>/webhooks/github` feed the
327
+ inbox; they never start the Agent directly. `GET /_vitehub/host/drain`
328
+ reports drain status, and `GET /_vitehub/host/health` reports each host's
301
329
  health and queue. SIGUSR2 starts a drain. The build fails with `AGENT_B0022` on
302
330
  hosts that cannot keep a process running, and with `AGENT_B0023` without SQL
303
331
  Agent State. Hosts start in production builds, or in development only with
304
332
  `VITEHUB_AGENT_PROCESS_HOSTS=1`, so a development server does not repair real
305
- 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.
306
336
 
307
337
  The host reads the GitHub App from `env.server.github` or `VITEHUB_GITHUB_APP_ID`,
308
338
  `VITEHUB_GITHUB_PRIVATE_KEY` (or `VITEHUB_GITHUB_PRIVATE_KEY_PATH`), and
@@ -394,7 +424,7 @@ still revoke further repair operations.
394
424
 
395
425
  ## Babysitter GitHub host
396
426
 
397
- `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:
398
428
 
399
429
  ```ts fragment
400
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-CjX3PSqM.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";
@@ -10,7 +10,7 @@ interface BabysitterRepositories {
10
10
  /** The list without a GitHub read. */
11
11
  known(): readonly string[];
12
12
  /** The list, read again from the App installations when it is stale. A failed read keeps the last list and rejects. */
13
- current(): Promise<readonly string[]>;
13
+ current(signal?: AbortSignal): Promise<readonly string[]>;
14
14
  /**
15
15
  * Notes a signed delivery. Installation events update the list and make it stale. An event from a
16
16
  * repository the list does not have yet adds it, because GitHub sends only events of installed repositories.
@@ -50,7 +50,7 @@ export interface BabysitterRuntimeOptions {
50
50
  providerRetryDelayMs?: number;
51
51
  /** Delay between live reads while GitHub computes mergeability before a direct merge. Defaults to 3 seconds. */
52
52
  mergeabilityRetryDelayMs?: number;
53
- admission?: () => Promise<Pick<BabysitterAdmissionResult, "accepting" | "hostOnly" | "reason" | "retryAt" | "detail">>;
53
+ admission?: (signal?: AbortSignal) => Promise<Pick<BabysitterAdmissionResult, "accepting" | "hostOnly" | "reason" | "retryAt" | "detail">>;
54
54
  /**
55
55
  * Samples memory and pressure for work that runs like a worker before the model starts, such as the
56
56
  * merge and install of a conflicting PR. `active` counts the worker passes and preparations already
@@ -65,15 +65,44 @@ export interface BabysitterRuntimeOptions {
65
65
  }>;
66
66
  /** One kept workspace per open PR. Without it, each pass clones and installs into temporary directories. */
67
67
  workspaces?: PullRequestWorkspaces;
68
+ /**
69
+ * How long one reconcile may wait before the runtime reports `babysitter.reconcile.stalled` and stops
70
+ * it, so the next reconcile can claim work. Defaults to 15 minutes.
71
+ */
72
+ stallMs?: number;
68
73
  }
69
74
  /**
70
75
  * GitHub settles most asynchronous merges in seconds, so poll a pending request less often as it ages:
71
76
  * after 30 seconds at first, then after as long as it has been pending, at most every five minutes.
72
- * vite-hub/vitehub#3350 was polled every 30 seconds for 19 hours.
77
+ * A fixed 30-second poll can run for hours on a request that GitHub never settles.
73
78
  */
74
79
  export declare function pendingMergeRetryAt(startedAt: number, now: number): number;
75
80
  /** Provider quota and rate-limit failures. Cancellation is never a rate limit. */
76
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
+ }
77
106
  /** Own one durable PR inbox and its repair passes inside a process host. */
78
107
  export interface BabysitterRuntime {
79
108
  inbox: PullRequestInbox;
@@ -83,6 +112,8 @@ export interface BabysitterRuntime {
83
112
  workload(): {
84
113
  running: number;
85
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;
86
117
  /**
87
118
  * Makes the next reconcile check the default branch of the delivery's repository when the delivery
88
119
  * is a failed push run of a watched workflow there. Returns whether it did.
@@ -1,2 +1,2 @@
1
- import { n as isProviderRateLimit, o as createGitHubAppCredentials, r as pendingMergeRetryAt, s as createGitHubHost, t as createBabysitterRuntime } from "../server-CIgjUG63.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 };
@@ -1,4 +1,4 @@
1
- import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-BTBW9sZx.js";
1
+ import { i as isRuntimeRecord, n as hasRuntimeType, t as presetsErrorDiagnostics } from "./error-diagnostics-o3pHscWs.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";
@@ -13,7 +13,7 @@ import { Diagnostic, defineDiagnostics } from "nostics";
13
13
  import { parseMarkdown } from "comark";
14
14
  import html from "comark/plugins/html";
15
15
  import linkify from "comark/plugins/linkify";
16
- import { setTimeout } from "node:timers/promises";
16
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
17
17
  import { agentProcessHostIntake, withAgentProcessHost } from "@vite-hub/agent/process";
18
18
  //#region src/babysitter/result.ts
19
19
  const babysitterSha = /^[a-f0-9]{40,64}$/;
@@ -132,7 +132,9 @@ Never park a PR to ask a maintainer to choose between requirements. Pick the opt
132
132
 
133
133
  ## Checks and validation
134
134
 
135
- Failing required checks come before review findings. When a required check fails in setup, install, lint, typecheck, build or tests, repairing it is this pass's work, even when P1 findings are open: a broken lockfile or a duplicate declaration left by a merge blocks the merge, and review findings do not. Repair only failures this PR causes, except when the host supplies a verified-main-repair block outside the PR snapshot. That host-owned block authorizes repairing inherited default-branch failures, even when the initial PR tree equals the base tree; in that mode the prohibition on pushing fixes for failures shared with the base does not apply. Reproduce the base failures, repair them, and do not report reviewedHead until the branch contains a repair. Before you change code for a failing check, compare it with the base through readBaseCheckEvidence and readBaseCheckLogs. Do not push for a check that fails the same way on the base, or for a runner or network error such as a lost runner or a failed registry, Git or image fetch; name each such failure in the result. When the current base already passes a check that fails here, copy its fix (\`git diff HEAD...origin/<base> -- <file>\`). Never ask anyone to rerun a check.
135
+ Failing required checks come before review findings. Repair required setup, install, lint, typecheck, build and test failures unless the host's live-base-attribution block verifies that the job fails the same way in the live base tip's CI, or a runner or network error such as a lost runner or a failed registry, Git or image fetch stopped it. Name inherited and infrastructure failures in the result; do not push for them. Use readBaseCheckEvidence and readBaseCheckLogs for diagnosis and reproduction on the assigned base, not as proof that the live tip still fails. A flaky, timing-dependent or order-dependent failure is this pass's work even if it also reproduces on base code: fix the flake at its root in this PR and never report it as inherited without live CI proof. Do not report reviewedHead while a repairable required failure remains. If the base already contains a fix, copy it (\`git diff HEAD...origin/<base> -- <file>\`). Never ask anyone to rerun a check.
136
+
137
+ A host-supplied verified-main-repair block authorizes repairing inherited default-branch failures, even when the initial PR tree equals the base tree. Reproduce and repair those base failures, and do not report reviewedHead until the branch contains a repair.
136
138
 
137
139
  Make at most one repair commit per pass. Use the focused-test recipe from the repository's AGENTS.md or CONTRIBUTING.md, including prerequisite builds, and run tests from the owning package rather than the repository root. When a focused test or typecheck cannot resolve a workspace export, build its owner with the repository's documented build target and retry the same command. List instruction files with \`git ls-files '*AGENTS.md' '*CONTRIBUTING.md'\`. Never search outside the checkout (\`find ..\`, \`/\`, \`~\`).
138
140
 
@@ -271,10 +273,14 @@ const maxRangeLines = 1e3;
271
273
  function compactCiLog(log, limit = compactLimit) {
272
274
  const compact = log.replace(/(?:\x1b|\^\[)\[[0-9;?]*[ -/]*[@-~]/g, "").split("\n").filter((line) => !/\s\* \[new (?:branch|tag)\]\s/.test(line)).join("\n");
273
275
  if (compact.length <= limit) return compact;
274
- 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++;
275
280
  let omitted = 0;
276
281
  for (let n = compact.indexOf("\n"); n !== -1 && n < start; n = compact.indexOf("\n", n + 1)) omitted++;
277
- 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)}`;
278
284
  }
279
285
  /** Bound log context explicitly; the full fetched log remains in the local cache. */
280
286
  function diagnosticExcerpt(log, limit = 16e3, failedSteps = []) {
@@ -413,9 +419,9 @@ const key = (kind, value) => `ci-evidence:v1:${kind}:${createHash("sha256").upda
413
419
  const failed = (item) => item.status === "completed" && failures.has(item.conclusion ?? "");
414
420
  const sourceUrl = (repository, job) => `https://github.com/${repository}/actions/runs/${job.run_id}/job/${job.id}`;
415
421
  /**
416
- * The run of one check that counts: the newer one, unless it was cancelled beside a finished run. On
417
- * onmax/comark-plugins#87 and #103 the push and pull_request runs of one workflow shared a concurrency
418
- * group, the later one was cancelled, and the PRs waited 17 h on checks that had already passed.
422
+ * The run of one check that counts: the newer one, unless it was cancelled beside a finished run. When
423
+ * the push and pull_request runs of one workflow share a concurrency group, the later one is cancelled,
424
+ * and the PR must not wait on checks that already passed.
419
425
  */
420
426
  function newestCheckRun(previous, check) {
421
427
  if (!previous) return check;
@@ -1277,6 +1283,62 @@ function createGitHubPullRequestOperations(github, options) {
1277
1283
  };
1278
1284
  }
1279
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
1280
1342
  //#region src/babysitter/merge.ts
1281
1343
  const failing = /* @__PURE__ */ new Set([
1282
1344
  "failure",
@@ -1417,16 +1479,11 @@ function feedbackFingerprints(snapshot, policy = {}, legacy = false) {
1417
1479
  value.state
1418
1480
  ])).digest("hex").slice(0, 32)));
1419
1481
  }
1420
- /** Author and reviewer associations that GitHub gives to people with write access to the repository. */
1421
- const writeAccess = /* @__PURE__ */ new Set([
1422
- "OWNER",
1423
- "MEMBER",
1424
- "COLLABORATOR"
1425
- ]);
1426
- const hasWriteAccess = (association) => writeAccess.has(String(association ?? "").toUpperCase());
1427
1482
  /**
1428
1483
  * The `"approved-if-outside"` merge gate. Each write-access reviewer's latest APPROVED or
1429
- * 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.
1430
1487
  */
1431
1488
  function approvedIfOutside(input) {
1432
1489
  return approvedIfOutsideGate(input, /* @__PURE__ */ new Set());
@@ -1437,20 +1494,15 @@ function accountLogin(user) {
1437
1494
  if (!login) return "";
1438
1495
  return (login.endsWith("[bot]") || String(user?.type ?? user?.__typename ?? "").toLowerCase() === "bot") && !login.endsWith("[bot]") ? `${login}[bot]` : login;
1439
1496
  }
1440
- function approvedIfOutsideGate({ head, snapshot }, trustedAuthors) {
1497
+ function approvedIfOutsideGate({ head, snapshot, writers }, trustedAuthors) {
1441
1498
  const pr = snapshot.pr;
1499
+ const author = accountLogin(pr?.user ?? pr?.author);
1442
1500
  if (hasWriteAccess(pr?.author_association ?? pr?.authorAssociation)) return true;
1443
- if (trustedAuthors.has(accountLogin(pr?.user ?? pr?.author))) return true;
1444
- const latest = /* @__PURE__ */ new Map();
1445
- 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 ?? "")));
1446
- for (const review of decisive) {
1447
- const reviewer = feedbackAuthor(review);
1448
- if (reviewer) latest.set(reviewer, review);
1449
- }
1501
+ if (trustedAuthors.has(author)) return true;
1502
+ const approval = maintainerApproval(snapshot, head, writers);
1450
1503
  const short = head.slice(0, 7);
1451
- const blocking = [...latest].filter(([, review]) => String(review.state).toUpperCase() === "CHANGES_REQUESTED").map(([reviewer]) => reviewer);
1452
- if (blocking.length) return `a maintainer's approval of ${short}: ${blocking.join(", ")} requested changes`;
1453
- 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}`;
1454
1506
  }
1455
1507
  function resolveBabysitterMerge(merge) {
1456
1508
  if (merge === false) return { mode: "off" };
@@ -1498,13 +1550,29 @@ function resolveBabysitterMerge(merge) {
1498
1550
  if (checks.length) bypassInheritedChecks.set(repository.toLowerCase(), new Set(checks.map((check) => check.toLowerCase())));
1499
1551
  }
1500
1552
  }
1553
+ const forkHeadBranches = /* @__PURE__ */ new Map();
1554
+ if (merge.forkHeadBranches !== void 0) {
1555
+ const expected = "an object of branch names by repository, such as { \"acme/app\": \"preview/pr-{number}\" }";
1556
+ if (!isRuntimeRecord(merge.forkHeadBranches) || Array.isArray(merge.forkHeadBranches)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_OPTION_INVALID({
1557
+ option: "merge.forkHeadBranches",
1558
+ expected
1559
+ });
1560
+ for (const [repository, branch] of Object.entries(merge.forkHeadBranches)) {
1561
+ if (!hasRuntimeType(branch, "string") || !branch.includes("{number}") || !/^[\w.{}/-]+$/.test(branch)) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_OPTION_INVALID({
1562
+ option: `merge.forkHeadBranches["${repository}"]`,
1563
+ expected: "a branch name with {number}, such as \"preview/pr-{number}\""
1564
+ });
1565
+ forkHeadBranches.set(repository.toLowerCase(), branch);
1566
+ }
1567
+ }
1501
1568
  return {
1502
1569
  mode: "direct",
1503
1570
  method,
1504
1571
  foldStacks: merge.foldStacks ?? true,
1505
1572
  ...ready ? { ready } : {},
1506
1573
  ...drafts?.length ? { markDraftsReady: new Set(drafts.map((login) => login.trim().toLowerCase())) } : {},
1507
- ...bypassInheritedChecks.size ? { bypassInheritedChecks } : {}
1574
+ ...bypassInheritedChecks.size ? { bypassInheritedChecks } : {},
1575
+ ...forkHeadBranches.size ? { forkHeadBranches } : {}
1508
1576
  };
1509
1577
  }
1510
1578
  throw presetsErrorDiagnostics.PRESETS_BABYSITTER_OPTION_INVALID({
@@ -1607,6 +1675,39 @@ function liveMergeReadiness(live, head, reviewPolicy = {}) {
1607
1675
  };
1608
1676
  }
1609
1677
  //#endregion
1678
+ //#region src/babysitter/shared-read.ts
1679
+ function sharedBabysitterRead(read) {
1680
+ let pending;
1681
+ return async (caller, ...args) => {
1682
+ caller?.throwIfAborted();
1683
+ if (!pending || pending.controller.signal.aborted) {
1684
+ const controller = new AbortController();
1685
+ const signal = controller.signal;
1686
+ const timer = setTimeout(() => controller.abort(new DOMException("Babysitter read timed out", "TimeoutError")), 9e5);
1687
+ timer.unref?.();
1688
+ const timeout = new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }));
1689
+ pending = {
1690
+ result: Promise.race([Promise.resolve().then(() => {
1691
+ signal.throwIfAborted();
1692
+ return read(signal, ...args);
1693
+ }), timeout]).finally(() => {
1694
+ clearTimeout(timer);
1695
+ if (pending?.controller === controller) pending = void 0;
1696
+ }),
1697
+ controller
1698
+ };
1699
+ }
1700
+ const { result, controller } = pending;
1701
+ const stop = () => controller.abort(caller?.reason);
1702
+ caller?.addEventListener("abort", stop, { once: true });
1703
+ try {
1704
+ return await result;
1705
+ } finally {
1706
+ caller?.removeEventListener("abort", stop);
1707
+ }
1708
+ };
1709
+ }
1710
+ //#endregion
1610
1711
  //#region src/babysitter/admission.ts
1611
1712
  const tokenLimit = (value) => value === void 0 || Number.isSafeInteger(value) && Number(value) >= 0;
1612
1713
  /** Whether `value` is a valid `admission` option. */
@@ -1686,12 +1787,13 @@ function babysitterAdmissionDecision(state, limits) {
1686
1787
  };
1687
1788
  return { accepting: true };
1688
1789
  }
1689
- async function readInvocationInputTokens(invocations, since) {
1790
+ async function readInvocationInputTokens(invocations, since, signal) {
1690
1791
  invariant(invocations, "the admission controller reads token usage only after the runtime assigns the invocation journal");
1691
1792
  const usage = [];
1692
1793
  let cursor;
1693
1794
  const seenCursors = /* @__PURE__ */ new Set();
1694
1795
  do {
1796
+ signal?.throwIfAborted();
1695
1797
  const page = await invocations.list({
1696
1798
  cursor,
1697
1799
  limit: 100,
@@ -1707,6 +1809,7 @@ async function readInvocationInputTokens(invocations, since) {
1707
1809
  invariant(!page.cursor || !seenCursors.has(page.cursor), "the Agent Invocation store returns a new pagination cursor for each page");
1708
1810
  if (page.cursor) seenCursors.add(page.cursor);
1709
1811
  for (const summary of page.invocations) {
1812
+ signal?.throwIfAborted();
1710
1813
  if (Date.parse(summary.updatedAt) < since) continue;
1711
1814
  const record = await invocations.get(summary.id);
1712
1815
  if (!record) continue;
@@ -1744,20 +1847,17 @@ function normalizeAdmissionPause(value) {
1744
1847
  return pause;
1745
1848
  }
1746
1849
  function coalesceBabysitterAdmission(read, clock = Date.now) {
1747
- let pending;
1748
1850
  let latest;
1749
- function check(now) {
1750
- pending ??= Promise.resolve().then(() => read(now)).then((result) => {
1751
- latest = {
1752
- ...result,
1753
- observedAt: clock()
1754
- };
1755
- return latest;
1756
- }).finally(() => {
1757
- pending = void 0;
1758
- });
1759
- return pending;
1760
- }
1851
+ const sample = sharedBabysitterRead(async (signal, now) => {
1852
+ const result = await read(now, signal);
1853
+ signal.throwIfAborted();
1854
+ latest = {
1855
+ ...result,
1856
+ observedAt: clock()
1857
+ };
1858
+ return latest;
1859
+ });
1860
+ const check = (now, signal) => sample(signal, now);
1761
1861
  return Object.assign(check, {
1762
1862
  health: () => latest && clock() - latest.observedAt <= 12e4 ? Promise.resolve(latest) : check(),
1763
1863
  invalidate: () => {
@@ -1769,7 +1869,7 @@ function createBabysitterAdmission(options) {
1769
1869
  const usage = /* @__PURE__ */ new Map();
1770
1870
  let readAt;
1771
1871
  let cursor;
1772
- return coalesceBabysitterAdmission(async function check(now = Date.now()) {
1872
+ return coalesceBabysitterAdmission(async function check(now = Date.now(), signal) {
1773
1873
  const windows = babysitterBudgetWindows(now);
1774
1874
  const state = {
1775
1875
  windows,
@@ -1781,9 +1881,12 @@ function createBabysitterAdmission(options) {
1781
1881
  } catch (error) {
1782
1882
  state.errors = [`tmp: ${error instanceof Error ? error.message : String(error)}`];
1783
1883
  }
1884
+ signal?.throwIfAborted();
1784
1885
  if ((options.limits.hourlyInputTokens !== void 0 || options.limits.dailyInputTokens !== void 0) && (readAt === void 0 || now - readAt >= 6e4)) try {
1785
1886
  const since = cursor === void 0 ? windows.dayStart : Math.max(windows.dayStart, cursor - 6e4);
1786
- for (const entry of await readInvocationInputTokens(options.invocations, since)) usage.set(entry.id, {
1887
+ const entries = await readInvocationInputTokens(options.invocations, since, signal);
1888
+ signal?.throwIfAborted();
1889
+ for (const entry of entries) usage.set(entry.id, {
1787
1890
  updatedAt: Date.parse(entry.updatedAt),
1788
1891
  tokens: Number(entry.tokens) || 0
1789
1892
  });
@@ -1793,12 +1896,13 @@ function createBabysitterAdmission(options) {
1793
1896
  } catch (error) {
1794
1897
  state.errors = [...state.errors ?? [], `tokens: ${error instanceof Error ? error.message : String(error)}`];
1795
1898
  }
1899
+ signal?.throwIfAborted();
1796
1900
  if (readAt !== void 0) {
1797
1901
  state.hourlyInputTokens = sumInvocationInputTokens(usage, windows.hourStart);
1798
1902
  state.dailyInputTokens = sumInvocationInputTokens(usage, windows.dayStart);
1799
1903
  }
1800
1904
  if (options.check && !options.limits.paused) try {
1801
- const pause = normalizeAdmissionPause(await options.check());
1905
+ const pause = normalizeAdmissionPause(await options.check(signal));
1802
1906
  if (pause) state.pause = pause;
1803
1907
  } catch (error) {
1804
1908
  state.errors = [...state.errors ?? [], `check: ${error instanceof Error ? error.message : String(error)}`];
@@ -1981,7 +2085,7 @@ function createPullRequestWorkspaces(options) {
1981
2085
  try {
1982
2086
  while (!await tryLockFile(name)) {
1983
2087
  signal?.throwIfAborted();
1984
- await setTimeout(500, void 0, { signal });
2088
+ await setTimeout$1(500, void 0, { signal });
1985
2089
  }
1986
2090
  } catch (error) {
1987
2091
  unlock();
@@ -2214,7 +2318,7 @@ function validMainRepair(mainRepair) {
2214
2318
  return names(workflows, /\S/) && (repositories === void 0 || names(repositories, /^[\w.-]+\/[\w.-]+$/)) && (stuckJobMinutes === void 0 || stuckJobMinutes === false || Number.isSafeInteger(stuckJobMinutes) && Number(stuckJobMinutes) >= 1);
2215
2319
  }
2216
2320
  const babysitterHost = { async create(context) {
2217
- const { createBabysitterProcessHost } = await import("./host-Dsi6saqi.js");
2321
+ const { createBabysitterProcessHost } = await import("./host-gF2JTvw8.js");
2218
2322
  return await createBabysitterProcessHost(context);
2219
2323
  } };
2220
2324
  function plainSecret(value) {
@@ -2227,9 +2331,9 @@ const babysitterIntake = channelAdapter("babysitter-github", {
2227
2331
  webhooks: [{
2228
2332
  id: "github",
2229
2333
  provider: "github",
2230
- signature: "github-sha256",
2334
+ signature: "github",
2231
2335
  secretHeader: "x-hub-signature-256",
2232
- secretToken: async (context) => {
2336
+ secret: async (context) => {
2233
2337
  const secret = plainSecret(await channelEnvValue("github", "webhookSecret", context));
2234
2338
  if (!secret) throw presetsErrorDiagnostics.PRESETS_BABYSITTER_ENV_MISSING({ variables: ["VITEHUB_GITHUB_WEBHOOK_SECRET"] });
2235
2339
  return secret;
@@ -2311,6 +2415,10 @@ function resolveBabysitterLifecycleFilter(configured, lifecycle) {
2311
2415
  option: "lifecycle",
2312
2416
  expected: "an object"
2313
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
+ });
2314
2422
  const labels = lifecycle?.labels;
2315
2423
  if (labels === void 0) return filter.labels ? filter : {
2316
2424
  ...filter,
@@ -2484,4 +2592,4 @@ const babysitter = defineAgent({
2484
2592
  }
2485
2593
  });
2486
2594
  //#endregion
2487
- export { actionLocation as A, normalizeGitHubMentionAllowlist as C, invariantError as D, invariant as E, isBabysitterCheckRun as F, createBabysitterPassResultSchema as I, hydrateFailedCiEvidence as M, newestCheckRun as N, hasGitHubLogin as O, createBabysitterCheckRuns as P, isReviewThreadOutcome as S, reviewerLabeledSevere as T, matchesMergeReviewEvidence as _, isBabysitterPlacementCapacityError as a, snapshotCheckEvidence as b, workspaceDecision as c, resolveBabysitterAdmissionLimits as d, directMergeReadiness as f, liveMergeReadiness as g, isAutomatedFeedback as h, BabysitterPlacementCapacityError as i, failed as j, matchesBabysitterPullRequestFilter as k, babysitterModelAdmission as l, hasHumanComment as m, babysitterPassResultSchema as n, createPullRequestWorkspaces as o, feedbackFingerprints as p, resolveBabysitterLifecycleFilter as r, providerSessionDecision as s, babysitter as t, createBabysitterAdmission as u, mergeReviewEvidenceKey as v, reviewThreadOutcomes as w, createGitHubPullRequestOperations as x, resolveBabysitterMerge 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 };