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

Knobs: the autonomy card shows the week's budget as a share of the week and a pace, with no daily dollar ceiling #12312

Merged opened this

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

Merged

torque/forge:torque/10623-knobs-the-autonomy-card-shows-the-week-s → main 28 commits fork 5 threads · 5 unresolved

  • Merged. torque/10623-knobs-the-autonomy-card-shows-the-week-s was merged into main as b0c4221.

Review

Sign in to review this change.
98 files changed +503 −444
bench/snappy.ts −1
@@ -104,7 +104,6 @@ export async function snappyFixture(
104104 const on = await updateRepoSettings(app, owner, repo, {
105105 autonomy: "assisted",
106106 autonomyDirection: "Keep going.",
107 autonomyCeilingUsd: 10,
108107 autonomySlots: 1,
109108 autonomyBy: owner.id,
110109 });
docs/CACHING.md +1 −1
@@ -393,7 +393,7 @@ or stops saying what it did, this doc goes red before the cache goes stale.
393393 | `actions/runs#announceRun` | `run.finished` | a ringed card, the lane's crew |
394394 | `actions/crew#addToCrew` | `crew.added` | who speaks for the crew |
395395 | `actions/crew#removeFromCrew` | `crew.removed` | who speaks for the crew |
396 | `actions/repos#updateRepoSettings` | `repo.settings_updated` | autonomy, ceiling, slots |
396 | `actions/repos#updateRepoSettings` | `repo.settings_updated` | autonomy, slots |
397397 | `actions/repos#setCrewOutsiders` | `repo.crew_outsiders` | unadopted cards |
398398 | `actions/returns#reportSpend` | `spend.reported` | the spend bar |
399399
docs/PLANNING.md +1 −1
@@ -129,7 +129,7 @@ nothing to draw are left out; a forge with nothing to draw anywhere says
129129 so in one sentence. It is reached from the user menu and the command
130130 palette, and from the Apps card on either home. `GET /api/v1/map` is the
131131 same, one entry per repository, each the repository's map data plus
132 `autonomy`, `spentTodayUsd`, `ceilingUsd`, `inFlight`, `workers` and
132 `autonomy`, `spentTodayUsd`, `week`, `inFlight`, `workers` and
133133 `idle`.
134134
135135 ## Parked twice
docs/REFERENCE.md +1 −1
@@ -85,7 +85,7 @@ In the terminal, `T` on a shipped pull's screen takes it back, as the pull page'
8585
8686 In the terminal, `m` on a local repository's issue list opens the plan screen (`src/tui/screens/plan.ts`): Working, Ready now, Waiting and Parked twice, each headed with its count. It reads what MCP `map` reads (`repoGraph` under the reader's sealed scope, `pillarView`, `mapHeldFor`, the runs in flight), so a sealed issue the reader may not see is left out. Enter opens the issue, `r` reads again, and the headings are skipped over. It is not offered on the pulls list or on a live browse of another forge.
8787
88 In the terminal, open a repository and pick **Autonomy** from the palette (`:`): mode, dollar ceiling a day and slots, as Settings › Autonomy has them. It is offered only to whoever administers the repository (`canAdmin`, an agent included, as the page's API allows); anyone else gets no entry and sees no value. `m` opens a confirm naming each mode and the ceiling, with Off, Assisted and Autonomous as its buttons and Cancel selected, so any mode is one pick away; `c` sets the ceiling, `s` the slots; bounds are the page's (`checkAutonomy`), and each saves through `updateRepoSettings` and says the page's flash (`AUTONOMY_SAID`).
88 In the terminal, open a repository and pick **Autonomy** from the palette (`:`): mode, the week's budget as a share of the week and the pace it is spending at (read-only: Weekly budget is the knob), and slots, as Settings › Autonomy has them. There is no daily dollar ceiling (#10623). It is offered only to whoever administers the repository (`canAdmin`, an agent included, as the page's API allows); anyone else gets no entry and sees no value. `m` opens a confirm naming each mode and the week's budget, with Off, Assisted and Autonomous as its buttons and Cancel selected, so any mode is one pick away; `s` sets the slots; bounds are the page's (`checkAutonomy`), and each saves through `updateRepoSettings` and says the page's flash (`AUTONOMY_SAID`).
8989
9090 In the terminal, a repository screen's `:` palette offers **Delete this repository** (`<owner>/<name> — Delete this repository`, "cannot be undone") to a person who administers it, never to an agent, a writer who is not an admin or a reader. It asks for the full `<owner>/<name>`; anything else is refused with "Type <owner>/<name> to confirm." and nothing changes. The exact name calls `deleteRepo` (`src/actions/repos.ts`, as Settings' danger zone does), toasts the result and unwinds the stack to the screen beneath the repository's (`leaveRepo`), so no screen reads the deleted row.
9191
docs/features/crew-week.md +1 −2
@@ -4,8 +4,7 @@
44
55 - Only new picks wait on it. Finishing, rework and reviews use `repoPace(..., false)` and run ahead.
66 - `autonomyTick` drives repositories with a backed bet first, so a short budget goes to what the owner backed, then the rest in order.
7 - A repository that hit its daily ceiling yesterday restarts at its own time in the first six hours of the UTC day (`src/crew/ceiling_stagger.ts`), so the midnight reset is not a burst.
7 - There is no daily dollar ceiling and no midnight stagger (#10623): the week's share is the one gate. `autonomy_ceiling_usd` stays in the table, unread and unwritten, so no migration rewrites the table; the autonomy card, the terminal screen and `GET /api/v1/map` show the share of the week used (`week`: used, allowed, elapsed, `pace`, `resetsAt`) instead of `ceilingUsd`; the `ceiling` fleet verb is gone.
88 - Home and the terminal print the crew's number: "the week allows the whole crew N of M slots".
99 - Picks made earlier in the same tick in other repositories count against the budget before their runs show, so a burst across repositories cannot pass the crew's floor.

Stale: there is no ceiling of 0 and no 'hit yesterday' read any more. Delete this bullet.

10 - A ceiling of 0 allows no spend and is held by the ceiling itself; it is never also held until an offset. The "hit yesterday" read is remembered per repository for one instant, so `repoPace` runs it once a tick.
1110 - Work a person assigns starts through the dispatcher, which does not read `repoPace`, so it is not held by the crew's budget.
docs/features/seat-slots.md +1 −1
@@ -24,7 +24,7 @@ A change takes effect on the next tick and is a `repo.settings_updated` line on
2424 | Planner on or off by removing it from the crew | **Replaced** by the planner's number; pausing is no longer removal. |
2525 | Mode (off, assisted, autonomous) | Keep: the one switch for whether the team works alone. |
2626 | Direction | Keep: what the planner plans against. |
27 | Ceiling per day | Keep: the only dollar limit. |
27 | Ceiling per day | **Removed** (#10623): the week's share is the one gate; the form no longer has the field. |
2828 | Decisions here, Plans need a nod, Outsiders may trigger the crew | Keep: each is who answers, and none holds work silently. |
2929 | File holds (Settings › Held files) | Keep: an admin's explicit, named hold on one path; it is the only setting here that holds work, so it says so where the work waits: the hold's row lists the issues it keeps waiting, and `flow` on such an issue says an admin holds the file, not that it is hot. |
3030 | Team dials (Settings › Teams) | Keep: a share between teams, not a seat's number; it only reorders queued starts and holds nothing (all at 0 is the order the forge always had). |
src/core/repos.ts +8 −15
@@ -88,7 +88,7 @@ export const isAutonomy = (value: unknown): value is Autonomy =>
8888
8989 /** What the settings page and the terminal say when autonomy input is out of bounds. */
9090 export const AUTONOMY_BOUNDS =
91 "Mode is off, assisted or autonomous; the ceiling is a number of dollars; slots are 0 (paused) to 8.";
91 "Mode is off, assisted or autonomous; slots are 0 (paused) to 8.";
9292
9393 /** What each mode does, in one sentence: the settings page's flash and the terminal's toast. */
9494 export const AUTONOMY_SAID: Readonly<Record<Autonomy, string>> = {
@@ -97,16 +97,13 @@ export const AUTONOMY_SAID: Readonly<Record<Autonomy, string>> = {
9797 autonomous: "Autonomous: the crew works what is ready and ships on green, as you.",
9898 };
9999
100 /** The mode, dollar ceiling and slots, checked once for every surface; the sentence is the refusal. */
100 /** The mode and slots, checked once for every surface; the sentence is the refusal. */
101101 export function checkAutonomy(
102102 mode: unknown,
103 ceiling: number,
104103 slots: number,
105104 ): { ok: true; mode: Autonomy } | { ok: false; message: string } {
106105 if (
107106 !isAutonomy(mode) ||
108 !Number.isFinite(ceiling) ||
109 ceiling < 0 ||
110107 !Number.isInteger(slots) ||
111108 slots < 0 ||
112109 slots > PILLAR_MAX
@@ -151,7 +148,6 @@ export interface Repo {
151148 */
152149 readonly autonomy: Autonomy;
153150 readonly autonomyDirection: string;
154 readonly autonomyCeilingUsd: number;
155151 readonly autonomySlots: number;
156152 /** Planning passes at once: 0 pauses the planner, 1 is the most. */
157153 readonly plannerSlots: number;
@@ -213,7 +209,6 @@ interface RepoRow {
213209 landing: string;
214210 autonomy: string;
215211 autonomy_direction: string;
216 autonomy_ceiling_usd: number;
217212 autonomy_slots: number;
218213 planner_slots: number;
219214 reviewer_slots: number;
@@ -260,7 +255,6 @@ function toRepo(row: RepoRow): Repo {
260255 landing: row.landing === "linear" ? "linear" : "merge",
261256 autonomy: isAutonomy(row.autonomy) ? row.autonomy : "off",
262257 autonomyDirection: row.autonomy_direction,
263 autonomyCeilingUsd: row.autonomy_ceiling_usd,
264258 autonomySlots: row.autonomy_slots,
265259 plannerSlots: row.planner_slots,
266260 reviewerSlots: row.reviewer_slots,
@@ -960,8 +954,8 @@ export function listReposToTake(db: Database, viewer: User | undefined, limit =
960954 /** The columns `toRepo` shows; `issue_seq` is not one, since a sealed report moves it. */
961955 const SHOWN = [
962956 "repo.id", "repo.owner_id", "user.username", "repo.name", "repo.visibility", "repo.description",
963 "repo.default_branch", "repo.protect_default", "repo.require_review", "repo.require_checks", "repo.landing",
964 "repo.autonomy", "repo.autonomy_direction", "repo.autonomy_ceiling_usd", "repo.autonomy_slots",
957 "repo.default_branch", "repo.protect_default", "repo.require_review", "repo.require_checks",
958 "repo.landing", "repo.autonomy", "repo.autonomy_direction", "repo.autonomy_slots",
965959 "repo.planner_slots", "repo.reviewer_slots", "repo.polish_share", "repo.autonomy_by",
966960 "repo.crew_outsiders", "repo.decisions_by", "repo.plans_need_nod", "repo.direction_issue_id",
967961 "repo.fork_parent_id", "repo.sealed_for", "repo.archived_at", "repo.origin_id",
@@ -1371,7 +1365,6 @@ export interface RepoSettings {
13711365 defaultBranch?: string;
13721366 autonomy?: Autonomy;
13731367 autonomyDirection?: string;
1374 autonomyCeilingUsd?: number;
13751368 autonomySlots?: number;
13761369 plannerSlots?: number;
13771370 reviewerSlots?: number;
@@ -1405,9 +1398,10 @@ export function updateRepoSettings(
14051398 db.query(
14061399 `UPDATE repo SET visibility = ?1, description = ?2, protect_default = ?3,
14071400 default_branch = ?4, require_review = ?5, require_checks = ?7,
1408 autonomy = ?8, autonomy_direction = ?9, autonomy_ceiling_usd = ?10,
1409 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13, decisions_by = ?14,
1410 plans_need_nod = ?15, planner_slots = ?16, reviewer_slots = ?17, polish_share = ?18, landing = ?19
1401 autonomy = ?8, autonomy_direction = ?9,
1402 autonomy_slots = ?10, autonomy_by = ?11, crew_outsiders = ?12, decisions_by = ?13,
1403 plans_need_nod = ?14, planner_slots = ?15, reviewer_slots = ?16, polish_share = ?17,
1404 landing = ?18
14111405 WHERE id = ?6`,
14121406 ).run(
14131407 settings.visibility ?? repo.visibility,
@@ -1419,7 +1413,6 @@ export function updateRepoSettings(
14191413 (settings.requireChecks ?? repo.requireChecks) ? 1 : 0,
14201414 settings.autonomy ?? repo.autonomy,
14211415 settings.autonomyDirection ?? repo.autonomyDirection,
1422 settings.autonomyCeilingUsd ?? repo.autonomyCeilingUsd,
14231416 settings.autonomySlots ?? repo.autonomySlots,
14241417 settings.autonomyBy === undefined ? repo.autonomyBy : settings.autonomyBy,
14251418 (settings.crewOutsiders ?? repo.crewOutsiders) ? 1 : 0,
src/crew/autonomy.ts +43 −26
@@ -1,6 +1,6 @@
11 /**
22 * A repository that runs on its own. Every minute, for each repository whose
3 * autonomy is on: spend today against the ceiling; free slots against the
3 * autonomy is on: the week's share spent; free slots against the
44 * runs in flight; the map's ready list against the builders; and, when the
55 * map has run dry, the planner against the direction. Green pulls land
66 * when the repository is autonomous. All of it acts as the person who
@@ -8,7 +8,7 @@
88 * every run and merge is credited and bounded exactly as theirs would be.
99 *
1010 * What it never does: start more than the slots allow, spend past the
11 * ceiling, re-queue anything a person must decide, or write to a
11 * week's share, re-queue anything a person must decide, or write to a
1212 * repository's origin.
1313 */
1414
@@ -107,8 +107,7 @@ import { grantedAccounts } from "../core/subscriptions.ts";
107107 import { reviewSummary } from "../core/reviews.ts";
108108 import { standing } from "../core/standing.ts";
109109 import { pace, type Pace } from "./pacing.ts";
110 import { staggeredUntil } from "./ceiling_stagger.ts";
111 import { crewWeekFor } from "./week_read.ts";
110 import { crewWeekFor, weekSpent } from "./week_read.ts";
112111 import { announceGovernor, governorFor } from "./governed.ts";
113112 import { BREAKER_NOTE, breakerTripped } from "./breaker.ts";
114113 import { REPEAT_NOTE } from "./repeat_note.ts";
@@ -170,12 +169,23 @@ export const AUTONOMY_TICK_MS = 60_000;
170169 */
171170 const REPLAN_AFTER_MS = 20 * 60_000;
172171
173 export type Paused = "ceiling" | "forge ceiling" | "nobody" | "no crew";
172 export type Paused = "week" | "forge ceiling" | "nobody" | "no crew";
174173
175174 export interface AutonomyStatus {
176175 readonly autonomy: Repo["autonomy"];
177176 readonly spentTodayUsd: number;
178 readonly ceilingUsd: number;
177 /**
178 * The week's budget as a share of the week and the pace it is spending at,
179 * as the provider's meter reads it; null while the week is unmeasured.
180 * There is no daily dollar ceiling beside it.
181 */
182 readonly week: {
183 readonly usedPct: number;
184 readonly mayUsePct: number;
185 readonly elapsedPct: number;
186 readonly pace: "ahead" | "on" | "behind";
187 readonly resetsAt: string;
188 } | null;
179189 readonly slots: number;
180190 /**
181191 * Agent runs in flight here that spend a slot — what `slottedRuns` counts,
@@ -183,7 +193,10 @@ export interface AutonomyStatus {
183193 */
184194 readonly active: number;
185195 readonly paused: Paused | null;
186 /** When a ceiling pause lifts: the next UTC midnight. */
196 /**
197 * When a pause lifts: the week's reset for a spent week, the next UTC midnight for the
198 * forge's cap.
199 */
187200 readonly resumesAt: string | null;
188201 }
189202
@@ -257,22 +270,22 @@ export function spentTodayForRepos(
257270 }
258271
259272 /**
260 * Whether a repository is paused at today's ceiling right now — the same
261 * three conditions `autonomyStatus`'s own `"ceiling"` reads for one, but
262 * asked of crew and spend already read for the whole set
263 * (`crewForRepos`, `spentTodayForRepos`), never a query of its own. The
264 * ask card (`studio/asks.ts`) and the studio home's cost line
273 * Whether a repository is paused because the week's share is spent right
274 * now — the same conditions `autonomyStatus`'s own `"week"` reads for one,
275 * asked of crew already read for the whole set (`crewForRepos`). The ask
276 * card (`studio/asks.ts`) and the studio home's cost line
265277 * (`studio/home.ts`) both decide from this, so neither can disagree with
266278 * the other about which app is paused.
267279 */
268 export function isPausedAtCeiling(
280 export function isPausedForWeek(
281 app: Pick<App, "db">,
269282 repo: Repo,
270283 crew: ReadonlyMap<string, readonly string[]>,
271 spent: ReadonlyMap<string, number>,
284 now: Date = new Date(),
272285 ): boolean {
273286 if (repo.autonomy === "off" || repo.autonomyBy === null) return false;
274287 if ((crew.get(repo.id)?.length ?? 0) === 0) return false;
275 return (spent.get(repo.id) ?? 0) >= repo.autonomyCeilingUsd;
288 return weekSpent(app, repo, now);
276289 }
277290
278291 function activeRuns(app: App, repoId: string) {
@@ -326,6 +339,7 @@ export function autonomyStatus(
326339 const spent = spentToday(app.db, repo.id, now);
327340 const crew = listCrewRoles(app.db, repo.id);
328341 const forgeCap = forgeCeiling(app.config);
342 const decision = crewWeekFor(app, repo, now);
329343 const paused: Paused | null =
330344 repo.autonomy === "off"
331345 ? null
@@ -333,8 +347,8 @@ export function autonomyStatus(
333347 ? "nobody"
334348 : crew.length === 0
335349 ? "no crew"
336 : spent >= repo.autonomyCeilingUsd
337 ? "ceiling"
350 : decision !== null && decision.slots === 0
351 ? "week"
338352 : ceilingReached(spentTodayEverywhere(app.db, now), forgeCap)
339353 ? "forge ceiling"
340354 : null;
@@ -343,14 +357,19 @@ export function autonomyStatus(
343357 return {
344358 autonomy: repo.autonomy,
345359 spentTodayUsd: spent,
346 ceilingUsd: repo.autonomyCeilingUsd,
360 week:
361 decision === null
362 ? null
363 : { usedPct: decision.usedPct, mayUsePct: decision.mayUsePct, elapsedPct: decision.elapsedPct, pace: decision.pace, resetsAt: decision.resetsAt },
347364 slots: repo.autonomySlots,
348365 active: slottedRuns(activeRuns(app, repo.id), crew).length,
349366 paused,
350367 resumesAt:
351 paused === "ceiling" || paused === "forge ceiling"
352 ? tomorrow.toISOString()
353 : null,
368 paused === "week" && decision !== null
369 ? decision.resetsAt
370 : paused === "forge ceiling"
371 ? tomorrow.toISOString()
372 : null,
354373 };
355374 }
356375
@@ -387,13 +406,10 @@ export function repoPace(app: App, repo: Repo, now = new Date(), crew = true, pi
387406 );
388407 const paced = pace(accounts, repo.autonomySlots, meanRunUsd(app.db, repo.id), now);
389408 // Finishing and rework run ahead of new picks: only a new pick waits on the governor, the
390 // crew's week and the midnight spread.
409 // crew's week.
391410 if (!crew) return paced;
392411 const governed = governorFor(app, repo, now).slots;
393412 const limited = governed < paced.slots ? { ...paced, slots: governed } : paced;
394 const until = staggeredUntil(app.db, repo, now);
395 if (until !== null)
396 return { ...limited, slots: 0, reason: `0 of ${repo.autonomySlots} slots until ${until.toISOString().slice(11, 16)} UTC: the daily ceilings reset together and each repository restarts at its own time` };
397413 // The week's ceiling is one budget for the whole crew on these accounts (#8989).
398414 const week = crewWeekFor(app, repo, now);
399415 return week !== null && week.slots === 0 ? { ...limited, slots: 0, reason: week.sentence } : limited;
@@ -1398,7 +1414,8 @@ export async function autonomyTick(
13981414 batch: batchWords(current.id, queueBatch(app.db)),
13991415 // Pulls the queue found red on top of others of their candidate (#4235).
14001416 clashes: queueClashes(current.id),
1401 spent: `${status.spentTodayUsd.toFixed(2)}/${status.ceilingUsd}`,
1417 spent: status.spentTodayUsd.toFixed(2),
1418 ...(status.week === null ? {} : { week: `${status.week.usedPct}/${status.week.mayUsePct}%` }),
14021419 ...(status.paused === null ? {} : { paused: status.paused }),
14031420 // Starts after the first, and how many followed a crash (#3708).
14041421 restarts: boots.restarts,
src/crew/ceiling_stagger.ts deleted −56
@@ -1,56 +0,0 @@
1 /**
2 * The daily ceilings reset together at 00:00 UTC. A repository that hit its
3 * ceiling yesterday starts again at its own offset into the day, spread over
4 * `SPREAD_MS` by a hash of its id, so the reset is not a burst (#8989).
5 * Pure but for one read of yesterday's spend.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 /** How far into the day the offsets reach. */
11 export const SPREAD_MS = 6 * 3_600_000;
12
13 const DAY_MS = 86_400_000;
14
15 /** A stable offset in [0, SPREAD_MS) from the repository's id. */
16 export function offsetOf(repoId: string): number {
17 let h = 2166136261;
18 for (let i = 0; i < repoId.length; i++) h = Math.imul(h ^ repoId.charCodeAt(i), 16777619) >>> 0;
19 return h % SPREAD_MS;
20 }
21
22 interface Memo {
23 readonly nowMs: number;
24 readonly ceiling: number;
25 readonly until: Date | null;
26 }
27
28 /** The answer per repository for the instant it was asked: `repoPace` asks many times a tick, with one `now`. */
29 const memo = new Map<string, Memo>();
30
31 /** Forget what was read; for tests that change yesterday's spend under one `now`. */
32 export function forgetStagger(): void {
33 memo.clear();
34 }
35
36 /**
37 * When this repository may start again today, or null: it did not hit its
38 * ceiling yesterday, or its time has come. A ceiling of 0 allows no spend at
39 * all and is held by the ceiling itself, so it is never "hit yesterday" here.
40 */
41 export function staggeredUntil(db: Database, repo: { id: string; autonomyCeilingUsd: number }, now: Date): Date | null {
42 const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
43 const at = today + offsetOf(repo.id);
44 if (now.getTime() >= at || !(repo.autonomyCeilingUsd > 0)) return null;
45 const seen = memo.get(repo.id);
46 if (seen !== undefined && seen.nowMs === now.getTime() && seen.ceiling === repo.autonomyCeilingUsd) return seen.until;
47 const spent =
48 db
49 .query<{ s: number | null }, [string, string, string]>(
50 `SELECT SUM(cost_usd) AS s FROM run WHERE repo_id = ?1 AND kind = 'agent' AND created_at >= ?2 AND created_at < ?3`,
51 )
52 .get(repo.id, new Date(today - DAY_MS).toISOString(), new Date(today).toISOString())?.s ?? 0;
53 const until = spent >= repo.autonomyCeilingUsd ? new Date(at) : null;
54 memo.set(repo.id, { nowMs: now.getTime(), ceiling: repo.autonomyCeilingUsd, until });
55 return until;
56 }
src/crew/dispatch.ts +5 −14
@@ -14,7 +14,7 @@ import { crewFilters, isStrangerPull } from "./stranger.ts";
1414 import { TEMP_FULL } from "../checks/disk_full.ts";
1515 import { freshPullFor } from "./fresh_pull.ts";
1616 import { weekHold } from "./week_hold.ts";
17 import { weekFor } from "./week_read.ts";
17 import { weekFor, weekSpent } from "./week_read.ts";
1818 import { twinNote, twinOf, type Twin } from "./twin.ts";
1919 import { NO_MERGE } from "../checks/merged.ts";
2020 import { resolveListConflicts } from "../actions/list-conflicts.ts";
@@ -111,7 +111,6 @@ import {
111111 landIfGreen,
112112 parkForBreaker,
113113 settleAgentRun,
114 spentToday,
115114 } from "./autonomy.ts";
116115 import { checksFor } from "../checks/service.ts";
117116 import { redMain, sharedWithMain } from "../checks/red_main.ts";
@@ -404,14 +403,6 @@ function handOver(
404403 });
405404 }
406405
407 /** Whether `spentUsd` has reached the repository's daily ceiling: the test that stops a run being queued. */
408 export function atCeiling(
409 repo: Pick<Repo, "autonomyCeilingUsd">,
410 spentUsd: number,
411 ): boolean {
412 return spentUsd >= repo.autonomyCeilingUsd;
413 }
414
415406 /**
416407 * Whether this run is a job outside the agent's seat here: a build for one
417408 * that is not a builder (the direction issue is the planner's), a review for
@@ -504,16 +495,16 @@ export function queueAgentRun(
504495 // actions that start one by name refuse out loud before they get here.
505496 const asker = actorId === undefined ? undefined : getUserById(app.db, actorId);
506497 if (asker !== undefined && lacks(app.db, asker, "run_crew")) return undefined;
507 // The day's ceiling gates every run the crew starts on its own, not only
508 // the picks: a review, a feedback run or a conflict run past the ceiling
498 // The week's share gates every run the crew starts on its own, not only
499 // the picks: a review, a feedback run or a conflict run past the week's share
509500 // is money the person did not agree to. A person's own assignment is not
510501 // the crew's.
511502 if (
512503 reason !== "assigned" &&
513504 repo.autonomy === "autonomous" &&
514 atCeiling(repo, spentToday(app.db, repo.id))
505 weekSpent(app, repo, new Date())
515506 ) {
516 log.info("at the ceiling; not queued", {
507 log.info("the week's share is spent; not queued", {
517508 repo: `${repo.ownerName}/${repo.name}`,
518509 issue: issue.number,
519510 reason,
src/crew/handover.ts +9 −2
@@ -32,6 +32,7 @@ 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";
3434 import { spentTodayForRepos } from "./autonomy.ts";
35 import { crewWeekFor } from "./week_read.ts";
3536 import { certain, decideOr, type Answers, type Questions } from "./decide.ts";
3637 import { parkReasons } from "./parks.ts";
3738
@@ -95,7 +96,11 @@ export interface HandContext {
9596 readonly pinned: boolean;
9697 readonly muted: boolean;
9798 };
98 readonly spend: { readonly todayUsd: number; readonly ceilingUsd: number };
99 /**
100 * Today's spend, and the week as the provider's meter reads it (percent used, percent the
101 * crew may use); null while the week is unmeasured.
102 */
103 readonly spend: { readonly todayUsd: number; readonly weekUsedPct: number | null; readonly weekMayUsePct: number | null };
99104 readonly recent: readonly { kind: string; how: string; at: string }[];
100105 readonly evidence: {
101106 readonly number: number;
@@ -113,6 +118,7 @@ export function handContext(
113118 issue: Issue,
114119 ): HandContext {
115120 const db = app.db;
121 const week = crewWeekFor(app, repo, new Date());
116122 return {
117123 direction: repo.autonomyDirection.slice(0, DIRECTION_MAX),
118124 repository: {
@@ -122,7 +128,8 @@ export function handContext(
122128 },
123129 spend: {
124130 todayUsd: spentTodayForRepos(db, [repo.id]).get(repo.id) ?? 0,
125 ceilingUsd: repo.autonomyCeilingUsd,
131 weekUsedPct: week?.usedPct ?? null,
132 weekMayUsePct: week?.mayUsePct ?? null,
126133 },
127134 recent: recentEnds(db, owner.id, repo.id, 10),
128135 evidence: {
src/crew/idle_reason.ts +9 −6
@@ -3,8 +3,8 @@
33 * the terminal's dashboard (and a later tile) to print.
44 *
55 * Every reason is asked of the module the dispatcher asks it of, in the
6 * dispatcher's order, and the first that holds is the answer: the day's
7 * ceiling (`atCeiling` against `spentToday`, as `queueAgentRun` asks it), then
6 * dispatcher's order, and the first that holds is the answer: the week's
7 * share (`weekSpent`, as `queueAgentRun` asks it), then
88 * what `heldNow` sorts (`held.ts`: `nothing
99 * ready` is its empty `startable`), and the subscriptions' headroom (`pace`,
1010 * as `repoPace` asks it). The repository is the first autonomous one with a
@@ -17,8 +17,8 @@ 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, spentToday } from "./autonomy.ts";
21 import { atCeiling } from "./dispatch.ts";
20 import { slottedRuns } from "./autonomy.ts";
21 import { weekSpent } from "./week_read.ts";
2222 import { governorFor } from "./governed.ts";
2323 import { heldNow, HOLDS } from "./held.ts";
2424 import { pace } from "./pacing.ts";
@@ -28,10 +28,13 @@ export interface IdleReason {
2828 readonly href: string;
2929 }
3030
31 /** The ceiling or the subscriptions, when one of them is why this repository starts nothing; null when neither is. */
31 /**
32 * The week's share or the subscriptions, when one of them is why this repository starts
33 * nothing; null when neither is.
34 */
3235 export function whatBlocks(app: App, repo: Repo, now: Date): IdleReason | null {
3336 const { db } = app;
34 if (atCeiling(repo, spentToday(db, repo.id, now))) return { word: "ceiling reached", href: "/meter" };
37 if (weekSpent(app, repo, now)) return { word: "week spent", href: "/meter" };
3538
3639 const granted = grantedAccounts(db, repo.id, repo.ownerId);
3740 if (granted.length > 0) {
src/crew/triage.ts +2 −2
@@ -483,9 +483,9 @@ export async function triageTick(app: App, now = new Date()): Promise<number> {
483483 const first = new Date(oldest.receivedAt).getTime();
484484 // The batch closes once its first thought is two minutes old.
485485 if (now.getTime() - first < BATCH_MS) continue;
486 // Over the day's ceiling the planner waits; so does the repository.
486 // With the week's share spent the planner waits; so does the repository.
487487 const paused = autonomyStatus(app, repo, now).paused;
488 if (paused === "ceiling" || paused === "forge ceiling") continue;
488 if (paused === "week" || paused === "forge ceiling") continue;
489489 const batch = waiting.filter((t) => new Date(t.receivedAt).getTime() - first <= BATCH_MS).slice(0, BATCH_MAX);
490490 for (const t of batch) {
491491 await placeThought(app, repo, by, t, now);
src/crew/week.ts +26
@@ -37,6 +37,15 @@ export interface WeekDecision {
3737 /** Percent of the week used, and the most the crew may use. */
3838 readonly usedPct: number;
3939 readonly mayUsePct: number;
40 /** Percent of the week gone since the last reset (0..100): an even spend's share by now. */
41 readonly elapsedPct: number;
42 /**
43 * Spending ahead of, on, or behind an even pace: used share against the share of the week
44 * gone (a point of slack counts as on).
45 */
46 readonly pace: "ahead" | "on" | "behind";
47 /** When the provider's week resets (ISO). */
48 readonly resetsAt: string;
4049 /** One sentence for home and the log. */
4150 readonly sentence: string;
4251 }
@@ -55,7 +64,12 @@ export function weekDecision(input: WeekInput): WeekDecision | null {
5564 const stopped = used >= wall;
5665 const usedPct = Math.round(used);
5766 const mayUsePct = Math.round(wall);
67 const elapsed = Math.min(100, Math.max(0, (1 - left / WINDOW_MS.week) * 100));
68 const elapsedPct = Math.round(elapsed);
5869 return {
70 elapsedPct,
71 pace: used > elapsed + 1 ? "ahead" : used < elapsed - 1 ? "behind" : "on",
72 resetsAt: meter.resetsAt.toISOString(),
5973 slots: stopped ? 0 : ceiling,
6074 usedPct,
6175 mayUsePct,
@@ -63,6 +77,18 @@ export function weekDecision(input: WeekInput): WeekDecision | null {
6377 };
6478 }
6579
80 /**
81 * The week's budget for the autonomy card, the terminal and the board, in two
82 * short plain pieces a `dl` row each: the share used of the share allowed, and
83 * the pace spend runs at against an even one. Percent of the provider's week,
84 * never dollars. Null while the week is unmeasured.
85 */
86 export function weekCardRows(
87 week: Pick<WeekDecision, "usedPct" | "mayUsePct" | "pace"> | null,
88 ): { readonly week: string; readonly pace: string } | null {
89 return week === null ? null : { week: `${week.usedPct}% used of ${week.mayUsePct}% allowed`, pace: week.pace };
outdated

Principles 1 and 8: one long sentence with '·' and a parenthetical. Split into plain short rows (Week: used of allowed; Pace: ahead/on/behind) and let callers place them as dl rows.

90 }
91
6692 /** What each real landing cost, and how many runs it took, over a window. */
6793 export interface Efficiency {
6894 readonly landings: number;
src/crew/week_read.ts +23 −5
@@ -16,6 +16,12 @@ interface Week {
1616 readonly meter: WeekMeter | null;
1717 }
1818
19 /**
20 * What reading a repository's week needs of the app: its database only, so a list that
21 * holds no `App` can ask whether the week is spent.
22 */
23 type Reads = Pick<App, "db">;
24
outdated

Cache rekeying from Map to WeakMap is unrelated to the autonomy card. Separate pull.

1925 /** How long a repository's week is remembered: `weekFor` is asked many times a tick. */
2026 const REMEMBER_MS = 5_000;
2127 const remembered = new Map<string, { at: number; week: Week }>();
@@ -26,8 +32,8 @@ export function forgetWeek(): void {
2632 }
2733
2834 /** The week's meter over the repository's accounts; an unknown meter while none has a known limit. */
29 function weekOf(app: App, repo: Repo, now: Date): Week {
30 const key = `${app.config.dataDir}\0${repo.id}`;
35 function weekOf(app: Reads, repo: Repo, now: Date): Week {
36 const key = `${app.db.filename}\0${repo.id}`;
3137 const hit = remembered.get(key);
3238 if (hit !== undefined && Math.abs(now.getTime() - hit.at) < REMEMBER_MS) return hit.week;
3339 const week = readWeek(app, repo, now);
@@ -35,7 +41,7 @@ function weekOf(app: App, repo: Repo, now: Date): Week {
3541 return week;
3642 }
3743
38 function readWeek(app: App, repo: Repo, now: Date): Week {
44 function readWeek(app: Reads, repo: Repo, now: Date): Week {
3945 // A crew with no grant runs on the forge's own token: the account `usage`
4046 // prints as `platform`. It is metered too, never skipped (#8873).
4147 const granted = grantedAccounts(app.db, repo.id, repo.ownerId).map((a) => a.id);
@@ -98,13 +104,13 @@ export function weekFor(app: App, repo: Repo, now: Date): WeekDecision | null {
98104 * under (`dispatch.ts`), so home never says 5 of 5 while the crew runs 4
99105 * (#10440) — else the repository's own.
100106 */
101 export function crewCeiling(app: App, repo: Repo): number {
107 export function crewCeiling(app: Reads, repo: Repo): number {
102108 const booted = Number(capacityValue(app.db, "crew.concurrency"));
103109 return capacityCount(app.db, "crew.concurrency", Number.isInteger(booted) && booted > 0 ? booted : repo.autonomySlots);
104110 }
105111
106112 /** The week's decision for the whole crew drawing on this repository's accounts, at the crew's ceiling. */
107 export function crewWeekFor(app: App, repo: Repo, now: Date): WeekDecision | null {
113 export function crewWeekFor(app: Reads, repo: Repo, now: Date): WeekDecision | null {
108114 return weekDecision({ meter: weekOf(app, repo, now).meter, now, ceiling: crewCeiling(app, repo), reserve: 1 - weekUse(app.db) / 100 });
109115 }
110116
@@ -158,3 +164,15 @@ export function budgetEffect(app: App, now: Date = new Date()): string {
158164 export function weekShare(app: App, now: Date = new Date()): { readonly usedPct: number; readonly mayUsePct: number } | null {
159165 return busiest(app, now, (_repo, week) => ({ usedPct: week.usedPct, mayUsePct: week.mayUsePct }));
160166 }
167
168 /**
169 * Whether the week's share is spent for the crew on this repository: the
170 * provider's own percent of the week used has reached what the Weekly budget
171 * lets the crew use. The one test that stops a crew run being queued or
172 * picked; it is false while the week is unmeasured. There is no daily
173 * dollar ceiling beside it.
174 */
175 export function weekSpent(app: Reads, repo: Repo, now: Date): boolean {
176 const week = crewWeekFor(app, repo, now);
177 return week !== null && week.slots === 0;
178 }
src/fleet/verbs.ts +2 −9
@@ -131,7 +131,7 @@ const WORDS: Record<string, string> = {
131131 not_finished: "only a cancelled or failed run is queued again",
132132 no_task: "its issue is closed or its agent is gone",
133133 archived: ARCHIVED_WHY,
134 not_queued: "the crew would not take it now (already queued, parked, or at the ceiling)",
134 not_queued: "the crew would not take it now (already queued, parked, or the week's share is spent)",
135135 unknown_branch: "unknown branch",
136136 };
137137
@@ -155,7 +155,7 @@ const replace = (_before: FleetValue, value: FleetValue): FleetValue => value;
155155
156156 /** A repository setting: the row holds the setting's value. */
157157 function setting(
158 field: "autonomy" | "autonomySlots" | "autonomyCeilingUsd" | "autonomyDirection",
158 field: "autonomy" | "autonomySlots" | "autonomyDirection",
159159 parse: (value: unknown) => Result<FleetValue, string>,
160160 ): Verb {
161161 return {
@@ -175,8 +175,6 @@ function setting(
175175 settings.autonomyDirection = after;
176176 else if (field === "autonomySlots" && typeof after === "number")
177177 settings.autonomySlots = after;
178 else if (field === "autonomyCeilingUsd" && typeof after === "number")
179 settings.autonomyCeilingUsd = after;
180178 else return "not a value for this setting";
181179 return done(await updateRepoSettings(app, actor, t.repo, settings));
182180 },
@@ -304,11 +302,6 @@ export const VERBS: Record<string, Verb> = {
304302 ? ok(v)
305303 : err("slots are a whole number from 1 to 8"),
306304 ),
307 ceiling: setting("autonomyCeilingUsd", (v) =>
308 typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 10_000
309 ? ok(Math.round(v * 100) / 100)
310 : err("the ceiling is a number of dollars from 0 to 10000"),
311 ),
312305 direction: setting("autonomyDirection", (v) =>
313306 typeof v === "string" && v.trim().length <= 2000
314307 ? ok(v.trim())
src/flow/keeper_cause.ts +6 −7
@@ -2,7 +2,7 @@
22 * What binds the forge's landings right now (#7645): one cause from a closed
33 * list, in the order the dispatcher meets them. `pickCause` is plain data in,
44 * plain data out; `readKeeperFacts` reads the same questions the dispatcher
5 * asks (`heldNow`, `atCeiling`, `pace`) so the keeper and the builders cannot
5 * asks (`heldNow`, `weekSpent`, `pace`) so the keeper and the builders cannot
66 * disagree. No model is asked anything.
77 */
88
@@ -12,8 +12,8 @@ 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, spentToday } from "../crew/autonomy.ts";
16 import { atCeiling } from "../crew/dispatch.ts";
15 import { slottedRuns } from "../crew/autonomy.ts";
16 import { weekSpent } from "../crew/week_read.ts";
1717 import { heldNow } from "../crew/held.ts";
1818 import { pace } from "../crew/pacing.ts";
1919 import { readPile } from "./pile.ts";
@@ -43,7 +43,7 @@ export interface RepoFacts {
4343 /** Builder runs in flight, and the slots they fill. */
4444 readonly running: number;
4545 readonly slots: number;
46 readonly ceilingUsd: number;
46 /** The week's share is spent: the crew waits for the provider's reset. */
4747 readonly atCeiling: boolean;
4848 readonly noHeadroom: boolean;
4949 /** When the soonest spent window resets (ISO), if a subscription is out. */
@@ -79,7 +79,7 @@ export function pickCause(f: KeeperFacts, skip: ReadonlySet<KeeperCause> = new S
7979 for (const r of f.repos) {
8080 const waiting = r.startable;
8181 if (r.atCeiling && waiting > 0 && !skip.has("ceiling"))
82 return { cause: "ceiling", move: "say", repoId: r.repoId, says: `The daily ceiling ($${r.ceilingUsd}) is reached in ${r.slug}: builders start again at 00:00 UTC.` };
82 return { cause: "ceiling", move: "say", repoId: r.repoId, says: `The week's share is spent in ${r.slug}: builders start again when the week resets.` };
8383 }
8484 for (const r of f.repos) {
8585 if (r.noHeadroom && r.startable > 0 && !skip.has("usage"))
@@ -156,8 +156,7 @@ export function readKeeperFacts(app: App, now: Date): KeeperFacts {
156156 startable: held.startable.length,
157157 running: slottedRuns(active, crew).length,
158158 slots: repo.autonomySlots,
159 ceilingUsd: repo.autonomyCeilingUsd,
160 atCeiling: atCeiling(repo, spentToday(db, repo.id, now)),
159 atCeiling: weekSpent(app, repo, now),
161160 noHeadroom,
162161 resetsAt,
163162 });
src/tui/screens/autonomy.ts +13 −16
@@ -16,6 +16,8 @@
1616
1717 import { updateRepoSettings } from "../../actions/repos.ts";
1818 import { POLISH_SHARE_MAX, validPolishShare } from "../../crew/polish_share.ts";
19 import { weekCardRows } from "../../crew/week.ts";
20 import { crewWeekFor } from "../../crew/week_read.ts";
1921 import { seatSlotsSaid, setSeatSlots } from "../../actions/seat_slots.ts";
2022 import { checkSeatSlots, seatSlotsOf, seatSlotsWords } from "../../crew/seat_slots.ts";
2123 import type { CrewRole } from "../../core/agents.ts";
@@ -39,7 +41,12 @@ import { confirmScreen, promptScreen } from "./common.ts";
3941
4042 const MODE_LABEL: Record<Autonomy, string> = { off: "Off", assisted: "Assisted", autonomous: "Autonomous" };
4143
42 const dollars = (n: number): string => `$${n}`;
44
45 /** The card's Week and Pace lines; one plain line while the week is unmeasured. */
46 function weekLines(week: Parameters<typeof weekCardRows>[0]): string[] {
47 const rows = weekCardRows(week);
48 return rows === null ? ["Week not measured yet"] : [`Week ${rows.week}`, `Pace ${rows.pace}`];
49 }
4350
4451 const mayAdminister = (f: Session, repo: Repo): boolean =>
4552 f.user !== undefined && canAdmin(f.db, repo, f.user);
@@ -62,16 +69,14 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6269 // Whoever administers the repository; the action decides again on save.
6370 const mayChange = (): boolean => mayAdminister(f, current());
6471
65 const save = (patch: { mode?: Autonomy; ceiling?: number; slots?: number }, said: string): void => {
72 const save = (patch: { mode?: Autonomy; slots?: number }, said: string): void => {
6673 const now = current();
6774 const mode = patch.mode ?? now.autonomy;
68 const ceiling = patch.ceiling ?? now.autonomyCeilingUsd;
6975 const slots = patch.slots ?? now.autonomySlots;
70 const checked = checkAutonomy(mode, ceiling, slots);
76 const checked = checkAutonomy(mode, slots);
7177 if (!checked.ok) return void ctx.toast(checked.message, "danger");
7278 void updateRepoSettings(f.app, f.user, now, {
7379 autonomy: mode,
74 autonomyCeilingUsd: ceiling,
7580 autonomySlots: slots,
7681 autonomyBy: mode === "off" ? null : (f.user?.id ?? null),
7782 }).then(
@@ -104,7 +109,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
104109 title: "Autonomy",
105110 get keys() {
106111 return mayChange()
107 ? [binding(["m"], "mode"), binding(["c"], "ceiling"), binding(["p"], "planner"), binding(["s"], "builder"), binding(["r"], "reviewer"), binding(["o"], "polish share")]
112 ? [binding(["m"], "mode"), binding(["p"], "planner"), binding(["s"], "builder"), binding(["r"], "reviewer"), binding(["o"], "polish share")]
108113 : [];
109114 },
110115 render(area, s) {
@@ -117,7 +122,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
117122 "",
118123 `Mode ${r.autonomy}`,
119124 ` ${AUTONOMY_SAID[r.autonomy]}`,
120 `Ceiling ${dollars(r.autonomyCeilingUsd)} a day`,
125 ...weekLines(crewWeekFor(f.app, r, new Date())),
121126 `Polish ${r.polishShare}% of the week's spend`,
122127 ...seatSlotsOf(f.db, r).map(
123128 (p) => `${(p.role[0]!.toUpperCase() + p.role.slice(1)).padEnd(9)}${p.slots} at once · ${seatSlotsWords(p)}`,
@@ -139,7 +144,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
139144 title: `Set autonomy (now ${now.autonomy})`,
140145 body: [
141146 ...AUTONOMY.map((mode) => AUTONOMY_SAID[mode]),
142 `The ceiling that applies is ${dollars(now.autonomyCeilingUsd)} a day.`,
147 "The week's budget applies: its share used and its pace are on the card.",
143148 ],
144149 actions: [
145150 ...AUTONOMY.map((mode) => ({ label: MODE_LABEL[mode] })),
@@ -156,14 +161,6 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
156161 );
157162 return true;
158163 }
159 if (e.key === "c") {
160 ask("Ceiling", "dollars a day, 0 or more", "0 or more", String(current().autonomyCeilingUsd), (raw) => {
161 const n = /^\d+(\.\d+)?$/.test(raw) ? Number(raw) : Number.NaN;
162 save({ ceiling: n }, `Ceiling is ${dollars(n)} a day.`);
163 return undefined;
164 });
165 return true;
166 }
167164 if (e.key === "o") {
168165 ask("Polish share", `percent of the week's spend, 0 to ${POLISH_SHARE_MAX}`, `0 to ${POLISH_SHARE_MAX}`, String(current().polishShare), (raw) => {
169166 const n = /^\d{1,3}$/.test(raw) ? Number(raw) : Number.NaN;
src/web/pages/board.ts +12 −5
@@ -18,6 +18,7 @@
1818 * pointer. The old big view (`/big`, every address it had) lands here.
1919 */
2020
21 import { weekCardRows } from "../../crew/week.ts";
2122 import { hoursSpan, readThroughput } from "../../flow/throughput.ts";
2223 import { usd } from "../../core/money.ts";
2324 import { NO_CLOUD_BODY } from "../../core/placement_policy.ts";
@@ -885,13 +886,19 @@ function byPillar(ctx: Ctx, scope: BoardScope): Html | null {
885886 // ---- decided ----
886887
887888 /** A hand-over's row says why, and what the decider saw (`crew/handover.ts`). */
889 /** The meter's title: the week's share used of the share allowed, in the card's words. */
890 function weekMeterTitle(week: Parameters<typeof weekCardRows>[0]): string {
891 const rows = weekCardRows(week);
892 return rows === null ? "The week is not measured yet" : `Week: ${rows.week}`;
893 }
894
888895 function handContextLine(d: Decision): string {
889896 const s = d.state as Partial<HandContext> & { reason?: string };
890897 const seen = [
891898 // One person's pins and mutes stay out of a line other owners read.
892899 s.spend === undefined
893900 ? null
894 : `${money(s.spend.todayUsd)} of ${money(s.spend.ceilingUsd)} today`,
901 : `${money(s.spend.todayUsd)} today${s.spend.weekUsedPct === null ? "" : `, ${s.spend.weekUsedPct}% of the week used`}`,
895902 `${s.recent?.length ?? 0} past decisions`,
896903 `${s.evidence?.reasons.length ?? 0} park notes`,
897904 ].filter((x): x is string => x !== null);
@@ -1048,7 +1055,7 @@ function today(ctx: Ctx, scope: BoardScope): Html {
10481055 // than the week: counted by the database, not off a page of rows.
10491056 const runs = agentRunTotals(db, repo.id, since).runs;
10501057 const shipped = mergedPullCount(db, repo.id, since);
1051 const share = s.ceilingUsd > 0 ? s.spentTodayUsd / s.ceilingUsd : 0;
1058 const share = s.week === null || s.week.mayUsePct <= 0 ? 0 : s.week.usedPct / s.week.mayUsePct;
10521059 const review = reviewWords(reviewStats(db, repo.id, since));
10531060 const held =
10541061 repo.autonomy === "autonomous" ? plannerHold(ctx.app, repo, now) : null;
@@ -1062,7 +1069,7 @@ function today(ctx: Ctx, scope: BoardScope): Html {
10621069 ? html`<span class="muted small">${note}</span>`
10631070 : badge(note, { tone: "attn" })}`,
10641071 meta: [
1065 html`<span><b>${money(s.spentTodayUsd)}</b> of $${s.ceilingUsd.toFixed(0)}</span>
1072 html`<span><b>${money(s.spentTodayUsd)}</b> today</span>
10661073 · <span><b>${runs}</b> run${runs === 1 ? "" : "s"}</span> ·
10671074 <span><b>${shipped}</b> shipped</span>`,
10681075 `${perShippedWords(week.get(repo.id))} this week`,
@@ -1071,8 +1078,8 @@ function today(ctx: Ctx, scope: BoardScope): Html {
10711078 ],
10721079 under: meter(
10731080 share * 100,
1074 `${money(s.spentTodayUsd)} of its $${s.ceilingUsd.toFixed(0)} ceiling today`,
1075 s.paused === "ceiling" ? "attn" : undefined,
1081 weekMeterTitle(s.week),
1082 s.paused === "week" ? "attn" : undefined,
10761083 ),
10771084 });
10781085 });
src/web/pages/crew.ts +9 −7
@@ -40,6 +40,7 @@ import {
4040 type SplitScorecard,
4141 } from "../../core/scorecard.ts";
4242 import { keeperDays, type KeeperDay } from "../../flow/keeper_rate.ts";
43 import { weekCardRows } from "../../crew/week.ts";
4344 import { weekCard, weekReturns, WEEK_DAYS, type ReturnedPull, type WeekLine } from "../../crew/week_card.ts";
4445 import { knobsCard } from "./knobs.ts";
4546 import { decideChange, readReview } from "../../actions/model_review.ts";
@@ -444,13 +445,14 @@ function weekCardPanel(lines: readonly WeekLine[], returns: ReadonlyMap<string,
444445 );
445446 }
446447
447 /** Today's spend against each ceiling: the drain, and the knob for it. */
448 /** Today's spend and the week's share spent, per app: the drain, and where to turn it. */
448449 function spendingCard(
449450 spending: readonly { repo: Repo; status: AutonomyStatus }[],
450451 forgeCap: number | undefined,
451452 ): Html {
452453 const total = spending.reduce((n, s) => n + s.status.spentTodayUsd, 0);
453 const cap = spending.reduce((n, s) => n + s.status.ceilingUsd, 0);
454 // The provider's week is one for the crew: said once, here, not per app.
455 const weekRows = weekCardRows(spending.find((s) => s.status.week !== null)?.status.week ?? null);
454456 return panel(
455457 html`<ul class="list">
456458 ${spending.map(
@@ -468,8 +470,8 @@ function spendingCard(
468470 <span class="row-meta"
469471 >${repo.autonomy} · ${status.slots}
470472 ${status.slots === 1 ? "slot" : "slots"} · ${status.active}
471 active${status.paused === "ceiling"
472 ? " · paused at the ceiling until 00:00 UTC"
473 active${status.paused === "week"
474 ? " · paused: the week's share is spent, until the week resets"
473475 : status.paused === "forge ceiling"
474476 ? " · paused at the forge's ceiling until 00:00 UTC"
475477 : ""}</span
@@ -478,7 +480,7 @@ function spendingCard(
478480 <span class="row-trail">
479481 <b>$${status.spentTodayUsd.toFixed(0)}</b>
outdated

Principle 1: the same provider-week sentence repeats on every app row of the card. State the week once in the card note; keep per-row dollars only.

480482 <span class="muted"
481 >/ $${status.ceilingUsd.toFixed(0)} today</span
483 >today</span
482484 >
483485 </span>
484486 </a>
@@ -487,12 +489,12 @@ function spendingCard(
487489 </ul>`,
488490 {
489491 title: "Spending today",
490 note: html`$${total.toFixed(0)} of $${cap.toFixed(0)} across ${spending.length}
492 note: html`$${total.toFixed(0)} today across ${spending.length}
491493 ${spending.length === 1 ? "app" : "apps"} running on their
492494 own${forgeCap === undefined
493495 ? "; no forge-wide ceiling is set (FORGE_CREW_CEILING_USD)"
494496 : `, under the forge's $${forgeCap.toFixed(0)} a day`};
495 the ceilings reset at 00:00 UTC`,
497 the week's share resets with the provider's week${weekRows === null ? "" : `. Week: ${weekRows.week}. Pace: ${weekRows.pace}`}`,
496498 },
497499 );
498500 }
src/web/pages/global-map.ts +1 −1
@@ -352,7 +352,7 @@ export function globalMapJson(
352352 ...mapJson(lane.repo, lane.graph, lane.marks),
353353 autonomy: lane.repo.autonomy,
354354 spentTodayUsd: lane.status?.spentTodayUsd ?? null,
355 ceilingUsd: lane.status?.ceilingUsd ?? null,
355 week: lane.status?.week ?? null,
356356 inFlight: lane.inFlight,
357357 workers: lane.workers,
358358 idle: lane.idle,
src/web/pages/settings.ts +1 −3
@@ -1516,11 +1516,10 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
15161516 if (gate instanceof Response) return gate;
15171517 const { repo, form } = gate;
15181518 const base = repoBase(repo);
1519 const ceiling = Number(field(form, "ceiling"));
15201519 // The builders' slots are the Builder pillar's number on the team card; this form only keeps them.
15211520 const slotsField = field(form, "slots");
15221521 const slots = slotsField === "" ? repo.autonomySlots : Number(slotsField);
1523 const checked = checkAutonomy(field(form, "autonomy"), ceiling, slots);
1522 const checked = checkAutonomy(field(form, "autonomy"), slots);
15241523 if (!checked.ok)
15251524 return flashTo(ctx, `${base}/settings#autonomy`, {
15261525 tone: "danger",
@@ -1537,7 +1536,6 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
15371536 const updated = await updateRepoSettings(ctx.app, ctx.auth.user, repo, {
15381537 autonomy: mode,
15391538 autonomyDirection: field(form, "direction").trim().slice(0, 2000),
1540 autonomyCeilingUsd: ceiling,
15411539 autonomySlots: slots,
15421540 autonomyBy: mode === "off" ? null : (ctx.auth.user?.id ?? null),
15431541 // Only a change is sent: an agent admin may save the rest of the form.
src/web/studio/app.ts +3 −5
@@ -28,7 +28,7 @@ import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
2828 import type { PreviewLatency } from "../../core/runs.ts";
2929 import { autonomyStatus } from "../../crew/autonomy.ts";
3030 import { governorSeen } from "../../crew/governed.ts";
31 import { governorRows } from "./governor_rows.ts";
31 import { governorRows, weekCardDl } from "./governor_rows.ts";
3232 import { repoDir } from "../../git/repos.ts";
3333 import type { Ctx } from "../../http/context.ts";
3434 import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts";
@@ -442,11 +442,9 @@ export async function studioApp(
442442 <dd>
443443 ${repo.autonomy === "autonomous" ? "By itself" : "With you"}
444444 </dd>
445 ${weekCardDl(autonomy.week)}
445446 <dt>Today</dt>
446 <dd>
447 $${autonomy.spentTodayUsd.toFixed(2)} of
448 $${autonomy.ceilingUsd.toFixed(0)}
449 </dd>
447 <dd>$${autonomy.spentTodayUsd.toFixed(2)} spent</dd>
450448 <dt>Slots</dt>
451449 <dd>${autonomy.active} of ${autonomy.slots} in use</dd>
452450 ${governorRows(governor)}
src/web/studio/asks.ts +5 −10
@@ -54,9 +54,8 @@ import {
5454 } from "../../core/runs.ts";
5555 import { getUserById, getUsersByIds, type User } from "../../core/users.ts";
5656 import {
57 isPausedAtCeiling,
57 isPausedForWeek,
5858 plannerDeclines,
59 spentTodayForRepos,
6059 } from "../../crew/autonomy.ts";
6160 import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts";
6261 import { handoversOf, passReasonOf, type Handover } from "../../crew/guard.ts";
@@ -623,7 +622,7 @@ function askCandidatesFor(
623622 return out;
624623 }
625624
626 /** The asks a repository makes that are not a pull's: a ceiling pause, a
625 /** The asks a repository makes that are not a pull's: a spent week, a
627626 * parked issue, a planner's decline, a wave waiting for its nod. */
628627 function repoAsksInto(
629628 db: Database,
@@ -635,16 +634,12 @@ function repoAsksInto(
635634 db,
636635 repos.map((r) => r.id),
637636 );
638 const spent = spentTodayForRepos(
639 db,
640 repos.map((r) => r.id),
641 );
642 // Only a ceiling pause is an ask — "nobody" and "no crew" are settings
637 // Only a spent week is an ask — "nobody" and "no crew" are settings
643638 // problems, not a decision, so neither needs its own card.
644 // A ceiling pause is today's: tomorrow it is a new one.
639 // A pause is dated to today: after a reset it is a new one.
645640 const today = `${new Date().toISOString().slice(0, 10)}T00:00:00.000Z`;
646641 for (const repo of repos)
647 if (isPausedAtCeiling(repo, crew, spent))
642 if (isPausedForWeek({ db }, repo, crew))
648643 out.push({
649644 kind: "paused",
650645 id: `paused:${repo.id}`,
src/web/studio/cost_line.ts +4 −4
@@ -1,6 +1,6 @@
11 /**
22 * What the crew cost today across the apps a person can write, and how many
3 * are paused at their ceiling — the owner's first question about their apps,
3 * are paused with the week's share spent — the owner's first question about their apps,
44 * asked on `/apps` (#599: it was the old home's). One bounded read each
55 * (`spentTodayForRepos`, `crewForRepos`), never a query per app; every app
66 * passed is one the viewer can write, so the money stays the owner's own.
@@ -8,7 +8,7 @@
88
99 import { crewForRepos } from "../../core/agents.ts";
1010 import type { Repo } from "../../core/repos.ts";
11 import { isPausedAtCeiling, spentTodayForRepos } from "../../crew/autonomy.ts";
11 import { isPausedForWeek, spentTodayForRepos } from "../../crew/autonomy.ts";
1212 import type { Database } from "bun:sqlite";
1313 import { html, type Html } from "../html.ts";
1414
@@ -18,10 +18,10 @@ export function costLine(db: Database, writable: readonly Repo[]): Html | null {
1818 const spentToday = spentTodayForRepos(db, ids);
1919 const crew = crewForRepos(db, ids);
2020 const spentUsd = writable.reduce((sum, r) => sum + (spentToday.get(r.id) ?? 0), 0);
21 const paused = writable.filter((r) => isPausedAtCeiling(r, crew, spentToday)).length;
21 const paused = writable.filter((r) => isPausedForWeek({ db }, r, crew)).length;
2222 const noun = `app${writable.length === 1 ? "" : "s"}`;
2323 const sentence = `$${spentUsd.toFixed(2)} spent today across ${writable.length} ${noun} you can write`;
2424 return html`<p class="small muted studio-cost">
25 ${sentence} · ${paused} paused at <a href="/board">their ceiling</a>
25 ${sentence} · ${paused} paused with the <a href="/board">week's share spent</a>
2626 </p>`;
2727 }
src/web/studio/crew.ts +5 −14
@@ -32,7 +32,7 @@ import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
3232 import { seatsOf, type Seat } from "../../crew/seats.ts";
3333 import { autonomyStatus } from "../../crew/autonomy.ts";
3434 import { governorSeen } from "../../crew/governed.ts";
35 import { governorRows } from "./governor_rows.ts";
35 import { governorRows, weekCardDl } from "./governor_rows.ts";
3636 import { crewOffInPreview } from "../../crew/preview.ts";
3737 import type { Ctx } from "../../http/context.ts";
3838 import { repoBase } from "../chrome.ts";
@@ -348,19 +348,17 @@ function autonomyCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html
348348 : html`<dl>
349349 <dt>Mode</dt>
350350 <dd>${repo.autonomy === "autonomous" ? "Autonomous" : "Assisted"}</dd>
351 ${weekCardDl(status.week)}
351352 <dt>Today</dt>
352 <dd>
353 $${status.spentTodayUsd.toFixed(2)} of
354 $${status.ceilingUsd.toFixed(0)}
355 </dd>
353 <dd>$${status.spentTodayUsd.toFixed(2)} spent</dd>
356354 <dt>Slots</dt>
357355 <dd>${status.active} of ${status.slots} in use</dd>
358356 ${governorRows(governor)}
359357 ${status.paused
360358 ? html`<dt>Paused</dt>
361359 <dd>
362 ${status.paused === "ceiling"
363 ? "at the ceiling, until 00:00 UTC"
360 ${status.paused === "week"
361 ? "the week's share is spent, until the week resets"
364362 : status.paused}
365363 </dd>`
366364 : null}
@@ -429,13 +427,6 @@ ${repo.autonomyDirection}</textarea
429427 },
430428 ],
431429 })}
432 ${field({
433 label: "Ceiling per day",
434 name: "ceiling",
435 value: String(repo.autonomyCeilingUsd),
436 type: "number",
437 hint: `Dollars of agent spend on this ${getAppByRepo(ctx.app.db, repo.id) === undefined ? "repository" : "app"} per UTC day. At the ceiling the crew stops picking until midnight; nothing in flight is cut.`,
438 })}
439430 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
440431 </form>`;
441432 return html`<section class="settings-block" id="autonomy">
src/web/studio/decisions.ts +2 −3
@@ -34,7 +34,6 @@ const movedSays = (moved: boolean | undefined): string =>
3434 moved === true ? " It was approved, and its head or base has moved since that approval." : "";
3535
3636 /** Dollars as a person reads them: cents when small, whole when not. */
37 const dollars = (n: number): string => (n < 10 ? n.toFixed(2) : n.toFixed(0));
3837
3938 /** What asks the viewer now, and, when `onHidden` is given, how many rows their filters hid in the same pass. */
4039 function withoutHidden(db: Database, user: User | undefined, repos: readonly Repo[], onHidden?: (rows: number) => void): Scored[] {
@@ -206,8 +205,8 @@ export function decisionsFor(
206205 id: `paused:${c.repo.id}`,
207206 repo: c.repo,
208207 who: "the crew",
209 says: `${c.repo.name} reached its $${dollars(c.repo.autonomyCeilingUsd)} for today. The crew picks nothing more until 00:00 UTC. Raise the ceiling in settings to go on now.`,
210 short: `at its $${dollars(c.repo.autonomyCeilingUsd)} ceiling until 00:00 UTC`,
208 says: `${c.repo.name} has spent the share of the week the Weekly budget gives the crew. The crew picks nothing more until the week resets. Raise the Weekly budget on the crew page to go on now.`,
209 short: `the week's share is spent, until the week resets`,
211210 };
212211 };
213212 const previewOf = (c: Scored): string | undefined =>
src/web/studio/governor_rows.ts +10
@@ -2,9 +2,19 @@
22
33 import type { GovernorSeen } from "../../crew/governed.ts";
44 import { governorLine } from "../../crew/governed.ts";
5 import { weekCardRows } from "../../crew/week.ts";
56 import { html, type Html } from "../html.ts";
67
78 /** The `<dt>/<dd>` pair for the governor, or null while the crew is off or the reader may not see it. */
89 export function governorRows(governor: GovernorSeen | undefined): Html | null {
910 return governor === undefined ? null : html`<dt>Governor</dt><dd>${governorLine(governor)}</dd>`;
1011 }
12
13 /**
14 * The autonomy card's Week and Pace rows: the share of the week used against what is
15 * allowed, and the pace; one plain row while the week is unmeasured.
16 */
17 export function weekCardDl(week: Parameters<typeof weekCardRows>[0]): Html {
18 const rows = weekCardRows(week);
19 return rows === null ? html`<dt>Week</dt><dd>not measured yet</dd>` : html`<dt>Week</dt><dd>${rows.week}</dd><dt>Pace</dt><dd>${rows.pace}</dd>`;
20 }
src/web/studio/words.ts +2 −2
@@ -582,8 +582,8 @@ export function wordBadge(word: Word, id?: string, who?: string): Html {
582582 * the app page's *On its own* card and the board's *Today* row both. */
583583 export function pausedWords(paused: Paused): string {
584584 switch (paused) {
585 case "ceiling":
586 return "at the ceiling, until 00:00 UTC";
585 case "week":
586 return "the week's share is spent, until the week resets";
587587 case "forge ceiling":
588588 return "at the forge's ceiling, until 00:00 UTC";
589589 case "nobody":
test/apps-cost-line.test.ts +13 −9
@@ -1,10 +1,12 @@
11 /**
22 * The cost line on /apps (#6874): today's dollars across only the apps the
3 * viewer can write, how many sit paused at their ceiling, and nothing — no
3 * viewer can write, how many sit paused with the week's share spent, and nothing — no
44 * sentence, no figure — for a guest or a reader who writes no app. Runs are
55 * created now, so "today" holds without the test reading the clock itself.
66 */
77
8 import { noteMeasure } from "../src/core/measure.ts";
9 import { PLATFORM } from "../src/core/subscriptions.ts";
810 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
911 import { mkdtemp, rm } from "node:fs/promises";
1012 import { tmpdir } from "node:os";
@@ -53,13 +55,13 @@ describe("the cost line on /apps", () => {
5355 };
5456
5557 /** A public app owned by `owner` (the admin makes its agent), with one crew run costing `cost` today;
56 * `ceiling` turns autonomy on with that daily ceiling. */
58 * `on` turns autonomy on. */
5759 const appWithSpend = async (
5860 admin: User,
5961 owner: User,
6062 name: string,
6163 cost: number,
62 ceiling?: number,
64 on?: boolean,
6365 ) => {
6466 const made = await createRepo(app, owner, {
6567 name,
@@ -79,11 +81,10 @@ describe("the cost line on /apps", () => {
7981 const created = await createAgent(app, admin, { username: agent });
8082 if (!created.ok) throw new Error(String(created.error));
8183 expect(addToCrew(app, owner, repo, agent).ok).toBe(true);
82 if (ceiling !== undefined) {
84 if (on === true) {
8385 const on = await updateRepoSettings(app, owner, repo, {
8486 autonomy: "assisted",
8587 autonomyDirection: "",
86 autonomyCeilingUsd: ceiling,
8788 autonomySlots: 2,
8889 autonomyBy: owner.id,
8990 });
@@ -114,9 +115,12 @@ describe("the cost line on /apps", () => {
114115 const alice = await person("alice");
115116 const dave = await person("dave");
116117 await person("carol"); // writes no app
117 await appWithSpend(boss, alice, "beacon", 6, 5); // paused: $6 >= $5
118 await appWithSpend(boss, alice, "beacon", 6, true); // paused once the week is spent
118119 await appWithSpend(boss, alice, "loom", 2); // no autonomy: never paused
119120 await appWithSpend(boss, dave, "other", 3.5); // alice cannot write it
121 // The provider's week is used up: the one app on its own is paused; the rest are not.
122 const at = Date.now();
123 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 100, resetsAt: new Date(at + 3 * 86_400_000).toISOString(), observedAt: new Date(at).toISOString() });
120124 });
121125
122126 afterAll(async () => {
@@ -128,7 +132,7 @@ describe("the cost line on /apps", () => {
128132 test("the owner reads the sum of only their own two apps and the one paused", async () => {
129133 const text = (await apps(cookies.alice)).replace(/\s+/g, " ");
130134 expect(text).toContain(
131 "$8.00 spent today across 2 apps you can write · 1 paused at <a href=\"/board\">their ceiling</a>",
135 "$8.00 spent today across 2 apps you can write · 1 paused with the <a href=\"/board\">week's share spent</a>",
132136 );
133137 expect(text).not.toContain("$11.50");
134138 });
@@ -141,11 +145,11 @@ describe("the cost line on /apps", () => {
141145 }
142146 });
143147
144 test("one app reads '1 app', and the ceiling link answers the owner 200", async () => {
148 test("one app reads '1 app', and the week link answers the owner 200", async () => {
145149 const html = (await apps(cookies.dave)).replace(/\s+/g, " ");
146150 expect(html).toContain("$3.50 spent today across 1 app you can write · 0 paused");
147151 expect(html).not.toContain("1 apps");
148 const href = /<a href="([^"]+)">their ceiling<\/a>/.exec(html)?.[1];
152 const href = /<a href="([^"]+)">week's share spent<\/a>/.exec(html)?.[1];
149153 expect(href).toBe("/board");
150154 const res = await fetch(`${base}${href}`, {
151155 headers: { cookie: `${cookies.dave}; forge_mode=studio` },
test/asks-autonomous.test.ts −1
@@ -59,7 +59,6 @@ describe("autonomous repositories ask no one about the crew's own stalls", () =>
5959 repo = updateRepoSettings(app.db, repo, {
6060 autonomy: "autonomous",
6161 autonomyBy: alice.id,
62 autonomyCeilingUsd: 10,
6362 });
6463 expect(getRepoById(app.db, repo.id)!.autonomy).toBe("autonomous");
6564 expect(asking()).toBe(false);
test/autonomy.test.ts +24 −15
@@ -10,6 +10,9 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1010 import { mkdtemp, rm } from "node:fs/promises";
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
13 import { noteMeasure } from "../src/core/measure.ts";
14 import { PLATFORM } from "../src/core/subscriptions.ts";
15 import { forgetWeek } from "../src/crew/week_read.ts";
1316 import { createApp, type App } from "../src/app.ts";
1417 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1518 import { openIssue } from "../src/actions/issues.ts";
@@ -150,7 +153,6 @@ describe("a repository on its own", () => {
150153 const on = await updateRepoSettings(app, alice, repo, {
151154 autonomy: "autonomous",
152155 autonomyDirection: "Pull the engine out of the game.",
153 autonomyCeilingUsd: 10,
154156 autonomySlots: 1,
155157 autonomyBy: alice.id,
156158 });
@@ -182,7 +184,7 @@ describe("a repository on its own", () => {
182184 finishRun(app.db, run.id, { state: "ok", summary: "done", costUsd: 4 });
183185 });
184186
185 test("the ceiling pauses picking until midnight and says so", async () => {
187 test("a spent week share pauses picking until the week resets and says so; dollars alone pause nothing", async () => {
186188 const spent = createRun(app.db, {
187189 repoId: repo.id,
188190 kind: "agent",
@@ -192,14 +194,24 @@ describe("a repository on its own", () => {
192194 });
193195 claimRun(app.db, spent.id);
194196 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 7 });
197 // $11 today and the week unmeasured: nothing holds the crew but the provider.
198 const open = autonomyStatus(app, fresh());
199 expect(open.spentTodayUsd).toBeCloseTo(11, 5);
200 expect(open.paused).toBeNull();
201 expect(open.week).toBeNull();
202 // The provider says the week's share is used, early in the week: spending ahead of pace.
203 const at = Date.now();
204 const resetsAt = new Date(at + 6 * 86_400_000).toISOString();
205 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 100, resetsAt, observedAt: new Date(at).toISOString() });
206 forgetWeek();
195207 const status = autonomyStatus(app, fresh());
196 expect(status.spentTodayUsd).toBeCloseTo(11, 5);
197 expect(status.paused).toBe("ceiling");
198 expect(status.resumesAt).not.toBeNull();
208 expect(status.paused).toBe("week");
209 expect(status.week).toMatchObject({ usedPct: 100, pace: "ahead", resetsAt });
210 expect(status.resumesAt).toBe(resetsAt);
199211 expect(await driveRepo(app, fresh())).toBe("paused");
200 app.db
201 .query("UPDATE repo SET autonomy_ceiling_usd = 100 WHERE id = ?1")
202 .run(repo.id);
212 // The week resets: the crew goes on.
213 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 0, resetsAt, observedAt: new Date(at + 1000).toISOString() });
214 forgetWeek();
203215 expect(autonomyStatus(app, fresh()).paused).toBeNull();
204216 });
205217
@@ -558,7 +570,6 @@ describe("a repository on its own", () => {
558570 body: new URLSearchParams({
559571 autonomy: "assisted",
560572 direction: "Keep the engine small.",
561 ceiling: "25",
562573 slots: "2",
563574 }),
564575 redirect: "manual",
@@ -566,7 +577,6 @@ describe("a repository on its own", () => {
566577 expect(saved.status).toBe(303);
567578 const now = fresh();
568579 expect(now.autonomy).toBe("assisted");
569 expect(now.autonomyCeilingUsd).toBe(25);
570580 expect(now.autonomyDirection).toBe("Keep the engine small.");
571581 const role = await fetch(
572582 `${servers.url}/alice/engine/settings/crew/mason/role`,
@@ -584,13 +594,15 @@ describe("a repository on its own", () => {
584594 })
585595 ).text();
586596 expect(crew).toContain("reviewer");
587 // Today's spend against the new ceiling is the forge's crew page's; the
597 // Today's spend and the week's budget are the forge's crew page's; the
588598 // map only draws what waits for what.
589599 const forgeCrew = await (
590600 await fetch(`${servers.url}/settings/crew`, { headers: { cookie } })
591601 ).text();
592602 expect(forgeCrew).toMatch(/alice\/engine[\s\S]*?assisted/);
593 expect(forgeCrew).toMatch(/\/ \$25 today/);
603 // The page shows the day's spend and the week's budget, never a dollar ceiling.
604 expect(forgeCrew).toMatch(/today/);
605 expect(forgeCrew).not.toMatch(/\/ \$\d+ today/);
594606 const map = await (
595607 await fetch(`${servers.url}/alice/engine/map`, { headers: { cookie } })
596608 ).text();
@@ -602,7 +614,6 @@ describe("a repository on its own", () => {
602614 const on = await updateRepoSettings(app, alice, repo, {
603615 autonomy: "autonomous",
604616 autonomyDirection: "Keep going.",
605 autonomyCeilingUsd: 1000,
606617 autonomySlots: 1,
607618 autonomyBy: alice.id,
608619 });
@@ -691,7 +702,6 @@ describe("the slot count is the rule the loop enforces", () => {
691702 const on = await updateRepoSettings(app, alice, repo, {
692703 autonomy: "autonomous",
693704 autonomyDirection: "",
694 autonomyCeilingUsd: 10,
695705 autonomySlots: 2,
696706 autonomyBy: alice.id,
697707 });
@@ -828,7 +838,6 @@ describe("the planner is held while nothing lands or the plate is full", () => {
828838 const on = await updateRepoSettings(app, alice, repo, {
829839 autonomy: "autonomous",
830840 autonomyDirection: "Weave the loom",
831 autonomyCeilingUsd: 10,
832841 autonomySlots: 1,
833842 autonomyBy: alice.id,
834843 });
test/autonomy_sweep.test.ts −1
@@ -77,7 +77,6 @@ describe("the green sweep runs beside the tick", () => {
7777 const on = await updateRepoSettings(app, alice, repo, {
7878 autonomy: "autonomous",
7979 autonomyDirection: "Pull the engine out of the game.",
80 autonomyCeilingUsd: 10,
8180 autonomySlots: 1,
8281 autonomyBy: alice.id,
8382 });
test/bets.test.ts +1 −1
@@ -134,7 +134,7 @@ beforeAll(async () => {
134134 if (!agent.ok) throw new Error(String(agent.error));
135135 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
136136 }
137 expect((await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", autonomyDirection: "Keep notes tidy.", autonomyCeilingUsd: 10, autonomySlots: 3, autonomyBy: alice.id })).ok).toBe(true);
137 expect((await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", autonomyDirection: "Keep notes tidy.", autonomySlots: 3, autonomyBy: alice.id })).ok).toBe(true);
138138 servers = await serve(app);
139139 });
140140
test/board.test.ts +3 −3
@@ -113,7 +113,6 @@ describe("the board", () => {
113113 notes = updateRepoSettings(app.db, notes, {
114114 autonomy: "autonomous",
115115 autonomyDirection: "Notes that load fast.",
116 autonomyCeilingUsd: 20,
117116 autonomySlots: 2,
118117 autonomyBy: alice.id,
119118 });
@@ -148,9 +147,10 @@ describe("the board", () => {
148147 expect(html).toContain("Nobody is working right now.");
149148 expect(html).toContain("Nothing has shipped yet.");
150149 expect(html).toContain("Nothing decided yet.");
151 // The one app that runs on its own, with its ceiling.
150 // The one app that runs on its own, with its day's spend and the week's budget.
152151 expect(html).toContain('data-key="app:');
153 expect(html).toMatch(/\$0\.00<\/b> of\s+\$20/);
152 expect(html).toMatch(/\$0\.00<\/b> today/);
153 expect(html).not.toMatch(/ceiling today/);
154154 expect(html).toContain('id="board-live"');
155155 expect(html).toContain('id="board-clock"');
156156 expect(await withScripts(servers.url, html)).toContain("new EventSource('/events')");
test/box-pass.test.ts −1
@@ -122,7 +122,6 @@ describe("the reviewer's pass over the boxes", () => {
122122 const set = await updateRepoSettings(app, alice, made.value, {
123123 autonomy: "autonomous",
124124 autonomyDirection: "Keep the engine small.",
125 autonomyCeilingUsd: 100,
126125 autonomySlots: 1,
127126 autonomyBy: alice.id,
128127 });
test/crew-direction-autonomy.test.ts −1
@@ -128,7 +128,6 @@ async function autonomous(): Promise<Repo> {
128128 await updateRepoSettings(app, alice, repo, {
129129 autonomy: "autonomous",
130130 autonomyDirection: "Make the square rounder.",
131 autonomyCeilingUsd: 10,
132131 autonomySlots: 2,
133132 autonomyBy: alice.id,
134133 }),
test/crew-direction-cap.test.ts −1
@@ -97,7 +97,6 @@ describe("the direction is paced, not capped", () => {
9797 const set = await updateRepoSettings(app, alice, repo, {
9898 autonomy: "autonomous",
9999 autonomyDirection: "Keep the engine small.",
100 autonomyCeilingUsd: 100,
101100 autonomyBy: alice.id,
102101 });
103102 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/crew-early.test.ts −1
@@ -394,7 +394,6 @@ describe("the crew, with a stand-in Claude Code: the early pull", () => {
394394 const on = await updateRepoSettings(app, alice, repo, {
395395 autonomy: "autonomous",
396396 autonomyDirection: "Keep the garden small.",
397 autonomyCeilingUsd: 100,
398397 autonomyBy: alice.id,
399398 });
400399 expect(on.ok).toBe(true);
test/crew-governed.test.ts −1
@@ -48,7 +48,6 @@ describe("the governor in the picker", () => {
4848 const on = await updateRepoSettings(app, alice, repo, {
4949 autonomy: "autonomous",
5050 autonomyDirection: "Weave the loom",
51 autonomyCeilingUsd: 100,
5251 autonomySlots: 5,
5352 autonomyBy: alice.id,
5453 });
test/crew-guard.test.ts −1
@@ -423,7 +423,6 @@ describe("the planner is not given the direction again with nothing new (#1097)"
423423 await updateRepoSettings(app, alice, round, {
424424 autonomy: "autonomous",
425425 autonomyDirection: "Make the square rounder.",
426 autonomyCeilingUsd: 10,
427426 autonomySlots: 2,
428427 autonomyBy: alice.id,
429428 }),
test/crew-held.test.ts −1
@@ -55,7 +55,6 @@ async function crewed(
5555 const set = await updateRepoSettings(app, alice, made.value, {
5656 autonomy: "autonomous",
5757 autonomyDirection: "Keep the engine small.",
58 autonomyCeilingUsd: 100,
5958 autonomySlots: 1,
6059 autonomyBy: alice.id,
6160 });
test/crew-hot-files.test.ts −1
@@ -127,7 +127,6 @@ describe("the picker holds a build on a hot file", () => {
127127 const set = await updateRepoSettings(app, alice, made.value, {
128128 autonomy: "autonomous",
129129 autonomyDirection: "Keep the engine small.",
130 autonomyCeilingUsd: 100,
131130 autonomySlots: 1,
132131 autonomyBy: alice.id,
133132 });
test/crew-loop.test.ts −5
@@ -79,7 +79,6 @@ describe("an agent's own comment never starts its next run", () => {
7979 const set = await updateRepoSettings(app, alice, repo, {
8080 autonomy: "autonomous",
8181 autonomyDirection: "Keep the engine small.",
82 autonomyCeilingUsd: 100,
8382 autonomyBy: alice.id,
8483 });
8584 if (!set.ok) throw new Error(JSON.stringify(set.error));
@@ -318,7 +317,6 @@ describe("a crew reviewer's changes-requested wakes the builder", () => {
318317 test(`in ${autonomy}, the verdict queues the builder's follow-up with no person speaking`, async () => {
319318 const set = await updateRepoSettings(app, alice, fresh(), {
320319 autonomy,
321 autonomyCeilingUsd: 100,
322320 autonomyBy: alice.id,
323321 });
324322 if (!set.ok) throw new Error(JSON.stringify(set.error));
@@ -337,7 +335,6 @@ describe("a crew reviewer's changes-requested wakes the builder", () => {
337335 test("the third round hands the pull to a person in one card, and starts nothing", async () => {
338336 const set = await updateRepoSettings(app, alice, fresh(), {
339337 autonomy: "autonomous",
340 autonomyCeilingUsd: 100,
341338 autonomyBy: alice.id,
342339 });
343340 if (!set.ok) throw new Error(JSON.stringify(set.error));
@@ -433,7 +430,6 @@ describe("a crew reviewer's changes-requested wakes the builder", () => {
433430 test("the hand-over note quotes each review up to 600 characters, cut at a sentence end, with its line comments", async () => {
434431 const set = await updateRepoSettings(app, alice, fresh(), {
435432 autonomy: "autonomous",
436 autonomyCeilingUsd: 100,
437433 autonomyBy: alice.id,
438434 });
439435 if (!set.ok) throw new Error(JSON.stringify(set.error));
@@ -477,7 +473,6 @@ describe("a crew reviewer's changes-requested wakes the builder", () => {
477473 test("the third changes-requested hands the pull to a person; a fourth queues nothing", async () => {
478474 const set = await updateRepoSettings(app, alice, fresh(), {
479475 autonomy: "autonomous",
480 autonomyCeilingUsd: 100,
481476 autonomyBy: alice.id,
482477 });
483478 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/crew-own-forge.test.ts −1
@@ -41,7 +41,6 @@ describe("a forge of its own: its key, its limits, and the work picked back up",
4141 const on = await updateRepoSettings(app, alice, repo, {
4242 autonomy: "autonomous",
4343 autonomyDirection: "Keep the garden small.",
44 autonomyCeilingUsd: 100,
4544 autonomyBy: alice.id,
4645 });
4746 expect(on.ok).toBe(true);
test/crew-ranked-pick.test.ts −1
@@ -63,7 +63,6 @@ beforeAll(async () => {
6363 const on = await updateRepoSettings(app, alice, repo, {
6464 autonomy: "autonomous",
6565 autonomyDirection: "Keep the notes tidy.",
66 autonomyCeilingUsd: 10,
6766 autonomySlots: 3,
6867 autonomyBy: alice.id,
6968 });
test/crew-reserve.test.ts −1
@@ -142,7 +142,6 @@ describe("a planner that keeps a standing reserve", () => {
142142 const set = await updateRepoSettings(app, alice, repo, {
143143 autonomy: "autonomous",
144144 autonomyDirection: "Keep the engine small.",
145 autonomyCeilingUsd: 100,
146145 autonomySlots: 7,
147146 autonomyBy: alice.id,
148147 });
test/crew-retired.test.ts −1
@@ -75,7 +75,6 @@ describe("the picker and retirement issues", () => {
7575 const on = await updateRepoSettings(app, alice, repo, {
7676 autonomy: "autonomous",
7777 autonomyDirection: "Retire the old rules.",
78 autonomyCeilingUsd: 10,
7978 autonomySlots: 1,
8079 autonomyBy: alice.id,
8180 });
test/crew-retry-parked.test.ts +1 −1
@@ -62,7 +62,7 @@ describe("a parked-twice issue is tried again", () => {
6262 }
6363 seatAs(app.db, made.value.id, getUserByName(app.db, "atlas")!.id, "planner");
6464 const set = await updateRepoSettings(app, alice, made.value, {
65 autonomy: "autonomous", autonomyDirection: "Keep it small.", autonomyCeilingUsd: 100,
65 autonomy: "autonomous", autonomyDirection: "Keep it small.",
6666 autonomySlots: 1, autonomyBy: alice.id,
6767 });
6868 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/crew-small-share.test.ts −1
@@ -104,7 +104,6 @@ beforeAll(async () => {
104104 const on = await updateRepoSettings(app, alice, repo, {
105105 autonomy: "autonomous",
106106 autonomyDirection: "Keep the notes tidy.",
107 autonomyCeilingUsd: 10,
108107 autonomySlots: 5,
109108 autonomyBy: alice.id,
110109 });
test/crew-stalls.test.ts −1
@@ -59,7 +59,6 @@ async function crewed(builders: readonly string[]): Promise<Repo> {
5959 const set = await updateRepoSettings(app, alice, created.value, {
6060 autonomy: "assisted",
6161 autonomyDirection: "Keep the engine small.",
62 autonomyCeilingUsd: 100,
6362 autonomySlots: 2,
6463 autonomyBy: alice.id,
6564 });
test/crew-week.test.ts +2 −53
@@ -1,4 +1,4 @@
1 /** What the crew's repositories share: their own slots, the midnight spread and the bets' order (#8989). */
1 /** What the crew's repositories share: their own slots and the bets' order (#8989). */
22 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
33 import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
@@ -8,13 +8,11 @@ import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
88 import { createApp, type App } from "../src/app.ts";
99 import { setCapacity } from "../src/core/capacity.ts";
1010 import { getRepoById, type Repo } from "../src/core/repos.ts";
11 import { createRun } from "../src/core/runs.ts";
1211 import { setHeadroom } from "../src/core/standing.ts";
1312 import { addSubscription } from "../src/core/subscriptions.ts";
1413 import { type User } from "../src/core/users.ts";
1514 import { insertBet, markBacked } from "../src/core/bets.ts";
1615 import { byBackedBets, repoPace } from "../src/crew/autonomy.ts";
17 import { forgetStagger, offsetOf, SPREAD_MS, staggeredUntil } from "../src/crew/ceiling_stagger.ts";
1816 import { seedAdmin } from "./helpers/admin.ts";
1917 import { quietLogs } from "./helpers/globals.ts";
2018
@@ -43,7 +41,7 @@ beforeAll(async () => {
4341 const made = await createRepo(app, alice, { name, visibility: "private" });
4442 if (!made.ok) throw new Error(String(made.error));
4543 expect(addToCrew(app, alice, made.value, "builderbot").ok).toBe(true);
46 const on = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Ship it.", autonomyCeilingUsd: 1000, autonomySlots: 5, autonomyBy: alice.id });
44 const on = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Ship it.", autonomySlots: 5, autonomyBy: alice.id });
4745 expect(on.ok).toBe(true);
4846 app.db.query("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)").run(made.value.id, sub);
4947 repos.push(getRepoById(app.db, made.value.id)!);
@@ -66,55 +64,6 @@ test("a repository's own slots are its limit", () => {
6664 app.db.query("UPDATE repo SET autonomy_slots = 5 WHERE id = ?1").run(repos[2]!.id);
6765 });
6866
69 test("a repository that hit its ceiling yesterday restarts at its own time, spread over the morning", () => {
70 // Midnight itself: repository ids are random, so an instant past 00:00 would
71 // find a repository whose offset has already come and nothing held.
72 const midnight = new Date(Date.UTC(2026, 10, 3, 0, 0, 0));
73 for (const r of repos) {
74 const run = createRun(app.db, { repoId: r.id, kind: "agent" });
75 app.db.query("UPDATE run SET cost_usd = 1000, created_at = ?2, state = 'ok' WHERE id = ?1").run(run.id, new Date(Date.UTC(2026, 10, 2, 20, 0, 0)).toISOString());
76 }
77 const ready = repos.map((r) => staggeredUntil(app.db, r, midnight)?.getTime() ?? 0);
78 expect(new Set(ready).size).toBeGreaterThan(1);
79 for (const at of ready) expect(at).toBeLessThan(Date.UTC(2026, 10, 3) + SPREAD_MS);
80 for (const r of repos) {
81 expect(offsetOf(r.id)).toBeGreaterThanOrEqual(0);
82 expect(offsetOf(r.id)).toBeLessThan(SPREAD_MS);
83 }
84 // FNV-1a of "a" is fixed, so the offsets cannot drift between releases and move every repository's restart.
85 expect(offsetOf("a")).toBe(2_802_220);
86 expect(repoPace(app, repos[0]!, midnight, true).slots).toBe(0);
87 // Past the spread nothing waits.
88 expect(staggeredUntil(app.db, repos[0]!, new Date(Date.UTC(2026, 10, 3, 7)))).toBeNull();
89 // A repository that did not hit its ceiling is never held.
90 app.db.query("DELETE FROM run WHERE repo_id = ?1").run(repos[3]!.id);
91 forgetStagger();
92 expect(staggeredUntil(app.db, repos[3]!, midnight)).toBeNull();
93 });
94
95 test("a ceiling of 0 allows no spend and is held by the ceiling, so it is never also held until an offset", () => {
96 // Midnight itself: repository ids are random, so an instant past 00:00 would
97 // find a repository whose offset has already come and nothing held.
98 const midnight = new Date(Date.UTC(2026, 10, 3, 0, 0, 0));
99 forgetStagger();
100 expect(staggeredUntil(app.db, { id: repos[0]!.id, autonomyCeilingUsd: 0 }, midnight)).toBeNull();
101 });
102
103 test("the stagger reads yesterday's spend once for one instant", () => {
104 // Midnight itself: repository ids are random, so an instant past 00:00 would
105 // find a repository whose offset has already come and nothing held.
106 const midnight = new Date(Date.UTC(2026, 10, 3, 0, 0, 0));
107 const run = createRun(app.db, { repoId: repos[3]!.id, kind: "agent" });
108 app.db.query("UPDATE run SET cost_usd = 1000, created_at = ?2, state = 'ok' WHERE id = ?1").run(run.id, new Date(Date.UTC(2026, 10, 2, 20, 0, 0)).toISOString());
109 forgetStagger();
110 const first = staggeredUntil(app.db, repos[3]!, midnight);
111 expect(first).not.toBeNull();
112 app.db.query("DELETE FROM run WHERE id = ?1").run(run.id);
113 expect(staggeredUntil(app.db, repos[3]!, midnight)).toEqual(first);
114 forgetStagger();
115 expect(staggeredUntil(app.db, repos[3]!, midnight)).toBeNull();
116 });
117
11867 test("repositories with a backed bet are driven first, the rest in their order", () => {
11968 const bet = insertBet(app.db, { repoId: repos[3]!.id, name: "Search", journeys: "", appetite: 5, leadId: null, issueIds: [] }, NOW);
12069 markBacked(app.db, bet.id, 5, "owner", NOW);
test/data-browser.test.ts +3
@@ -23,6 +23,7 @@ quietLogs();
2323
2424 const AUDITED_CLEAR: string[] = [
2525 "app_domain.said",
26 // A variable (not a secret) kept in the clear and shown; secrets are sealed in value_enc.
2627 "app_env.value_plain",
2728 "app_feature_setting.value",
2829 "ask_filter.value",
@@ -31,6 +32,7 @@ const AUDITED_CLEAR: string[] = [
3132 "child_reach_grant.body_id",
3233 "comment.body",
3334 "degraded_span.sentence",
35 "desk_note.body",
3436 "efficiency_sample.value",
3537 // What one thread observed for another (`engine/observed.ts`): file paths, pull numbers, ids.
3638 "engine_observation.body",
@@ -46,6 +48,7 @@ const AUDITED_CLEAR: string[] = [
4648 "report.body",
4749 "review.body",
4850 "run.check_detail",
51 // When a secret start was last written: a timestamp, not the value.
4952 "secret_start.value_updated_at",
5053 "subscription.resting_said",
5154 "subscription_limit.said",
test/did-you-mean.test.ts +3 −1
@@ -15,7 +15,9 @@ let servers: Awaited<ReturnType<typeof serve>>;
1515 /** Statements the page of a found repository makes; a change to it is a change to this number. */
1616 // 41 and 18 until 2026-11-13: every page of a repository runs two statements fewer since
1717 // that day's pushes.
18 const FOUND_QUERIES = 40; // one more: the fork-reach lookup of the repository row
18 // 40: the fork-reach lookup of the repository row adds one; the autonomy status's week read
19 // replaces the daily-ceiling read, so it adds none beside it.
20 const FOUND_QUERIES = 40;
1921 const BARE_404_QUERIES = 3; // a 404 with no owner/name to suggest from
2022 const NEAR_404_QUERIES = 16; // the same 404 for a mistyped repository
2123 const cookies: Record<string, string> = {};
test/engine-keeps-landing.test.ts −1
@@ -158,7 +158,6 @@ describe("the engine keeps landing", () => {
158158 const on = await updateRepoSettings(app, alice, repo, {
159159 autonomy: "autonomous",
160160 autonomyDirection: "Keep landing",
161 autonomyCeilingUsd: 100,
162161 autonomySlots: 5,
163162 autonomyBy: alice.id,
164163 });
test/fleet-ops.test.ts +6 −4
@@ -327,7 +327,9 @@ describe("fleet operations", () => {
327327 const rw = createToken(app.db, alice.id, "rw", "rw").token;
328328 const admin = createToken(app.db, alice.id, "admin", "admin").token;
329329 const bobs = createToken(app.db, bob.id, "bob", "admin").token;
330 const action = { verb: "ceiling", value: 7.5 };
330 const action = { verb: "slots", value: 3 };
331 const slotsBefore = fresh(engine).autonomySlots;
332 expect(slotsBefore).not.toBe(3);
331333 const query = "repo owner:alice";
332334
333335 const dry = await call(ro, "/api/v1/fleet/ops", { query, action });
@@ -335,7 +337,7 @@ describe("fleet operations", () => {
335337 const plan = (await dry.json()) as { dryRun: boolean; rows: unknown[] };
336338 expect(plan.dryRun).toBe(true);
337339 expect(plan.rows.length).toBe(2);
338 expect(fresh(engine).autonomyCeilingUsd).toBe(20);
340 expect(fresh(engine).autonomySlots).toBe(slotsBefore);
339341
340342 for (const token of [ro, rw]) {
341343 const refused = await call(token, "/api/v1/fleet/ops", { query, action, dryRun: false });
@@ -345,7 +347,7 @@ describe("fleet operations", () => {
345347 expect(applied.status).toBe(201);
346348 const op = (await applied.json()) as { id: string; dryRun: boolean };
347349 expect(op.dryRun).toBe(false);
348 expect(fresh(engine).autonomyCeilingUsd).toBe(7.5);
350 expect(fresh(engine).autonomySlots).toBe(3);
349351
350352 expect((await call(ro, `/api/v1/fleet/ops/${op.id}`)).status).toBe(200);
351353 expect((await call(bobs, `/api/v1/fleet/ops/${op.id}`)).status).toBe(404);
@@ -357,7 +359,7 @@ describe("fleet operations", () => {
357359
358360 const undo = await call(admin, `/api/v1/fleet/ops/${op.id}/undo`, {});
359361 expect(undo.status).toBe(201);
360 expect(fresh(engine).autonomyCeilingUsd).toBe(20);
362 expect(fresh(engine).autonomySlots).toBe(slotsBefore);
361363 expect((await call(admin, `/api/v1/fleet/ops/${op.id}/undo`, {})).status).toBe(409);
362364
363365 const bad = await call(ro, "/api/v1/fleet/ops", { query: "nonsense", action });
test/flow-alarm-idle-crew.test.ts −1
@@ -42,7 +42,6 @@ describe("alarmIdleCrew", () => {
4242 autonomy: "assisted",
4343 autonomyDirection: "keep the shop open",
4444 autonomySlots: 2,
45 autonomyCeilingUsd: 15,
4645 autonomyBy: u.value.id,
4746 });
4847 if (!set.ok) throw new Error(String(set.error));
test/flow-keeper.test.ts +1 −2
@@ -59,7 +59,6 @@ beforeAll(async () => {
5959 const on = await updateRepoSettings(app, admin, repo, {
6060 autonomy: "autonomous",
6161 autonomyDirection: "Build.",
62 autonomyCeilingUsd: 10,
6362 autonomySlots: 2,
6463 autonomyBy: admin.id,
6564 });
@@ -153,7 +152,7 @@ test("usage is the limit: it says when it resets, and spends nothing to say it",
153152 test("the closed list: the ceiling outranks usage, and a tried cause gives way to the next", () => {
154153 const repoFacts: RepoFacts = {
155154 repoId: "r", slug: "a/b", startable: 2, running: 0, slots: 1,
156 ceilingUsd: 10, atCeiling: true, noHeadroom: true, resetsAt: null,
155 atCeiling: true, noHeadroom: true, resetsAt: null,
157156 };
158157 const facts: KeeperFacts = { repos: [repoFacts], red: 0, stale: 0 };
159158 expect(pickCause(facts)?.cause).toBe("ceiling");
test/flow-pipeline.test.ts −1
@@ -83,7 +83,6 @@ describe("/flow: the forge shows its own bottleneck", () => {
8383 autonomy: "assisted",
8484 autonomyDirection: "keep the shop open",
8585 autonomySlots: 2,
86 autonomyCeilingUsd: 15,
8786 autonomyBy: alice.id,
8887 });
8988 if (!set.ok) throw new Error(String(set.error));
test/flow-ready-since.test.ts +1 −1
@@ -42,7 +42,7 @@ test("ready age starts at the unblocking or the last run's end, not at opening",
4242 const made = await createRepo(app, u.value, { name: "shop" });
4343 if (!made.ok) throw new Error(String(made.error));
4444 const set = await updateRepoSettings(app, u.value, made.value, {
45 autonomy: "assisted", autonomyDirection: "x", autonomySlots: 2, autonomyCeilingUsd: 15, autonomyBy: u.value.id,
45 autonomy: "assisted", autonomyDirection: "x", autonomySlots: 2, autonomyBy: u.value.id,
4646 });
4747 if (!set.ok) throw new Error(String(set.error));
4848 const repo = set.value;
test/flow-waiting-offthread.test.ts −1
@@ -34,7 +34,6 @@ beforeAll(async () => {
3434 autonomy: "assisted",
3535 autonomyDirection: "keep the shop open",
3636 autonomySlots: 2,
37 autonomyCeilingUsd: 15,
3837 autonomyBy: a.value.id,
3938 });
4039 if (!set.ok) throw new Error(String(set.error));
test/hand-decider.test.ts +1 −1
@@ -146,7 +146,7 @@ describe("let the decider answer a hand-over", () => {
146146 const state = row!.state as any;
147147 expect(state.reason).toContain("90%");
148148 expect(state.repository).toEqual({ name: "shelf", pinned: false, muted: false });
149 expect(state.spend.ceilingUsd).toBe(repo.autonomyCeilingUsd);
149 expect(state.spend).toEqual({ todayUsd: expect.any(Number), weekUsedPct: null, weekMayUsePct: null });
150150 expect(state.evidence.title).toBe("old idea");
151151 expect(state.evidence.reasons.length).toBe(1);
152152 expect(Array.isArray(state.recent)).toBe(true);
test/helpers/parks-engine.ts −1
@@ -54,7 +54,6 @@ export async function engine(
5454 const set = await updateRepoSettings(app, alice, repo, {
5555 autonomy: "autonomous",
5656 autonomyDirection: "Keep the engine small.",
57 autonomyCeilingUsd: 100,
5857 autonomyBy: alice.id,
5958 });
6059 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/home-builders-idle.test.ts +23 −15
@@ -1,4 +1,7 @@
11 /** Why builders sit idle (#5799): the first reason that holds, on home and in the terminal, from the scheduler's own checks. */
2 import { noteMeasure } from "../src/core/measure.ts";
3 import { grantedAccounts } from "../src/core/subscriptions.ts";
4 import { forgetWeek } from "../src/crew/week_read.ts";
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
@@ -55,7 +58,6 @@ beforeAll(async () => {
5558 const on = await updateRepoSettings(app, admin, repo, {
5659 autonomy: "autonomous",
5760 autonomyDirection: "Build.",
58 autonomyCeilingUsd: 10,
5961 autonomySlots: 1,
6062 autonomyBy: admin.id,
6163 });
@@ -113,7 +115,7 @@ test("a ready issue and a builder with room: no reason is named", async () => {
113115 const page = await home();
114116 expect(tile(page)).not.toContain("nothing ready");
115117 expect(tile(page)).toContain("at work now");
116 expect(await terminal()).not.toMatch(/Builders running 0 of 1 · (nothing|no sub|ceiling)/);
118 expect(await terminal()).not.toMatch(/Builders running 0 of 1 · (nothing|no sub|week)/);
117119 });
118120
119121 test("no subscription with headroom: the granted account's window is full", async () => {
@@ -134,14 +136,20 @@ test("no subscription with headroom: the granted account's window is full", asyn
134136 expect(await terminal()).toContain("Builders running 0 of 1 · no subscription with headroom");
135137 });
136138
137 test("ceiling reached outranks the others", async () => {
139 test("week spent outranks the others: dollars alone do not, the provider's week does", async () => {
138140 const spent = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: builder.id, reason: "assigned" });
139141 claimRun(app.db, spent.id);
140142 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 12 });
143 // $12 today is no ceiling: the reason is still the subscription's.
144 expect(idleReason(app, new Date())?.word).toBe("no subscription with headroom");
145 const at = Date.now();
146 for (const a of grantedAccounts(app.db, repo.id, repo.ownerId))
147 noteMeasure(app.db, a.id, { window: "week", usedPct: 100, resetsAt: new Date(at + 3 * 86_400_000).toISOString(), observedAt: new Date(at).toISOString() });
148 forgetWeek();
141149 const page = await home();
142 expect(tile(page)).toContain("ceiling reached");
150 expect(tile(page)).toContain("week spent");
143151 expect(tile(page)).toContain('href="/meter"');
144 expect(await terminal()).toContain("Builders running 0 of 1 · ceiling reached");
152 expect(await terminal()).toContain("Builders running 0 of 1 · week spent");
145153 });
146154
147155 test("every slot busy: no reason is shown", async () => {
@@ -149,9 +157,9 @@ test("every slot busy: no reason is shown", async () => {
149157 claimRun(app.db, run.id);
150158 const page = await home();
151159 expect(tile(page)).toContain("1 of 1");
152 expect(tile(page)).not.toContain("ceiling reached");
160 expect(tile(page)).not.toContain("week spent");
153161 expect(await terminal()).toContain("Builders running 1 of 1");
154 expect(await terminal()).not.toContain("ceiling reached");
162 expect(await terminal()).not.toContain("week spent");
155163 });
156164
157165 test("both doors agree within home's 60 s KPI entry: the run ends, each says 0 of 1 and why (#7624)", async () => {
@@ -162,8 +170,8 @@ test("both doors agree within home's 60 s KPI entry: the run ends, each says 0 o
162170 // Within the entry the counts changed, so the reason is asked again rather than left silent.
163171 const page = await home(true);
164172 expect(tile(page)).toContain("0 of 1");
165 expect(tile(page)).toContain("ceiling reached");
166 expect(await terminal()).toContain("Builders running 0 of 1 · ceiling reached");
173 expect(tile(page)).toContain("week spent");
174 expect(await terminal()).toContain("Builders running 0 of 1 · week spent");
167175 });
168176
169177 test("the reason rides in the cached KPI answer: readKpis carries it, the tile and line print it (#7664)", async () => {
@@ -171,8 +179,8 @@ test("the reason rides in the cached KPI answer: readKpis carries it, the tile a
171179 finishRun(app.db, r.id, { state: "ok", summary: "done" });
172180 const now = new Date();
173181 const k = readKpis(app.db, now, { ceilingUsd: null, idle: () => idleReason(app, now) });
174 expect(k.builders.idle).toEqual({ word: "ceiling reached", href: "/meter" });
175 expect(kpiLines(k, null)[3]).toBe("Builders running 0 of 1 · ceiling reached");
182 expect(k.builders.idle).toEqual({ word: "week spent", href: "/meter" });
183 expect(kpiLines(k, null)[3]).toBe("Builders running 0 of 1 · week spent");
176184 // Every slot busy: nothing is added, and the reason is not asked.
177185 claimRun(app.db, createRun(app.db, { repoId: repo.id, kind: "agent", actorId: builder.id, reason: "assigned" }).id);
178186 const busy = readKpis(app.db, now, { ceilingUsd: null, idle: () => { throw new Error("asked"); } });
@@ -185,7 +193,7 @@ test("a cached reason is dropped when the counts change: one of two slots runnin
185193 app.db.query("UPDATE repo SET autonomy_slots = 2 WHERE autonomy != 'off'").run();
186194 kpiCache(app.db).clear();
187195 const now = new Date();
188 const ceiling = { word: "ceiling reached", href: "/meter" };
196 const ceiling = { word: "week spent", href: "/meter" };
189197 let reason: typeof ceiling | null = ceiling;
190198 const forge = { ceilingUsd: null, idle: () => reason };
191199 expect(cachedKpis(app.db, now, forge).builders).toEqual({ running: 0, slots: 2, idle: ceiling });
@@ -198,7 +206,7 @@ test("a cached reason is dropped when the counts change: one of two slots runnin
198206 });
199207
200208 test("slots shown are the crew's concurrency, not the sum of the repositories' ceilings (#10440)", async () => {
201 const wide = await updateRepoSettings(app, admin, repo, { autonomy: "autonomous", autonomyDirection: "Build.", autonomyCeilingUsd: 10, autonomySlots: 16, autonomyBy: admin.id });
209 const wide = await updateRepoSettings(app, admin, repo, { autonomy: "autonomous", autonomyDirection: "Build.", autonomySlots: 16, autonomyBy: admin.id });
202210 expect(wide.ok).toBe(true);
203211 const set = (v: string) =>
204212 app.db.query("INSERT OR REPLACE INTO forge_setting (key, value, updated_by, updated_at) VALUES ('crew.concurrency', ?1, ?2, datetime('now'))").run(v, admin.id);
@@ -220,14 +228,14 @@ test("slots shown are the crew's concurrency, not the sum of the repositories' c
220228 });
221229
222230 test("the slots figure is crew.concurrency on home and in the terminal, and the running figure is the runs' own count (#10440)", async () => {
223 const wide = await updateRepoSettings(app, admin, repo, { autonomy: "autonomous", autonomyDirection: "Build.", autonomyCeilingUsd: 10, autonomySlots: 16, autonomyBy: admin.id });
231 const wide = await updateRepoSettings(app, admin, repo, { autonomy: "autonomous", autonomyDirection: "Build.", autonomySlots: 16, autonomyBy: admin.id });
224232 expect(wide.ok).toBe(true);
225233 try {
226234 app.db.query("INSERT OR REPLACE INTO forge_setting (key, value, updated_by, updated_at) VALUES ('crew.concurrency', '3', ?1, datetime('now'))").run(admin.id);
227235 const running = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM run WHERE kind = 'agent' AND state = 'running'").get()!.n;
228236 const text = await terminal();
229237 expect(text).toContain(`Builders running ${running} of 3`);
230 expect(text).not.toContain("of 16");
238 expect(text.split("\n").find((l) => l.startsWith("Builders running"))).not.toContain("of 16");
231239 expect(tile(await home())).toContain(`${running} of 3`);
232240 } finally {
233241 app.db.query("DELETE FROM forge_setting WHERE key = 'crew.concurrency'").run();
test/idle-reason.test.ts +23 −14
@@ -14,8 +14,10 @@ import { addDependency } from "../src/core/dependencies.ts";
1414 import { type Issue } from "../src/core/issues.ts";
1515 import type { Repo } from "../src/core/repos.ts";
1616 import { createRun } from "../src/core/runs.ts";
17 import { noteMeasure } from "../src/core/measure.ts";
18 import { forgetWeek } from "../src/crew/week_read.ts";
1719 import { noteLimit } from "../src/core/standing.ts";
18 import { addSubscription, setGrants } from "../src/core/subscriptions.ts";
20 import { addSubscription, PLATFORM, setGrants } from "../src/core/subscriptions.ts";
1921 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2022 import { idleLine, idleReason } from "../src/crew/idle_reason.ts";
2123
@@ -56,8 +58,9 @@ describe("idleReason", () => {
5658 await rm(dataDir, { recursive: true, force: true });
5759 });
5860
59 // A fresh autonomous repository with one builder, a $10 ceiling and two slots.
61 // A fresh autonomous repository with one builder, two slots.
6062 beforeEach(async () => {
63 spendWeek(0);
6164 if (repo) set("UPDATE repo SET autonomy = 'off' WHERE id = ?1", repo.id);
6265 const made = await createRepo(app, alice, { name: `svc${n++}`, visibility: "private" });
6366 if (!made.ok) throw new Error(String(made.error));
@@ -67,19 +70,25 @@ describe("idleReason", () => {
6770 expect(addToCrew(app, alice, repo, `bot${n}`).ok).toBe(true);
6871 bot = getUserByName(app.db, `bot${n}`)!;
6972 set(
70 "UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_ceiling_usd = 10, autonomy_slots = 2 WHERE id = ?1",
73 "UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_slots = 2 WHERE id = ?1",
7174 repo.id,
7275 alice.id,
7376 );
7477 });
7578
76 const spend = (usd: number) => {
77 const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: bot.id });
78 set("UPDATE run SET cost_usd = ?2, state = 'ok' WHERE id = ?1", run.id, usd);
79 // The provider's week is used up, early in it.
80 const spendWeek = (usedPct = 100) => {
81 noteMeasure(app.db, PLATFORM, {
82 window: "week",
83 usedPct,
84 resetsAt: new Date(Date.now() + 6 * 86_400_000).toISOString(),
85 observedAt: new Date().toISOString(),
86 });
87 forgetWeek();
7988 };
80
81 test("every slot busy: null, even with the ceiling spent", () => {
89 test("every slot busy: null, even with the week spent", () => {
8290 open("Work");
91 spendWeek();
8392 for (let i = 0; i < 2; i++) {
8493 const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: bot.id, reason: "assigned" });
8594 set("UPDATE run SET state = 'running', cost_usd = 6 WHERE id = ?1", run.id);
@@ -93,10 +102,10 @@ describe("idleReason", () => {
93102 expect(idleReason(app, NOW)?.word).toBe("nothing ready");
94103 });
95104
96 test("ceiling reached", () => {
105 test("week spent", () => {
97106 open("Work");
98 spend(10);
99 expect(idleReason(app, new Date())).toEqual({ word: "ceiling reached", href: "/meter" });
107 spendWeek();
108 expect(idleReason(app, new Date())).toEqual({ word: "week spent", href: "/meter" });
100109 });
101110
102111 test("no subscription with headroom", () => {
@@ -124,9 +133,9 @@ describe("idleReason", () => {
124133 expect(idleReason(app, NOW)?.word).toBe("nothing ready");
125134 });
126135
127 test("the first reason that holds wins: the ceiling before nothing", () => {
128 spend(10);
129 expect(idleReason(app, new Date())?.word).toBe("ceiling reached");
136 test("the first reason that holds wins: the week before nothing", () => {
137 spendWeek();
138 expect(idleReason(app, new Date())?.word).toBe("week spent");
130139 });
131140
132141 test("an issue the dispatcher holds is not ready: a run in flight on the only one says none startable, not nothing ready", () => {
test/landed-held.test.ts −1
@@ -85,7 +85,6 @@ describe("a landing with boxes unticked waits for a person", () => {
8585 const set = await updateRepoSettings(app, alice, made.value, {
8686 autonomy: "autonomous",
8787 autonomyDirection: "Keep the engine small.",
88 autonomyCeilingUsd: 100,
8988 autonomySlots: 1,
9089 autonomyBy: alice.id,
9190 });
test/ledger.test.ts +10 −5
@@ -115,7 +115,6 @@ describe("the decision ledger", () => {
115115 updateRepoSettings(app.db, repo, {
116116 autonomy: "autonomous",
117117 autonomyDirection: "Sell one real thing end to end.",
118 autonomyCeilingUsd: 20,
119118 autonomySlots: 1,
120119 autonomyBy: alice.id,
121120 });
@@ -659,14 +658,19 @@ describe("the decision ledger", () => {
659658 updateRepoSettings(app.db, fresh(), { autonomySlots: 2 });
660659 });
661660
662 test("the ceiling gates every run the crew starts on its own; a person's assignment is not the crew's", async () => {
661 test("the week's share gates every run the crew starts on its own; a person's assignment is not the crew's", async () => {
663662 const { queueAgentRun } = await import("../src/crew/dispatch.ts");
664663 const { getAgentByName } = await import("../src/core/agents.ts");
665664 const work = openIssue(app, alice, repo, { title: "Loyalty points" });
666665 if (!work.ok) throw new Error(String(work.error));
667666 const scoutAgent = getAgentByName(app.db, "scout")!;
668 updateRepoSettings(app.db, fresh(), { autonomyCeilingUsd: 0 });
669 // At the ceiling: no feedback run.
667 const { noteMeasure } = await import("../src/core/measure.ts");
668 const { forgetWeek } = await import("../src/crew/week_read.ts");
669 const { PLATFORM } = await import("../src/core/subscriptions.ts");
670 const at = Date.now();
671 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 100, resetsAt: new Date(at + 3 * 86_400_000).toISOString(), observedAt: new Date(at).toISOString() });
672 forgetWeek();
673 // The week's share is spent: no feedback run.
670674 expect(
671675 queueAgentRun(app, fresh(), work.value, scoutAgent, "feedback"),
672676 ).toBeUndefined();
@@ -674,7 +678,8 @@ describe("the decision ledger", () => {
674678 expect(
675679 queueAgentRun(app, fresh(), work.value, scoutAgent, "assigned"),
676680 ).toBeDefined();
677 updateRepoSettings(app.db, fresh(), { autonomyCeilingUsd: 20 });
681 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 0, resetsAt: new Date(at + 3 * 86_400_000).toISOString(), observedAt: new Date(at + 1000).toISOString() });
682 forgetWeek();
678683 });
679684
680685 test("the ledger is on the API, newest first, with the week per kind", async () => {
test/lift-startable.test.ts −1
@@ -71,7 +71,6 @@ beforeAll(async () => {
7171 const on = await updateRepoSettings(app, alice, repo, {
7272 autonomy: "autonomous",
7373 autonomyDirection: "Keep the notes tidy.",
74 autonomyCeilingUsd: 10,
7574 autonomySlots: 1,
7675 autonomyBy: alice.id,
7776 });
test/limb-replan.test.ts −1
@@ -146,7 +146,6 @@ describe("a limb handed to the planner", () => {
146146 const set = await updateRepoSettings(app, alice, repo, {
147147 autonomy: "autonomous",
148148 autonomyDirection: "Keep the engine small.",
149 autonomyCeilingUsd: 100,
150149 autonomyBy: alice.id,
151150 });
152151 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/livetriage.test.ts −3
@@ -55,7 +55,6 @@ describe("live triage", () => {
5555 const set = await updateRepoSettings(app, alice, repo, {
5656 autonomy: "autonomous",
5757 autonomyDirection: "Keep it small.",
58 autonomyCeilingUsd: 100,
5958 autonomyBy: alice.id,
6059 });
6160 if (!set.ok) throw new Error(JSON.stringify(set.error));
@@ -433,7 +432,6 @@ describe("live triage files unplaced issues", () => {
433432 const set = await updateRepoSettings(app, alice, repo, {
434433 autonomy: "autonomous",
435434 autonomyDirection: "Keep it small.",
436 autonomyCeilingUsd: 100,
437435 autonomyBy: alice.id,
438436 });
439437 if (!set.ok) throw new Error(JSON.stringify(set.error));
@@ -547,7 +545,6 @@ describe("live triage where there is little to file under", () => {
547545 const set = await updateRepoSettings(app, alice, made.value, {
548546 autonomy: "autonomous",
549547 autonomyDirection: "Keep it small.",
550 autonomyCeilingUsd: 100,
551548 autonomyBy: alice.id,
552549 });
553550 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/map-first.test.ts −1
@@ -50,7 +50,6 @@ describe("this first", () => {
5050 const set = await updateRepoSettings(app, alice, made.value, {
5151 autonomy: "autonomous",
5252 autonomyDirection: "Keep the engine small.",
53 autonomyCeilingUsd: 100,
5453 autonomySlots: 1,
5554 autonomyBy: alice.id,
5655 });
test/map.test.ts +3 −3
@@ -307,7 +307,6 @@ describe("the map, per app and across the forge", () => {
307307 const on = await updateRepoSettings(app, bob, secret.repo, {
308308 autonomy: "assisted",
309309 autonomyDirection: "Keep the keys fresh.",
310 autonomyCeilingUsd: 10,
311310 autonomySlots: 1,
312311 autonomyBy: bob.id,
313312 });
@@ -619,7 +618,7 @@ describe("the map, per app and across the forge", () => {
619618 repo: { owner: string; name: string };
620619 autonomy: string;
621620 spentTodayUsd: number | null;
622 ceilingUsd: number | null;
621 week: { usedPct: number } | null;
623622 inFlight: number;
624623 workers: string[];
625624 idle: boolean;
@@ -684,7 +683,8 @@ describe("the map, per app and across the forge", () => {
684683 expect(dormant.idle).toBe(true);
685684 expect(dormant.workers).toEqual([]);
686685 const secret = data.repos.find((r) => r.repo.name === "secret")!;
687 expect(secret.ceilingUsd).toBe(10);
686 expect(secret).not.toHaveProperty("ceilingUsd");
687 expect(secret.week).toBeNull();
688688 expect(secret.spentTodayUsd).toBe(0);
689689
690690 // The per-repo data says the same.
test/mcp-fleet-act.test.ts +3 −3
@@ -35,7 +35,7 @@ const api = async (token: string, input: unknown) =>
3535 body: JSON.stringify(input),
3636 }).then((r) => r.json())) as any;
3737
38 const ceilings = () => repos.map((r) => getRepoById(app.db, r.id)!.autonomyCeilingUsd);
38 const ceilings = () => repos.map((r) => getRepoById(app.db, r.id)!.autonomySlots);
3939
4040 beforeAll(async () => {
4141 dir = await mkdtemp(join(tmpdir(), "forge-mcp-fleet-act-"));
@@ -64,7 +64,7 @@ afterAll(async () => {
6464 });
6565
6666 const query = "repo owner:alice";
67 const action = { verb: "ceiling", value: 7.5 };
67 const action = { verb: "slots", value: 3 };
6868
6969 test("an action plans by default, even with a read token, and the plan is the API's", async () => {
7070 const before = ceilings();
@@ -88,7 +88,7 @@ test("applying needs `apply: true` and an admin token; then it writes and return
8888 expect(done.value.dryRun).toBe(false);
8989 expect(typeof done.value.id).toBe("string");
9090 expect(done.value.rows.map((r: any) => r.outcome)).toEqual(["ok", "ok"]);
91 expect(ceilings()).toEqual([7.5, 7.5]);
91 expect(ceilings()).toEqual([3, 3]);
9292
9393 const res = await fetch(`${servers.url}/mcp`, {
9494 method: "POST",
test/mcp-refusal-hints.test.ts +7
@@ -10,6 +10,7 @@ import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { createToken } from "../src/core/tokens.ts";
1212 import { createUser } from "../src/core/users.ts";
13 import { askingOf } from "../src/perf/asking.ts";
1314 import { serve, type Servers } from "../src/http/server.ts";
1415 import { READ_ONLY_REFUSAL, withNextStep } from "../src/http/mcp/hints.ts";
1516 import { TOKEN_FREE_HANDLERS } from "../src/http/mcp.ts";
@@ -55,6 +56,7 @@ beforeAll(async () => {
5556 member = createToken(app.db, b.value.id, "t", "admin").token;
5657 });
5758 afterAll(async () => {
59 askingOf(app).forget();
5860 await servers.stop();
5961 await rm(dir, { recursive: true, force: true });
6062 });
@@ -73,6 +75,11 @@ test("a stranger calling every listed tool is refused with the sign-in, or answe
7375 list.flatMap((name) =>
7476 [{}, { nope: 1 }].map(async (args) => {
7577 const r = await rpc(undefined, "tools/call", { name, arguments: args });
78 if (name === "explore" || name === "search") {
79 // Token-free reads (#12429): a stranger gets the public answer, not a refusal.
80 expect(r.status).toBe(200);
81 return;
82 }
7683 if (name === "report" || name === "start") {
7784 const text = String(r.body.result?.content?.[0]?.text ?? "");
7885 expect(r.body.result?.isError).toBe(true);
test/not-startable.test.ts +1 −1
@@ -89,7 +89,7 @@ beforeAll(async () => {
8989 if (!agent.ok) throw new Error(String(agent.error));
9090 expect(addToCrew(app, alice, repo, "b1").ok).toBe(true);
9191 expect((await updateRepoSettings(app, alice, repo, {
92 autonomy: "autonomous", autonomyDirection: "Keep the notes tidy.", autonomyCeilingUsd: 10, autonomySlots: 1, autonomyBy: alice.id,
92 autonomy: "autonomous", autonomyDirection: "Keep the notes tidy.", autonomySlots: 1, autonomyBy: alice.id,
9393 })).ok).toBe(true);
9494 insertApp(app.db, { repoId: repo.id, slug: "notes", access: "private" });
9595 open("P0 Notes: keep notes");
test/notes.test.ts +1 −1
@@ -111,7 +111,7 @@ describe("notes", () => {
111111 const r = await createRepo(app, alice, { name: "forge", visibility: "private" });
112112 if (!r.ok) throw new Error(String(r.error));
113113 repo = r.value;
114 await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", autonomyDirection: "Steer by thought.", autonomyCeilingUsd: 10, autonomySlots: 1, autonomyBy: alice.id });
114 await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", autonomyDirection: "Steer by thought.", autonomySlots: 1, autonomyBy: alice.id });
115115 servers = await serve(app);
116116 });
117117 afterAll(async () => {
test/outside-spend.test.ts −1
@@ -92,7 +92,6 @@ beforeAll(async () => {
9292 const on = await updateRepoSettings(app, alice, repo, {
9393 autonomy: "autonomous",
9494 autonomyDirection: "Grind the grain",
95 autonomyCeilingUsd: 5,
9695 autonomySlots: 3,
9796 autonomyBy: alice.id,
9897 });
test/pace-floor.test.ts +1 −1
@@ -53,7 +53,7 @@ async function pacedRepo(name: string, spentUsd: number): Promise<Repo> {
5353 const now = Date.now();
5454 // The provider's meter: `spentUsd` percent of the week used, with half the week's time gone.
5555 noteMeasure(app.db, sub.value.id, { window: "week", usedPct: spentUsd, resetsAt: new Date(now + 3.5 * DAY).toISOString(), observedAt: new Date(now).toISOString() });
56 const on = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Ship.", autonomyCeilingUsd: 1000, autonomySlots: 4, autonomyBy: alice.id });
56 const on = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Ship.", autonomySlots: 4, autonomyBy: alice.id });
5757 expect(on.ok).toBe(true);
5858 forgetWeek();
5959 return getRepoById(app.db, made.value.id)!;
test/planner-lent.test.ts −1
@@ -77,7 +77,6 @@ describe("a migrated repository with only a builder", () => {
7777 const on = await updateRepoSettings(app, alice, pixel, {
7878 autonomy: "autonomous",
7979 autonomyDirection: "build more games!",
80 autonomyCeilingUsd: 10,
8180 autonomySlots: 1,
8281 autonomyBy: alice.id,
8382 });
test/policy.test.ts −1
@@ -286,7 +286,6 @@ describe("a pull landed at the wall", () => {
286286 const on = await updateRepoSettings(w.app, w.alice, w.repo, {
287287 autonomy: "autonomous",
288288 autonomyDirection: "Notes for everyone.",
289 autonomyCeilingUsd: 10,
290289 autonomySlots: 1,
291290 autonomyBy: w.alice.id,
292291 });
test/polish-share.test.ts +1 −1
@@ -104,7 +104,7 @@ beforeAll(async () => {
104104 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
105105 }
106106 const on = await updateRepoSettings(app, alice, repo, {
107 autonomy: "autonomous", autonomyDirection: "Keep the notes tidy.", autonomyCeilingUsd: 100, autonomySlots: 2, autonomyBy: alice.id,
107 autonomy: "autonomous", autonomyDirection: "Keep the notes tidy.", autonomySlots: 2, autonomyBy: alice.id,
108108 });
109109 expect(on.ok).toBe(true);
110110 servers = await serve(app);
test/reopen-stands.test.ts −1
@@ -68,7 +68,6 @@ describe("a reopen stands; unfinished work stays open", () => {
6868 const set = await updateRepoSettings(app, alice, repo, {
6969 autonomy: "autonomous",
7070 autonomyDirection: "Keep it small.",
71 autonomyCeilingUsd: 100,
7271 });
7372 if (!set.ok) throw new Error(JSON.stringify(set.error));
7473 setRepo(app.db, fresh(), { autonomyBy: alice.id });
test/seat-slots.test.ts +5 −5
@@ -80,7 +80,7 @@ beforeAll(async () => {
8080 const id = (n: string) => getUserByName(app.db, n)!.id;
8181 seatAs(app.db, repo.id, id("atlas"), "planner");
8282 seatAs(app.db, repo.id, id("judge"), "reviewer");
83 ok(await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", requireReview: true, autonomyDirection: "Make the yard rounder.", autonomyCeilingUsd: 10, autonomySlots: 2, autonomyBy: alice.id }));
83 ok(await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", requireReview: true, autonomyDirection: "Make the yard rounder.", autonomySlots: 2, autonomyBy: alice.id }));
8484 const res = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: PASSWORD }), redirect: "manual" });
8585 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
8686 admin = createToken(app.db, alice.id, "admin", "admin").token;
@@ -169,16 +169,16 @@ test("a builder set to none starts nothing, and the On its own form keeps the sl
169169 const form = await fetch(`${servers.url}/alice/yard/settings/autonomy`, {
170170 method: "POST",
171171 headers: { origin: servers.url, cookie },
172 body: new URLSearchParams({ autonomy: "assisted", ceiling: "7", direction: "Make the yard rounder." }),
172 body: new URLSearchParams({ autonomy: "assisted", direction: "Make the yard rounder." }),
173173 redirect: "manual",
174174 });
175175 expect(form.status).toBe(303);
176176 // The form really saved (a refusal is a 303 too): mode and ceiling moved, the 0 stayed.
177 expect(fresh()).toMatchObject({ autonomy: "assisted", autonomyCeilingUsd: 7, autonomySlots: 0 });
178 expect(checkAutonomy("assisted", 7, 0).ok).toBe(true);
177 expect(fresh()).toMatchObject({ autonomy: "assisted", autonomySlots: 0 });
178 expect(checkAutonomy("assisted", 0).ok).toBe(true);
179179 expect(await driveRepo(app, fresh())).not.toBe("picked");
180180 await post({ seat: "builder", slots: "2" });
181 ok(await updateRepoSettings(app, alice, fresh(), { autonomy: "autonomous", autonomyCeilingUsd: 10 }));
181 ok(await updateRepoSettings(app, alice, fresh(), { autonomy: "autonomous" }));
182182 });
183183
184184 test("a paused reviewer is said to be paused in what waits for the owner", () => {
test/spawn-keys.test.ts +1 −2
@@ -304,10 +304,9 @@ describe("a spawned child's own keys and domain", () => {
304304 expect(listGrants(child.db, org.id).map((g) => g.subscriptionId)).toEqual(
305305 [sub.id],
306306 );
307 // The budget is on the key, locked; no repository ceiling is touched.
307 // The budget is on the key, locked.
308308 expect(budgetsOf(child.db).get(sub.id)).toEqual({ budgetUsd: 5, spentUsd: 0, locked: true });
309309 expect(setBudget(child.db, sub.id, 1000)).toBe(false);
310 expect(getRepo(child.db, "maria", "bakery")!.autonomyCeilingUsd).not.toBe(5);
311310 expect(crewHasCredential(child.db, {})).toBe(true);
312311 } finally {
313312 child.close();
test/stale_reds.test.ts +1 −1
@@ -244,7 +244,7 @@ test("the flow report counts stale reds and the keeper names them as a cause", (
244244 expect(read.oldestHours).toBeCloseTo(700 / 60, 5);
245245 const line = flowReportLines(flowReadings(app.db, now)).find((l) => l.startsWith("stale_reds:"))!;
246246 expect(line).toBe("stale_reds: 5 red with no run for 30 min, oldest 11.7 h");
247 const found = pickCause({ repos: [{ repoId: "r", slug: "a/b", startable: 1, running: 1, slots: 4, ceilingUsd: 10, atCeiling: false, noHeadroom: false, resetsAt: null }], red: 0, staleReds: STALE_REDS, stale: 0 });
247 const found = pickCause({ repos: [{ repoId: "r", slug: "a/b", startable: 1, running: 1, slots: 4, atCeiling: false, noHeadroom: false, resetsAt: null }], red: 0, staleReds: STALE_REDS, stale: 0 });
248248 expect(found?.cause).toBe("stale_reds");
249249 });
250250
test/studio-runs.test.ts −1
@@ -118,7 +118,6 @@ describe("the studio's slot count", () => {
118118 const on = await updateRepoSettings(app, alice, repo, {
119119 autonomy: "autonomous",
120120 autonomyDirection: "",
121 autonomyCeilingUsd: 10,
122121 autonomySlots: 2,
123122 autonomyBy: alice.id,
124123 });
test/studio-search.test.ts +10 −6
@@ -6,6 +6,8 @@
66 * every test under 1 s, one fixture per describe, nothing sleeps (#3576).
77 */
88
9 import { noteMeasure } from "../src/core/measure.ts";
10 import { PLATFORM } from "../src/core/subscriptions.ts";
911 import { logBox } from "../src/web/studio/log.ts";
1012 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1113 import { mkdtemp, rm } from "node:fs/promises";
@@ -342,7 +344,7 @@ describe("finding things in the studio: /search", () => {
342344 /**
343345 * The studio home's own answer to "what is this costing me today?" (#94):
344346 * one line, the sum of today's agent spend across the apps the viewer can
345 * write, and how many of those sit paused at their ceiling right now.
347 * write, and how many of those sit paused with the week's share spent right now.
346348 */
347349 describe("the studio home says what the crew cost you today", () => {
348350 let dataDir: string;
@@ -398,7 +400,7 @@ describe("the studio home says what the crew cost you today", () => {
398400 aliceCookie = await signIn("alice");
399401 carolCookie = await signIn("carol");
400402
401 // "beacon": on its own, over its $5 ceiling today — paused.
403 // "beacon": on its own, its week's share spent — paused.
402404 const beaconMade = await createRepo(app, alice, {
403405 name: "beacon",
404406 visibility: "public",
@@ -421,7 +423,6 @@ describe("the studio home says what the crew cost you today", () => {
421423 const on = await updateRepoSettings(app, alice, beacon, {
422424 autonomy: "assisted",
423425 autonomyDirection: "",
424 autonomyCeilingUsd: 5,
425426 autonomySlots: 2,
426427 autonomyBy: alice.id,
427428 });
@@ -463,6 +464,9 @@ describe("the studio home says what the crew cost you today", () => {
463464 });
464465 claimRun(app.db, loomRun.id);
465466 noteRunProgress(app.db, loomRun.id, { costUsd: 2 });
467 // The provider's week is used up: the one app on its own is paused.
468 const at = Date.now();
469 noteMeasure(app.db, PLATFORM, { window: "week", usedPct: 100, resetsAt: new Date(at + 3 * 86_400_000).toISOString(), observedAt: new Date(at).toISOString() });
466470 });
467471
468472 afterAll(async () => {
@@ -471,11 +475,11 @@ describe("the studio home says what the crew cost you today", () => {
471475 await rm(dataDir, { recursive: true, force: true });
472476 });
473477
474 test("the owner sees the day's total across both apps, and the one that is paused at its ceiling", async () => {
478 test("the owner sees the day's total across both apps, and the one that is paused with the week's share spent", async () => {
475479 const html = await home(aliceCookie);
476480 expect(html).toContain("$8.00 spent today across 2 apps you can write");
477 expect(html).toContain("1 paused at");
478 expect(html).toMatch(/<a href="\/board">their ceiling<\/a>/);
481 expect(html).toContain("1 paused with");
482 expect(html).toMatch(/<a href="\/board">week's share spent<\/a>/);
479483 });
480484
481485 test("a viewer who can only read sees no figure at all", async () => {
test/studio-shipping.test.ts +6 −4
@@ -124,7 +124,6 @@ describe("a stranger sees the app, not the owner's books", () => {
124124 const on = await updateRepoSettings(app, alice, repo, {
125125 autonomy: "assisted",
126126 autonomyDirection: "",
127 autonomyCeilingUsd: 25,
128127 autonomySlots: 2,
129128 autonomyBy: alice.id,
130129 });
@@ -338,7 +337,6 @@ describe("a stranger sees the app, not the owner's books", () => {
338337 const on = await updateRepoSettings(app, alice, lamp, {
339338 autonomy: "autonomous",
340339 autonomyDirection: "",
341 autonomyCeilingUsd: 5,
342340 autonomySlots: 1,
343341 autonomyBy: alice.id,
344342 });
@@ -364,7 +362,7 @@ describe("a stranger sees the app, not the owner's books", () => {
364362 expect(joined).not.toContain("nobody on the crew");
365363 });
366364
367 test("the studio's settings page renders the crew and the ceiling for a writer, with the same numbers the app page shows", async () => {
365 test("the studio's settings page renders the crew and the week's budget for a writer, with no dollar ceiling field, with the same numbers the app page shows", async () => {
368366 const owner = await (
369367 await get("/alice/beacon/settings", ownerCookie)
370368 ).text();
@@ -372,7 +370,11 @@ describe("a stranger sees the app, not the owner's books", () => {
372370 // The crew card itself: the account menu's Crew row, which once answered for it, is gone.
373371 expect(owner).toContain('id="crew"');
374372 expect(owner).toContain(">On its own<");
375 expect(owner).toMatch(/\$42\.50\s+of\s+\$25/);
373 expect(owner).toMatch(/<dt>Today<\/dt>\s*<dd>\$42\.50 spent<\/dd>/);
374 // The week as a share and a pace; no daily dollar ceiling to read or to set (#10623).
375 expect(owner).toMatch(/<dt>Week<\/dt>\s*<dd>/);
376 expect(owner).not.toMatch(/name="ceiling"/);
377 expect(owner).not.toContain("Ceiling per day");
376378 // The crew card says the governor's reason in one line (#7644).
377379 expect(owner).toMatch(/<dt>Governor<\/dt>\s*<dd>Builders \d+: /);
378380 expect(owner).toContain("Remove");
test/triage.test.ts −1
@@ -64,7 +64,6 @@ describe("triage", () => {
6464 await updateRepoSettings(app, alice, r.value, {
6565 autonomy: "autonomous",
6666 autonomyDirection: "Steer by thought.",
67 autonomyCeilingUsd: 10,
6867 autonomySlots: 1,
6968 autonomyBy: alice.id,
7069 });
test/tui-autonomy.test.ts +9 −19
@@ -111,14 +111,14 @@ describe("autonomy in the terminal", () => {
111111 // The confirm opens on Cancel; each `left` moves one mode back: Autonomous, Assisted, Off.
112112 const pick = { autonomous: ["left"], assisted: ["left", "left"], off: ["left", "left", "left"] } as const;
113113
114 test("an admin picks the mode after a confirm that names the modes and the ceiling; Cancel is the default", async () => {
114 test("an admin picks the mode after a confirm that names the modes and the week's budget; Cancel is the default", async () => {
115115 const h = boot(erin);
116116 await h.open();
117117 expect(h.text()).toContain("Autonomy is off.");
118118 await h.press("m");
119119 expect(h.text()).toContain("Set autonomy (now off)");
120120 expect(h.text()).toContain(AUTONOMY_SAID.autonomous);
121 expect(h.text()).toContain(`The ceiling that applies is $${saved().autonomyCeilingUsd} a day.`);
121 expect(h.text()).toContain("The week's budget applies:");
122122 await h.press("enter");
123123 expect(saved().autonomy).toBe("off");
124124 await h.press("m", "esc");
@@ -185,20 +185,19 @@ describe("autonomy in the terminal", () => {
185185 }
186186 });
187187
188 test("the ceiling and the slots are saved", async () => {
188 test("the slots are saved, and the screen shows the week's budget, never a dollar ceiling", async () => {
189189 const h = boot(ada);
190190 await h.open();
191 expect(h.text()).toContain("Week ");
192 expect(h.text()).not.toContain("Ceiling");
193 expect(h.text()).not.toContain("a day");
191194 await h.press("c");
192 for (let i = 0; i < 10; i++) await h.press("backspace");
193 await h.type("12.5");
194 await h.press("enter");
195 expect(saved().autonomyCeilingUsd).toBe(12.5);
195 expect(h.text()).not.toContain("dollars a day");
196196 await h.press("s");
197197 for (let i = 0; i < 4; i++) await h.press("backspace");
198198 await h.type("3");
199199 await h.press("enter");
200200 expect(saved().autonomySlots).toBe(3);
201 expect(h.text()).toContain("$12.5");
202201 h.stop();
203202 });
204203
@@ -224,18 +223,10 @@ describe("autonomy in the terminal", () => {
224223 h.stop();
225224 });
226225
227 test("a ceiling or slots out of range are refused with the page's sentence and nothing is saved", async () => {
226 test("slots out of range are refused with the page's sentence and nothing is saved", async () => {
228227 const h = boot(ada);
229228 await h.open();
230229 const before = saved();
231 for (const bad of ["-1", "abc", ""]) {
232 await h.press("c");
233 for (let i = 0; i < 10; i++) await h.press("backspace");
234 await h.type(bad);
235 await h.press("enter");
236 expect(h.text()).toContain(AUTONOMY_BOUNDS);
237 expect(saved().autonomyCeilingUsd).toBe(before.autonomyCeilingUsd);
238 }
239230 for (const bad of ["9", "2.5", "x", "-1"]) {
240231 await h.press("s");
241232 for (let i = 0; i < 4; i++) await h.press("backspace");
@@ -295,11 +286,10 @@ describe("autonomy in the terminal", () => {
295286 expect(h.text()).not.toContain("Builder");
296287 expect(h.text()).not.toContain("Ceiling");
297288 expect(h.text()).not.toContain("Mode ");
298 await h.press("m", "left", "enter", "c", "s");
289 await h.press("m", "left", "enter", "s");
299290 expect(h.text()).not.toContain("Set autonomy");
300291 const after = saved();
301292 expect(after.autonomy).toBe(before.autonomy);
302 expect(after.autonomyCeilingUsd).toBe(before.autonomyCeilingUsd);
303293 expect(after.autonomySlots).toBe(before.autonomySlots);
304294 h.stop();
305295 });
test/tui-dashboard-idle.test.ts +19 −5
@@ -6,7 +6,10 @@ import { join } from "node:path";
66 import { addToCrew, createAgent } from "../src/actions/crew.ts";
77 import { createRepo } from "../src/actions/repos.ts";
88 import { createApp, type App as Forge } from "../src/app.ts";
9 import { noteMeasure } from "../src/core/measure.ts";
910 import { createRun } from "../src/core/runs.ts";
11 import { PLATFORM } from "../src/core/subscriptions.ts";
12 import { forgetWeek } from "../src/crew/week_read.ts";
1013 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1114 import { idleLine, idleReason } from "../src/crew/idle_reason.ts";
1215 import { createForgeApp } from "../src/tui/forge.ts";
@@ -58,6 +61,18 @@ async function firstScreen(user: User): Promise<string> {
5861 return text;
5962 }
6063
64 /** The provider's week, early in it, as used as `usedPct` says. */
65 function measureWeek(usedPct: number): void {
66 const at = Date.now();
67 noteMeasure(forge.db, PLATFORM, {
68 window: "week",
69 usedPct,
70 resetsAt: new Date(at + 6 * 86_400_000).toISOString(),
71 observedAt: new Date(at).toISOString(),
72 });
73 forgetWeek();
74 }
75
6176 test("the admin's home prints the reason's line; nobody else's does", async () => {
6277 const made = await createRepo(forge, alice, { name: "svc", visibility: "private" });
6378 if (!made.ok) throw new Error(String(made.error));
@@ -65,20 +80,19 @@ test("the admin's home prints the reason's line; nobody else's does", async () =
6580 if (!created.ok) throw new Error(String(created.error));
6681 expect(addToCrew(forge, alice, made.value, "idlebot").ok).toBe(true);
6782 forge.db
68 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_ceiling_usd = 1, autonomy_slots = 2 WHERE id = ?1")
83 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_slots = 2 WHERE id = ?1")
6984 .run(made.value.id, alice.id);
70 const run = createRun(forge.db, { repoId: made.value.id, kind: "agent", actorId: getUserByName(forge.db, "idlebot")!.id });
71 forge.db.query("UPDATE run SET cost_usd = 5, state = 'ok' WHERE id = ?1").run(run.id);
85 measureWeek(100);
7286
7387 const reason = idleReason(forge, new Date());
74 expect(reason).toEqual({ word: "ceiling reached", href: "/meter" });
88 expect(reason).toEqual({ word: "week spent", href: "/meter" });
7589 expect(await firstScreen(alice)).toContain(idleLine(reason!));
7690 expect(await firstScreen(bob)).not.toContain("Builders idle");
7791 });
7892
7993 test("the builders line ends with the reason's word while a slot is free; with every slot busy it has none", async () => {
8094 const repo = forge.db.query("SELECT id FROM repo WHERE name = 'svc'").get() as { id: string };
81 forge.db.query("UPDATE repo SET autonomy_ceiling_usd = 1000 WHERE id = ?1").run(repo.id);
95 measureWeek(0);
8296 const reason = idleReason(forge, new Date());
8397 expect(reason?.word).toBe("nothing ready");
8498 const free = await firstScreen(alice);
test/tui-kpis.test.ts +13 −2
@@ -1,4 +1,7 @@
11 /** The terminal's first screen carries the figures the web home does (#2871): an admin sees them; nobody else does. */
2 import { noteMeasure } from "../src/core/measure.ts";
3 import { PLATFORM } from "../src/core/subscriptions.ts";
4 import { forgetWeek } from "../src/crew/week_read.ts";
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
@@ -125,13 +128,21 @@ test("with since-lines, moving-lines and idle crew all drawn, the admin still se
125128 const admin = a.value;
126129 const made = await createRepo(full, admin, { name: "svc", visibility: "private" });
127130 if (!made.ok) throw new Error(String(made.error));
128 // Idle crew: an autonomous repository past its own ceiling.
131 // Idle crew: an autonomous repository whose week is spent.
129132 const bot = await createAgent(full, admin, { username: "idlebot" });
130133 if (!bot.ok) throw new Error(String(bot.error));
131134 expect(addToCrew(full, admin, made.value, "idlebot").ok).toBe(true);
132135 full.db
133 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_ceiling_usd = 1, autonomy_slots = 2 WHERE id = ?1")
136 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_slots = 2 WHERE id = ?1")
134137 .run(made.value.id, admin.id);
138 noteMeasure(full.db, PLATFORM, {
139 window: "week",
140 usedPct: 100,
141 resetsAt: new Date(Date.now() + 6 * 86_400_000).toISOString(),
142 observedAt: new Date().toISOString(),
143 });
144 forgetWeek();
145 // The day's spend the line below prints.
135146 const run = createRun(full.db, { repoId: made.value.id, kind: "agent", actorId: getUserByName(full.db, "idlebot")!.id });
136147 full.db.query("UPDATE run SET cost_usd = 5, state = 'ok' WHERE id = ?1").run(run.id);
137148 // Since-lines: pulls landed in the last hour.
test/tui-limbs-replanned.test.ts −1
@@ -95,7 +95,6 @@ describe("the limbs screen after a re-plan", () => {
9595 const set = await updateRepoSettings(app, alice, repo, {
9696 autonomy: "autonomous",
9797 autonomyDirection: "Keep the engine small.",
98 autonomyCeilingUsd: 100,
9998 autonomyBy: alice.id,
10099 });
101100 if (!set.ok) throw new Error(JSON.stringify(set.error));
test/tui-limbs.test.ts −1
@@ -279,7 +279,6 @@ describe("raise and lower a limb in the terminal", () => {
279279 await updateRepoSettings(forge, alice, r, {
280280 autonomy: "autonomous",
281281 autonomyDirection: "Keep it small.",
282 autonomyCeilingUsd: 10,
283282 autonomyBy: alice.id,
284283 });
285284 const search = open(r, alice, "Search everything");
test/vision-pull.test.ts +2 −2
@@ -77,7 +77,7 @@ describe("a vision thought", () => {
7777 async function repoWith(name: string, files: { path: string; content: string }[]): Promise<Repo> {
7878 const r = await createRepo(app, alice, { name, visibility: "private" });
7979 if (!r.ok) throw new Error(String(r.error));
80 await updateRepoSettings(app, alice, r.value, { autonomy: "autonomous", autonomyDirection: "x", autonomyCeilingUsd: 10, autonomySlots: 1, autonomyBy: alice.id });
80 await updateRepoSettings(app, alice, r.value, { autonomy: "autonomous", autonomyDirection: "x", autonomySlots: 1, autonomyBy: alice.id });
8181 const repo = getRepoById(app.db, r.value.id)!;
8282 const e = await editFiles(app, alice, repo, { files });
8383 if (!e.ok) throw new Error(JSON.stringify(e.error));
@@ -137,7 +137,7 @@ describe("a vision thought", () => {
137137 test("a repository with no commits still places the thought, without a pull", async () => {
138138 const r = await createRepo(app, alice, { name: "empty", visibility: "private" });
139139 if (!r.ok) throw new Error(String(r.error));
140 await updateRepoSettings(app, alice, r.value, { autonomy: "autonomous", autonomyDirection: "x", autonomyCeilingUsd: 10, autonomySlots: 1, autonomyBy: alice.id });
140 await updateRepoSettings(app, alice, r.value, { autonomy: "autonomous", autonomyDirection: "x", autonomySlots: 1, autonomyBy: alice.id });
141141 const t = await think(getRepoById(app.db, r.value.id)!, "vision: smaller");
142142 expect(t.p.kind).toBe("vision");
143143 expect(t.p.placed.some((x) => x.action === "proposed")).toBe(false);
test/week-card.test.ts added +34
@@ -0,0 +1,34 @@
1 /** The week's budget as a share of the week and a pace (#10623): by hand, no dollar ceiling. */
2 import { expect, test } from "bun:test";
3 import { weekCardRows, weekDecision } from "../src/crew/week.ts";
4 import { weekHold } from "../src/crew/week_hold.ts";
5
6 const DAY = 86_400_000;
7 const NOW = new Date(Date.UTC(2026, 10, 10, 12));
8 const at = (daysLeft: number) => new Date(NOW.getTime() + daysLeft * DAY);
9
10 // By hand: 3.5 days left of 7 is 50% of the week gone; 60% used is 10 points ahead of an even pace;
11 // the Weekly budget keeps 10% (reserve 0.1), so the crew may use up to 90%.
12 test("a week half gone with 60% used is ahead of pace, below its 90% share, and runs", () => {
13 const w = weekDecision({ meter: { freePct: 40, keptPct: 0, resetsAt: at(3.5) }, now: NOW, ceiling: 3, reserve: 0.1 })!;
14 expect(w).toMatchObject({ usedPct: 60, mayUsePct: 90, elapsedPct: 50, pace: "ahead", slots: 3 });
15 expect(weekHold(w)).toBeNull();
16 expect(weekCardRows(w)).toEqual({ week: "60% used of 90% allowed", pace: "ahead" });
17 });
18
19 test("dispatch holds when the week's share is spent and the pace is ahead", () => {
20 const w = weekDecision({ meter: { freePct: 5, keptPct: 0, resetsAt: at(5) }, now: NOW, ceiling: 3, reserve: 0.1 })!;
21 // 5 days left is 29% gone; 95% used is past the 90% share.
22 expect(w).toMatchObject({ usedPct: 95, mayUsePct: 90, elapsedPct: 29, pace: "ahead", slots: 0 });
23 expect(weekHold(w)).toContain("queued, not started");
24 });
25
26 test("on and behind pace read as such, and an unmeasured week is said plainly", () => {
27 const on = weekDecision({ meter: { freePct: 50, keptPct: 0, resetsAt: at(3.5) }, now: NOW, ceiling: 1, reserve: 0.1 })!;
28 expect(on.pace).toBe("on");
29 const behind = weekDecision({ meter: { freePct: 90, keptPct: 0, resetsAt: at(3.5) }, now: NOW, ceiling: 1, reserve: 0.1 })!;
30 expect(behind.pace).toBe("behind");
31 expect(weekCardRows(null)).toBeNull();
32 expect(weekCardRows(behind)).toEqual({ week: "10% used of 90% allowed", pace: "behind" });
33 expect(JSON.stringify(weekCardRows(behind))).not.toMatch(/\$/);
34 });
test/week-pump.test.ts +1 −1
@@ -49,7 +49,7 @@ test("past the week's reserve an assigned run stays queued, with the reason in i
4949 const now = Date.now();
5050 const measure = (used: number) => noteMeasure(app.db, sub.value.id, { window: "week", usedPct: used, resetsAt: new Date(now + 3.5 * DAY).toISOString(), observedAt: new Date(now).toISOString() });
5151 measure(95);
52 const on = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Ship.", autonomyCeilingUsd: 1000, autonomySlots: 4, autonomyBy: alice.id });
52 const on = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Ship.", autonomySlots: 4, autonomyBy: alice.id });
5353 expect(on.ok).toBe(true);
5454 const repo = getRepoById(app.db, made.value.id)!;
5555 const issue = openIssue(app, alice, repo, { title: "Assigned work", body: "Do it." });
test/week-wiring.test.ts +65 −2
@@ -15,6 +15,9 @@ import { addSubscription } from "../src/core/subscriptions.ts";
1515 import { recordUsage } from "../src/core/usage.ts";
1616 import { type User } from "../src/core/users.ts";
1717 import { repoPace } from "../src/crew/autonomy.ts";
18 import { queueAgentRun } from "../src/crew/dispatch.ts";
19 import { openIssue } from "../src/actions/issues.ts";
20 import { getAgent } from "../src/core/agents.ts";
1821 import { changeCapacity } from "../src/actions/capacity.ts";
1922 import { capacityDefault, setCapacity } from "../src/core/capacity.ts";
2023 import { forgetWeek, weekWords } from "../src/crew/week_read.ts";
@@ -80,7 +83,6 @@ beforeAll(async () => {
8083 const on = await updateRepoSettings(app, alice, repo, {
8184 autonomy: "autonomous",
8285 autonomyDirection: "Ship it.",
83 autonomyCeilingUsd: 1000,
8486 autonomySlots: 4,
8587 autonomyBy: alice.id,
8688 });
@@ -207,7 +209,7 @@ test("home reads the repository the crew works, not the first by name", async ()
207209 const quiet = await createRepo(app, alice, { name: "aaa-quiet", visibility: "private" });
208210 if (!quiet.ok) throw new Error(String(quiet.error));
209211 expect(addToCrew(app, alice, quiet.value, "builderbot").ok).toBe(true);
210 const on = await updateRepoSettings(app, alice, quiet.value, { autonomy: "autonomous", autonomyDirection: "Ship.", autonomyCeilingUsd: 1000, autonomySlots: 4, autonomyBy: alice.id });
212 const on = await updateRepoSettings(app, alice, quiet.value, { autonomy: "autonomous", autonomyDirection: "Ship.", autonomySlots: 4, autonomyBy: alice.id });
211213 expect(on.ok).toBe(true);
212214 app.db.query("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)").run(quiet.value.id, sub);
213215 forgetWeek();
@@ -216,3 +218,64 @@ test("home reads the repository the crew works, not the first by name", async ()
216218 expect(words).not.toContain("(0 runs");
217219 expect(words).toMatch(/\(\d+ runs/);
218220 });
221
222 test("a spent share holds a queued run whatever the pace; pace alone holds nothing", () => {
223 const opened = openIssue(app, alice, repo, { title: "Plant tulips", body: "Along the fence." });
224 if (!opened.ok) throw new Error("issue not opened");
225 const bot = app.db.query("SELECT id FROM user WHERE username = 'builderbot'").get() as { id: string };
226 const agent = getAgent(app.db, bot.id)!;
227 const runs = () => app.db.query("SELECT COUNT(*) AS n FROM run WHERE repo_id = ?1").get(repo.id) as { n: number };
228 // By hand: 3.5 of 7 days left is 50% gone; 60% used is ahead of pace but under the 90% share.
229 week(60);
230 expect(repoPace(app, repo, NOW).slots).toBe(4);
231 // 95% used passes the 90% share and is ahead of pace: held, the week's sentence the reason.
232 week(95);
233 const held = repoPace(app, repo, NOW);
234 expect(held.slots).toBe(0);
235 expect(held.reason).toContain("95% of the week used");
236 const before = runs().n;
237 expect(queueAgentRun(app, repo, opened.value, agent, "feedback")).toBeUndefined();
238 expect(runs().n).toBe(before);
239 // Behind pace with the share spent is held the same: the share is the one gate.
240 noteMeasure(app.db, sub, { window: "week", usedPct: 91, resetsAt: new Date(NOW.getTime() + 6.9 * DAY).toISOString(), observedAt: NOW.toISOString() });
241 forgetWeek();
242 expect(repoPace(app, repo, NOW).slots).toBe(0);
243 expect(queueAgentRun(app, repo, opened.value, agent, "feedback")).toBeUndefined();
244 expect(runs().n).toBe(before);
245 });
246
247 test("the autonomy card shows the week and the pace as two rows, once, with no dollar-ceiling field, and the form still saves", async () => {
248 week(40);
249 const servers = await serve(app);
250 try {
251 const signin = await fetch(`${servers.url}/signin`, {
252 method: "POST",
253 redirect: "manual",
254 headers: { origin: servers.url },
255 body: new URLSearchParams({ username: "alice", password: "a-long-passphrase" }),
256 });
257 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
258 const page = (path: string) => fetch(`${servers.url}${path}`, { headers: { cookie } }).then((r) => r.text());
259 const settings = (await page(`/${alice.username}/${repo.name}/settings`)).replace(/\s+/g, " ");
260 expect(settings).toContain('id="autonomy"');
261 // The autonomy block alone: other blocks on the page may say "a day" of other limits.
262 const crew = settings.slice(settings.indexOf('id="autonomy"'), settings.indexOf("</section>", settings.indexOf('id="autonomy"')));
263 expect(crew).toContain("<dt>Week</dt><dd>40% used of 90% allowed</dd><dt>Pace</dt><dd>behind</dd>");
264 expect(crew).not.toContain('name="ceiling"');
265 expect(crew).not.toContain("a day");
266 expect(crew.match(/% used of 90% allowed/g)?.length).toBe(1);
267 const saved = await fetch(`${servers.url}/${alice.username}/${repo.name}/settings/autonomy`, {
268 method: "POST",
269 redirect: "manual",
270 headers: { cookie, origin: servers.url },
271 body: new URLSearchParams({ autonomy: "autonomous", direction: "Ship the tulips.", slots: "3" }),
272 });
273 expect(saved.status).toBe(303);
274 const after = getRepoById(app.db, repo.id)!;
275 expect(after.autonomyDirection).toBe("Ship the tulips.");
276 expect(after.autonomySlots).toBe(3);
277 app.db.query("UPDATE repo SET autonomy_slots = 4 WHERE id = ?1").run(repo.id);
278 } finally {
279 servers.stop();
280 }
281 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs