Public: anyone can read this; the crew can change it.

Split src/crew/autonomy.ts into modules of one concept each, same behaviour #16820

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/16788-split-src-crew-autonomy-ts-into-modules → main 0 commits fork

  • Merged. torque/16788-split-src-crew-autonomy-ts-into-modules was merged into main as 3c14bf9.

Review

Sign in to review this change.
178 files changed +2978 −2747
docs/PLANNING.md +1 −1
@@ -601,7 +601,7 @@ Where it decides today:
601601 sentence is told in the studio and when a repository on its own picks
602602 from the map. An issue already assigned to a builder keeps its builder;
603603 the decider is not asked.
604 - **Which issue next** (`crew/autonomy.ts`, `nextOf`): when a repository
604 - **Which issue next** (`crew/next_pick.ts`, `nextOf`): when a repository
605605 on its own has more than one ready issue, the decider chooses among the
606606 first six with the direction in hand. The rule takes the top of the ready
607607 list, the critical path.
docs/STUDIO.md +1 −1
@@ -193,7 +193,7 @@ own. The words are the studio's; the mechanics are `docs/FOLLOWING.md`.
193193 **The box** is the front door. A sentence becomes an issue — the first line
194194 its title, the rest its body — and the routing decision hands it to a
195195 builder: the builder with the least in flight, then by name. That is one
196 fixed-choice function (`crew/autonomy.ts`, `pickBuilder`), the place a
196 fixed-choice function (`crew/route.ts`, `pickBuilder`), the place a
197197 faster or wiser decider plugs in. The run starts on the crew's next tick,
198198 and the page shows it waiting, then working.
199199
docs/features/batch-doctor.md +1 −1
@@ -4,7 +4,7 @@ row: Batch doctor
44 ---
55 # Batch doctor (#7555)
66
7 When the merge queue's re-gate hands a pull back red (the re-gate carries it alone, so a red on top of other pulls is the queue's own search, #4999), `src/checks/doctor.ts` classes the red (`doctor_classify.ts`) and acts, in `crew/autonomy.ts`'s `handBack`:
7 When the merge queue's re-gate hands a pull back red (the re-gate carries it alone, so a red on top of other pulls is the queue's own search, #4999), `src/checks/doctor.ts` classes the red (`doctor_classify.ts`) and acts, in `actions/give_back.ts`'s `handBack`:
88
99 - **functional, alone on its merge**: the pull is held "until green" (out of the line), commented with the test, file, error line and `bun test ./file` to reproduce, and assigned back to its builder. A new head that passes its own check lifts the hold (`releaseOnGreen`). A red is held only when it reproduces on the queue's re-gate (the same head and base red again), so a flaky red still lands (#3155). A hold already on the pull (a person's) is kept, never overwritten.
1010 - **budget / infra**: recorded as `recheck`, not held. the queue re-gates a red pull alone later (#3155).
docs/features/chapters.md +1 −1
@@ -49,7 +49,7 @@ The chapter line on `/next`, the open chapter's page, the terminal's Queue scree
4949
5050 ## The crew follows the order (#15762)
5151
52 While a chapter is open, the crew starts its ready issues in the order the owner set on the chapter's list (ties by issue number), ahead of every other ready issue; those keep their own Next up order after them (`inSlotOrder` in `src/crew/autonomy.ts`, reading `openOrder` in `src/core/chapters.ts`). Move an item **Up** and it is the next one a builder takes.
52 While a chapter is open, the crew starts its ready issues in the order the owner set on the chapter's list (ties by issue number), ahead of every other ready issue; those keep their own Next up order after them (`inSlotOrder` in `src/crew/autonomy_pace.ts`, reading `openOrder` in `src/core/chapters.ts`). Move an item **Up** and it is the next one a builder takes.
5353
5454 The position shows only where an issue really waits. When the free builder slots (the slots set in the repository's settings, less the builder runs in flight) run out before a startable chapter item, `/next` (and the API, the MCP `next_up` tool and the terminal's Next up screen, which share `notStartable` in `src/crew/not_startable.ts`) gives that row `position 3 in v1, after #12`: its place in the list, and the first chapter item that will start. A held item is skipped over, so `#12` is always one that can start. With a slot free for each, no row carries the words: they all start on the same tick.
5555
docs/features/week-pace.md +1 −1
@@ -15,7 +15,7 @@ The settings are the plain values in `WEEK` (`src/crew/week.ts`); the decision i
1515
1616 ## Bets (#8713)
1717
18 Bets are not in the forge yet, so the release above falls back to the lowest-numbered gate-held issue. When bets land, "behind" releases the next scope of a backed bet, or offers the next bet to back, in place of that fallback; the change is the one candidate read in `releaseForPace` (`src/crew/autonomy.ts`). Appetites then sit inside the week's capacity the decision already works out (`capUsd` less the reserve), so no bet's share can exceed it.
18 Bets are not in the forge yet, so the release above falls back to the lowest-numbered gate-held issue. When bets land, "behind" releases the next scope of a backed bet, or offers the next bet to back, in place of that fallback; the change is the one candidate read in `releaseForPace` (`src/crew/autonomy_pace.ts`). Appetites then sit inside the week's capacity the decision already works out (`capUsd` less the reserve), so no bet's share can exceed it.
1919
2020 **What the week bought (#14250).** The efficiency sentence on Home and the terminal's dashboard also says what share of the week's agent spend is on work that has not landed (a run on a pull closed without merging, or on a closed issue no merged pull closes; work still open, work merged before the week, and runs with no issue are not counted as lost, though they stay in the spend), and, at the rate so far, what the allowance left should buy: landings per point of the week used times the points left up to the weekly budget. This is ask 3 only; it comes first because the owner's choice to hold or spend the reserve needs the figure before the pipeline work (asks 1, 2 and 4) changes what it measures, and the issue is narrowed to it. Left out: the split of large issues, the stop after a red pull's third run (a red is handed back only when the same failure repeats, `sameRedTwice`), and checks while the allowance is gone.
2121
src/actions/box_pass.ts +1 −1
@@ -196,7 +196,7 @@ export function tickDelivery(app: App, repo: Repo, pull: Pull, issue: Issue, by:
196196 /**
197197 * The already-done note on an issue a landing leaves open, naming the merge
198198 * commit. Written as the person the crew acts for, as the crew's own
199 * already-done note is (`crew/autonomy.ts`); as the lander when the crew is off.
199 * already-done note is (`crew/settle_run.ts`); as the lander when the crew is off.
200200 */
201201 export function noteLandedDone(app: App, repo: Repo, issue: Issue, lander: User, mergeOid: string): void {
202202 if (!/^[0-9a-f]{40}$/.test(mergeOid)) return;
src/actions/crew_now.ts +1 −1
@@ -12,7 +12,7 @@ import { ownerFactRepoIds, readsByStanding } from "../core/repos.ts";
1212 import { roleOf } from "../core/roles.ts";
1313 import { reviewSays } from "../crew/review_says.ts";
1414 import { reviewerPaused } from "../crew/reviewer_paused.ts";
15 import { plannerDeclines } from "../crew/autonomy.ts";
15 import { plannerDeclines } from "../crew/planner_decline.ts";
1616 import { listActiveRuns } from "../core/runs.ts";
1717 import { getUsersByIds } from "../core/users.ts";
1818 import { appsOf } from "../web/studio/asks.ts";
src/actions/owner_waits.ts +1 −1
@@ -9,7 +9,7 @@
99 import { getIssuesByIds, type Issue } from "../core/issues.ts";
1010 import { joinMany } from "../core/pulls.ts";
1111 import type { Repo } from "../core/repos.ts";
12 import { plannerDeclines } from "../crew/autonomy.ts";
12 import { plannerDeclines } from "../crew/planner_decline.ts";
1313 import { reviewerPaused } from "../crew/reviewer_paused.ts";
1414 import { reviewersOf, waitsForPerson } from "../crew/review.ts";
1515 import type { Database } from "bun:sqlite";
src/actions/proposals.ts +1 −1
@@ -15,7 +15,7 @@ import { CREW_OFF_LINE, crewBuildsHere } from "../core/crew_switch.ts";
1515 import { getProposal, moveProposal, type Proposal, type ProposalState } from "../core/proposals.ts";
1616 import { ARCHIVED_WHY, getRepoById, ownerFactRepoIds, canRead, type Repo } from "../core/repos.ts";
1717 import type { User } from "../core/users.ts";
18 import { ensureDirectionIssue } from "../crew/autonomy.ts";
18 import { ensureDirectionIssue } from "../crew/direction_issue.ts";
1919 import { queueAgentRun } from "../crew/dispatch.ts";
2020 import { err, ok, type Result } from "../kernel/result.ts";
2121 import { MAX_BODY } from "../core/issues.ts";
src/checks/event_handler.ts +1 −1
@@ -135,7 +135,7 @@ export async function onEvent(lane: LaneState, event: ForgeEvent): Promise<void>
135135 const env = `pull-${pull.number}`;
136136 const dir = await pullDir(app.db, app.reposRoot, repo, pull);
137137 const tip = await resolveOid(dir, `refs/heads/${pull.baseBranch}`);
138 // The merge queue gates only an autonomous repository's lands (`crew/autonomy.ts` admit).
138 // The merge queue gates only an autonomous repository's lands (`crew/land_admit.ts` `admit`).
139139 const landGated = repo.autonomy === "autonomous" && repo.autonomyBy !== null;
140140 if (!checkOnApproval(checksForHead(app.db, pull.id, head), env, tip, landGated))
141141 return;
src/core/app-crew.ts +1 −1
@@ -5,7 +5,7 @@
55 */
66
77 import type { Database } from "bun:sqlite";
8 import { DIRECTION_PREFIX } from "../crew/autonomy.ts";
8 import { DIRECTION_PREFIX } from "../crew/direction_issue.ts";
99 import { getIssueById } from "./issues.ts";
1010 import type { Repo } from "./repos.ts";
1111 import { getUserById } from "./users.ts";
src/core/migrations/20261113220000-run-latest-and-review-indexes.ts +1 −1
@@ -1,4 +1,4 @@
1 // An issue's newest agent run (the stalled and declined holds, `crew/held.ts`, `crew/autonomy.ts`
1 // An issue's newest agent run (the stalled and declined holds, `crew/held.ts`, `crew/plan_owed.ts`
22 // declineOf) read and sorted every agent run on it, up to 880 on the direction issues; the review
33 // history (`crew/review.ts` reviewAttemptsFor) read every run of each open pull. Each index holds
44 // what its query reads in the order it reads it: 2.2 ms to 0.0 ms, 2.2 to 0.9, 1.4 to 0.3 on a
src/crew/approved_week.ts +1 −1
@@ -35,7 +35,7 @@ import type { User } from "../core/users.ts";
3535 import { engineActor } from "../core/engine.ts";
3636 import { mergeable, resolveOid } from "../git/merge.ts";
3737 import { createLog } from "../kernel/log.ts";
38 import { landIfGreen } from "./autonomy.ts";
38 import { landIfGreen } from "./land_queue.ts";
3939 import { readConflictRoom } from "./conflict_room.ts";
4040 import { CHECK_FAILED_LIMIT, queueAgentRun } from "./dispatch.ts";
4141 import { ownBuilder } from "./finishing.ts";
src/crew/autonomy.ts deleted −2543

Diff not shown — 100,316 bytes of diff (limit 100,000). −2543

View file
src/crew/autonomy_pace.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * How many builders may start now: the paced slots, the free ones, the order they are picked in.
3 */
4
5 import type { App } from "../app.ts";
6 import { listCrewRoles } from "../core/agents.ts";
7 import { openOrder } from "../core/chapters.ts";
8 import type { Ranked } from "../core/dependencies.ts";
9 import { fromAppIssues } from "../core/from_app.ts";
10 import { pickOrder } from "../core/next_up.ts";
11 import { ranksInRepo } from "../core/rank.ts";
12 import type { Repo } from "../core/repos.ts";
13 import { standing } from "../core/standing.ts";
14 import { grantedAccounts } from "../core/subscriptions.ts";
15 import { meanRunUsd } from "./autonomy_spend.ts";
16 import { activeRuns, autonomyStatus, slottedRuns } from "./autonomy_status.ts";
17 import { governorFor } from "./governed.ts";
18 import { pace, type Pace } from "./pacing.ts";
19 import { pickFilter } from "./pick_filter.ts";
20 import { crewWeekFor } from "./week_read.ts";
21
22 /**
23 * The issues each repository picked in this tick, by repository id: their runs may not show yet.
24 */
25 export type TickPicks = ReadonlyMap<string, ReadonlySet<string>>;
26
27 /**
28 * The crew's pace here: the operator's slots, held to what the windows have left. Only a new
29 * pick (`crew`) is also held to the governor's: it brakes on pulls opening faster than they
30 * land, and what lands them (an approved pull brought up to date, a reviewer's request
31 * answered, a red reworked) keeps every slot the operator set. Braked alike, 5 → 1 with one
32 * build running left a changes-requested pull waiting for a slot for hours (2026-11-13).
33 */
34 export function repoPace(app: App, repo: Repo, now = new Date(), crew = true, picked: TickPicks = new Map()): Pace {
35 const accounts = grantedAccounts(app.db, repo.id, repo.ownerId).flatMap(
36 (a) => {
37 const s = standing(app.db, a.id, now);
38 return s === undefined ? [] : [{ name: a.name, standing: s }];
39 },
40 );
41 const paced = pace(accounts, repo.autonomySlots, meanRunUsd(app.db, repo.id), now);
42 // Finishing and rework run ahead of new picks: only a new pick waits on the governor, the
43 // crew's week.
44 if (!crew) return paced;
45 const governed = governorFor(app, repo, now).slots;
46 const limited = governed < paced.slots ? { ...paced, slots: governed } : paced;
47 // The week's ceiling is one budget for the whole crew on these accounts (#8989).
48 const week = crewWeekFor(app, repo, now);
49 return week !== null && week.slots === 0 ? { ...limited, slots: 0, reason: week.sentence } : limited;
50 }
51
52 /**
53 * Why the crew's pace allows no run here now, in a sentence ("espo-corp's 5-hour window is full
54 * until …", the week's sentence), or undefined while one may start: the words beside a tick that
55 * did `waiting`, the idle reason and the flow's why. `crew` as `repoPace`'s: a new pick or not.
56 */
57 export function paceHold(app: App, repo: Repo, now = new Date(), crew = true): string | undefined {
58 const paced = repoPace(app, repo, now, crew);
59 return paced.slots > 0 ? undefined : paced.reason || "no run may start at the crew's pace";
60 }
61
62 /** The builder slots free now: none while paused, else the paced slots less what is slotted. */
63 export function freeSlots(app: App, repo: Repo, now: Date): number {
64 if (autonomyStatus(app, repo, now).paused !== null) return 0;
65 const slotted = slottedRuns(activeRuns(app, repo.id), listCrewRoles(app.db, repo.id));
66 return Math.max(0, repoPace(app, repo, now, false).slots - slotted.length);
67 }
68
69 /** The pickable issues in slot order: the order Next up shows. */
70 export function inSlotOrder(app: App, repo: Repo, ready: readonly Ranked[], now: Date = new Date()): Ranked[] {
71 const ranked = ranksInRepo(app.db, repo.id).places;
72 const { allowed } = pickFilter(app, repo, ready, now);
73 // The order is the one Next up shows (#8826): ranked by place, then the ready order.
74 const order = pickOrder(allowed, ranked, (r) => r.issue.id, [], fromAppIssues(app.db, allowed.map((r) => r.issue.id)));
75 // An open chapter (#15762): its issues come first, by the position the owner set, ties by number;
76 // every other issue keeps the order above, untouched.
77 const open = openOrder(app.db, repo.id);
78 if (open === undefined) return order;
79 const place = (r: Ranked): number | undefined => open.places.get(r.issue.id);
80 const inChapter = order
81 .filter((r) => place(r) !== undefined)
82 .sort((a, b) => place(a)! - place(b)! || a.issue.number - b.issue.number);
83 return [...inChapter, ...order.filter((r) => place(r) === undefined)];
84 }
src/crew/autonomy_spend.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * What the crew has spent today, per repository and everywhere, and whether the week's share is
3 * spent.
4 */
5
6 import type { App } from "../app.ts";
7 import type { Repo } from "../core/repos.ts";
8 import { weekSpent } from "./week_read.ts";
9 import type { Database } from "bun:sqlite";
10
11 export function startOfTodayUtc(now: Date): Date {
12 const day = new Date(now);
13 day.setUTCHours(0, 0, 0, 0);
14 return day;
15 }
16
17 /** Agent spend on this repository since UTC midnight. */
18 export function spentToday(
19 db: App["db"],
20 repoId: string,
21 now = new Date(),
22 ): number {
23 const since = startOfTodayUtc(now).toISOString();
24 return (
25 db
26 .query<{ spent: number | null }, [string, string]>(
27 `SELECT SUM(cost_usd) AS spent FROM run
28 WHERE repo_id = ?1 AND kind = 'agent' AND created_at >= ?2`,
29 )
30 .get(repoId, since)?.spent ?? 0
31 );
32 }
33
34 /** What the crew spent today across every repository, in dollars. */
35 export function spentTodayEverywhere(db: Database, now = new Date()): number {
36 const since = startOfTodayUtc(now).toISOString();
37 return (
38 db
39 .query<{ spent: number | null }, [string]>(
40 `SELECT SUM(cost_usd) AS spent FROM run INDEXED BY run_agent_cost
41 WHERE kind = 'agent' AND created_at >= ?1`,
42 )
43 .get(since)?.spent ?? 0
44 );
45 }
46
47 /**
48 * Agent spend since UTC midnight for many repositories at once, keyed by
49 * repo id — one query, for a count that must not slow down as the apps
50 * grow (the topbar's ask count is the reason this exists).
51 */
52 export function spentTodayForRepos(
53 db: App["db"],
54 repoIds: readonly string[],
55 now = new Date(),
56 ): Map<string, number> {
57 const out = new Map<string, number>();
58 const unique = [...new Set(repoIds)];
59 if (unique.length === 0) return out;
60 const since = startOfTodayUtc(now).toISOString();
61 const CHUNK = 400;
62 for (let i = 0; i < unique.length; i += CHUNK) {
63 const batch = unique.slice(i, i + CHUNK);
64 const rows = db
65 .query<
66 { repo_id: string; spent: number | null },
67 string[]
68 >(
69 `SELECT repo_id, SUM(cost_usd) AS spent FROM run
70 WHERE kind = 'agent' AND created_at >= ?${batch.length + 1}
71 AND repo_id IN (${batch.map((_, n) => `?${n + 1}`).join(",")})
72 GROUP BY repo_id`,
73 )
74 .all(...batch, since);
75 for (const row of rows) out.set(row.repo_id, row.spent ?? 0);
76 }
77 return out;
78 }
79
80 /**
81 * Whether a repository is paused because the week's share is spent right
82 * now — the same conditions `autonomyStatus`'s own `"week"` reads for one,
83 * asked of crew already read for the whole set (`crewForRepos`). The ask
84 * card (`studio/asks.ts`) and the studio home's cost line
85 * (`studio/home.ts`) both decide from this, so neither can disagree with
86 * the other about which app is paused.
87 */
88 export function isPausedForWeek(
89 app: Pick<App, "db">,
90 repo: Repo,
91 crew: ReadonlyMap<string, readonly string[]>,
92 now: Date = new Date(),
93 ): boolean {
94 if (repo.autonomy === "off" || repo.autonomyBy === null) return false;
95 if ((crew.get(repo.id)?.length ?? 0) === 0) return false;
96 return weekSpent(app, repo, now);
97 }
98
99 /** What a run costs here on average lately; a dollar before there is a history. */
100 export function meanRunUsd(db: App["db"], repoId: string): number {
101 return (
102 db
103 .query<{ m: number | null }, [string]>(
104 `SELECT AVG(cost_usd) AS m FROM (
105 SELECT cost_usd FROM run WHERE repo_id = ?1 AND kind = 'agent'
106 AND state IN ('ok','failed') AND cost_usd > 0
107 ORDER BY created_at DESC LIMIT 20)`,
108 )
109 .get(repoId)?.m ?? 1
110 );
111 }
src/crew/autonomy_status.ts added +133
@@ -0,0 +1,133 @@
1 /** A repository's autonomy at a glance: paused or not, the slots, the runs that spend one. */
2
3 import type { App } from "../app.ts";
4 import { type Agent, type CrewRole, listCrewRoles } from "../core/agents.ts";
5 import type { Repo } from "../core/repos.ts";
6 import { listActive, type Run } from "../core/runs.ts";
7 import { ceilingReached, forgeCeiling } from "../flow/ceiling.ts";
8 import { spentToday, spentTodayEverywhere, startOfTodayUtc } from "./autonomy_spend.ts";
9 import { crewWeekFor } from "./week_read.ts";
10
11 export type Paused = "week" | "forge ceiling" | "nobody" | "no crew";
12
13 export interface AutonomyStatus {
14 readonly autonomy: Repo["autonomy"];
15 readonly spentTodayUsd: number;
16 /**
17 * The week's budget as a share of the week and the pace it is spending at,
18 * as the provider's meter reads it; null while the week is unmeasured.
19 * There is no daily dollar ceiling beside it.
20 */
21 readonly week: {
22 readonly usedPct: number;
23 readonly mayUsePct: number;
24 readonly elapsedPct: number;
25 readonly pace: "ahead" | "on" | "behind";
26 readonly resetsAt: string;
27 } | null;
28 readonly slots: number;
29 /**
30 * Agent runs in flight here that spend a slot — what `slottedRuns` counts,
31 * which is what the loop gates on. Not every run in flight: see there.
32 */
33 readonly active: number;
34 readonly paused: Paused | null;
35 /**
36 * When a pause lifts: the week's reset for a spent week, the next UTC midnight for the
37 * forge's cap.
38 */
39 readonly resumesAt: string | null;
40 }
41
42 export function activeRuns(app: App, repoId: string) {
43 return listActive(app.db, "agent").filter((r) => r.repoId === repoId);
44 }
45
46 /**
47 * Of the agent runs in flight here, the ones that spend a slot. Slots are
48 * the builders' work-in-progress limit, so two kinds of run take none: a
49 * review, which is the reviewer's short pass over a pull and must never
50 * keep a builder from picking up the next issue, and any run by a planner
51 * or a reviewer, whose work refills the map rather than works it.
52 *
53 * The rule lives here only: `driveRepo` gates on this set and
54 * `autonomyStatus` counts it, so the number a page shows is the number the
55 * loop enforces. The runs it leaves out are still in flight and still shown
56 * — Now on the studio page lists every one of them.
57 */
58 export function slottedRuns(
59 active: readonly Run[],
60 crew: readonly { readonly agent: Agent; readonly role: CrewRole }[],
61 ): Run[] {
62 const notBuilders = new Set(
63 crew.filter((c) => c.role !== "builder").map((c) => c.agent.user.id),
64 );
65 return active.filter(
66 (r) =>
67 r.reason !== "review" &&
68 (r.actorId === null || !notBuilders.has(r.actorId)),
69 );
70 }
71
72 /**
73 * The builders with nothing in flight here. One agent runs one thing at a
74 * time, so `active` on the tick line climbs to at most
75 * min(slots, startable, idle builders + active) (#7006).
76 */
77 export function idleBuilders(
78 active: readonly Run[],
79 crew: readonly { readonly agent: Agent; readonly role: CrewRole }[],
80 ): number {
81 const busy = new Set(active.map((r) => r.actorId));
82 return crew.filter((c) => c.role === "builder" && !busy.has(c.agent.user.id)).length;
83 }
84
85 export function autonomyStatus(
86 app: App,
87 repo: Repo,
88 now = new Date(),
89 ): AutonomyStatus {
90 const spent = spentToday(app.db, repo.id, now);
91 const crew = listCrewRoles(app.db, repo.id);
92 const forgeCap = forgeCeiling(app.config);
93 const decision = crewWeekFor(app, repo, now);
94 const paused: Paused | null =
95 repo.autonomy === "off"
96 ? null
97 : repo.autonomyBy === null
98 ? "nobody"
99 : crew.length === 0
100 ? "no crew"
101 : decision !== null && decision.slots === 0
102 ? "week"
103 : ceilingReached(spentTodayEverywhere(app.db, now), forgeCap)
104 ? "forge ceiling"
105 : null;
106 const tomorrow = startOfTodayUtc(now);
107 tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
108 return {
109 autonomy: repo.autonomy,
110 spentTodayUsd: spent,
111 week:
112 decision === null
113 ? null
114 : { usedPct: decision.usedPct, mayUsePct: decision.mayUsePct, elapsedPct: decision.elapsedPct, pace: decision.pace, resetsAt: decision.resetsAt },
115 slots: repo.autonomySlots,
116 active: slottedRuns(activeRuns(app, repo.id), crew).length,
117 paused,
118 resumesAt:
119 paused === "week" && decision !== null
120 ? decision.resetsAt
121 : paused === "forge ceiling"
122 ? tomorrow.toISOString()
123 : null,
124 };
125 }
126
127 export function roleOf(app: App, repo: Repo, agent: Agent): CrewRole {
128 return (
129 listCrewRoles(app.db, repo.id).find(
130 (c) => c.agent.user.id === agent.user.id,
131 )?.role ?? "builder"
132 );
133 }
src/crew/autonomy_tick.ts added +287
@@ -0,0 +1,287 @@
1 /** The loop's tick: every repository that runs on its own, one turn each, and the line it logs. */
2
3 import type { App } from "../app.ts";
4 import { measureWhenFull, recheckWhenFull } from "../checks/full_window_recheck.ts";
5 import { batchWords, queueClashes, queueWords } from "../checks/queue.ts";
6 import { listCrewRoles } from "../core/agents.ts";
7 import { betsInUse } from "../core/bets.ts";
8 import { queueBatch } from "../core/capacity.ts";
9 import { readyNow, repoGraph } from "../core/dependencies.ts";
10 import { getRepoById, listAutonomousRepos, type Repo } from "../core/repos.ts";
11 import { sharedVitals, vitalsMisses, vitalsWords } from "../flow/vitals.ts";
12 import { bootCounts } from "../kernel/boots.ts";
13 import { breathe } from "../kernel/breathe.ts";
14 import { createLog } from "../kernel/log.ts";
15 import { sweepApprovedWeek } from "./approved_week.ts";
16 import { freeSlots, paceHold } from "./autonomy_pace.ts";
17 import { activeRuns, autonomyStatus, idleBuilders } from "./autonomy_status.ts";
18 import { forgetBacklog, noteBacklog, waitingBy, waitingWords } from "./backlog.ts";
19 import { driveOrBeat } from "./beat.ts";
20 import { readConflictLane } from "./conflict_room.ts";
21 import { sweepConflicts } from "./conflict_sweep.ts";
22 import { driveRepo } from "./drive.ts";
23 import { finishApproved, finishFields } from "./finishing.ts";
24 import { warnExpiring } from "./fold_in.ts";
25 import { announceGovernor } from "./governed.ts";
26 import { pruneLine, startSweep, sweepGreen } from "./green_sweep.ts";
27 import { heldBy, heldWords } from "./held.ts";
28 import { hotFiles, hotWords } from "./hot_files.ts";
29 import { liveTriage, none as noTriage, tickFields } from "./livetriage.ts";
30 import { passedWords, pickFilter } from "./pick_filter.ts";
31 import { crewOffInPreview } from "./preview.ts";
32 import { recheckRedApproved } from "./red_approved.ts";
33 import { sweepRepeats } from "./repeat_checks.ts";
34 import { moveRequested, tallyRequested, tallyWords } from "./requested.ts";
35 import { reserveOf, reserveWords } from "./reserve.ts";
36 import { sweepReviews } from "./review.ts";
37 import { sentinelTick } from "./sentinel.ts";
38 import { closedToday } from "./stale_pulls.ts";
39 import { sweepStaleReds } from "./stale_reds.ts";
40 import { sweepStranded } from "./stranded.ts";
41 import { triageTick } from "./triage.ts";
42 import { unstickNow } from "./unstick.ts";
43 import { lastWaits, waitWords } from "./waits.ts";
44
45 const log = createLog("autonomy");
46
47 export const AUTONOMY_TICK_MS = 60_000;
48
49 /**
50 * Repositories with a backed bet go first, so a short week budget (#8989) is
51 * spent on what the owner backed before the rest; the order is otherwise kept.
52 */
53 export function byBackedBets(db: App["db"], repos: Repo[]): Repo[] {
54 const backed = (r: Repo): number => (betsInUse(db, r.id) ? 0 : 1);
55 return [...repos].sort((a, b) => backed(a) - backed(b));
56 }
57
58 /** Every repository that runs on its own, one turn each. */
59 export async function autonomyTick(
60 app: App,
61 now = new Date(),
62 sweep: (app: App, repo: Repo) => Promise<number> = sweepGreen,
63 ): Promise<void> {
64 if (crewOffInPreview()) return;
65 // A pull a person holds with changes requested goes back to its builder after a day of silence,
66 // in any repository.
67 try {
68 sweepStranded(app, now);
69 } catch (error) {
70 log.error("stranded sweep failed", { error: String(error) });
71 }
72 // An approved pull that has waited a week is landed, rebased or closed (#12491),
73 // in any repository.
74 try {
75 await sweepApprovedWeek(app, now);
76 } catch (error) {
77 log.error("approved-week sweep failed", { error: String(error) });
78 }
79 // Three days before a trusted source lapses, a note (#8937).
80 try {
81 warnExpiring(app, now);
82 } catch (error) {
83 log.error("trust note failed", { error: String(error) });
84 }
85 const picked = new Map<string, Set<string>>();
86 for (const repo of byBackedBets(app.db, listAutonomousRepos(app.db))) {
87 // An archived repository is put away: the crew starts nothing in it.
88 if (repo.archivedAt !== null) {
89 forgetBacklog(app, repo.id);
90 continue;
91 }
92 try {
93 // A hold, a close, a push or a lost approval leaves the line before
94 // the next batch is formed, not at its gate (#6611).
95 pruneLine(app, repo);
96 void startSweep(app, repo, sweep);
97 // Each pass below is one slice of the thread: a request waiting is served between them
98 // (#8848).
99 await breathe();
100 // First of all: a slot freed goes to an approved pull that no longer
101 // merges, before a changes-requested one or a new issue (#3682).
102 const finishing = await finishApproved(app, repo, freeSlots(app, repo, now));
103 await breathe();
104 // An approved pull red for a day gets one re-check, then goes back (#6349).
105 await recheckRedApproved(app, repo, now).catch((error) =>
106 log.error("red approved re-check failed", {
107 repo: `${repo.ownerName}/${repo.name}`,
108 error: String(error),
109 }),
110 );
111 await breathe();
112 // Quick, and before the picks: a pull main moved under is brought up
113 // to date within this tick, not after a landing gate (#2039).
114 await sweepConflicts(app, repo).catch((error) =>
115 log.error("conflict sweep failed", {
116 repo: `${repo.ownerName}/${repo.name}`,
117 error: String(error),
118 }),
119 );
120 const current = getRepoById(app.db, repo.id) ?? repo;
121 await breathe();
122 // A red pull nobody is working is checked again, reworked, parked or closed (#8245).
123 await sweepStaleReds(app, current, now, freeSlots(app, current, now)).catch((error) => {
124 log.error("stale red sweep failed", {
125 repo: `${repo.ownerName}/${repo.name}`,
126 error: String(error),
127 });
128 });
129 // With the week's window full, stale reds are still checked again: no model runs (#15821).
130 await recheckWhenFull(app, current, now).catch((error) => {
131 log.error("stale red recheck failed", {
132 repo: `${repo.ownerName}/${repo.name}`,
133 error: String(error),
134 });
135 });
136 // And once a day the full suite on main's head, so the idle week still measures (#15911).
137 await measureWhenFull(app, current, now).catch((error) => {
138 log.error("full-window measurement failed", {
139 repo: `${repo.ownerName}/${repo.name}`,
140 error: String(error),
141 });
142 });
143 // What reviewers keep asking for becomes an issue to automate it (#8716).
144 try {
145 await sweepRepeats(app, current, now);
146 } catch (error) {
147 log.error("repeat check sweep failed", { repo: `${repo.ownerName}/${repo.name}`, error: String(error) });
148 }
149 await breathe();
150 // Before the picks: a pull a reviewer answered is finished before new
151 // work takes the slots it needs (#2172).
152 const requested = await moveRequested(app, current, freeSlots(app, current, now), now);
153 await breathe();
154 const unstuck = unstickNow(app, current, now);
155 const did = await driveOrBeat(app, current, now, picked, driveRepo);
156 await breathe();
157 // Rules only, no run: an issue noted already done on the base closes.
158 const triaged = await liveTriage(app, current, now).catch((error) => {
159 log.error("live triage failed", {
160 repo: `${repo.ownerName}/${repo.name}`,
161 error: String(error),
162 });
163 return noTriage();
164 });
165 await breathe();
166 // Every tick says what it did and why, so an app that sits still is
167 // never a mystery: the numbers behind "idle" are on the line.
168 const status = autonomyStatus(app, current, now);
169 await breathe();
170 const approved = waitWords(lastWaits(current.id));
171 const graphNow = repoGraph(app.db, current.id, { sealed: true });
172 const ready = readyNow(graphNow);
173 const crewNow = listCrewRoles(app.db, current.id);
174 const activeNow = activeRuns(app, current.id);
175 await breathe();
176 const held = heldBy(app, current, ready, crewNow, activeNow);
177 // Every open issue is accounted for: the ready ones below, the rest per reason. A crew that
178 // stands still beside them is kept for the needs stack (`actions/needs.ts`).
179 const waiting = waitingBy(graphNow, ready);
180 const openNow = graphNow.issues.filter((i) => i.state === "open").length;
181 noteBacklog(app, current.id, {
182 open: openNow,
183 startable: held.startable.length,
184 waiting,
185 still: did === "idle" && !activeNow.some((r) => r.issueId === current.directionIssueId),
186 at: now.getTime(),
187 });
188 const boots = bootCounts(app.config.dataDir);
189 await breathe();
190 await breathe();
191 const staleToday = closedToday(app, current.id, now);
192 // Says when the governor lowers the slots (#6375); one feed item per change.
193 const governor = announceGovernor(app, current, now);
194 const paceWhy = did === "waiting" ? paceHold(app, current, now) : undefined;
195 log.info("tick", {
196 repo: `${repo.ownerName}/${repo.name}`,
197 did,
198 ...tickFields(triaged),
199 // The open issues, and why the ones that are not ready wait: `later=245 plan=17 blocked=6`.
200 open: openNow,
201 waiting: waitingWords(waiting),
202 ready: ready.length,
203 // What the builders could start after the filters (#2143), and
204 // what holds the rest, per filter (#2244).
205 startable: held.startable.length,
206 // The standing reserve the planner keeps: startable/target (#3237).
207 reserve: reserveWords(reserveOf(held.startable.length, status.slots)),
208 held: heldWords(held),
209 // What the picker passes over among the startable, so no ready issue goes unexplained
210 // (#8924).
211 passed: passedWords(pickFilter(app, current, held.startable, now).passed),
212 // The files 5 or more open pulls touch, which no new build starts on (#5934).
213 ...(held.by.hot_file.length === 0 ? {} : { hot: hotWords(hotFiles(current.id)) }),
214 // Stalled issues this tick parked and freed for another builder (#4073).
215 unstuck,
216 // Crew pulls closed today after 3 days in conflict (#5940).
217 ...(staleToday === 0 ? {} : { staleClosed: staleToday }),
218 // Open pulls, opened/landed per hour and per 6 h, conflicted (#5935).
219 ...flowVitals(app.db, now, app.config.dataDir),
220 active: status.active,
221 slots: status.slots,
222 // Builders with nothing in flight: what bounds active beside slots and startable (#7006).
223 idle: idleBuilders(activeNow, crewNow),
224 ...(governor === undefined ? {} : { governor }),
225 // Approved conflicted pulls: queued, in flight, and why each other is
226 // skipped (#3682, #6237), or "0 candidates of N open" (#6263); and the lane for rebases:
227 // conflicted N, rebasing M, room R (#6140).
228 ...finishFields(finishing.moves, readConflictLane(app.db), finishing.open),
229 ...(requested.length === 0
230 ? {}
231 : {
232 requested: tallyWords(tallyRequested(requested)),
233 }),
234 // The approved pulls the last green sweep saw, and why each waits (#3055).
235 ...(approved === undefined ? {} : { approved }),
236 // What the merge queue is doing now, not what the sweep admitted (#3430).
237 queue: queueWords(current.id),
238 // The size of the next batch: `8`, or `4 of 16` after a red (#6674).
239 batch: batchWords(current.id, queueBatch(app.db)),
240 // Pulls the queue found red on top of others of their candidate (#4235).
241 clashes: queueClashes(current.id),
242 spent: status.spentTodayUsd.toFixed(2),
243 ...(status.week === null ? {} : { week: `${status.week.usedPct}/${status.week.mayUsePct}%` }),
244 ...(status.paused === null ? {} : { paused: status.paused }),
245 // Why the pace started nothing, when it did not (`paceHold`): the account and its reset.
246 ...(paceWhy === undefined ? {} : { pace: paceWhy }),
247 // Starts after the first, and how many followed a crash (#3708).
248 restarts: boots.restarts,
249 ...(boots.unclean === 0 ? {} : { unclean: boots.unclean }),
250 });
251 } catch (error) {
252 log.error("autonomy tick failed", {
253 repo: `${repo.ownerName}/${repo.name}`,
254 error: String(error),
255 });
256 }
257 }
258 await breathe();
259 // Every thought is placed within minutes (`crew/triage.ts`).
260 try {
261 await triageTick(app, now);
262 } catch (error) {
263 log.error("triage failed", { error: String(error) });
264 }
265 await breathe();
266 // The forge hunts its own faults on the same clock (`crew/sentinel.ts`).
267 try {
268 sentinelTick(app, now.getTime());
269 } catch (error) {
270 log.error("sentinel failed", { error: String(error) });
271 }
272 await breathe();
273 // Review is not autonomy's alone: an agent's green pull is read by the
274 // crew's reviewer in every repository that has one.
275 try {
276 await sweepReviews(app);
277 } catch (error) {
278 log.error("review sweep failed", { error: String(error) });
279 }
280 }
281
282 /** The tick line's flow vitals (#5935): the counts in words, and the targets they miss. */
283 export function flowVitals(db: App["db"], now: Date, dataDir?: string): { pulls: string; offTarget?: string } {
284 const v = sharedVitals(db, now, false, dataDir);
285 const misses = vitalsMisses(v);
286 return { pulls: vitalsWords(v), ...(misses.length === 0 ? {} : { offTarget: misses.join("; ") }) };
287 }
src/crew/beat.ts +1 −1
@@ -22,7 +22,7 @@ import { createLog } from "../kernel/log.ts";
2222
2323 const log = createLog("beat");
2424
25 /** What one turn of a repository's autonomy loop did (`autonomy.ts` `Drove`). */
25 /** What one turn of a repository's autonomy loop did (`drive.ts` `Drove`). */
2626 export type Drove = "off" | "paused" | "waiting" | "full" | "picked" | "planned" | "idle" | "stalled";
2727 export type Drive = (app: App, repo: Repo, now: Date, picked: Map<string, Set<string>>) => Promise<Drove>;
2828
src/crew/breaker.ts +1 −1
@@ -7,7 +7,7 @@
77
88 import type { Database } from "bun:sqlite";
99 import type { Repo } from "../core/repos.ts";
10 import { CAP_NOTE } from "./guard.ts";
10 import { CAP_NOTE } from "./cap_note.ts";
1111 import { directorsAmong } from "./direct.ts";
1212 import { REPEAT_NOTE } from "./repeat_note.ts";
1313
src/crew/cap_note.ts added +3
@@ -0,0 +1,3 @@
1 /** The note a capped issue is parked with: the map reads it as `parked`, the asks as a question. */
2 export const CAP_NOTE =
3 "Parked by the crew: this issue started its day's share of runs without landing, so nothing more starts here until a person says what to try.";
src/crew/conflict_release.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * Closing a pull main moved under (superseded or released) and queueing its bring-up-to-date run.
3 */
4
5 import { addComment, assignIssue, setIssueState } from "../actions/issues.ts";
6 import type { App } from "../app.ts";
7 import { CLOSED_NOTE, leftNote, reopenedByPerson, unticked } from "../core/done_on_main.ts";
8 import { getHold } from "../core/holds.ts";
9 import { getIssue, getIssueById } from "../core/issues.ts";
10 import { closesFromBody, type Pull } from "../core/pulls.ts";
11 import type { Repo } from "../core/repos.ts";
12 import { activeRunFor, automaticRunsSince } from "../core/runs.ts";
13 import { getUserById } from "../core/users.ts";
14 import { createLog } from "../kernel/log.ts";
15 import { agentFor, CHECK_FAILED_LIMIT, lastHumanWord, queueAgentRun } from "./dispatch.ts";
16
17 const log = createLog("autonomy");
18
19 /**
20 * Close a pull whose change is already on the base, naming the commits that
21 * carry it, and close the issues it said it closes as done (#2121). Not a
22 * park and no strike: nothing failed, the work landed another way.
23 */
24 export function closeSuperseded(
25 app: App,
26 repo: Repo,
27 pull: Pull,
28 oids: readonly string[],
29 ): boolean {
30 if (repo.autonomyBy === null) return false;
31 const by = getUserById(app.db, repo.autonomyBy);
32 const issue = getIssueById(app.db, pull.id);
33 if (!by || !issue || issue.state !== "open") return false;
34 const named = oids.map((o) => o.slice(0, 8)).join(" ");
35 addComment(
36 app,
37 by,
38 repo,
39 issue,
40 `Closed by the crew: superseded, its change is already on ${pull.baseBranch} in ${named}.`,
41 );
42 const closed = setIssueState(app, by, repo, issue, "closed");
43 if (!closed.ok) return false;
44 for (const number of closesFromBody(pull.body)) {
45 const about = getIssue(app.db, repo.id, number);
46 if (!about || about.state !== "open") continue;
47 // A superseded pull landed nothing: a person's reopen stands against it,
48 // and so does work still unticked.
49 if (reopenedByPerson(app.db, repo.id, number)) continue;
50 const left = unticked(about.body);
51 if (left.length > 0) {
52 addComment(app, by, repo, issue, leftNote(number, left));
53 continue;
54 }
55 if (about.assigneeId !== null) assignIssue(app, by, repo, about, null);
56 addComment(app, by, repo, about, `${CLOSED_NOTE}${named} (pull #${pull.number}).`);
57 setIssueState(app, by, repo, about, "closed", { reason: "done", system: true });
58 }
59 log.info("superseded pull closed", {
60 repo: `${repo.ownerName}/${repo.name}`,
61 pull: pull.number,
62 commits: oids.length,
63 });
64 return true;
65 }
66
67 /**
68 * Close a pull the crew could not bring up to date, and put its issues back
69 * on the map unassigned with the conflict named. Unlike `parkPull` it is
70 * main that moved, not the builder that failed: the note is not a park, so
71 * it is never a strike against the issue or the builder.
72 */
73 export function releaseConflicted(
74 app: App,
75 repo: Repo,
76 pull: Pull,
77 why: string,
78 files: readonly string[],
79 ): boolean {
80 if (repo.autonomy !== "autonomous" || repo.autonomyBy === null) return false;
81 if (getHold(app.db, pull.id) !== undefined) return false;
82 const by = getUserById(app.db, repo.autonomyBy);
83 const issue = getIssueById(app.db, pull.id);
84 if (!by || !issue || issue.state !== "open") return false;
85 const named = files.length > 0 ? ` Conflicting files: ${files.join(", ")}.` : "";
86 addComment(app, by, repo, issue, `Closed by the crew: ${why}.${named}`);
87 const closed = setIssueState(app, by, repo, issue, "closed", {
88 reason: "parked",
89 });
90 if (!closed.ok) return false;
91 for (const number of closesFromBody(pull.body)) {
92 const about = getIssue(app.db, repo.id, number);
93 if (!about || about.state !== "open") continue;
94 if (about.assigneeId !== null) assignIssue(app, by, repo, about, null);
95 addComment(
96 app,
97 by,
98 repo,
99 about,
100 `Ready again: pull #${pull.number} was closed because main moved under it and it could not be brought up to date.${named}`,
101 );
102 }
103 log.info("conflicted pull released", {
104 repo: `${repo.ownerName}/${repo.name}`,
105 pull: pull.number,
106 why,
107 });
108 return true;
109 }
110
111 /**
112 * Queue one run for the pull's agent to merge main into its branch. One
113 * waiting is enough, and the automatic tries since a person last spoke
114 * stop at the same limit a failing check does — past it, the pull waits
115 * for a person.
116 */
117 export function bringUpToDate(
118 app: App,
119 repo: Repo,
120 pull: Pull,
121 files: readonly string[],
122 episodeStart = "",
123 ): string | undefined {
124 const issue = getIssueById(app.db, pull.id);
125 if (!issue || issue.state !== "open") return undefined;
126 const agent = agentFor(app, issue);
127 if (!agent) return undefined;
128 if (activeRunFor(app.db, "agent", issue.id) !== undefined)
129 return agent.user.username;
130 const tries = automaticRunsSince(
131 app.db,
132 issue.id,
133 episodeStart > lastHumanWord(app, issue, agent)
134 ? episodeStart
135 : lastHumanWord(app, issue, agent),
136 );
137 if (tries >= CHECK_FAILED_LIMIT) {
138 // Autonomous: closed, never waiting. Assisted: the person's word.
139 releaseConflicted(
140 app,
141 repo,
142 pull,
143 `main moved under it ${tries} times and the branch could not be brought up to date`,
144 files,
145 );
146 return undefined;
147 }
148 queueAgentRun(app, repo, issue, agent, "conflict", undefined, {
149 notBefore: new Date().toISOString(),
150 attempt: 0,
151 summary: `main moved: ${files.join(", ")}`,
152 });
153 return agent.user.username;
154 }
src/crew/conflict_sweep.ts added +199
@@ -0,0 +1,199 @@
1 /** The sweep that asks the crew to bring a pull up to date when main moved under it. */
2
3 import { onlyListDocs, resolveListConflicts } from "../actions/list-conflicts.ts";
4 import type { App } from "../app.ts";
5 import { getHold } from "../core/holds.ts";
6 import { getIssueById, type Issue } from "../core/issues.ts";
7 import { listOpenPulls, pullDir } from "../core/pulls.ts";
8 import type { Repo } from "../core/repos.ts";
9 import { activeRunFor } from "../core/runs.ts";
10 import { mergeable, resolveOid, treeOf } from "../git/merge.ts";
11 import { bringUpToDate, closeSuperseded, releaseConflicted } from "./conflict_release.ts";
12 import { readConflictRoom } from "./conflict_room.ts";
13 import { agentFor, CHECK_FAILED_LIMIT, lastHumanWord } from "./dispatch.ts";
14 import { approvedOnHead } from "./finishing.ts";
15 import { closeStale } from "./stale_pulls.ts";
16
17 /** Pull id → the tips git last read, and the files in conflict (null: clean). */
18 const checked = new Map<
19 string,
20 { head: string; key: string; files: string[] | null; tree: string | null }
21 >();
22 /** Pull id → the head it conflicts at, and when the sweep first saw that (#5940). */
23 const conflictedAt = new Map<string, { head: string; since: string }>();
24 /** Pull id → when the sweep last saw it merge cleanly. */
25 const cleanAt = new Map<string, string>();
26
27 /**
28 * Where this conflict began counting: a person's last word, or the last
29 * time the pull was seen clean. After a restart nothing is remembered, so a
30 * run that ended well is taken as the end of the episode before it. A
31 * finished run in the episode that left the pull conflicted is a failed
32 * attempt, whatever state it ended in.
33 */
34 function conflictEpisodeStart(app: App, issue: Issue, pullId: string): string {
35 const agent = agentFor(app, issue);
36 let start = agent ? lastHumanWord(app, issue, agent) : issue.createdAt;
37 const clean = cleanAt.get(pullId);
38 if (clean !== undefined) {
39 if (clean > start) start = clean;
40 } else {
41 const ended = app.db
42 .query<{ at: string | null }, [string]>(
43 `SELECT MAX(finished_at) AS at FROM run
44 WHERE kind = 'agent' AND reason = 'conflict' AND issue_id = ?1 AND state = 'ok'`,
45 )
46 .get(pullId)?.at;
47 if (ended != null && ended > start) start = ended;
48 }
49 return start;
50 }
51
52 /** Conflict runs the crew may spend on one pull for one main tip. */
53 const RUNS_PER_TIP = 2;
54
55 /** Pull id → the main tip it was last asked about, and how many times. */
56 const asked = new Map<string, { tip: string; n: number }>();
57
58 /** How long a conflicted pull may wait to be brought up to date. */
59 const CONFLICT_LIMIT_MS = 24 * 3_600_000;
60
61 /**
62 * Every tick, each open crew pull that no longer merges gets a
63 * bring-up-to-date run (one in flight per pull). After two finished
64 * attempts, or 24 h since the first, it is closed and its issue is ready
65 * again. An approved pull is not this sweep's but `finishApproved`'s.
66 * Runs start oldest pull first, only as many as the check lane has room
67 * for (`conflict_room.ts`); the rest wait for a later tick (#4459).
68 * Returns how many pulls were acted on.
69 */
70 export async function sweepConflicts(
71 app: App,
72 repo: Repo,
73 now: Date = new Date(),
74 ): Promise<number> {
75 if (repo.autonomy !== "autonomous") return 0;
76 let acted = 0;
77 let room = readConflictRoom(app.db);
78 // Forget pulls that are no longer open: closed, merged or released.
79 for (const id of new Set([...checked.keys(), ...cleanAt.keys(), ...conflictedAt.keys()]))
80 if (getIssueById(app.db, id)?.state !== "open") {
81 checked.delete(id);
82 conflictedAt.delete(id);
83 cleanAt.delete(id);
84 asked.delete(id);
85 }
86 // Every open pull, not the newest page: an old one main moved under is
87 // the crew's too (#6263).
88 for (const pull of listOpenPulls(app.db, repo.id)) {
89 if (!pull.authorIsAgent || pull.mergedAt !== null) continue;
90 if (getHold(app.db, pull.id) !== undefined) continue;
91 const dir = await pullDir(app.db, app.reposRoot, repo, pull);
92 const baseTip = await resolveOid(dir, `refs/heads/${pull.baseBranch}`);
93 if (baseTip === undefined) continue;
94 // Git is asked once per pair of tips; until one moves, the answer stands.
95 const key = `${pull.headOid}:${baseTip}`;
96 let seen = checked.get(pull.id);
97 // The head moved since the last read: the builder pushed (or a person
98 // did), so what was tried before belongs to an earlier episode.
99 if (seen !== undefined && seen.head !== pull.headOid)
100 cleanAt.set(pull.id, new Date().toISOString());
101 if (seen?.key !== key) {
102 const reading = await mergeable(dir, baseTip, pull.headOid);
103 seen = {
104 head: pull.headOid,
105 key,
106 tree: reading.ok ? reading.value.treeOid : null,
107 files: reading.ok
108 ? null
109 : reading.error.kind === "conflict"
110 ? reading.error.files
111 : null,
112 };
113 checked.set(pull.id, seen);
114 }
115 // Merging main leaves main's own tree: the pull adds nothing, so there
116 // is no work to bring up to date and no run to spend on it.
117 if (seen.tree !== null && seen.tree === (await treeOf(dir, baseTip))) {
118 if (closeSuperseded(app, repo, pull, [baseTip])) {
119 acted++;
120 checked.delete(pull.id);
121 cleanAt.delete(pull.id);
122 }
123 continue;
124 }
125 if (seen.files === null) {
126 // Merges cleanly: whatever came before was a different episode.
127 cleanAt.set(pull.id, new Date().toISOString());
128 conflictedAt.delete(pull.id);
129 continue;
130 }
131 const files = seen.files;
132 // A push moves the head and the 72-hour clock starts again.
133 let conflict = conflictedAt.get(pull.id);
134 if (conflict?.head !== pull.headOid)
135 conflictedAt.set(
136 pull.id,
137 (conflict = { head: pull.headOid, since: now.toISOString() }),
138 );
139 // An approved pull is finished first, and handed to a person rather
140 // than closed: the tick's finishing pass has it (`finishing.ts`).
141 if (approvedOnHead(app.db, pull)) continue;
142 const issue = getIssueById(app.db, pull.id);
143 if (!issue || issue.state !== "open") continue;
144 if (activeRunFor(app.db, "agent", issue.id) !== undefined) continue;
145 // Past 72 hours in conflict, whatever the attempts did (#5940).
146 if (closeStale(app, repo, pull, conflict.since, now)) {
147 acted++;
148 checked.delete(pull.id);
149 cleanAt.delete(pull.id);
150 conflictedAt.delete(pull.id);
151 continue;
152 }
153 const since = conflictEpisodeStart(app, issue, pull.id);
154 const runs = app.db
155 .query<{ n: number; first: string | null }, [string, string]>(
156 `SELECT COUNT(*) AS n, MIN(created_at) AS first FROM run
157 WHERE kind = 'agent' AND reason = 'conflict' AND issue_id = ?1
158 AND created_at > ?2 AND state IN ('ok','failed')`,
159 )
160 .get(pull.id, since);
161 const aged =
162 runs?.first != null &&
163 Date.now() - Date.parse(runs.first) >= CONFLICT_LIMIT_MS;
164 if ((runs?.n ?? 0) >= CHECK_FAILED_LIMIT || aged) {
165 const why = aged
166 ? "main moved under it and the branch was not brought up to date within 24 hours"
167 : `main moved under it and ${runs?.n} attempts to bring the branch up to date failed`;
168 if (releaseConflicted(app, repo, pull, why, files)) {
169 acted++;
170 checked.delete(pull.id);
171 cleanAt.delete(pull.id);
172 }
173 continue;
174 }
175 // Main's tip asks no more than twice: a run that ends "ok" without a
176 // push must not be queued again on every tick.
177 const tried = asked.get(pull.id);
178 if (tried?.tip === baseTip && tried.n >= RUNS_PER_TIP) continue;
179 // A clash only in list docs is settled by the forge, with no run: its
180 // push is a check, and the next tick sees the pull clean (#7909).
181 if (onlyListDocs(files) && room > 0 && (await resolveListConflicts(app, repo, pull)) !== undefined) {
182 room--;
183 acted++;
184 checked.delete(pull.id);
185 continue;
186 }
187 // Its push is a check: none starts that the lane has no slot for (#4459).
188 if (room <= 0) continue;
189 if (bringUpToDate(app, repo, pull, files, since) !== undefined) {
190 room--;
191 acted++;
192 asked.set(pull.id, {
193 tip: baseTip,
194 n: tried?.tip === baseTip ? tried.n + 1 : 1,
195 });
196 }
197 }
198 return acted;
199 }
src/crew/conflicted_tips.ts added +10
@@ -0,0 +1,10 @@
1 /** The merge conflicts last seen, per pull, by the tips they were between. */
2
3 import { BoundedMap } from "../perf/bounded.ts";
4 import { threadHeld } from "../perf/held.ts";
5
6 /** How many conflicted pulls are remembered; past it, the one set longest ago is tried again. */
7 export const CONFLICTED_MAX = 1024;
8 /** Pull id → the `head:base` tips a merge last conflicted between. */
9 export const conflicted = new BoundedMap<string, string>(CONFLICTED_MAX);
10 threadHeld.add("autonomy conflicted pulls", () => conflicted.size);
src/crew/converge.ts +1 −1
@@ -44,7 +44,7 @@ import { runGit } from "../git/env.ts";
4444 import { isSafeOid } from "../git/guard.ts";
4545 import { repoDir } from "../git/repos.ts";
4646 import { createLog } from "../kernel/log.ts";
47 import { parkedCount } from "./autonomy.ts";
47 import { parkedCount } from "./park_issue.ts";
4848 import { PARK_STRIKES } from "./parks.ts";
4949 import { queueAgentRun } from "./dispatch.ts";
5050 import { pickBuilder } from "./route.ts";
src/crew/direct.ts +1 −1
@@ -85,7 +85,7 @@ export function threadNote(
8585 * Whether the crew takes this person's word here as direction: someone who
8686 * may direct it, or one of the crew's own agents, whose notes are the
8787 * crew's work. Everyone else is a reader — their words are quoted, never
88 * obeyed, and never re-arm the clock (`autonomy.ts`, `parks.ts`).
88 * obeyed, and never re-arm the clock (`plan_owed.ts`, `parks.ts`).
8989 */
9090 export function speaksForCrew(
9191 db: Database,
src/crew/direction_issue.ts added +51
@@ -0,0 +1,51 @@
1 /** The issue the planner works from: the repository's direction as an open issue. */
2
3 import { openIssue } from "../actions/issues.ts";
4 import type { App } from "../app.ts";
5 import { getIssueById, type Issue, MAX_TITLE } from "../core/issues.ts";
6 import { type Repo, setDirectionIssue } from "../core/repos.ts";
7 import type { User } from "../core/users.ts";
8
9 /** The label every direction issue's title starts with. Read elsewhere to
10 * find a repository's standing direction — keep it exactly as it is. */
11 export const DIRECTION_PREFIX = "Direction: ";
12 /** How much of the direction fits in the title, capped so the title
13 * (prefix included) never exceeds `MAX_TITLE`. */
14 const DIRECTION_TITLE_LIMIT = Math.min(120, MAX_TITLE - DIRECTION_PREFIX.length);
15
16 /** Cuts `text` to at most `limit` characters at a word boundary, ending in
17 * "…" when something was cut — never mid-word, never a dangling "(" before
18 * the ellipsis. Text that already fits is returned unchanged. */
19 export function truncateAtWord(text: string, limit: number): string {
20 if (text.length <= limit) return text;
21 const ellipsis = "…";
22 const budget = Math.max(limit - ellipsis.length, 0);
23 let cut = text.slice(0, budget);
24 if (text[budget] !== " " && text[budget] !== undefined) {
25 const lastSpace = cut.lastIndexOf(" ");
26 cut = lastSpace === -1 ? "" : cut.slice(0, lastSpace);
27 }
28 return cut.replace(/[\s(]+$/, "") + ellipsis;
29 }
30
31 /**
32 * The issue the planner works from: the direction, as an open issue the
33 * run can be about. Made once, kept, and never counted as work.
34 */
35 export function ensureDirectionIssue(
36 app: App,
37 by: User,
38 repo: Repo,
39 ): Issue | undefined {
40 if (repo.directionIssueId !== null) {
41 const existing = getIssueById(app.db, repo.directionIssueId);
42 if (existing && existing.state === "open") return existing;
43 }
44 const opened = openIssue(app, by, repo, {
45 title: `${DIRECTION_PREFIX}${truncateAtWord(repo.autonomyDirection.trim(), DIRECTION_TITLE_LIMIT)}`,
46 body: `${repo.autonomyDirection.trim()}\n\nThis issue carries the repository's direction. The planner is given it when a person writes on it or the crew hands it an issue; it opens and links the issues that follow from it, and this one stays open.`,
47 });
48 if (!opened.ok) return undefined;
49 setDirectionIssue(app.db, repo.id, opened.value.id);
50 return opened.value;
51 }
src/crew/dispatch.ts +5 −8
@@ -101,8 +101,8 @@ import { detectAgent } from "./agent_runner.ts";
101101 import { followDivergence, settleAll, settleOnPush } from "./converge.ts";
102102 import { breakerTripped } from "./breaker.ts";
103103 import { REPEAT_NOTE, repeatTripped } from "./repeat.ts";
104 import { CAP_NOTE } from "./cap_note.ts";
104105 import {
105 CAP_NOTE,
106106 capNoted,
107107 capReached,
108108 HANDOVER_NOTE,
@@ -119,13 +119,10 @@ import { dataInTemp, sandboxAvailable, sweepRunTmp } from "./sandbox.ts";
119119 import { SANDBOX_ENV, noteSandbox, reprober, sandboxHoldSentence, sandboxRefusal, type SandboxProbe } from "./sandbox_policy.ts";
120120 import { sandboxCause } from "./sandbox_cause.ts";
121121 import { mayDirectCrew } from "./direct.ts";
122 import {
123 AUTONOMY_TICK_MS,
124 autonomyTick,
125 landIfGreen,
126 parkForBreaker,
127 settleAgentRun,
128 } from "./autonomy.ts";
122 import { AUTONOMY_TICK_MS, autonomyTick } from "./autonomy_tick.ts";
123 import { landIfGreen } from "./land_queue.ts";
124 import { parkForBreaker } from "./park_issue.ts";
125 import { settleAgentRun } from "./settle_run.ts";
129126 import { checksFor } from "../checks/service.ts";
130127 import { redMain, sharedWithMain } from "../checks/red_main.ts";
131128 import { diskRecovered, diskRed } from "../checks/disk_red.ts";
src/crew/drive.ts added +188
@@ -0,0 +1,188 @@
1 /**
2 * One turn of the loop for one repository: pick the next ready issue for a builder, or ask the
3 * planner.
4 */
5
6 import { tickBets } from "../actions/bets.ts";
7 import { assignIssue } from "../actions/issues.ts";
8 import { walkOwed } from "../actions/journey_walk.ts";
9 import type { App } from "../app.ts";
10 import { type Agent, type CrewRole, listCrewRoles } from "../core/agents.ts";
11 import { type Ranked, readyNow, repoGraph } from "../core/dependencies.ts";
12 import { getIssueById, type Issue } from "../core/issues.ts";
13 import { getRepoById, type Repo } from "../core/repos.ts";
14 import type { Run } from "../core/runs.ts";
15 import { getUserById } from "../core/users.ts";
16 import { createLog } from "../kernel/log.ts";
17 import { inSlotOrder, repoPace, type TickPicks } from "./autonomy_pace.ts";
18 import { activeRuns, autonomyStatus, slottedRuns } from "./autonomy_status.ts";
19 import { passLanded } from "./box_pass.ts";
20 import { heldBy } from "./held.ts";
21 import { holdHot, learnPullFiles } from "./hot_files.ts";
22 import { nextOf, withoutRetired } from "./next_pick.ts";
23 import { crewFor as crewForIssue, routable } from "./pick_filter.ts";
24 import { planIfOwed } from "./plan_owed.ts";
25 import { redUnattended } from "./red_unattended.ts";
26 import { routeIssue } from "./route.ts";
27 import { noteTooLarge } from "./too_large.ts";
28 import { freeParked, noteRedThrice } from "./unstick.ts";
29
30 const log = createLog("autonomy");
31
32 /**
33 * What one turn of the loop did, as a word. `stalled` (#12968): nothing to start, and open crew
34 * pulls are red with nobody working them. The only reader is the tick's `did` field, which logs
35 * the word as it is: nothing branches on a value, so a new one is never an error.
36 */
37 export type Drove = "off" | "paused" | "waiting" | "full" | "picked" | "planned" | "idle" | "stalled";
38
39 /**
40 * One turn of the loop for one repository. Returns what it did, for the
41 * log and for tests; the effects are an assignment (which the crew turns
42 * into a run) or a planner given the direction.
43 */
44 export async function driveRepo(
45 app: App,
46 repo: Repo,
47 now = new Date(),
48 picked: Map<string, Set<string>> = new Map(),
49 ): Promise<Drove> {
50 // One start per free builder slot (#8729). Each pass re-reads the ceiling,
51 // the paced slots and the held filters, so a start the dispatcher refused
52 // or a spend that reached the wall ends the tick's starts there.
53 // An issue picked this tick may not have its run yet: it is kept out of the
54 // next pass and counted against the slots until the run shows.
55 const taken = new Set<string>();
56 picked.set(repo.id, taken);
57 const did = await driveOnce(app, repo, now, taken, picked);
58 if (did !== "picked") return did;
59 for (let n = 1; n < Math.max(1, repo.autonomySlots); n++) {
60 const next = await driveOnce(app, getRepoById(app.db, repo.id) ?? repo, now, taken, picked);
61 if (next !== "picked") break;
62 }
63 return did;
64 }
65
66 async function driveOnce(
67 app: App,
68 repo: Repo,
69 now: Date,
70 taken: Set<string>,
71 picked: TickPicks,
72 ): Promise<Drove> {
73 if (repo.autonomy === "off") return "off";
74 tickBets(app, repo, now);
75 // Journeys are walked apart from the tick: a browser and a model call never hold the crew back.
76 void walkOwed(app, repo, now).catch(() => undefined);
77 const status = autonomyStatus(app, repo, now);
78 if (status.paused !== null) return "paused";
79 const by = getUserById(app.db, repo.autonomyBy!);
80 if (!by) return "paused";
81 const crew = listCrewRoles(app.db, repo.id);
82 const active = activeRuns(app, repo.id);
83 const slotted = slottedRuns(active, crew);
84 // Picked earlier in this tick and not yet running: still a slot spent.
85 const running = new Set(active.map((r) => r.issueId));
86 const pending = [...taken].filter((id) => !running.has(id)).length;
87 // Slots follow the subscriptions' remaining windows, never past the
88 // operator's; at a wall nothing new starts until the reset.
89 const paced = repoPace(app, repo, now, true, picked);
90 if (paced.slots === 0 && slotted.length === 0) return "waiting";
91 // The files the open pulls touch, read before the sort: a build that
92 // names a hot one waits for its pile to drain (#5934).
93 await learnPullFiles(app, repo).catch((error) =>
94 log.warn("could not read the open pulls' files", {
95 repo: `${repo.ownerName}/${repo.name}`,
96 error: String(error),
97 }),
98 );
99 const sorted = () => heldBy(app, repo, readyNow(repoGraph(app.db, repo.id, { sealed: true })), crew, active);
100 let held = sorted();
101 if (freeParked(app, repo, by, held) > 0) held = sorted();
102 // An issue over the size limit is handed to the planner once, with a note (#15820).
103 noteTooLarge(app, by, repo, held.by.too_large);
104 // A pull red on three checks is said once on its issue and owed to the planner.
105 noteRedThrice(app, repo, by);
106 // An issue a landing left open with boxes is given the reviewer's pass once (#8682).
107 await passLanded(app, repo, held.by.landed);
108 holdHot(
109 repo.id,
110 held.by.hot_file,
111 now,
112 new Map(
113 [...held.pinned].map(([n, h]) => [n, { path: h.path, byName: getUserById(app.db, h.by)?.username ?? "someone" }]),
114 ),
115 held.relieving,
116 );
117 const ready = held.startable.filter((r) => !taken.has(r.issue.id));
118 const used = slotted.length + pending;
119 if (used >= paced.slots) {
120 // The builders are busy; a pass may still be owed (a hand-over, a person's word).
121 if (await planIfOwed(app, repo, by, crew, active, ready.length, now)) return "planned";
122 return "full";
123 }
124
125 const inFlight = new Map<string, number>();
126 for (const r of active)
127 if (r.actorId !== null)
128 inFlight.set(r.actorId, (inFlight.get(r.actorId) ?? 0) + 1);
129 // A builder that stalled an issue within the hour leaves it to the
130 // others; one no builder may take now is skipped, not waited on (#4073).
131 const crewFor = (issue: Issue) => crewForIssue(app, repo, issue.id, crew, now);
132 const pickable = await withoutRetired(app, repo, routable(app, repo, ready, crew, now).kept);
133 // The roadmap first, and small issues held to their share of the slots (#7571).
134 const next = await nextOf(app, repo, inSlotOrder(app, repo, pickable, now));
135 if (next !== undefined) {
136 taken.add(next.issue.id);
137 const routed = await routeIssue(app, repo, next.issue, crewFor(next.issue), inFlight);
138 if (!routed) return "paused";
139 const builder = routed.builder;
140 // Assigning is the event that starts a run. An issue already carrying
141 // the builder's name is assigned afresh so the event fires once more.
142 if (next.issue.assigneeId === builder.user.id) {
143 const cleared = assignIssue(app, by, repo, next.issue, null);
144 if (!cleared.ok) return "idle";
145 }
146 const current = getIssueById(app.db, next.issue.id) ?? next.issue;
147 const assigned = assignIssue(app, by, repo, current, builder.user, undefined, true);
148 if (!assigned.ok) {
149 log.warn("could not assign the next ready issue", {
150 repo: `${repo.ownerName}/${repo.name}`,
151 issue: next.issue.number,
152 error: assigned.error,
153 });
154 return "idle";
155 }
156 log.info("picked", {
157 repo: `${repo.ownerName}/${repo.name}`,
158 issue: next.issue.number,
159 agent: builder.user.username,
160 size: routed.size,
161 by: routed.by,
162 });
163 // Planning runs alongside building: a pass owed is asked for now.
164 await planIfOwed(app, repo, by, crew, active, ready.length - 1, now);
165 return "picked";
166 }
167
168 // Nothing is startable with slots free: that alone is no reason to run a model (#16231).
169 // A pass is asked for only when something is owed (`planIfOwed`).
170 if (await planIfOwed(app, repo, by, crew, active, 0, now)) return "planned";
171 // Red pulls nobody is working are a stall, not idleness (#12968): the tick says so.
172 return redUnattended(app, repo, active) > 0 ? "stalled" : "idle";
173 }
174
175 /**
176 * The ready issues a builder may start now: not the direction, and held by
177 * none of `held.ts`'s filters. The tick log counts these beside the raw
178 * ready list, and the held ones per filter.
179 */
180 export function startable(
181 app: App,
182 repo: Repo,
183 ready: readonly Ranked[],
184 crew: readonly { agent: Agent; role: CrewRole }[],
185 active: readonly Run[],
186 ): Ranked[] {
187 return heldBy(app, repo, ready, crew, active).startable;
188 }
src/crew/fold_walls.ts +4 −4
@@ -14,14 +14,14 @@ import { runGitCapture } from "../git/env.ts";
1414 /**
1515 * Paths a person decides on whoever wrote them: secrets and credentials,
1616 * who may do what, the contract's walls, the machinery that releases and
17 * the machinery that enforces these very walls (fold-in, autonomy, the
18 * trust list's actions and page, the auth routes, event audiences) and
19 * every migration. Each rule says why in the words a person reads on the card.
17 * the machinery that enforces these very walls (fold-in, autonomy and the modules it was split
18 * into, the trust list's actions and page, the auth routes, event audiences) and every migration.
19 * Each rule says why in the words a person reads on the card.
2020 */
2121 const WALLS: readonly { readonly test: RegExp; readonly why: string }[] = [
2222 { test: /(^|\/)\.env([./]|$)|(^|\/)(secrets?|credentials?)([./_-]|$)|\.(pem|key|p12|pfx)$|(^|\/)id_(rsa|ed25519|ecdsa)/i, why: "secrets or credentials" },
2323 { test: /^src\/(auth|origins\/credential|kernel\/secret|core\/(secret|tokens|keys|sessions|passkeys|run_token|run_grant|proposal_token))/, why: "secrets or credentials" },
24 { test: /^src\/(contract|core\/(roles|access_fingerprint|pull_trust|trusted_sources|event_audience)|crew\/(fold_|autonomy|direct|finishing)|http\/(run_gate|[^/]*auth[^/]*|settings_routes|admin_gate)|actions\/(access|app_members|egress_grants|model_grant|trusted_sources|pulls|upstream_follow)|web\/pages\/trusted|tui\/screens\/trusted)/, why: "permissions or the contract's walls" },
24 { test: /^src\/(contract|core\/(roles|access_fingerprint|pull_trust|trusted_sources|event_audience)|crew\/(fold_|autonomy|direct|finishing|(drive|last_week|unstick|next_pick|planner_hold|plan_owed|planner_decline|park_issue|settle_run|green_sweep|conflict_sweep|conflict_release|conflicted_tips|review_gate|land_queue|land_admit|regate|land_gated)\.ts)|http\/(run_gate|[^/]*auth[^/]*|settings_routes|admin_gate)|actions\/(access|app_members|egress_grants|model_grant|trusted_sources|pulls|upstream_follow)|web\/pages\/trusted|tui\/screens\/trusted)/, why: "permissions or the contract's walls" },
2525 { test: /^(src\/(release|keeper)\/|src\/core\/migration|scripts\/(gate|check|cut-release|roll|dark-roll|rehearse-roll|roll-preflight|pin-migrations)\.ts$|Dockerfile$|charts\/|infra\/|forge\.json$|package\.json$|bun\.lock$|bunfig\.toml$|\.github\/)/, why: "release machinery" },
2626 ];
2727
src/crew/green_sweep.ts added +95
@@ -0,0 +1,95 @@
1 /** The sweep that lands green pulls that have not landed, and the merge queue's line it prunes. */
2
3 import type { App } from "../app.ts";
4 import { dropFromLine, enqueue, type Queued, waitingPulls } from "../checks/queue.ts";
5 import { getHold } from "../core/holds.ts";
6 import { getPull, listOpenPulls } from "../core/pulls.ts";
7 import type { Repo } from "../core/repos.ts";
8 import { reviewSummary } from "../core/reviews.ts";
9 import { verdictForHead } from "../core/runs.ts";
10 import { createLog } from "../kernel/log.ts";
11 import { isFirstChange } from "./first_change.ts";
12 import { admit } from "./land_admit.ts";
13 import { gateFor, queueOptions } from "./land_queue.ts";
14 import { noteWaits, tallyWaits, type Wait } from "./waits.ts";
15
16 const log = createLog("autonomy");
17
18 /**
19 * Green pulls that have not landed — a check that passed before autonomy
20 * was turned on, or one the event missed — land on the tick, so nothing
21 * green waits on chance.
22 */
23 export async function sweepGreen(app: App, repo: Repo, now: Date = new Date()): Promise<number> {
24 if (repo.autonomy !== "autonomous") return 0;
25 // Admitted one by one, queued together, oldest first: the green pulls of
26 // one sweep are one candidate and one gate (#2036).
27 const entries: Queued[] = [];
28 // Why each approved pull waits, for the tick line (#3055).
29 const waits: Wait[] = [];
30 for (const pull of listOpenPulls(app.db, repo.id)) {
31 const admitted = await admit(app, repo, pull, now);
32 if (admitted.ok) entries.push(admitted.value);
33 const seen = reviewSummary(app.db, pull.id, pull.headOid);
34 if (seen.approvals > 0 && seen.changesRequested === 0)
35 waits.push(admitted.ok ? "queued" : admitted.error);
36 }
37 noteWaits(repo.id, tallyWaits(waits));
38 if (entries.length === 0) return 0;
39 const landed = await enqueue(repo.id, entries, gateFor(app, repo), queueOptions(app, repo));
40 return landed.filter(Boolean).length;
41 }
42
43 /**
44 * Take out of the merge queue's line every waiting pull that would no
45 * longer be admitted (#6611): held, closed or merged, pushed to since it
46 * joined, no longer green on its head, or with changes requested on it.
47 * Run on every tick, beside the sweep: a sweep in flight waits on its whole
48 * line, so the line is cleared here, not there. Reads only rows: cheap.
49 * How many were taken out.
50 */
51 export function pruneLine(app: App, repo: Repo): number {
52 const out = new Set<string>();
53 for (const joined of waitingPulls(repo.id)) {
54 const row = getPull(app.db, repo.id, joined.number);
55 const stays =
56 row !== undefined &&
57 row.state === "open" &&
58 row.mergedAt === null &&
59 row.headOid === joined.headOid &&
60 getHold(app.db, row.id) === undefined &&
61 verdictForHead(app.db, row.id, row.headOid).every((c) => c.state === "ok") &&
62 (reviewSummary(app.db, row.id, row.headOid).changesRequested === 0 || isFirstChange(app.db, repo, row));
63 if (!stays) out.add(joined.id);
64 }
65 return out.size === 0 ? 0 : dropFromLine(repo.id, out);
66 }
67
68 /** The sweep each repository has in flight, by repository id. */
69 const sweeping = new Map<string, Promise<number>>();
70
71 /**
72 * Starts the green sweep beside the tick, never in front of it: a landing
73 * gate takes minutes, and builders are picked meanwhile (#2015). One sweep
74 * per repository is in flight — a tick that finds one running returns it
75 * rather than start a second. Never rejects; a failure is logged.
76 */
77 export function startSweep(
78 app: App,
79 repo: Repo,
80 sweep: (app: App, repo: Repo) => Promise<number> = sweepGreen,
81 ): Promise<number> {
82 const running = sweeping.get(repo.id);
83 if (running) return running;
84 const started = sweep(app, repo)
85 .catch((error) => {
86 log.error("green sweep failed", {
87 repo: `${repo.ownerName}/${repo.name}`,
88 error: String(error),
89 });
90 return 0;
91 })
92 .finally(() => sweeping.delete(repo.id));
93 sweeping.set(repo.id, started);
94 return started;
95 }
src/crew/guard.ts +1 −4
@@ -23,6 +23,7 @@ import { recordDecision } from "../core/decisions.ts";
2323 import type { Issue } from "../core/issues.ts";
2424 import { listPulls } from "../core/pulls.ts";
2525 import type { Repo } from "../core/repos.ts";
26 import { CAP_NOTE } from "./cap_note.ts";
2627 import { directorsAmong } from "./direct.ts";
2728 import { nothingNew, plannerNothingNew } from "./news.ts";
2829
@@ -40,10 +41,6 @@ export function runCapOf(
4041 : (caps.issueRunCap ?? ISSUE_RUN_CAP);
4142 }
4243
43 /** The note a capped issue is parked with: the map reads it as `parked`, the asks as a question. */
44 export const CAP_NOTE =
45 "Parked by the crew: this issue started its day's share of runs without landing, so nothing more starts here until a person says what to try.";
46
4744 /** What a skipped follow-up records, and what its run says when one was already queued. */
4845 export const SKIP_SUMMARY = "skipped: nothing new to act on since the last run";
4946
src/crew/handover.ts +1 −1
@@ -31,7 +31,7 @@ import type { Issue } from "../core/issues.ts";
3131 import { isPinned } from "../core/pins.ts";
3232 import { canAdmin, getRepoById, type DecisionsBy, type Repo } from "../core/repos.ts";
3333 import type { User } from "../core/users.ts";
34 import { spentTodayForRepos } from "./autonomy.ts";
34 import { spentTodayForRepos } from "./autonomy_spend.ts";
3535 import { crewWeekFor } from "./week_read.ts";
3636 import { certain, decideOr, type Answers, type Questions } from "./decide.ts";
3737 import { parkReasons } from "./parks.ts";
src/crew/held.ts +1 −1
@@ -12,7 +12,7 @@
1212 * - `open_pull`: an open pull already proposes it (`direct.ts`), or one a
1313 * builder opened in the last 10 minutes (`fresh_pull.ts`).
1414 * - `planner`: the planner or a reviewer holds it, not a builder. The tick
15 * frees these (`freeParked` in `autonomy.ts`): neither ever builds it.
15 * frees these (`freeParked` in `unstick.ts`): neither ever builds it.
1616 * - `with_planner`: its limb was handed to the planner by a person and the
1717 * planner has not answered (`core/limb_replan.ts`).
1818 * - `done_on_main`: the crew found it done on the base branch and waits for
src/crew/idle_reason.ts +1 −1
@@ -17,7 +17,7 @@ import { listAutonomousRepos, type Repo } from "../core/repos.ts";
1717 import { listActive } from "../core/runs.ts";
1818 import { standings } from "../core/standing.ts";
1919 import { grantedAccounts } from "../core/subscriptions.ts";
20 import { slottedRuns } from "./autonomy.ts";
20 import { slottedRuns } from "./autonomy_status.ts";
2121 import { weekSpent } from "./week_read.ts";
2222 import { governorFor } from "./governed.ts";
2323 import { heldNow, HOLDS } from "./held.ts";
src/crew/land_admit.ts added +270
@@ -0,0 +1,270 @@
1 /** Everything a green pull must be before it joins the merge queue. */
2
3 import { addComment } from "../actions/issues.ts";
4 import { mergePull } from "../actions/pulls.ts";
5 import type { App } from "../app.ts";
6 import { noteRed, treatRed } from "../checks/doctor.ts";
7 import { releaseOnLand } from "../checks/landing.ts";
8 import { addLearned } from "../checks/learned.ts";
9 import type { Queued } from "../checks/queue.ts";
10 import { wallOf, wallPlain, wallSentence } from "../contract/policy.ts";
11 import { latestDecision, recordDecision, stopStands } from "../core/decisions.ts";
12 import { getHold } from "../core/holds.ts";
13 import { getIssueById } from "../core/issues.ts";
14 import { getPull, type Pull, pullDir } from "../core/pulls.ts";
15 import type { Repo } from "../core/repos.ts";
16 import { verdictForHead } from "../core/runs.ts";
17 import { getUserById } from "../core/users.ts";
18 import { mergeable, resolveOid, treeOf } from "../git/merge.ts";
19 import { createLog } from "../kernel/log.ts";
20 import { err, ok, type Result } from "../kernel/result.ts";
21 import { bringUpToDate } from "./conflict_release.ts";
22 import { conflicted } from "./conflicted_tips.ts";
23 import { landsOnItsOwn } from "./direct.ts";
24 import { approvedOnHead } from "./finishing.ts";
25 import { foldWall } from "./fold_walls.ts";
26 import { landGated } from "./land_gated.ts";
27 import { redAt, redOf, type RedState, regateDue } from "./regate.ts";
28 import { reviewed } from "./review_gate.ts";
29 import { sourceHeld } from "./source_held.ts";
30 import type { Wait } from "./waits.ts";
31
32 const log = createLog("autonomy");
33
34 /**
35 * Everything a green pull must be before it joins the merge queue
36 * (#2036): autonomous, open, unheld, green on its head, clear of the wall,
37 * reviewed, and not already told red on this head and base. The queue
38 * entry, or undefined when it does not join (and why is already done:
39 * a conflict sent to the crew, a pull closed as carried, a wall card).
40 */
41 export async function admit(
42 app: App,
43 repo: Repo,
44 pull: Pull,
45 now: Date = new Date(),
46 ): Promise<Result<Queued, Wait>> {
47 if (repo.autonomy !== "autonomous" || repo.autonomyBy === null) return err("off");
48 if (pull.state !== "open" || pull.mergedAt !== null) return err("closed");
49 // The caller's copy may predate a landing: the row says whether it is
50 // still open (#2017).
51 const row = getPull(app.db, repo.id, pull.number);
52 if (row === undefined || row.state !== "open" || row.mergedAt !== null)
53 return err("closed");
54 // A person said "not this one yet": nothing below happens until it is
55 // released — no landing, no review sent, no run to bring the branch up
56 // to date (`core/holds.ts`).
57 if (getHold(app.db, pull.id) !== undefined) return err("held");
58 // Only work the crew wrote, or a writer's, lands on green by itself: a
59 // reader's pull — from a fork, say — waits for a person, outsiders
60 // switch or not; not from here is it sent to the crew's reviewer (#619),
61 // only through `sendToReview` on an autonomous repository (#9575).
62 if (!landsOnItsOwn(app.db, repo, pull, now)) return err("outsider");
63 const by = getUserById(app.db, repo.autonomyBy);
64 if (!by) return err("off");
65 // The newest run of each kind is what the head says: a red that a re-run
66 // on the same commit has since turned green is history.
67 const checks = verdictForHead(app.db, pull.id, pull.headOid);
68 if (checks.length === 0) return err("unchecked");
69 if (checks.some((c) => c.state !== "ok")) return err("not-green");
70 // A stop the crew took on a red check ends with the green after it; a
71 // person's stop waits for a person.
72 const greenAt = checks
73 .map((c) => c.finishedAt ?? "")
74 .reduce((a, b) => (a > b ? a : b), "");
75 if (stopStands(latestDecision(app.db, pull.id, "retry"), greenAt))
76 return err("stopped");
77 // Conflicts first: a pull that no longer merges is the crew's to bring
78 // up to date, before anyone is asked whether it should land. A conflict
79 // is remembered by the two tips it was between: until one of them moves
80 // there is nothing new to try.
81 // Asked where the pull's objects are: a sealed one's own place (`pullDir`).
82 const dir = await pullDir(app.db, app.reposRoot, repo, pull);
83 const baseTip =
84 (await resolveOid(dir, `refs/heads/${pull.baseBranch}`)) ?? "";
85 const between = `${pull.headOid}:${baseTip}`;
86 if (conflicted.get(pull.id) === between) return err("conflict");
87 if (baseTip !== "") {
88 const clean = await mergeable(dir, baseTip, pull.headOid);
89 if (!clean.ok) {
90 if (clean.error.kind === "conflict") {
91 conflicted.set(pull.id, between);
92 // An approved one waits for the tick's finishing pass and its slot.
93 if (!approvedOnHead(app.db, pull)) bringUpToDate(app, repo, pull, clean.error.files);
94 }
95 return err("conflict");
96 }
97 // A merge of a followed source's head that leaves most of its diff
98 // behind marks the work taken without taking it (#9034): decided by a
99 // person, trusted or not, and before "nothing new" closes it as carried.
100 const dropped = await sourceHeld(app, repo, pull, baseTip);
101 if (dropped.length > 0) {
102 const earlier = latestDecision(app.db, pull.id, "land");
103 const told =
104 earlier?.answer === "wall" &&
105 (earlier.state as { head?: unknown } | null)?.head === pull.headOid;
106 if (!told)
107 recordDecision(app.db, {
108 kind: "land",
109 repoId: repo.id,
110 issueId: pull.id,
111 state: { head: pull.headOid, cells: dropped, plain: dropped, unsound: false },
112 answer: "wall",
113 p: 1,
114 by: "wall",
115 ms: 0,
116 });
117 return err("wall");
118 }
119 // Nothing the base does not already hold: no gate and no review, for
120 // there is nothing to land. The merge closes the pull as merged into
121 // the commit that carried it, and main does not move (#2017).
122 if (clean.value.treeOid === (await treeOf(dir, baseTip))) {
123 const closed = await mergePull(app, by, repo, pull, "squash");
124 log.info("already on the base, not landed again", {
125 repo: `${repo.ownerName}/${repo.name}`,
126 pull: pull.number,
127 closed: closed.ok,
128 });
129 return err("carried");
130 }
131 }
132 // A pull that loosens the contract is a change of policy, which is a
133 // wall: decided by a person, never crossed by the crew. The pull stays
134 // green and open, on the studio's cards, until someone lands it.
135 const wall = await wallOf(dir, baseTip, pull.headOid);
136 if (wall !== undefined) {
137 // Once per head, as a ledger row: it is what puts the card on the
138 // studio, and what the audit's third lens will read as a crossing.
139 const cells = wall.unsound ?? wall.loosened.map(wallSentence);
140 const earlier = latestDecision(app.db, pull.id, "land");
141 // Told once per head — and again if what the wall says about this head
142 // has changed, so the card never quotes cells the rule no longer counts.
143 const told =
144 earlier?.answer === "wall" &&
145 typeof earlier.state === "object" &&
146 earlier.state !== null &&
147 (earlier.state as { head?: unknown }).head === pull.headOid &&
148 JSON.stringify((earlier.state as { cells?: unknown }).cells) ===
149 JSON.stringify(cells);
150 if (!told) {
151 recordDecision(app.db, {
152 kind: "land",
153 repoId: repo.id,
154 issueId: pull.id,
155 state: {
156 head: pull.headOid,
157 cells,
158 plain: wall.unsound ?? wall.loosened.map(wallPlain),
159 unsound: wall.unsound !== undefined,
160 },
161 answer: "wall",
162 p: 1,
163 by: "wall",
164 ms: 0,
165 });
166 log.info("green; crosses the wall, left to a person", {
167 repo: `${repo.ownerName}/${repo.name}`,
168 pull: pull.number,
169 cells: cells.join("; "),
170 });
171 }
172 return err("wall");
173 }
174 // A trusted source's pull that touches secrets, credentials, permissions,
175 // the contract or release machinery waits for a person like a guest's.
176 const folded = await foldWall(app, repo, pull, baseTip, now);
177 if (folded.length > 0) {
178 const earlier = latestDecision(app.db, pull.id, "land");
179 const told =
180 earlier?.answer === "wall" &&
181 (earlier.state as { head?: unknown } | null)?.head === pull.headOid;
182 if (!told)
183 recordDecision(app.db, {
184 kind: "land",
185 repoId: repo.id,
186 issueId: pull.id,
187 state: { head: pull.headOid, cells: folded, plain: folded, unsound: false },
188 answer: "wall",
189 p: 1,
190 by: "wall",
191 ms: 0,
192 });
193 return err("wall");
194 }
195 // One gate for every pull, whoever wrote it: when the crew has a
196 // reviewer, a green head is queued for review and waits for an approval
197 // on that very head (a person's counts the same). A push is a new head,
198 // so it starts over. An agent's pull waits for that approval however
199 // long it takes — with no reviewer, or after one lapsed, a person's
200 // (#597). Only a person's own pull lands without a reviewer, or after a
201 // review lapsed.
202 const review = await reviewed(app, repo, pull, now);
203 if (review === "hold") return err("review");
204 // The full tier, once, on the queue's candidate (#1198, #2036). Red is
205 // told to the pull once per head and base, and the pull is out of the
206 // queue until a push — a base that moved is no new try, or a pull red on
207 // main rides every batch after each landing (#4235). A red the pull has
208 // not moved off is gated once more after REGATE_RED_MS, alone (the queue
209 // remembers it), so a red that was the machine's and not the code's does
210 // not hold it for good; a red that reproduces stays red (#3155).
211 const told = latestDecision(app.db, pull.id, "land");
212 if (redOf(told)?.head === pull.headOid && !regateDue(told!, Date.now())) return err("red");
213 // Green only against a base that has moved since is admitted as it is:
214 // the candidate's full gate runs on the base tip with this pull merged,
215 // which is the proof a re-check of its own would give, and a red one
216 // bisects out (#3316). Re-checking each first made the line serial — a
217 // landing staled every other pull, and each waited a check of its own.
218 return ok({
219 pull,
220 dir,
221 land: (expect) => landGated(app, repo, by, pull, review, expect),
222 // On the forge's own code, the landed tree is checked out and
223 // preflighted off to the side; the landing does not wait on it
224 // (#1662). Once per candidate, at the last step that landed: that is
225 // the tree main is at.
226 release: (tip) =>
227 void releaseOnLand(app, by, repo, pull, tip).catch((error) =>
228 log.warn("release checkout failed", {
229 pull: pull.number,
230 why: error instanceof Error ? error.message : String(error),
231 }),
232 ),
233 handBack: (red, baseOid, together) => {
234 // Told on the base it was found red on: a new base is a new try. Red
235 // again on the same head and base is the re-gate reproducing it: it
236 // stays red for good, and the pull is not told twice.
237 const at = `${pull.headOid}:${baseOid}`;
238 const again = redAt(latestDecision(app.db, pull.id, "land"), at);
239 const state: RedState = again ? { head: pull.headOid, at, again } : { head: pull.headOid, at };
240 recordDecision(app.db, {
241 kind: "land",
242 repoId: repo.id,
243 issueId: pull.id,
244 state,
245 answer: "red",
246 p: 1,
247 by: "rule",
248 ms: 0,
249 });
250 addLearned(app.config.dataDir, pull.id, red.learn);
251 if (!again) addComment(app, by, repo, getIssueById(app.db, pull.id) ?? pull, clashSaid(red.comment, together));
252 // A red that reproduces on the re-gate is the code's: only then is it the doctor's to hold.
253 if (again) treatRed(app, repo, by, pull, red, baseOid);
254 // Red only on top of pulls that landed first: no single culprit yet, so the class is recorded
255 // and the re-gate alone decides.
256 else noteRed(app, repo, pull, red, baseOid, together);
257 },
258 });
259 }
260
261 /**
262 * A red's comment, and when it was red on top of pulls of its candidate
263 * that landed first, a line naming them (#4235). The search does not gate
264 * the pull alone on the base before them, so it says both readings.
265 */
266 function clashSaid(comment: string, together: readonly number[]): string {
267 if (together.length === 0) return comment;
268 const names = together.map((n) => `#${n}`).join(", ");
269 return `${comment}\n\nRed on top of ${names}, which landed first from the same merge-queue candidate: red on its own on that base, or only together with them. Bring this pull up to date with the base and push.`;
270 }
src/crew/land_gated.ts added +159
@@ -0,0 +1,159 @@
1 /** Landing one gated step of the queue's candidate, and how: merge or squash. */
2
3 import type { AccessError } from "../actions/access.ts";
4 import { addComment } from "../actions/issues.ts";
5 import { mergePull } from "../actions/pulls.ts";
6 import { carriesUpstream } from "../actions/upstream_follow.ts";
7 import type { App } from "../app.ts";
8 import { latestDecision, recordDecision, resolveOpen } from "../core/decisions.ts";
9 import { getIssue, getIssueById } from "../core/issues.ts";
10 import { closesFromBody, getPull, type MergePullError, type Pull, pullDir } from "../core/pulls.ts";
11 import type { Repo } from "../core/repos.ts";
12 import { foldsIn } from "../core/trusted_sources.ts";
13 import type { User } from "../core/users.ts";
14 import { createLog } from "../kernel/log.ts";
15 import { bringUpToDate } from "./conflict_release.ts";
16 import { conflicted } from "./conflicted_tips.ts";
17 import { sayFirstLanded } from "./first_change.ts";
18 import { guardedList } from "./stranger.ts";
19
20 const log = createLog("autonomy");
21
22 /** A merge refusal in words a log can carry. */
23 function mergeWhy(error: AccessError | MergePullError): string {
24 if (typeof error === "string") return error;
25 switch (error.kind) {
26 case "conflict":
27 return `conflict: ${error.files.join(", ")}`;
28 case "git":
29 return `git: ${error.message}`;
30 case "guarded":
31 return `guarded: ${guardedList(error.paths)}`;
32 default:
33 return error.kind;
34 }
35 }
36
37 /**
38 * How a green pull lands. One carrying upstream's commits lands as a merge:
39 * squashed, their history would never be ours and the next check would
40 * count it again. Every other pull squashes.
41 */
42 export async function landingStrategy(
43 app: App,
44 repo: Repo,
45 pull: Pull,
46 baseOid: string,
47 now: Date = new Date(),
48 ): Promise<"merge" | "squash"> {
49 // A trusted source's work lands as a true merge: its commits stay
50 // ancestors of main and each author keeps their name (#8937).
51 if (foldsIn(app.db, pull.id, now)) return "merge";
52 return (await carriesUpstream(
53 app,
54 repo,
55 await pullDir(app.db, app.reposRoot, repo, pull),
56 pull.headOid,
57 baseOid,
58 ))
59 ? "merge"
60 : "squash";
61 }
62
63 /**
64 * Land one gated step of the queue's candidate: only onto the base it was
65 * built on, and only as the tree that was gated (`expect`). The new tip of
66 * the base, or undefined when it did not land.
67 */
68 export async function landGated(
69 app: App,
70 repo: Repo,
71 by: User,
72 pull: Pull,
73 review: "pass" | "lapsed" | "first",
74 expect: { baseOid: string; treeOid: string },
75 ): Promise<string | undefined> {
76 // The gate took minutes: the pull it was run on must still be the one
77 // here — open, unmerged, at the same head — or another landing, or a
78 // push, came first and this verdict is about nothing.
79 const still = getPull(app.db, repo.id, pull.number);
80 if (
81 still === undefined ||
82 still.state !== "open" ||
83 still.mergedAt !== null ||
84 still.headOid !== pull.headOid
85 )
86 return undefined;
87 // Green and clear of the wall lands. An autonomous repository does not
88 // wait on a person; the ledger keeps the landing as the rule it is, once
89 // per head, so the week's numbers still add up.
90 const already = latestDecision(app.db, pull.id, "land");
91 if (
92 !(
93 already?.answer === "ship" &&
94 typeof already.state === "object" &&
95 already.state !== null &&
96 (already.state as { head?: unknown }).head === pull.headOid
97 )
98 )
99 recordDecision(app.db, {
100 kind: "land",
101 repoId: repo.id,
102 issueId: pull.id,
103 state:
104 review === "lapsed"
105 ? { head: pull.headOid, review: "lapsed" }
106 : { head: pull.headOid },
107 answer: "ship",
108 p: 1,
109 by: "rule",
110 ms: 0,
111 });
112 const strategy = await landingStrategy(app, repo, pull, expect.baseOid);
113 const pastReviews = review === "first" || review === "lapsed";
114 const merged = await mergePull(app, by, repo, pull, strategy, expect, pastReviews ? { pastReviews: true } : {});
115 if (!merged.ok) {
116 const why = mergeWhy(merged.error);
117 log.info("green but not landed", {
118 repo: `${repo.ownerName}/${repo.name}`,
119 pull: pull.number,
120 why,
121 });
122 // Main moved under a green pull: that is the agent's to fix, once per
123 // move, and never past the same limit a red check gets.
124 if (typeof merged.error !== "string" && merged.error.kind === "conflict") {
125 conflicted.set(pull.id, `${pull.headOid}:${expect.baseOid}`);
126 bringUpToDate(app, repo, pull, merged.error.files);
127 }
128 return undefined;
129 }
130 conflicted.delete(pull.id);
131 // Closed as merged into what already carried it: main did not move, so
132 // there is no release to cut and nothing new was landed.
133 if (merged.value.carried) return undefined;
134 resolveOpen(app.db, pull.id, "land", "shipped");
135 // The app's first change: one sentence on the pull, and the reviewer's requests as one follow-up.
136 if (review === "first") sayFirstLanded(app, repo, pull, by);
137 // Said once it has landed, so the note wakes no builder: the review was
138 // asked for and never came.
139 if (review === "lapsed") {
140 const landed = getIssueById(app.db, pull.id);
141 if (landed)
142 addComment(
143 app,
144 by,
145 repo,
146 landed,
147 "Landed on green without a review: the crew's reviewer was asked twice and posted no verdict.",
148 );
149 }
150 for (const number of closesFromBody(pull.body)) {
151 const closed = getIssue(app.db, repo.id, number);
152 if (closed) resolveOpen(app.db, closed.id, "next", "shipped");
153 }
154 log.info("landed on green", {
155 repo: `${repo.ownerName}/${repo.name}`,
156 pull: pull.number,
157 });
158 return merged.value.mergeOid;
159 }
src/crew/land_queue.ts added +60
@@ -0,0 +1,60 @@
1 /** Landing a green pull through the merge queue: its options and its gate. */
2
3 import type { App } from "../app.ts";
4 import { recordQueueFlakes } from "../checks/flake.ts";
5 import { adoptGate, gateCandidate } from "../checks/landing.ts";
6 import { queueStore } from "../checks/queue_store.ts";
7 import { enqueue, type GateCandidate, type QueueOptions } from "../checks/queue.ts";
8 import { checksFor } from "../checks/service.ts";
9 import { queueBatch, queueDepth } from "../core/capacity.ts";
10 import type { Pull } from "../core/pulls.ts";
11 import { getRepoById, type Repo } from "../core/repos.ts";
12 import { keepVerdict } from "../flow/culprits.ts";
13 import { keepBatch } from "../flow/red_batches.ts";
14 import { admit } from "./land_admit.ts";
15
16 /**
17 * Ship on green. An open pull whose head has a passing check and a passing
18 * deploy, and nothing failed, lands as the person who turned autonomy on —
19 * with their review and check requirements still enforced inside the
20 * merge. Only in `autonomous`; `assisted` leaves every green pull for a
21 * look.
22 */
23 export async function landIfGreen(
24 app: App,
25 repo: Repo,
26 pull: Pull,
27 ): Promise<boolean> {
28 const admitted = await admit(app, repo, pull);
29 if (!admitted.ok) return false;
30 const [landed] = await enqueue(repo.id, [admitted.value], gateFor(app, repo), queueOptions(app, repo));
31 return landed === true;
32 }
33
34 /**
35 * How the merge queue may use the forge's check slots (#4053): its depth and
36 * batch size as an admin set them, and the slots the checks service has spare. Each judged
37 * batch is kept for the red-batch rate (#6427); its gates and red marks are
38 * kept in the database, and a gate a roll left running adopted (#6611).
39 */
40 export function queueOptions(app: App, repo: Repo): QueueOptions {
41 return {
42 depth: queueDepth(app.db),
43 batch: queueBatch(app.db),
44 room: () => checksFor(app)?.spareSlots?.() ?? 0,
45 onBatch: (repoId, red) => keepBatch(app.db, repoId, red),
46 onVerdict: (repoId, verdict) => keepVerdict(app.db, repoId, verdict),
47 onFlake: (repoId, reds, tip) => {
48 const owner = getRepoById(app.db, repoId);
49 if (owner !== undefined) recordQueueFlakes(app.db, app.bus, owner, reds, tip);
50 },
51 store: queueStore(app.db),
52 adopt: (record, signal) => adoptGate(app, repo, record, signal),
53 };
54 }
55
56 /** The queue's gate: the full tier on the candidate's tip, asked as its first pull. */
57 export function gateFor(app: App, repo: Repo): GateCandidate {
58 return (candidate, signal) =>
59 gateCandidate(app, repo, candidate.steps[0]!.entry.pull, candidate.dir, candidate.tipOid, signal);
60 }
src/crew/last_week.ts added +23
@@ -0,0 +1,23 @@
1 /** The last week of a repository as the dataset holds it, for the planner's brief. */
2
3 import type { App } from "../app.ts";
4 import { weekDigest, weekLines } from "../core/dataset.ts";
5 import type { Repo } from "../core/repos.ts";
6 import { createLog } from "../kernel/log.ts";
7
8 const log = createLog("autonomy");
9
10 /**
11 * The last week of this repository as the dataset holds it (`core/dataset.ts`):
12 * what landed, what parked, what it cost, which checks failed. The lines a
13 * planner is given before it plans, so the wave it proposes can answer them.
14 * A repository the dataset cannot read yields nothing, and plans as it did.
15 */
16 export function lastWeekFor(app: App, repo: Repo, now = new Date()): string[] {
17 try {
18 return weekLines(weekDigest(app.db, repo.id, now));
19 } catch (e) {
20 log.warn("last week unreadable", { repo: `${repo.ownerName}/${repo.name}`, error: String(e) });
21 return [];
22 }
23 }
src/crew/next_pick.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * Which ready issue next: the retired ones noted, then the top of the list or the decider's choice.
3 */
4
5 import type { App } from "../app.ts";
6 import type { Ranked } from "../core/dependencies.ts";
7 import { alreadyDone } from "../core/done_on_main.ts";
8 import type { Repo } from "../core/repos.ts";
9 import { repoDir } from "../git/repos.ts";
10 import { certain } from "./decide.ts";
11 import { markReaders } from "./direct.ts";
12 import { decideAndRecord } from "./ledger.ts";
13 import { removedBy, retiredNames } from "./retired.ts";
14 import { noteAlreadyDone } from "./settle_run.ts";
15 import type { Database } from "bun:sqlite";
16
17 /**
18 * Which ready issue next. The rule takes the top of the ready list (the
19 * critical path); the decider, when there is one, chooses among the first
20 * few with the direction in hand. Recorded, so a pick can be judged later.
21 */
22 /**
23 * The ready issues as the next-issue decider reads them: a reader's words
24 * carry the brief's mark here too (`markReaders`), though it can only pick
25 * a number.
26 */
27 export function readyState(
28 db: Database,
29 repo: Repo,
30 few: readonly Ranked[],
31 ): Record<string, unknown>[] {
32 return markReaders(
33 db,
34 repo,
35 few.map((r) => r.issue),
36 ).map((issue, n) =>
37 // A sealed report's words never leave the forge for a decider
38 // (`core/sealed.ts`): it is a number, and that it is sealed.
39 issue.sealed
40 ? { number: issue.number, sealed: true, holdsUp: few[n]!.holdsUp }
41 : {
42 number: issue.number,
43 title: issue.title,
44 body: issue.body.slice(0, 400),
45 holdsUp: few[n]!.holdsUp,
46 ...(issue.untrusted === undefined
47 ? {}
48 : { untrusted: issue.untrusted }),
49 },
50 );
51 }
52
53 /**
54 * The ready issues, less those that retire names already gone from the base
55 * (`retired.ts`): each gets the already-done note, once, and is not handed out.
56 */
57 export async function withoutRetired(
58 app: App,
59 repo: Repo,
60 ready: readonly Ranked[],
61 ): Promise<Ranked[]> {
62 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
63 const kept: Ranked[] = [];
64 for (const r of ready) {
65 const names = retiredNames(r.issue);
66 if (names.length === 0) {
67 kept.push(r);
68 continue;
69 }
70 const oids = await removedBy(dir, repo.defaultBranch, names);
71 if (oids.length === 0) {
72 kept.push(r);
73 continue;
74 }
75 if (!alreadyDone(app.db, [r.issue.id]).has(r.issue.id))
76 noteAlreadyDone(app, repo, r.issue, oids);
77 }
78 return kept;
79 }
80
81 export async function nextOf(
82 app: App,
83 repo: Repo,
84 ready: readonly Ranked[],
85 ): Promise<Ranked | undefined> {
86 const first = ready[0];
87 if (first === undefined) return undefined;
88 if (ready.length === 1 || app.config.decider === undefined) return first;
89 const few = ready.slice(0, 6);
90 const options = few.map((r) => String(r.issue.number));
91 const describe: Record<string, string> = {};
92 for (const r of few)
93 describe[String(r.issue.number)] =
94 `#${r.issue.number} ${r.issue.sealed ? "(sealed)" : r.issue.title}` +
95 (r.holdsUp > 0 ? ` (holds up ${r.holdsUp})` : "");
96 const decided = await decideAndRecord(
97 app,
98 { kind: "next", repo, issue: first.issue },
99 {
100 direction: repo.autonomyDirection,
101 ready: readyState(app.db, repo, few),
102 },
103 {
104 next: {
105 options,
106 about:
107 "Which of these ready issues moves the direction forward most right now? Prefer what unblocks others and what the direction names.",
108 describe,
109 },
110 },
111 () => ({ next: certain(options, options[0]!) }),
112 );
113 return (
114 few.find((r) => String(r.issue.number) === decided.answers.next.choice) ??
115 first
116 );
117 }
src/crew/not_startable.ts +1 −1
@@ -12,7 +12,7 @@ import type { Repo } from "../core/repos.ts";
1212 import { listActive } from "../core/runs.ts";
1313 import { listCrewRoles } from "../core/agents.ts";
1414 import { openOrder, type OpenOrder } from "../core/chapters.ts";
15 import { slottedRuns } from "./autonomy.ts";
15 import { slottedRuns } from "./autonomy_status.ts";
1616 import { PASSED_WORDS, pickFilter, routable } from "./pick_filter.ts";
1717 import { admits, heldBy, mapHolds } from "./held.ts";
1818
src/crew/park_issue.ts added +84
@@ -0,0 +1,84 @@
1 /** Parking an issue: the note with the reason, the assignee cleared, the strike counted. */
2
3 import { addComment, assignIssue } from "../actions/issues.ts";
4 import type { App } from "../app.ts";
5 import type { Agent } from "../core/agents.ts";
6 import { type Issue, listComments } from "../core/issues.ts";
7 import type { Repo } from "../core/repos.ts";
8 import { getUserById, type User } from "../core/users.ts";
9 import { createLog } from "../kernel/log.ts";
10 import { BREAKER_NOTE } from "./breaker.ts";
11 import { strikeNote } from "./park_pull.ts";
12 import { parkedCount as countParks } from "./parks.ts";
13 import { REPEAT_NOTE } from "./repeat_note.ts";
14
15 const log = createLog("autonomy");
16
17 /**
18 * The breaker trips: the assignment is cleared and one note says why, once.
19 * The map reads the note as `parked`; the asks list it for a person.
20 */
21 export function parkForBreaker(
22 app: App,
23 repo: Repo,
24 issue: Issue,
25 agent: Agent,
26 note: string = BREAKER_NOTE,
27 ): boolean {
28 const author =
29 (repo.autonomyBy === null ? undefined : getUserById(app.db, repo.autonomyBy)) ??
30 agent.user;
31 if (issue.assigneeId !== null) assignIssue(app, author, repo, issue, null);
32 const last = listComments(app.db, issue.id).at(-1);
33 if (last?.body === note) return false;
34 addComment(app, author, repo, issue, note);
35 log.info(note === BREAKER_NOTE ? "parked by the breaker" : note === REPEAT_NOTE ? "parked by the repeat stop" : "parked at the run cap", {
36 repo: `${repo.ownerName}/${repo.name}`,
37 issue: issue.number,
38 });
39 return true;
40 }
41
42 /**
43 * How many times the crew has parked this issue since a person who directs it last spoke
44 * (`parks.ts`).
45 */
46 export function parkedCount(app: App, repo: Repo, issueId: string): number {
47 return countParks(app.db, repo, issueId);
48 }
49
50 /**
51 * Park an issue: a note with the reason and the assignee cleared, so the
52 * planner rewrites it on its next pass and the crew tries it fresh once.
53 */
54 export function parkIssue(
55 app: App,
56 repo: Repo,
57 issue: Issue,
58 why: string,
59 ): boolean {
60 if (repo.autonomy !== "autonomous" || repo.autonomyBy === null) return false;
61 const by = getUserById(app.db, repo.autonomyBy);
62 if (!by) return false;
63 return parkAs(app, by, repo, issue, why, "parked");
64 }
65
66 /** Park `issue` in `by`'s name: the strike note, the assignee cleared, and `said` in the log. */
67 export function parkAs(
68 app: App,
69 by: User,
70 repo: Repo,
71 issue: Issue,
72 why: string,
73 said: string,
74 ): boolean {
75 if (issue.state !== "open") return false;
76 if (issue.assigneeId !== null) assignIssue(app, by, repo, issue, null);
77 addComment(app, by, repo, issue, strikeNote(app.db, repo, issue, why));
78 log.info(said, {
79 repo: `${repo.ownerName}/${repo.name}`,
80 issue: issue.number,
81 why,
82 });
83 return true;
84 }
src/crew/park_pull.ts +1 −1
@@ -1,6 +1,6 @@
11 /**
22 * Parking a pull the crew cannot finish, and the note a park leaves. Its own
3 * module so `autonomy.ts` and the stale-red sweep both reach it without
3 * module so `settle_run.ts` and the stale-red sweep both reach it without
44 * importing each other.
55 */
66
src/crew/plan_owed.ts added +205
@@ -0,0 +1,205 @@
1 /** Whether the planner is owed a pass, and asking for it by assigning it the direction issue. */
2
3 import { assignIssue, splitPending } from "../actions/issues.ts";
4 import type { App } from "../app.ts";
5 import type { Agent, CrewRole } from "../core/agents.ts";
6 import { CREW_OFF_WORDS, crewBuildsHere } from "../core/crew_switch.ts";
7 import { getIssueById } from "../core/issues.ts";
8 import { given, pendingReplans } from "../core/limb_replan.ts";
9 import { ceilingHold, pausedUntil, pauseSentence } from "../core/planner_pause.ts";
10 import type { Repo } from "../core/repos.ts";
11 import type { Run } from "../core/runs.ts";
12 import type { User } from "../core/users.ts";
13 import { createLog } from "../kernel/log.ts";
14 import { breakerTripped } from "./breaker.ts";
15 import { ensureDirectionIssue } from "./direction_issue.ts";
16 import { handedOverPulls, skipsReplan } from "./guard.ts";
17 import { parkedTwice } from "./parks.ts";
18 import { declinedUnanswered } from "./planner_decline.ts";
19 import { holdWhy, plannerHold } from "./planner_hold.ts";
20 import { ensurePlanner } from "./planner.ts";
21 import { redThricePulls } from "./red_thrice.ts";
22 import { reserveOf, reserveWords } from "./reserve.ts";
23 import { handedTooLarge } from "./too_large.ts";
24
25 const log = createLog("autonomy");
26
27 /**
28 * How soon a planner whose last pass did not end well — a decline a person
29 * answered, a failure — is asked again. A pass that ended well has no
30 * floor: while the reserve is short the planner is asked again as soon as
31 * the map moves, and a pass with nothing new is held by `plannerNothingNew`.
32 */
33 const REPLAN_AFTER_MS = 20 * 60_000;
34
35 /**
36 * Give the planner the direction when the reserve is due a pass — down to
37 * half of two startable issues per builder slot (`reserve.ts`) — or when the crew has handed it an
38 * issue it parked twice, and no planning run is in flight, and the last one is old enough. Returns
39 * whether a planning run was set up. Planning runs alongside building: the builders are never
40 * waited for.
41 *
42 * A hand-over is owed one pass, not one a minute: it asks only while it is
43 * newer than the last planning run. That one pass is owed even by a planner
44 * that declined the direction — the decline answered the direction, and
45 * this is something it has not seen. What the pass leaves as it was stays
46 * on the board and in every later brief (`parks.ts`).
47 */
48 function notPlanned(repo: Repo, why: string): false {
49 log.info("planner not asked", {
50 repo: `${repo.ownerName}/${repo.name}`,
51 why,
52 });
53 return false;
54 }
55
56 function plannerHeld(repo: Repo, why: string): false {
57 log.info("tick", {
58 repo: `${repo.ownerName}/${repo.name}`,
59 planner: "held",
60 why,
61 });
62 return false;
63 }
64
65 /**
66 * Give the planner the direction when the reserve is due a pass — down to
67 * half of two startable issues per builder slot (`reserve.ts`) — or when the crew has handed it an
68 * issue it parked twice, and no planning run is in flight, and the last one is old enough. Returns
69 * whether a planning run was set up. Planning runs alongside building: the builders are never
70 * waited for.
71 *
72 * A hand-over is owed one pass, not one a minute: it asks only while it is
73 * newer than the last planning run. That one pass is owed even by a planner
74 * that declined the direction — the decline answered the direction, and
75 * this is something it has not seen. What the pass leaves as it was stays
76 * on the board and in every later brief (`parks.ts`).
77 */
78
79 export async function planIfOwed(
80 app: App,
81 repo: Repo,
82 by: User,
83 crew: readonly { agent: Agent; role: CrewRole }[],
84 active: readonly Run[],
85 ready: number,
86 now: Date,
87 ): Promise<boolean> {
88 // The direction is the planner's own issue: a park on it (the breaker's, for runs that repeat)
89 // hands the planner nothing it has not read, so it owes no pass. Counted, each park bought
90 // another empty pass, which bought another park.
91 const handed = [
92 ...parkedTwice(app.db, [repo]),
93 ...handedTooLarge(app.db, repo),
94 ...handedOverPulls(app.db, repo),
95 ...redThricePulls(app.db, repo),
96 ].filter(
97 (h) => h.issueId !== repo.directionIssueId,
98 );
99 const limbs = pendingReplans(app.db, repo);
100 const reserve = reserveOf(ready, repo.autonomySlots);
101 // A repository with no direction issue yet is owed its first pass; after that only a word
102 // or an edit on the direction (`plannerNothingNew`), a hand-over or a limb is.
103 let worded = true;
104 if (repo.directionIssueId !== null) {
105 const seat = crew.find((c) => c.role === "planner")?.agent;
106 const issue = getIssueById(app.db, repo.directionIssueId);
107 const since = app.db
108 .query<{ at: string }, [string]>(
109 `SELECT created_at AS at FROM run WHERE issue_id = ?1 AND kind = 'agent' ORDER BY created_at DESC LIMIT 1`,
110 )
111 .get(repo.directionIssueId)?.at;
112 worded = seat !== undefined && issue !== undefined && !skipsReplan(app.db, repo, issue, seat, since ?? "");
113 }
114 if (!worded && handed.length === 0 && limbs.length === 0) return false;
115 // Paused by its pillar's setting (#7668): the planner stays on the crew.
116 if (repo.plannerSlots === 0) return notPlanned(repo, "the planner is paused");
117 if (repo.autonomyDirection.trim() === "")
118 return notPlanned(repo, "no direction written");
119 // A direction with no planner would go nowhere; the forge lends one (#7637).
120 const planner =
121 crew.find((c) => c.role === "planner")?.agent ?? ensurePlanner(app, repo, by);
122 if (planner === undefined) return notPlanned(repo, "no planner on the crew");
123 const direction = ensureDirectionIssue(app, by, repo);
124 if (!direction) return notPlanned(repo, "no direction issue");
125 if (active.some((r) => r.issueId === direction.id))
126 return notPlanned(repo, "a planning run is in flight");
127 const lastPlan = app.db
128 .query<{ state: string; created_at: string }, [string]>(
129 `SELECT state, created_at FROM run WHERE issue_id = ?1 AND kind = 'agent'
130 ORDER BY created_at DESC LIMIT 1`,
131 )
132 .get(direction.id);
133 if (breakerTripped(app.db, repo, direction.id, now))
134 return notPlanned(repo, "parked: three failed runs in an hour");
135 // The hand-overs the planner has not been given: newer than its last pass.
136 const seen = lastPlan?.created_at ?? "";
137 const owed = handed.filter((issue) => issue.at > seen);
138 // A limb a person handed over is owed one pass, whatever the map and
139 // whatever the planner said of the direction before (#761).
140 const limbsOwed = limbs.filter((r) => !given(app.db, repo, r.at));
141 if (!worded && owed.length === 0 && limbsOwed.length === 0) return false;
142 // The direction is the planner's standing issue, not one issue retried:
143 // no run count bounds it. The budget does, the breaker, and a pass that
144 // would plan the same input twice is skipped (`plannerNothingNew`).
145 // An issue the crew handed over is owed its pass whatever the hold: the
146 // planner splitting it is how work starts landing again.
147 // The owner's switch and ceiling stop the planner's run where it is queued (`dispatch.ts`). The
148 // tick says which one holds it, and gives the planner nothing the dispatcher would refuse.
149 if (!crewBuildsHere(app.db, repo.id)) return notPlanned(repo, CREW_OFF_WORDS);
150 const until = pausedUntil(app.db, repo.id, now);
151 if (until !== null) return notPlanned(repo, pauseSentence(until));
152 const ceiling = splitPending(app, repo) ? null : ceilingHold(app.db, repo.id);
153 if (ceiling !== null) return notPlanned(repo, ceiling);
154 const hold = owed.length + limbsOwed.length === 0 ? plannerHold(app, repo, now) : null;
155 if (hold !== null) return plannerHeld(repo, holdWhy(hold));
156 if (lastPlan !== null && lastPlan !== undefined) {
157 // A planner that declined the direction is not asked again until a
158 // person has said something on it, or the crew hands it an issue.
159 if (
160 owed.length + limbsOwed.length === 0 &&
161 lastPlan.state === "failed" &&
162 declinedUnanswered(app, repo, direction)
163 )
164 return notPlanned(repo, "the planner declined; waiting for a person");
165 if (lastPlan.state === "queued" || lastPlan.state === "running")
166 return notPlanned(repo, "a planning run is in flight");
167 // Only a pass that did not end well waits out the floor; a person's
168 // hand-over never does.
169 if (
170 limbsOwed.length === 0 &&
171 lastPlan.state !== "ok" &&
172 now.getTime() - new Date(lastPlan.created_at).getTime() <
173 REPLAN_AFTER_MS
174 )
175 return notPlanned(repo, "planned recently");
176 } else if (direction.assigneeId === planner.user.id) {
177 return notPlanned(repo, "the planner already holds the direction");
178 }
179 if (direction.assigneeId !== null) {
180 const cleared = assignIssue(app, by, repo, direction, null);
181 if (!cleared.ok)
182 return notPlanned(repo, `could not clear: ${String(cleared.error)}`);
183 }
184 const current = getIssueById(app.db, direction.id) ?? direction;
185 const assigned = assignIssue(app, by, repo, current, planner.user);
186 if (!assigned.ok)
187 return notPlanned(repo, `could not assign: ${String(assigned.error)}`);
188 log.info(
189 limbsOwed.length > 0
190 ? "a limb was handed over; planner asked"
191 : owed.length > 0
192 ? "parked twice; planner asked"
193 : "a person's direction; planner asked",
194 {
195 repo: `${repo.ownerName}/${repo.name}`,
196 planner: planner.user.username,
197 ready,
198 reserve: reserveWords(reserve),
199 ...(owed.length > 0
200 ? { parkedTwice: owed.map((issue) => `#${issue.number}`).join(" ") }
201 : {}),
202 },
203 );
204 return true;
205 }
src/crew/planner_decline.ts added +83
@@ -0,0 +1,83 @@
1 /** A planner's decline of the direction that no person has answered yet. */
2
3 import type { App } from "../app.ts";
4 import { BY_CREW, DONE_LIKE } from "../core/done_on_main.ts";
5 import { getIssueById, type Issue } from "../core/issues.ts";
6 import type { Repo } from "../core/repos.ts";
7 import { directorsAmong } from "./direct.ts";
8 import type { Database } from "bun:sqlite";
9
10 /** Whether the newest run on the issue was a decline and no person has spoken since. */
11 export function declinedUnanswered(app: App, repo: Repo, issue: Issue): boolean {
12 return declineOf(app.db, repo, issue.id) !== undefined;
13 }
14
15 /** A planner's decline that nobody has answered yet. */
16 export interface PlannerDecline {
17 readonly repo: Repo;
18 /** The direction issue the planner declined. */
19 readonly issue: Issue;
20 /** The declining run: a new decline is a new id, so it pages once. */
21 readonly runId: string;
22 /** What the planner said, without the `declined:` mark. */
23 readonly words: string;
24 readonly at: string;
25 }
26
27 /**
28 * The newest agent run on an issue, when it is a decline no person who
29 * may direct the crew has answered since: the state `planIfThin` waits in.
30 * A reader's comment is no answer (#619).
31 */
32 function declineOf(
33 db: Database,
34 repo: Repo,
35 issueId: string,
36 ): { id: string; summary: string; created_at: string } | undefined {
37 const last = db
38 .query<{ id: string; state: string; summary: string; created_at: string }, [string]>(
39 `SELECT id, state, summary, created_at FROM run WHERE issue_id = ?1 AND kind = 'agent'
40 ORDER BY created_at DESC LIMIT 1`,
41 )
42 .get(issueId);
43 if (!last || last.state !== "failed" || !last.summary.startsWith("declined"))
44 return undefined;
45 const spoke = db
46 .query<{ id: string }, [string, string]>(
47 `SELECT DISTINCT n.author_id AS id FROM comment n
48 WHERE n.issue_id = ?1 AND n.created_at > ?2 AND n.origin_author IS NULL
49 AND n.body NOT LIKE 'Parked by the crew%'
50 AND NOT (n.body LIKE '${DONE_LIKE}' AND ${BY_CREW})`,
51 )
52 .all(issueId, last.created_at)
53 .map((r) => r.id);
54 return directorsAmong(db, repo, spoke).length === 0 ? last : undefined;
55 }
56
57 /**
58 * The autonomous repositories among these whose planner declined the
59 * direction and waits for a person: the board's line, the asks, the phone.
60 * One small read per repository that has a direction issue.
61 */
62 export function plannerDeclines(
63 db: Database,
64 repos: readonly Repo[],
65 ): PlannerDecline[] {
66 const out: PlannerDecline[] = [];
67 for (const repo of repos) {
68 if (repo.autonomy !== "autonomous" || repo.directionIssueId === null)
69 continue;
70 const issue = getIssueById(db, repo.directionIssueId);
71 if (!issue || issue.state !== "open") continue;
72 const run = declineOf(db, repo, issue.id);
73 if (run === undefined) continue;
74 out.push({
75 repo,
76 issue,
77 runId: run.id,
78 words: run.summary.replace(/^declined:?\s*/, ""),
79 at: run.created_at,
80 });
81 }
82 return out;
83 }
src/crew/planner_hold.ts added +95
@@ -0,0 +1,95 @@
1 /** Whether the planner is held for a repository: nothing landing, or the plate full. */
2
3 import type { App } from "../app.ts";
4 import { readyNow, repoGraph } from "../core/dependencies.ts";
5 import { canWrite, type Repo } from "../core/repos.ts";
6 import { getUserById } from "../core/users.ts";
7
8 /** Nothing landing for this long, with a pull closed unmerged, holds the planner. */
9 const LANDING_WINDOW_MS = 48 * 60 * 60_000;
10 /** More ready, unassigned issues than slots × this fill the plate. */
11 const PLATE_PER_SLOT = 3;
12
13 export type PlannerHold =
14 | { readonly kind: "nothing landed"; readonly since: string }
15 | { readonly kind: "plate full"; readonly ready: number };
16
17 /** Why a hold is held, as the tick log says it. */
18 export function holdWhy(hold: PlannerHold): string {
19 return hold.kind === "plate full"
20 ? `plate full (${hold.ready} ready)`
21 : `nothing landed since ${hold.since.slice(0, 10)}`;
22 }
23
24 /** The same reason in plain words, for the board. */
25 export function holdWords(hold: PlannerHold): string {
26 if (hold.kind === "plate full")
27 return `Planning paused: ${hold.ready} issues are ready and waiting`;
28 const at = new Date(hold.since);
29 const day = at.toLocaleDateString("en-US", {
30 month: "short",
31 day: "numeric",
32 timeZone: "UTC",
33 });
34 return `Planning paused: nothing has landed since ${day}`;
35 }
36
37 /**
38 * A word on the direction issue from someone who may write here, newer than
39 * the planner's last pass: the owner steering, which is never held.
40 */
41 function steered(app: App, repo: Repo): boolean {
42 if (repo.directionIssueId === null) return false;
43 const last = app.db
44 .query<{ created_at: string }, [string]>(
45 `SELECT created_at FROM run WHERE issue_id = ?1 AND kind = 'agent'
46 ORDER BY created_at DESC LIMIT 1`,
47 )
48 .get(repo.directionIssueId);
49 return app.db
50 .query<{ id: string }, [string, string]>(
51 `SELECT DISTINCT author_id AS id FROM comment
52 WHERE issue_id = ?1 AND created_at > ?2 AND origin_author IS NULL`,
53 )
54 .all(repo.directionIssueId, last?.created_at ?? "")
55 .some((r) => {
56 const who = getUserById(app.db, r.id);
57 return who !== undefined && who.kind !== "agent" && canWrite(app.db, repo, who);
58 });
59 }
60
61 /**
62 * Whether the planner is held for this repository: no pull merged in 48 h
63 * while one closed unmerged, or more ready, unassigned issues than
64 * `slots × 3`. A steer from a writer on the direction issue lifts it.
65 */
66 export function plannerHold(
67 app: App,
68 repo: Repo,
69 now = new Date(),
70 ): PlannerHold | null {
71 if (steered(app, repo)) return null;
72 const cutoff = new Date(now.getTime() - LANDING_WINDOW_MS).toISOString();
73 const merged = app.db
74 .query<{ at: string | null }, [string]>(
75 `SELECT MAX(p.merged_at) AS at FROM pull p JOIN issue i ON i.id = p.issue_id
76 WHERE i.repo_id = ?1`,
77 )
78 .get(repo.id)?.at ?? null;
79 if (merged === null || merged < cutoff) {
80 const refused = app.db
81 .query<{ n: number }, [string, string]>(
82 `SELECT COUNT(*) AS n FROM issue i JOIN pull p ON p.issue_id = i.id
83 WHERE i.repo_id = ?1 AND i.kind = 'pull' AND i.state = 'closed'
84 AND p.merged_at IS NULL AND i.closed_at >= ?2`,
85 )
86 .get(repo.id, cutoff)?.n ?? 0;
87 if (refused > 0) return { kind: "nothing landed", since: merged ?? cutoff };
88 }
89 const ready = readyNow(repoGraph(app.db, repo.id, { sealed: true })).filter(
90 (r) => r.issue.id !== repo.directionIssueId && r.issue.assigneeId === null,
91 ).length;
92 if (ready > Math.max(1, repo.autonomySlots) * PLATE_PER_SLOT)
93 return { kind: "plate full", ready };
94 return null;
95 }
src/crew/regate.ts added +37
@@ -0,0 +1,37 @@
1 /** A red the merge queue told, and when it is gated once more. */
2
3 import type { Decision } from "../core/decisions.ts";
4
5 /** How long a red the pull has not moved off waits before it is gated once more (#3155). */
6 export const REGATE_RED_MS = 30 * 60_000;
7
8 /**
9 * What a `red` land decision holds: the head it was red on, `head:base`
10 * as `at`, and `again` when it is the re-gate that reproduced it.
11 */
12 export interface RedState {
13 readonly head: string;
14 readonly at: string;
15 readonly again?: true;
16 }
17
18 /** The red a land decision tells, read off the ledger's untyped state; undefined for any other. */
19 export function redOf(told: Decision | undefined): RedState | undefined {
20 if (told?.answer !== "red") return undefined;
21 const state = told.state;
22 if (typeof state !== "object" || state === null) return undefined;
23 const { head, at, again } = state as Record<string, unknown>;
24 if (typeof head !== "string" || typeof at !== "string") return undefined;
25 return again === true ? { head, at, again } : { head, at };
26 }
27
28 /** `told` is a red on this `head:base`. */
29 export function redAt(told: Decision | undefined, at: string): boolean {
30 return redOf(told)?.at === at;
31 }
32
33 /** A red that is old enough, and not itself a re-gate, is gated once more. */
34 export function regateDue(red: Decision, now: number): boolean {
35 if (redOf(red)?.again === true) return false;
36 return now - Date.parse(red.createdAt) >= REGATE_RED_MS;
37 }
src/crew/review_gate.ts added +57
@@ -0,0 +1,57 @@
1 /** Whether the review gate lets a green head land. */
2
3 import type { App } from "../app.ts";
4 import type { Pull } from "../core/pulls.ts";
5 import type { Repo } from "../core/repos.ts";
6 import { reviewSummary } from "../core/reviews.ts";
7 import { foldsIn, needsCrewReview } from "../core/trusted_sources.ts";
8 import { isFirstChange, reviewComing } from "./first_change.ts";
9 import { reviewersForRepos, reviewsOff, sendToReview } from "./review.ts";
10
11 /**
12 * Whether the review gate lets this green head land: `pass` with an
13 * approval on this head and no change requested; `hold` while the review
14 * is out or changes are asked for. An agent's pull is held until approved
15 * — with no reviewer, or after one lapsed, a person's review is what it
16 * waits for (#597). A person's own pull passes with no reviewer on the
17 * crew, and is `lapsed` when the reviewer was asked twice and never
18 * answered: it lands without it, and says so (`crew/review.ts`).
19 */
20 export async function reviewed(
21 app: App,
22 repo: Repo,
23 pull: Pull,
24 now: Date = new Date(),
25 ): Promise<"pass" | "hold" | "lapsed" | "first"> {
26 const seen = reviewSummary(app.db, pull.id, pull.headOid);
27 // An app's first change lands on green, whatever the reviewer says: what
28 // it asked for is filed as one follow-up when it lands (`first_change.ts`).
29 // A review already on its way is read first, for a few minutes at most.
30 if (isFirstChange(app.db, repo, pull)) {
31 if (seen.changesRequested === 0 && seen.approvals === 0 && reviewComing(app.db, pull, now)) return "hold";
32 return seen.approvals > 0 && seen.changesRequested === 0 ? "pass" : "first";
33 }
34 if (seen.changesRequested > 0) return "hold";
35 if (seen.approvals > 0) return "pass";
36 // A trusted source's pull needs no person's review (#8937); its check, the
37 // boot proof and the walls above still stood before this point.
38 // A big first fold, and the crew's resolution of a conflict, are reviewed
39 // by the crew first (#9003): they take the path below.
40 if (foldsIn(app.db, pull.id, now) && !needsCrewReview(app.db, pull.id)) return "pass";
41 // An agent's pull ships only on an approving review — the crew's reviewer
42 // or a person's. With no reviewer, or a review that lapsed, it waits for
43 // a person (`waitsForPerson` puts it where a person looks); never by lapse.
44 // An app whose owner has not asked for reviews lands a green pull without
45 // one (#11666); a verdict already on the head was handled above.
46 const seated = reviewersForRepos(app.db, [repo.id]);
47 if (reviewsOff(app.db, repo, seated)) return "pass";
48 const reviewers = seated.get(repo.id)?.length ?? 0;
49 if (pull.authorIsAgent) {
50 if (reviewers > 0) await sendToReview(app, repo, pull);
51 return "hold";
52 }
53 // A person's own pull is not held for a review that never comes.
54 if (reviewers === 0) return "pass";
55 const stage = await sendToReview(app, repo, pull);
56 return stage === "lapsed" ? "lapsed" : stage === "none" ? "pass" : "hold";
57 }
src/crew/runner.ts +1 −1
@@ -153,7 +153,7 @@ import {
153153 whenText,
154154 } from "./limits.ts";
155155 import { interruptedSummary, interruptionOf, landedPullOf, landedSummary, settleLanded } from "./interrupted.ts";
156 import { lastWeekFor } from "./autonomy.ts";
156 import { lastWeekFor } from "./last_week.ts";
157157 import { laterGate } from "./later.ts";
158158 import { MERGES_CLEAN_NOW, mergesCleanNow } from "./clean_now.ts";
159159 import { handedLimbs } from "./handed_limbs.ts";
src/crew/seat_slots.ts +1 −1
@@ -9,7 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import { isCrewRole, type CrewRole } from "../core/agents.ts";
1111 import { PILLAR_MAX, type Repo } from "../core/repos.ts";
12 import { startOfTodayUtc } from "./autonomy.ts";
12 import { startOfTodayUtc } from "./autonomy_spend.ts";
1313
1414 export type SeatSlots = {
1515 role: CrewRole;
src/crew/settle_run.ts added +137
@@ -0,0 +1,137 @@
1 /** What the loop does when a builder's run ends: park the issue, note it done, or leave it. */
2
3 import { addComment, assignIssue } from "../actions/issues.ts";
4 import type { App } from "../app.ts";
5 import { crewRole } from "../core/agents.ts";
6 import { getIssueById, type Issue } from "../core/issues.ts";
7 import { getPull } from "../core/pulls.ts";
8 import type { Repo } from "../core/repos.ts";
9 import { reviewSummary } from "../core/reviews.ts";
10 import { getUserById } from "../core/users.ts";
11 import { createLog } from "../kernel/log.ts";
12 import { ALREADY_NOTE, alreadyDoneOids } from "./already.ts";
13 import { closeSuperseded } from "./conflict_release.ts";
14 import { interruptionOf } from "./interrupted.ts";
15 import { afterNoChange } from "./no_change.ts";
16 import { parkIssue } from "./park_issue.ts";
17 import { parkPull } from "./park_pull.ts";
18 import { NO_PULL } from "./stalls.ts";
19
20 const log = createLog("autonomy");
21
22 /**
23 * After a builder's run on an issue ends without a pull to show for it —
24 * declined, out of budget, or simply nothing pushed — the issue is parked
25 * rather than left stalled: one fresh try later, then the planner's. A run
26 * the provider or a restart cut short is interrupted, not parked: no note,
27 * no strike.
28 */
29 export function settleAgentRun(
30 app: App,
31 repo: Repo,
32 run: {
33 readonly issueId: string;
34 readonly state: string;
35 readonly summary: string;
36 readonly reason: string;
37 readonly actorId: string | null;
38 },
39 ): boolean {
40 if (repo.autonomy !== "autonomous") return false;
41 if (run.state !== "ok" && run.state !== "failed") return false;
42 // A planner is done with the direction once its run ends, whichever way:
43 // a stale assignment must not start another.
44 if (run.issueId === repo.directionIssueId && repo.autonomyBy !== null) {
45 const direction = getIssueById(app.db, run.issueId);
46 const by = getUserById(app.db, repo.autonomyBy);
47 if (direction?.assigneeId && by) assignIssue(app, by, repo, direction, null);
48 return false;
49 }
50 if (run.reason === "review") return false;
51 if (/opened pull #|updated pull #/.test(run.summary)) return false;
52 if (interruptionOf(run.summary) !== undefined) return false;
53 // A builder who changed nothing on a red pull: check it again (#12968). Only a run that ended
54 // well said "no change"; one that errored said nothing, and is no answer to re-check on.
55 if (run.reason !== "feedback" && run.state === "ok") {
56 // Not a test: this queues a re-check or posts the failure, and the run is settled by it.
57 const move = afterNoChange(app, repo, run.issueId);
58 if (move !== undefined) return true;
59 }
60 if (answeredWithoutChange(app, repo, run)) return true;
61 const carried = alreadyDoneOids(run.summary);
62 if (run.state === "ok" && carried.length > 0) {
63 const asked = getIssueById(app.db, run.issueId);
64 const own = asked?.kind === "pull" ? getPull(app.db, repo.id, asked.number) : undefined;
65 if (own && own.mergedAt === null)
66 return closeSuperseded(app, repo, own, carried);
67 }
68 const issue = getIssueById(app.db, run.issueId);
69 if (!issue || issue.kind !== "issue" || issue.state !== "open") return false;
70 if (issue.id === repo.directionIssueId) return false;
71 if (
72 run.actorId !== null &&
73 crewRole(app.db, repo.id, run.actorId) !== "builder"
74 )
75 return false;
76 const done = alreadyDoneOids(run.summary);
77 if (run.state === "ok" && done.length > 0)
78 return noteAlreadyDone(app, repo, issue, done);
79 return parkIssue(
80 app,
81 repo,
82 issue,
83 `the ${NO_PULL}: ${run.summary || run.state}`,
84 );
85 }
86
87 /**
88 * A run found its issue done on the base, by commits that are there
89 * (`already.ts`): one note on the issue with the commits, the assignee
90 * cleared, and no park — it is no strike and never reaches the planner as
91 * parked twice. Closing it is the asker's. Said once per run.
92 */
93 export function noteAlreadyDone(
94 app: App,
95 repo: Repo,
96 issue: Issue,
97 oids: readonly string[],
98 ): boolean {
99 if (repo.autonomyBy === null) return false;
100 const by = getUserById(app.db, repo.autonomyBy);
101 if (!by) return false;
102 if (issue.assigneeId !== null) assignIssue(app, by, repo, issue, null);
103 addComment(app, by, repo, issue, `${ALREADY_NOTE}${oids.join(" ")}`);
104 log.info("already done", {
105 repo: `${repo.ownerName}/${repo.name}`,
106 issue: issue.number,
107 commits: oids.length,
108 });
109 return true;
110 }
111
112 /**
113 * A builder's run on its pull that ended without a push while the crew's
114 * reviewer still asks for changes on the head: the request was not
115 * answered, and nothing will answer it. The pull is parked rather than
116 * left waiting on a verdict that will not move.
117 */
118 function answeredWithoutChange(
119 app: App,
120 repo: Repo,
121 run: { readonly issueId: string; readonly reason: string; readonly actorId: string | null },
122 ): boolean {
123 if (run.reason !== "feedback" || run.actorId === null) return false;
124 if (crewRole(app.db, repo.id, run.actorId) !== "builder") return false;
125 const issue = getIssueById(app.db, run.issueId);
126 if (!issue || issue.kind !== "pull" || issue.state !== "open") return false;
127 const pull = getPull(app.db, repo.id, issue.number);
128 if (!pull || pull.mergedAt !== null) return false;
129 if (reviewSummary(app.db, pull.id, pull.headOid).changesRequested === 0)
130 return false;
131 return parkPull(
132 app,
133 repo,
134 pull,
135 "the reviewer asked for changes and the builder's run ended without pushing any",
136 );
137 }
src/crew/stale_pulls.ts +1 −1
@@ -4,7 +4,7 @@
44 * closed with one line, and the issue it closed goes back to ready,
55 * unassigned, to be built fresh from main.
66 *
7 * `sweepConflicts` (`autonomy.ts`) already reads every open crew pull per
7 * `sweepConflicts` (`conflict_sweep.ts`) already reads every open crew pull per
88 * pair of tips and keeps since when each has conflicted at its present
99 * head; it calls `closeStale` for one past `STALE_MS`. It leaves a held
1010 * pull and one approved on its head alone before it gets here, so those
src/crew/stalls.ts +1 −1
@@ -3,7 +3,7 @@
33 * nothing pushed — and was not cut short by the provider or a restart
44 * (#4073). The clock does not wait for a person to lift one:
55 *
6 * - The next tick parks it (`freeStalled` in `autonomy.ts`): a note with
6 * - The next tick parks it (`freeStalled` in `unstick.ts`): a note with
77 * who stalled it and the run's last summary, and the assignee cleared, so
88 * any builder may pick it.
99 * - The builder that stalled it does not pick it again within the hour,
src/crew/too_large.ts +1 −1
@@ -6,7 +6,7 @@
66 * knobs allow (`issue.maxBoxes`, `issue.maxChars`, on the crew settings
77 * page) is held as `too_large` (`held.ts`) and handed to the planner to
88 * split before a builder starts it, once: the crew writes a note on it, the
9 * planner is owed one pass (`autonomy.ts`), and when that pass has ended the
9 * planner is owed one pass (`plan_owed.ts`), and when that pass has ended the
1010 * hold lifts, so an issue the planner left whole is not held for good.
1111 *
1212 * A person's ask is held the same way and the note says the planner will
src/crew/triage.ts +2 −1
@@ -31,7 +31,8 @@ import { isStructural, pillarsOf, type Pillars } from "../core/pillars.ts";
3131 import { listAutonomousRepos, type Repo } from "../core/repos.ts";
3232 import { getUserById, type User } from "../core/users.ts";
3333 import { createLog } from "../kernel/log.ts";
34 import { autonomyStatus, ensureDirectionIssue } from "./autonomy.ts";
34 import { autonomyStatus } from "./autonomy_status.ts";
35 import { ensureDirectionIssue } from "./direction_issue.ts";
3536 import { certain, decideOr, type Answers, type Questions } from "./decide.ts";
3637 import { linkThoughts, raiseIssue } from "../core/thought_links.ts";
3738 import { crewOffInPreview } from "./preview.ts";
src/crew/unstick.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Issues the loop frees for another builder: parked on a non-builder, or stalled after a run, and
3 * the red-thrice note.
4 */
5
6 import { addComment, assignIssue } from "../actions/issues.ts";
7 import type { App } from "../app.ts";
8 import { listCrewRoles } from "../core/agents.ts";
9 import { readyNow, repoGraph } from "../core/dependencies.ts";
10 import { getIssue } from "../core/issues.ts";
11 import type { Repo } from "../core/repos.ts";
12 import { getUserById, type User } from "../core/users.ts";
13 import { createLog } from "../kernel/log.ts";
14 import { activeRuns, autonomyStatus } from "./autonomy_status.ts";
15 import { type Held, heldBy } from "./held.ts";
16 import { parkAs } from "./park_issue.ts";
17 import { notedAt, redThrice, redThriceNote } from "./red_thrice.ts";
18 import { landedUnder, stallReason } from "./stalls.ts";
19
20 const log = createLog("autonomy");
21
22 /**
23 * One note on each issue whose pull is red on three checks (`red_thrice.ts`), quoting the last
24 * failure; a streak already noted is not noted again. Returns how many notes it wrote.
25 */
26 export function noteRedThrice(app: App, repo: Repo, by: User): number {
27 let wrote = 0;
28 for (const [number, r] of redThrice(app.db, repo)) {
29 const issue = getIssue(app.db, repo.id, number);
30 if (issue === undefined || issue.state !== "open" || notedAt(app.db, issue.id, r) !== undefined) continue;
31 if (!addComment(app, by, repo, issue, redThriceNote(r)).ok) continue;
32 log.info("red on three checks; handed to the planner", { repo: `${repo.ownerName}/${repo.name}`, issue: number, pull: r.pull.number });
33 wrote++;
34 }
35 return wrote;
36 }
37
38 /**
39 * A ready issue assigned to a planner or a reviewer with no run on it is
40 * parked on a crew member that never builds it — a sentinel's finding, a
41 * planner's pass that ended (#3002). Its assignee is cleared so a builder
42 * may start it this tick. Returns how many were freed.
43 */
44 export function freeParked(app: App, repo: Repo, by: User, held: Held): number {
45 let freed = 0;
46 for (const issue of held.by.planner) {
47 const cleared = assignIssue(app, by, repo, issue, null);
48 if (!cleared.ok) {
49 log.warn("could not free an issue parked on a non-builder", {
50 repo: `${repo.ownerName}/${repo.name}`,
51 issue: issue.number,
52 error: cleared.error,
53 });
54 continue;
55 }
56 log.info("freed", { repo: `${repo.ownerName}/${repo.name}`, issue: issue.number });
57 freed++;
58 }
59 return freed;
60 }
61
62 /**
63 * A ready issue a builder ran on and left without a pull, nobody having
64 * spoken since, is parked by the next tick rather than held for a person
65 * (#4073): the note says whose run stalled it and the run's last summary,
66 * the assignee is cleared, and any other builder may pick it. That note is
67 * a strike (`parks.ts`), so a second stall hands it to the planner. A run
68 * still in flight is not a stall yet. Returns how many were freed.
69 */
70 export function freeStalled(app: App, repo: Repo, by: User, held: Held): number {
71 let freed = 0;
72 for (const issue of held.by.stalled) {
73 const last = app.db
74 .query<{ state: string; summary: string; actor: string | null }, [string]>(
75 `SELECT state, summary, actor_id AS actor FROM run
76 WHERE issue_id = ?1 AND kind = 'agent' ORDER BY created_at DESC LIMIT 1`,
77 )
78 .get(issue.id);
79 if (!last || last.state === "queued" || last.state === "running") continue;
80 // A run its pull landed under left the work on the base: no park, no strike (#8481).
81 if (landedUnder(last)) continue;
82 const who = last.actor === null ? undefined : getUserById(app.db, last.actor)?.username;
83 if (parkAs(app, by, repo, issue, stallReason(who, last.summary || last.state), "unstuck"))
84 freed++;
85 }
86 return freed;
87 }
88
89 /**
90 * The stalled issues freed this tick (`freeStalled`): none while the crew
91 * is off or paused, or nobody stands behind it.
92 */
93 export function unstickNow(app: App, repo: Repo, now: Date): number {
94 if (repo.autonomy === "off" || repo.autonomyBy === null) return 0;
95 if (autonomyStatus(app, repo, now).paused !== null) return 0;
96 const by = getUserById(app.db, repo.autonomyBy);
97 if (!by) return 0;
98 const held = heldBy(
99 app,
100 repo,
101 readyNow(repoGraph(app.db, repo.id, { sealed: true })),
102 listCrewRoles(app.db, repo.id),
103 activeRuns(app, repo.id),
104 );
105 return held.by.stalled.length === 0 ? 0 : freeStalled(app, repo, by, held);
106 }
src/fleet/verbs.ts +1 −1
@@ -26,7 +26,7 @@ import { updateRepoSettings } from "../actions/repos.ts";
2626 import { cancelRepoRun, requeueRepoRun } from "../actions/runs.ts";
2727 import { isCrew } from "../core/agents.ts";
2828 import { mergePull } from "../actions/pulls.ts";
29 import { bringUpToDate } from "../crew/autonomy.ts";
29 import { bringUpToDate } from "../crew/conflict_release.ts";
3030 import { moveLimb, parseSeat, type Seating } from "../core/limb_seats.ts";
3131 import { getHold } from "../core/holds.ts";
3232 import { recordInteraction, removeDismissals, removeMutes } from "../core/interactions.ts";
src/flow/alarm_idle_crew.ts +1 −1
@@ -5,7 +5,7 @@
55 */
66
77 import type { Database } from "bun:sqlite";
8 import { spentTodayEverywhere } from "../crew/autonomy.ts";
8 import { spentTodayEverywhere } from "../crew/autonomy_spend.ts";
99 import { ceilingReached } from "./ceiling.ts";
1010 import { readPipeline, span } from "./pipeline.ts";
1111
src/flow/alarm_lane.ts +1 −1
@@ -17,7 +17,7 @@
1717 */
1818
1919 import type { Database } from "bun:sqlite";
20 import { spentTodayEverywhere } from "../crew/autonomy.ts";
20 import { spentTodayEverywhere } from "../crew/autonomy_spend.ts";
2121 import type { Run } from "../core/runs.ts";
2222 import { getRepo } from "../core/repos.ts";
2323 import { agoWords } from "../keeper/beat.ts";
src/flow/ceiling.ts +2 −2
@@ -1,12 +1,12 @@
11 /**
22 * The forge's own daily crew ceiling (#5798): the one rule for reading the cap
3 * and for when it was hit. `crew/autonomy.ts`, the tiles and the terminal all
3 * and for when it was hit. `crew/autonomy_status.ts`, the tiles and the terminal all
44 * ask here, so they cannot disagree. Per-account ceilings are a different
55 * thing and never folded into this number.
66 */
77
88 import type { Database } from "bun:sqlite";
9 import { startOfTodayUtc } from "../crew/autonomy.ts";
9 import { startOfTodayUtc } from "../crew/autonomy_spend.ts";
1010
1111 /**
1212 * The forge cap in dollars, or null when none is set. Only a positive number
src/flow/keeper_cause.ts +1 −1
@@ -12,7 +12,7 @@ import { listAutonomousRepos } from "../core/repos.ts";
1212 import { listActive } from "../core/runs.ts";
1313 import { standings } from "../core/standing.ts";
1414 import { grantedAccounts } from "../core/subscriptions.ts";
15 import { slottedRuns } from "../crew/autonomy.ts";
15 import { slottedRuns } from "../crew/autonomy_status.ts";
1616 import { weekSpent } from "../crew/week_read.ts";
1717 import { heldNow } from "../crew/held.ts";
1818 import { pace } from "../crew/pacing.ts";
src/flow/kpis.ts +1 −1
@@ -20,7 +20,7 @@ import { backupVerdict, isWatched, type BackupVerdict } from "../snapshot/bucket
2020 import { lastDrill } from "../snapshot/drills.ts";
2121 import type { Database } from "bun:sqlite";
2222 import { crewConcurrency, shownSlots } from "./slot_cap.ts";
23 import { spentTodayEverywhere } from "../crew/autonomy.ts";
23 import { spentTodayEverywhere } from "../crew/autonomy_spend.ts";
2424 import { ceilingHitAt, ceilingReached } from "./ceiling.ts";
2525 import type { IdleReason } from "../crew/idle_reason.ts";
2626 import { lastOffBox } from "../snapshot/off_box.ts";
src/flow/why.ts +1 −1
@@ -16,7 +16,7 @@ import { refTip } from "../git/read.ts";
1616 import { resolveOid } from "../git/merge.ts";
1717 import { checkSummary } from "../core/runs.ts";
1818 import { ceilingHitAt, forgeCeiling } from "./ceiling.ts";
19 import { paceHold } from "../crew/autonomy.ts";
19 import { paceHold } from "../crew/autonomy_pace.ts";
2020 import { heldNow, mapHolds } from "../crew/held.ts";
2121 import { nextOfPull, type Actor } from "./next_actor.ts";
2222 import { wallWords } from "./wall_wait.ts";
src/http/mcp/tools/flow.ts +1 −1
@@ -4,7 +4,7 @@ import { noTelemetryBlocked } from "../../../actions/blocked_words.ts";
44 import { getIssue } from "../../../core/issues.ts";
55 import { getPull, pullDir, pullMergeState } from "../../../core/pulls.ts";
66 import { canWrite } from "../../../core/repos.ts";
7 import { bringUpToDate } from "../../../crew/autonomy.ts";
7 import { bringUpToDate } from "../../../crew/conflict_release.ts";
88 import { mayView, sealedScope } from "../../../core/sealed.ts";
99 import { growth } from "../../../core/growth.ts";
1010 import { DAYS } from "../../../web/pages/queue.ts";
src/maintain/keeper/lull.ts +1 −1
@@ -10,7 +10,7 @@ import type { App } from "../../app.ts";
1010 import { listCrewRoles } from "../../core/agents.ts";
1111 import { listAutonomousRepos } from "../../core/repos.ts";
1212 import { listActive } from "../../core/runs.ts";
13 import { slottedRuns } from "../../crew/autonomy.ts";
13 import { slottedRuns } from "../../crew/autonomy_status.ts";
1414 import { heldNow } from "../../crew/held.ts";
1515 import { whatBlocks } from "../../crew/idle_reason.ts";
1616 import { checkOn, type KPull } from "./pulls.ts";
src/snapshot/verify.ts +8 −1
@@ -128,7 +128,10 @@ export async function verifySnapshot(store: Store, name: string, options: { read
128128 return { name, files: manifest.files.length, chunks: ids.length, bytes, deep, ...said };
129129 }
130130
131 if (import.meta.main) {
131 /**
132 * The command line: `bun run src/snapshot/verify.ts <snapshot-name|latest> [--deep] [--offsite]`.
133 */
134 async function cli(): Promise<void> {
132135 const args = process.argv.slice(2);
133136 const flag = (name: string): boolean => {
134137 const at = args.indexOf(name);
@@ -170,3 +173,7 @@ if (import.meta.main) {
170173 process.exit(1);
171174 }
172175 }
176
177 // Not a top-level `await`: the roster `require`s modules that import this one
178 // (`maintain/registry.ts`).
179 if (import.meta.main) void cli();
src/spawn/first-boot.ts +1 −1
@@ -22,7 +22,7 @@ import { getAppByRepo } from "../core/apps.ts";
2222 import { listTeamMembers, listTeams, OWNERS_TEAM } from "../core/orgs.ts";
2323 import { getRepoById, listReposByOwner, type Repo } from "../core/repos.ts";
2424 import { getUserSetting, setUserSetting } from "../core/settings.ts";
25 import { ensureDirectionIssue } from "../crew/autonomy.ts";
25 import { ensureDirectionIssue } from "../crew/direction_issue.ts";
2626 import { resolveOid } from "../git/merge.ts";
2727 import { repoDir } from "../git/repos.ts";
2828 import { join } from "node:path";
src/spawn/heartbeat.ts +1 −1
@@ -17,7 +17,7 @@ import { createHmac, timingSafeEqual } from "node:crypto";
1717 import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
1818 import { join } from "node:path";
1919 import type { App } from "../app.ts";
20 import { spentTodayEverywhere } from "../crew/autonomy.ts";
20 import { spentTodayEverywhere } from "../crew/autonomy_spend.ts";
2121 import { beatKeyOf, listChildren } from "../actions/spawn.ts";
2222 import { shippedReleases } from "../release/shipped.ts";
2323 import { forgeLinkOf, forgeTipOf, FOLLOW_MODES, type FollowMode, type ForgeLink } from "./chain.ts";
src/tui/screens/dashboard.ts +1 −1
@@ -18,7 +18,7 @@ import { readyAsk } from "../../spawn/template_record.ts";
1818 import { DEFAULT_WEIGHTS, frontWeights, type FrontWeights } from "../../core/front.ts";
1919 import { quietSince, exploreCount, exploreFiltered, exploreLine, isExploreLine, exploreNote, exploreSuggestion, explorePage, groupForks, parseExploreQuery, readExploreLine, whyOf, figuresOf, peopleWords, PEOPLE_ORDER_WORDS, type ExploreRow } from "../../actions/explore.ts";
2020 import { protectionNotice } from "../../kernel/protection.ts";
21 import { holdWords, plannerHold } from "../../crew/autonomy.ts";
21 import { holdWords, plannerHold } from "../../crew/planner_hold.ts";
2222 import { governorLine, governorSeen } from "../../crew/governed.ts";
2323 import { forgeFlakes, forgeLane, forgeNeedList, needTermLine } from "../../actions/health.ts";
2424 import { ownerWaits, waitLine, withMore } from "../../actions/owner_waits.ts";
src/tui/screens/decider.ts +1 −1
@@ -7,7 +7,7 @@
77
88 import type { Database } from "bun:sqlite";
99 import { returnsRepos } from "../../actions/returns.ts";
10 import { startOfTodayUtc } from "../../crew/autonomy.ts";
10 import { startOfTodayUtc } from "../../crew/autonomy_spend.ts";
1111 import {
1212 DECIDER_PILES,
1313 PILE_EMPTY,
src/tui/screens/drift.ts +1 −1
@@ -7,7 +7,7 @@
77 * b, enter bring the pull up to date r read again
88 */
99
10 import { bringUpToDate } from "../../crew/autonomy.ts";
10 import { bringUpToDate } from "../../crew/conflict_release.ts";
1111 import { driftingPulls, readDrifts, type DriftingPull } from "../../flow/alarm_drift.ts";
1212 import { getPull } from "../../core/pulls.ts";
1313 import { mayView } from "../../core/sealed.ts";
src/web/pages/board.ts +3 −6
@@ -85,12 +85,9 @@ import {
8585 } from "../../core/repos.ts";
8686 import { agentRunTotals, listActiveRuns, type Run } from "../../core/runs.ts";
8787 import { getUsersByIds } from "../../core/users.ts";
88 import {
89 autonomyStatus,
90 holdWords,
91 plannerHold,
92 startOfTodayUtc,
93 } from "../../crew/autonomy.ts";
88 import { autonomyStatus } from "../../crew/autonomy_status.ts";
89 import { holdWords, plannerHold } from "../../crew/planner_hold.ts";
90 import { startOfTodayUtc } from "../../crew/autonomy_spend.ts";
9491 import { distinct, notesRegion, type Note } from "./board-notes.ts";
9592 import type { Ctx } from "../../http/context.ts";
9693 import { repoBase, signInFirst } from "../chrome.ts";
src/web/pages/crew.ts +1 −1
@@ -60,7 +60,7 @@ import { tryAgain } from "../../actions/try_again.ts";
6060 import { crewHandover, type CrewHandover } from "../../crew/handed.ts";
6161 import { MODELS } from "../../crew/models.ts";
6262 import type { Ctx } from "../../http/context.ts";
63 import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy.ts";
63 import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy_status.ts";
6464 import { listAutonomousRepos, type Repo } from "../../core/repos.ts";
6565 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
6666 import { field, readForm, type Form } from "../form.ts";
src/web/pages/global-map.ts +1 −1
@@ -7,7 +7,7 @@
77 */
88
99 import type { App } from "../../app.ts";
10 import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy.ts";
10 import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy_status.ts";
1111 import {
1212 criticalPath,
1313 readyNow,
src/web/studio/actions.ts +1 −1
@@ -28,7 +28,7 @@ import { revertPull } from "../../actions/revert.ts";
2828 import { takeBackWords } from "../../actions/revert_words.ts";
2929 import { getPull } from "../../core/pulls.ts";
3030 import { canRead, canWrite, getRepo, type Repo } from "../../core/repos.ts";
31 import { bringUpToDate } from "../../crew/autonomy.ts";
31 import { bringUpToDate } from "../../crew/conflict_release.ts";
3232 import type { Ctx } from "../../http/context.ts";
3333 import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, signInFirst } from "../chrome.ts";
3434 import { teamHoldRefusal } from "../../core/teams_words.ts";
src/web/studio/app.ts +1 −1
@@ -30,7 +30,7 @@ import { reviewCard } from "../pages/review.ts";
3030 import { growthPanel } from "../pages/growth_panel.ts";
3131 import { canAdmin, canSeeOwnerFacts, canWrite, type Repo } from "../../core/repos.ts";
3232 import type { PreviewLatency } from "../../core/runs.ts";
33 import { autonomyStatus } from "../../crew/autonomy.ts";
33 import { autonomyStatus } from "../../crew/autonomy_status.ts";
3434 import { governorSeen } from "../../crew/governed.ts";
3535 import { governorRows, weekCardDl } from "./governor_rows.ts";
3636 import { repoDir } from "../../git/repos.ts";
src/web/studio/asks.ts +2 −4
@@ -53,10 +53,8 @@ import {
5353 type Run,
5454 } from "../../core/runs.ts";
5555 import { getUserById, getUsersByIds, type User } from "../../core/users.ts";
56 import {
57 isPausedForWeek,
58 plannerDeclines,
59 } from "../../crew/autonomy.ts";
56 import { isPausedForWeek } from "../../crew/autonomy_spend.ts";
57 import { plannerDeclines } from "../../crew/planner_decline.ts";
6058 import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts";
6159 import { handoversOf, passReasonOf, type Handover } from "../../crew/guard.ts";
6260 import { conflictsOf, isLandedPull, isStalePull, knownBase, mergesAgainSince, staleGreen } from "../../crew/stale_asks.ts";
src/web/studio/cost_line.ts +1 −1
@@ -8,7 +8,7 @@
88
99 import { crewForRepos } from "../../core/agents.ts";
1010 import type { Repo } from "../../core/repos.ts";
11 import { isPausedForWeek, spentTodayForRepos } from "../../crew/autonomy.ts";
11 import { isPausedForWeek, spentTodayForRepos } from "../../crew/autonomy_spend.ts";
1212 import type { Database } from "bun:sqlite";
1313 import { html, type Html } from "../html.ts";
1414
src/web/studio/crew.ts +1 −1
@@ -30,7 +30,7 @@ import { listCrewRoles, type Agent, type CrewRole } from "../../core/agents.ts";
3030 import { getAppByRepo } from "../../core/apps.ts";
3131 import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
3232 import { seatsOf, type Seat } from "../../crew/seats.ts";
33 import { autonomyStatus } from "../../crew/autonomy.ts";
33 import { autonomyStatus } from "../../crew/autonomy_status.ts";
3434 import { governorSeen } from "../../crew/governed.ts";
3535 import { governorRows, weekCardDl } from "./governor_rows.ts";
3636 import { crewOffInPreview } from "../../crew/preview.ts";
src/web/studio/kpi_probe.ts +1 −1
@@ -16,7 +16,7 @@
1616
1717 import type { Database } from "bun:sqlite";
1818 import type { App } from "../../app.ts";
19 import { spentTodayEverywhere } from "../../crew/autonomy.ts";
19 import { spentTodayEverywhere } from "../../crew/autonomy_spend.ts";
2020 import { idleReason } from "../../crew/idle_reason.ts";
2121 import { countBugs } from "../../flow/bugs.ts";
2222 import { forgeCeiling } from "../../flow/ceiling.ts";
src/web/studio/words.ts +1 −1
@@ -43,7 +43,7 @@ import {
4343 } from "../../core/runs.ts";
4444 import { html, type Html } from "../html.ts";
4545 import { icon } from "../ui.ts";
46 import type { Paused } from "../../crew/autonomy.ts";
46 import type { Paused } from "../../crew/autonomy_status.ts";
4747 import { stillEnding } from "../../runs/ending.ts";
4848
4949 /**
test/api-reader-marks.test.ts +1 −1
@@ -21,7 +21,7 @@ import { createUser, type User } from "../src/core/users.ts";
2121 import { listCrewRoles } from "../src/core/agents.ts";
2222 import { getIssue, listComments, type Issue } from "../src/core/issues.ts";
2323 import { readersAmong, voiceOf } from "../src/crew/direct.ts";
24 import { readyState } from "../src/crew/autonomy.ts";
24 import { readyState } from "../src/crew/next_pick.ts";
2525 import { routingState } from "../src/crew/route.ts";
2626 import {
2727 systemPrompt,
test/authors-pull.test.ts +2 −1
@@ -25,7 +25,8 @@ import { submitReview } from "../src/core/reviews.ts";
2525 import { listRuns } from "../src/core/runs.ts";
2626 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2727 import { authorsInRepoPull, BACK_WITH_AUTHOR } from "../src/crew/authors_pull.ts";
28 import { parkPull, settleAgentRun } from "../src/crew/autonomy.ts";
28 import { parkPull } from "../src/crew/park_pull.ts";
29 import { settleAgentRun } from "../src/crew/settle_run.ts";
2930 import { finishApproved } from "../src/crew/finishing.ts";
3031 import { moveRequested } from "../src/crew/requested.ts";
3132 import { serve, type Servers } from "../src/http/server.ts";
test/autonomy.test.ts +8 −12
@@ -37,17 +37,13 @@ import { claimRun, createRun, finishRun, listRuns } from "../src/core/runs.ts";
3737 import { createUser, getUserByName, type User } from "../src/core/users.ts";
3838 import { serve, type Servers } from "../src/http/server.ts";
3939 import { addComment, setIssueState } from "../src/actions/issues.ts";
40 import {
41 autonomyStatus,
42 driveRepo,
43 holdWhy,
44 holdWords,
45 plannerHold,
46 landIfGreen,
47 pickBuilder,
48 sweepGreen,
49 truncateAtWord,
50 } from "../src/crew/autonomy.ts";
40 import { autonomyStatus } from "../src/crew/autonomy_status.ts";
41 import { driveRepo } from "../src/crew/drive.ts";
42 import { holdWhy, holdWords, plannerHold } from "../src/crew/planner_hold.ts";
43 import { landIfGreen } from "../src/crew/land_queue.ts";
44 import { pickBuilder } from "../src/crew/route.ts";
45 import { sweepGreen } from "../src/crew/green_sweep.ts";
46 import { truncateAtWord } from "../src/crew/direction_issue.ts";
5147 import { MAX_TITLE } from "../src/core/issues.ts";
5248
5349 describe("truncateAtWord", () => {
@@ -749,7 +745,7 @@ describe("the crew in a preview", () => {
749745 });
750746
751747 test("an autonomy tick is a no-op in a preview", async () => {
752 const { autonomyTick } = await import("../src/crew/autonomy.ts");
748 const { autonomyTick } = await import("../src/crew/autonomy_tick.ts");
753749 const dir = await mkdtemp(join(tmpdir(), "forge-prev-"));
754750 const app = await createApp({ dataDir: dir } as Parameters<typeof createApp>[0]);
755751 let touched = 0;
test/autonomy_sweep.test.ts +2 −1
@@ -14,7 +14,8 @@ import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/r
1414 import { getIssue, type Issue } from "../src/core/issues.ts";
1515 import { getRepoById, type Repo } from "../src/core/repos.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
17 import { autonomyTick, startSweep } from "../src/crew/autonomy.ts";
17 import { autonomyTick } from "../src/crew/autonomy_tick.ts";
18 import { startSweep } from "../src/crew/green_sweep.ts";
1819
1920 /** A sweep whose landing gate takes 10 s, released early by the test. */
2021 function slowSweep() {
test/beat.test.ts +1 −1
@@ -7,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
77 import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { autonomyTick } from "../src/crew/autonomy.ts";
10 import { autonomyTick } from "../src/crew/autonomy_tick.ts";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1313 import { parseBeat } from "../src/apps/beat_spec.ts";
test/bets.test.ts +1 −1
@@ -22,7 +22,7 @@ import { setModelGrant } from "../src/core/model_grant.ts";
2222 import { createRun } from "../src/core/runs.ts";
2323 import { recordUsage } from "../src/core/usage.ts";
2424 import { autoStarts, budgetSeconds, mayBack, mayPick, scopeState, spentSeconds, spentUp, walletRefusal } from "../src/crew/bets.ts";
25 import { driveRepo } from "../src/crew/autonomy.ts";
25 import { driveRepo } from "../src/crew/drive.ts";
2626 import { serve, type Servers } from "../src/http/server.ts";
2727
2828 describe("the rules", () => {
test/boot-no-stall.test.ts +1 −1
@@ -9,7 +9,7 @@
99 import { afterAll, beforeAll, expect, test } from "bun:test";
1010 import { rmSync } from "node:fs";
1111 import type { App } from "../src/app.ts";
12 import { autonomyTick } from "../src/crew/autonomy.ts";
12 import { autonomyTick } from "../src/crew/autonomy_tick.ts";
1313 import { sweepRepeats } from "../src/crew/repeat_checks.ts";
1414 import { group, wordsOf, type Finding } from "../src/flow/repeats.ts";
1515 import { getRepoById } from "../src/core/repos.ts";
test/bounded.test.ts +1 −1
@@ -1,6 +1,6 @@
11 import { describe, expect, test } from "bun:test";
22 import { BoundedMap, BoundedSet } from "../src/perf/bounded.ts";
3 import { CONFLICTED_MAX, conflicted } from "../src/crew/autonomy.ts";
3 import { CONFLICTED_MAX, conflicted } from "../src/crew/conflicted_tips.ts";
44 import { RETRIED_MAX, retriedChecks } from "../src/crew/dispatch.ts";
55 import { LINKS_SAID_MAX, said } from "../src/spawn/app_links.ts";
66
test/build-journey.test.ts +1 −1
@@ -24,7 +24,7 @@ import { getPull, listOpenPulls, type Pull } from "../src/core/pulls.ts";
2424 import { submitReview } from "../src/core/reviews.ts";
2525 import { listRuns } from "../src/core/runs.ts";
2626 import { createUser, type User } from "../src/core/users.ts";
27 import { landIfGreen } from "../src/crew/autonomy.ts";
27 import { landIfGreen } from "../src/crew/land_queue.ts";
2828 import { startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
2929 import { serve, type Servers } from "../src/http/server.ts";
3030 import { READING_V1, READING_V2, writeBuildStandIn } from "./helpers/build-standin.ts";
test/chapters-pick-order.test.ts +1 −1
@@ -6,7 +6,7 @@ import { join } from "node:path";
66 import { createRepo } from "../src/actions/repos.ts";
77 import { draft, fill, move, open } from "../src/actions/chapters.ts";
88 import { createApp, type App } from "../src/app.ts";
9 import { inSlotOrder } from "../src/crew/autonomy.ts";
9 import { inSlotOrder } from "../src/crew/autonomy_pace.ts";
1010 import { rankIssue } from "../src/actions/next.ts";
1111 import { notStartable } from "../src/crew/not_startable.ts";
1212 import { readyNow, repoGraph } from "../src/core/dependencies.ts";
test/conflict_sweep.test.ts +2 −1
@@ -21,7 +21,8 @@ import { createUser, getUserByName, type User } from "../src/core/users.ts";
2121 import { parkedCount } from "../src/crew/parks.ts";
2222 import { createToken } from "../src/core/tokens.ts";
2323 import { serve, type Servers } from "../src/http/server.ts";
24 import { settleAgentRun, sweepConflicts } from "../src/crew/autonomy.ts";
24 import { settleAgentRun } from "../src/crew/settle_run.ts";
25 import { sweepConflicts } from "../src/crew/conflict_sweep.ts";
2526 import { conflictedPulls, conflictedSays } from "../src/flow/conflicted.ts";
2627 import { forgetFlow } from "../src/system/flow_cache.ts";
2728 import { flowLines } from "../src/tui/screens/flow.ts";
test/crew-direction-autonomy.test.ts +4 −7
@@ -49,13 +49,10 @@ import { listReviewComments } from "../src/core/reviews.ts";
4949 import { getRepoById, type Repo } from "../src/core/repos.ts";
5050 import { claimRun, createRun, finishRun, listRuns } from "../src/core/runs.ts";
5151 import { createUser, getUserByName, type User } from "../src/core/users.ts";
52 import {
53 driveRepo,
54 landIfGreen,
55 parkedCount,
56 parkIssue,
57 plannerDeclines,
58 } from "../src/crew/autonomy.ts";
52 import { driveRepo } from "../src/crew/drive.ts";
53 import { landIfGreen } from "../src/crew/land_queue.ts";
54 import { parkedCount, parkIssue } from "../src/crew/park_issue.ts";
55 import { plannerDeclines } from "../src/crew/planner_decline.ts";
5956 import {
6057 READER,
6158 systemPrompt,
test/crew-direction-cap.test.ts +1 −1
@@ -18,7 +18,7 @@ import { getIssueById, type Issue } from "../src/core/issues.ts";
1818 import { getRepoById, type Repo } from "../src/core/repos.ts";
1919 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
2020 import { createUser, getUserByName, type User } from "../src/core/users.ts";
21 import { driveRepo } from "../src/crew/autonomy.ts";
21 import { driveRepo } from "../src/crew/drive.ts";
2222 import { ISSUE_RUN_CAP, runCapOf } from "../src/crew/guard.ts";
2323
2424 describe("the direction is paced, not capped", () => {
test/crew-governed-unit.test.ts +1 −1
@@ -19,7 +19,7 @@ import { noteLimit, setHeadroom } from "../src/core/standing.ts";
1919 import { addSubscription, setGrants } from "../src/core/subscriptions.ts";
2020 import { recordUsage } from "../src/core/usage.ts";
2121 import { createUser } from "../src/core/users.ts";
22 import { repoPace } from "../src/crew/autonomy.ts";
22 import { repoPace } from "../src/crew/autonomy_pace.ts";
2323 import { announceGovernor, governorFor, governorLine, governorSeen } from "../src/crew/governed.ts";
2424 import { governedSlots } from "../src/crew/governor.ts";
2525 import { readRepoFlow } from "../src/flow/repo_flow.ts";
test/crew-governed.test.ts +1 −1
@@ -11,7 +11,7 @@ import { getRepoById, type Repo } from "../src/core/repos.ts";
1111 import { createUser, type User } from "../src/core/users.ts";
1212 import { listEventsVisibleTo } from "../src/core/events.ts";
1313 import { readFeed } from "../src/feed/feed.ts";
14 import { autonomyTick } from "../src/crew/autonomy.ts";
14 import { autonomyTick } from "../src/crew/autonomy_tick.ts";
1515 import { setOpenPullsCeiling } from "../src/core/pulls_ceiling.ts";
1616 import { id } from "../src/kernel/id.ts";
1717 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
test/crew-guard-cap.test.ts +1 −1
@@ -17,8 +17,8 @@ import { getIssueById, type Issue } from "../src/core/issues.ts";
1717 import { getRepoById, type Repo } from "../src/core/repos.ts";
1818 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
1919 import { createUser, getUserByName, type User } from "../src/core/users.ts";
20 import { CAP_NOTE } from "../src/crew/cap_note.ts";
2021 import {
21 CAP_NOTE,
2222 CAP_WINDOW_MS,
2323 capNoted,
2424 capReached,
test/crew-guard.test.ts +2 −2
@@ -47,11 +47,11 @@ import {
4747 listRuns,
4848 } from "../src/core/runs.ts";
4949 import { createUser, getUserByName, type User } from "../src/core/users.ts";
50 import { driveRepo } from "../src/crew/autonomy.ts";
50 import { driveRepo } from "../src/crew/drive.ts";
5151 import { breakerParked, breakerTripped } from "../src/crew/breaker.ts";
5252 import { queueAgentRun } from "../src/crew/dispatch.ts";
53 import { CAP_NOTE } from "../src/crew/cap_note.ts";
5354 import {
54 CAP_NOTE,
5555 guardCounts,
5656 ISSUE_RUN_CAP,
5757 SKIP_SUMMARY,
test/crew-held.test.ts +1 −1
@@ -24,7 +24,7 @@ import { DONE_NOTE } from "../src/core/done_on_main.ts";
2424 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
2525 import { createToken } from "../src/core/tokens.ts";
2626 import { createUser, getUserByName, type User } from "../src/core/users.ts";
27 import { driveRepo } from "../src/crew/autonomy.ts";
27 import { driveRepo } from "../src/crew/drive.ts";
2828 import { taskPrompt } from "../src/crew/brief.ts";
2929 import { ISSUE_RUN_CAP } from "../src/crew/guard.ts";
3030 import { heldCounts, heldNow, heldWords, stuckOf } from "../src/crew/held.ts";
test/crew-hot-files.test.ts +1 −1
@@ -22,7 +22,7 @@ import { getRepoById, type Repo } from "../src/core/repos.ts";
2222 import { createToken } from "../src/core/tokens.ts";
2323 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2424 import { forgetHeat, warmingLine } from "../src/crew/hot_history.ts";
25 import { driveRepo } from "../src/crew/autonomy.ts";
25 import { driveRepo } from "../src/crew/drive.ts";
2626 import { heldNow, heldWords } from "../src/crew/held.ts";
2727 import {
2828 expectedFiles,

78 more files not shown.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs