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

Revert "Shrink the planner: rules count and order the work, the decider chooses, a mo…" #16608

opened this

Check · Review · Land · Live — Its check is red. Next: builder, its check is red.

Ready to land

revert-16522 → main 1 commit

Review

Sign in to review this change.
17 files changed +151 −423
docs/features/planner.md deleted −14
@@ -1,14 +0,0 @@
1 ---
2 topic: Tell the crew
3 row: What the planner has been doing
4 ---
5 # What the planner has been doing
6
7 The planner is asked for a pass only when a person writes on a direction or the crew hands it an
8 issue; a short map no longer starts one. Its card shows what that costs and what it gives.
9
10 - **Web:** Settings → Crew → Planner (`/settings/crew#planner`), a forge admin's page. Rows: the last pass (when and how it ended), how many issues it opened, its closing line; the passes and spend over 7 days with its share of the crew's spend; and what became of the issues it filed in 14 days (landed, dropped, split, open).
11 - **Terminal:** `forge tui`, the Planner command (admins), the same rows.
12 - Both draw `plannerRows()` in `src/crew/planner_card.ts`, so they say the same thing. The card is absent until the planner has run or filed something.
13 - Try it: open `/settings/crew` as an admin after a direction has had a pass.
14 - `test/planner-card.test.ts` covers the rows, the page's escaping and the admin gate.
src/core/repos.ts +1 −3
@@ -174,9 +174,7 @@ export interface Repo {
174174 readonly plansNeedNod: boolean;
175175 /** An admin's mark: a new forge may start from this repository (#12431). */
176176 readonly template: boolean;
177 /**
178 * The issue the planner is given, when a person has written on it or the crew handed it an issue.
179 */
177 /** The issue the planner is given, when the map has run dry. */
180178 readonly directionIssueId: string | null;
181179 /** The repo this was forked from, or null. */
182180 readonly forkParentId: string | null;
src/crew/autonomy.ts +57 −31
@@ -114,8 +114,8 @@ import { announceGovernor, governorFor } from "./governed.ts";
114114 import { BREAKER_NOTE, breakerTripped } from "./breaker.ts";
115115 import { REPEAT_NOTE } from "./repeat_note.ts";
116116 import { given, pendingReplans } from "../core/limb_replan.ts";
117 import { handedOverPulls, skipsReplan } from "./guard.ts";
118 import { type Held, heldBy, heldWords } from "./held.ts";
117 import { handedOverPulls, SKIP_SUMMARY, skipsReplan } from "./guard.ts";
118 import { type Held, heldBy, heldWords, replannable } from "./held.ts";
119119 import { driveOrBeat } from "./beat.ts";
120120 import { forgetBacklog, noteBacklog, waitingBy, waitingWords } from "./backlog.ts";
121121 import { ceilingHold, pausedUntil, pauseSentence } from "../core/planner_pause.ts";
@@ -132,7 +132,7 @@ import {
132132 parkedTwice,
133133 } from "./parks.ts";
134134 import { handedTooLarge, noteTooLarge } from "./too_large.ts";
135 import { reserveOf, reserveWords } from "./reserve.ts";
135 import { due, reserveOf, reserveWords } from "./reserve.ts";
136136 import { createLog } from "../kernel/log.ts";
137137 import { err, ok, type Result } from "../kernel/result.ts";
138138 import {
@@ -178,7 +178,7 @@ export const AUTONOMY_TICK_MS = 60_000;
178178 * How soon a planner whose last pass did not end well — a decline a person
179179 * answered, a failure — is asked again. A pass that ended well has no
180180 * floor: while the reserve is short the planner is asked again as soon as
181 * the map moves, and a pass with nothing new is held by `plannerNothingNew`.
181 * the map moves, and a pass that moved nothing is held by `skipsReplan`.
182182 */
183183 const REPLAN_AFTER_MS = 20 * 60_000;
184184
@@ -540,8 +540,11 @@ async function driveOnce(
540540 const ready = held.startable.filter((r) => !taken.has(r.issue.id));
541541 const used = slotted.length + pending;
542542 if (used >= paced.slots) {
543 // The builders are busy; a pass may still be owed (a hand-over, a person's word).
544 if (await planIfOwed(app, repo, by, crew, active, ready.length, now)) return "planned";
543 // The builders are busy; the planner can still refill the map, when
544 // the reserve is short — counted, never assumed: a full crew with a
545 // full reserve is not a reason to plan (#1097, #3237).
546 if (await planIfThin(app, repo, by, crew, active, ready.length, now))
547 return "planned";
545548 return "full";
546549 }
547550
@@ -583,14 +586,18 @@ async function driveOnce(
583586 size: routed.size,
584587 by: routed.by,
585588 });
586 // Planning runs alongside building: a pass owed is asked for now.
587 await planIfOwed(app, repo, by, crew, active, ready.length - 1, now);
589 // Planning runs alongside building: when the reserve is short, the
590 // planner is asked now, not when the builders have run it dry.
591 await planIfThin(app, repo, by, crew, active, ready.length - 1, now);
588592 return "picked";
589593 }
590594
591 // Nothing is startable with slots free: that alone is no reason to run a model (#16231).
592 // A pass is asked for only when something is owed (`planIfOwed`).
593 if (await planIfOwed(app, repo, by, crew, active, 0, now)) return "planned";
595 // Nothing is startable with slots free: the planner is asked. When
596 // ready issues are held by what re-planning lifts — stalled, capped,
597 // parked twice — it is asked with that breakdown, and neither a full
598 // plate nor its own unanswered decline holds it: nothing else will move them (#2244).
599 const stuck = replannable(held).length > 0 ? held : null;
600 if (await planIfThin(app, repo, by, crew, active, 0, now, stuck)) return "planned";
594601 // Red pulls nobody is working are a stall, not idleness (#12968): the tick says so.
595602 return redUnattended(app, repo, active) > 0 ? "stalled" : "idle";
596603 }
@@ -796,7 +803,7 @@ function held(repo: Repo, why: string): false {
796803 return false;
797804 }
798805
799 async function planIfOwed(
806 async function planIfThin(
800807 app: App,
801808 repo: Repo,
802809 by: User,
@@ -804,6 +811,7 @@ async function planIfOwed(
804811 active: readonly Run[],
805812 ready: number,
806813 now: Date,
814 stuck: Held | null = null,
807815 ): Promise<boolean> {
808816 // The direction is the planner's own issue: a park on it (the breaker's, for runs that repeat)
809817 // hands the planner nothing it has not read, so it owes no pass. Counted, each park bought
@@ -818,20 +826,7 @@ async function planIfOwed(
818826 );
819827 const limbs = pendingReplans(app.db, repo);
820828 const reserve = reserveOf(ready, repo.autonomySlots);
821 // A repository with no direction issue yet is owed its first pass; after that only a word
822 // or an edit on the direction (`plannerNothingNew`), a hand-over or a limb is.
823 let worded = true;
824 if (repo.directionIssueId !== null) {
825 const seat = crew.find((c) => c.role === "planner")?.agent;
826 const issue = getIssueById(app.db, repo.directionIssueId);
827 const since = app.db
828 .query<{ at: string }, [string]>(
829 `SELECT created_at AS at FROM run WHERE issue_id = ?1 AND kind = 'agent' ORDER BY created_at DESC LIMIT 1`,
830 )
831 .get(repo.directionIssueId)?.at;
832 worded = seat !== undefined && issue !== undefined && !skipsReplan(app.db, repo, issue, seat, since ?? "");
833 }
834 if (!worded && handed.length === 0 && limbs.length === 0) return false;
829 if (!due(reserve) && handed.length === 0 && limbs.length === 0) return false;
835830 // Paused by its pillar's setting (#7668): the planner stays on the crew.
836831 if (repo.plannerSlots === 0) return notPlanned(repo, "the planner is paused");
837832 if (repo.autonomyDirection.trim() === "")
@@ -858,7 +853,11 @@ async function planIfOwed(
858853 // A limb a person handed over is owed one pass, whatever the map and
859854 // whatever the planner said of the direction before (#761).
860855 const limbsOwed = limbs.filter((r) => !given(app.db, repo, r.at));
861 if (!worded && owed.length === 0 && limbsOwed.length === 0) return false;
856 if (!due(reserve) && owed.length === 0 && limbsOwed.length === 0) return false;
857 // Nothing startable for issues held since its last pass that re-planning
858 // lifts: owed one pass like a hand-over, once (#2244).
859 const unstuck = stuck === null ? [] : replannable(stuck).filter((issue) => heldSince(app, issue, seen));
860 const news = owed.length + unstuck.length + limbsOwed.length;
862861 // The direction is the planner's standing issue, not one issue retried:
863862 // no run count bounds it. The budget does, the breaker, and a pass that
864863 // would plan the same input twice is skipped (`plannerNothingNew`).
@@ -871,13 +870,13 @@ async function planIfOwed(
871870 if (until !== null) return notPlanned(repo, pauseSentence(until));
872871 const ceiling = splitPending(app, repo) ? null : ceilingHold(app.db, repo.id);
873872 if (ceiling !== null) return notPlanned(repo, ceiling);
874 const hold = owed.length + limbsOwed.length === 0 ? plannerHold(app, repo, now) : null;
873 const hold = news === 0 ? plannerHold(app, repo, now) : null;
875874 if (hold !== null) return held(repo, holdWhy(hold));
876875 if (lastPlan !== null && lastPlan !== undefined) {
877876 // A planner that declined the direction is not asked again until a
878877 // person has said something on it, or the crew hands it an issue.
879878 if (
880 owed.length + limbsOwed.length === 0 &&
879 news === 0 &&
881880 lastPlan.state === "failed" &&
882881 declinedUnanswered(app, repo, direction)
883882 )
@@ -893,6 +892,13 @@ async function planIfOwed(
893892 REPLAN_AFTER_MS
894893 )
895894 return notPlanned(repo, "planned recently");
895 // Nobody spoke and the map has not moved since the last pass: another
896 // would read its own summary and change nothing (#1097).
897 if (
898 news === 0 &&
899 skipsReplan(app.db, repo, direction, planner, lastPlan.created_at)
900 )
901 return notPlanned(repo, SKIP_SUMMARY);
896902 } else if (direction.assigneeId === planner.user.id) {
897903 return notPlanned(repo, "the planner already holds the direction");
898904 }
@@ -910,7 +916,11 @@ async function planIfOwed(
910916 ? "a limb was handed over; planner asked"
911917 : owed.length > 0
912918 ? "parked twice; planner asked"
913 : "a person's direction; planner asked",
919 : unstuck.length > 0
920 ? "nothing startable; planner asked"
921 : ready === 0
922 ? "map ran dry; planner asked"
923 : "reserve is short; planner asked",
914924 {
915925 repo: `${repo.ownerName}/${repo.name}`,
916926 planner: planner.user.username,
@@ -919,11 +929,27 @@ async function planIfOwed(
919929 ...(owed.length > 0
920930 ? { parkedTwice: owed.map((issue) => `#${issue.number}`).join(" ") }
921931 : {}),
932 ...(stuck === null ? {} : { held: heldWords(stuck) }),
922933 },
923934 );
924935 return true;
925936 }
926937
938 /**
939 * Whether `issue` came to be held after `since` — its newest builder run
940 * ended then, which is what stalls or caps it — so a planning pass that
941 * started before has not seen it.
942 */
943 function heldSince(app: App, issue: Issue, since: string): boolean {
944 const last = app.db
945 .query<{ at: string | null }, [string]>(
946 `SELECT MAX(COALESCE(finished_at, created_at)) AS at FROM run
947 WHERE issue_id = ?1 AND kind = 'agent'`,
948 )
949 .get(issue.id)?.at;
950 return typeof last === "string" && last > since;
951 }
952
927953 /** Whether the newest run on the issue was a decline and no person has spoken since. */
928954 function declinedUnanswered(app: App, repo: Repo, issue: Issue): boolean {
929955 return declineOf(app.db, repo, issue.id) !== undefined;
@@ -1301,7 +1327,7 @@ export function ensureDirectionIssue(
13011327 }
13021328 const opened = openIssue(app, by, repo, {
13031329 title: `${DIRECTION_PREFIX}${truncateAtWord(repo.autonomyDirection.trim(), DIRECTION_TITLE_LIMIT)}`,
1304 body: `${repo.autonomyDirection.trim()}\n\nThis issue carries the repository's direction. The planner is given it when a person writes on it or the crew hands it an issue; it opens and links the issues that follow from it, and this one stays open.`,
1330 body: `${repo.autonomyDirection.trim()}\n\nThis issue carries the repository's direction. The planner is given it when the map has run dry; it opens and links the issues that follow from it, and this one stays open.`,
13051331 });
13061332 if (!opened.ok) return undefined;
13071333 setDirectionIssue(app.db, repo.id, opened.value.id);
src/crew/brief.ts +21 −3
@@ -20,6 +20,7 @@ import { DESIGN_POINTER, DESIGN_PRINCIPLES } from "./design_principles.ts";
2020 import { READER } from "./direct.ts";
2121 import { hotFiles, hotWords } from "./hot_files.ts";
2222 import { newsSince } from "./news.ts";
23 import type { Reserve } from "./reserve.ts";
2324 import {
2425 REVIEW_ROUNDS,
2526 type Review,
@@ -216,8 +217,7 @@ export function systemPrompt(input: BriefInput): string {
216217 " It answers with what it opened (key and number), the numbers now ready, and those deferred.",
217218 "- One change on several things is one issue: the same shortcut, wording or rendering across many lists, pages or kinds is one issue whose body names each as a checkbox, and a builder lands it in one or two pulls. A plan with three or more items of one shape is refused (look_alike).",
218219 "- Polish — a shortcut, a wording, spacing, an existing page made nicer — is the small lane: start its title with `small:`. The forge holds that lane to the repository's polish share, and a pillar's umbrella is no reason to file polish as pillar work. A person's ask (a comment, an assignment, a `from-app` note) and the pillar work that is ready come before any polish; file polish behind them (blockedBy) when both are open.",
219 "- You are asked because a person wrote on the direction or the crew handed you an issue, not because the map is short: plan what those words ask, and nothing the direction merely allows. If there is nothing to plan, open nothing and say so in your last message.",
220 "- Write no explanation on the direction issue or any other: your last message is the record. Read the comments your task shows, not the whole thread again.",
220 "- The direction is never finished. When what it names is built, propose its next increment in the same spirit: what a demanding user would want next, what is fragile, slow, ugly, untested or undocumented, what the pictures and the previews show is off. Leave the map with the reserve your task names startable, every time.",
221221 '- An issue with a comment that starts "Parked by the crew" was tried and could not be finished as written. Split it into smaller issues, or rewrite what done looks like, or close it with a word if the direction no longer needs it — never leave it as it was. One the crew parked twice is yours: your task lists it, with what you may do with it.',
222222 "- Closing what you re-plan: PATCH …/issues/N with {\"state\":\"closed\",\"reason\":\"split\",\"into\":[A,B]} (open issues made since it was handed to you, or since the issue itself when it was never handed over), {\"state\":\"closed\",\"reason\":\"dropped\"} for an issue the crew wrote, or {\"state\":\"closed\",\"reason\":\"done\"} only when an \"already done on main\" note on it names commits on main. A person's ask is never yours to drop; nothing else is yours to close, and nothing to reopen.",
223223 "- Assign nobody and push nothing: the map is the result. The direction issue stays open.",
@@ -367,6 +367,8 @@ export interface TaskInput extends BriefInput {
367367 readonly owed?: readonly Owed[] | undefined;
368368 /** For a builder: the live holds on the desk that name its repository, as left (#12535). */
369369 readonly holds?: readonly string[] | undefined;
370 /** For a planner: the startable issues against the standing reserve (`reserve.ts`). */
371 readonly reserve?: Reserve | undefined;
370372 }
371373
372374 /** An issue and the boxes of it still unticked, in order. */
@@ -486,7 +488,7 @@ function taskBody(input: TaskInput): string {
486488 const { issue } = input;
487489 const out: string[] = [];
488490 const isAgent = (name: string): boolean => name === input.agent.user.username;
489 const handed = [earlierParkLines(input), parkedTwiceLines(input), landedLines(input), limbLines(input), stuckLines(input), teamLines(input), hotLines(input), holdLines(input)]
491 const handed = [reserveLines(input), earlierParkLines(input), parkedTwiceLines(input), landedLines(input), limbLines(input), stuckLines(input), teamLines(input), hotLines(input), holdLines(input)]
490492 .filter((lines) => lines.length > 0)
491493 .flatMap((lines, n) => (n === 0 ? lines : ["", ...lines]));
492494 const readers = input.readers ?? new Set<string>();
@@ -930,6 +932,22 @@ function teamLines(input: TaskInput): string[] {
930932 ];
931933 }
932934
935 /**
936 * What a planner is told of the standing reserve (#3237): how many issues a
937 * builder could start now, how many the crew keeps, and that a pass which
938 * leaves it short says why on the direction — the word that keeps the
939 * forge from asking again before the map moves.
940 */
941 function reserveLines(input: TaskInput): string[] {
942 const reserve = input.role === "planner" ? input.reserve : undefined;
943 if (reserve === undefined) return [];
944 const gap = Math.max(0, reserve.target - reserve.startable);
945 return [
946 `The crew keeps a standing reserve of ${reserve.target} startable issues, two per builder slot, so builders never wait for a plan. ${reserve.startable} can start now${gap > 0 ? `: plan at least ${gap} more a builder can start at once — ready, with nothing open in front of it` : ""}.`,
947 `If you finish with fewer than ${reserve.target} startable, say why in a comment on #${input.issue.number} before you finish: what the direction has left, or what holds the rest.`,
948 ];
949 }
950
933951 /**
934952 * What a builder is told of the holds on the desk that name its repository:
935953 * notes people and releases left, quoted as data about the repository now,
src/crew/held.ts +8
@@ -105,6 +105,9 @@ export const HOLDS = [
105105
106106 export type HoldName = (typeof HOLDS)[number];
107107
108 /** The holds the planner can lift by re-planning: the rest wait on work in flight or a person. */
109 export const REPLANNABLE: readonly HoldName[] = ["stalled", "run_cap", "parked_twice"];
110
108111 export interface Held {
109112 /** The ready issues a builder may start now, in the map's order. */
110113 readonly startable: Ranked[];
@@ -362,6 +365,11 @@ export function heldWords(held: Held): string {
362365 return said.length === 0 ? "none" : said.join(" ");
363366 }
364367
368 /** The held issues the planner can lift by re-planning them. */
369 export function replannable(held: Held): Issue[] {
370 return REPLANNABLE.flatMap((h) => held.by[h]);
371 }
372
365373 /** The ready list sorted now, from the map, the crew and the runs in flight. */
366374 export function heldNow(app: App, repo: Repo, now: number = Date.now()): Held {
367375 return heldBy(
src/crew/planner_card.ts deleted −138
@@ -1,138 +0,0 @@
1 /**
2 * What the planner has been doing, as plain data for the Crew page (#16231): its last pass in
3 * one line, its share of the week's spend, and what became of the issues it filed. The planner's
4 * runs are the agent runs on a repository's direction issue; its issues are the ones those
5 * runs' actors wrote. Plain data out: the page draws it.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { agoWords } from "../kernel/ago.ts";
10
11 const DAY_MS = 86_400_000;
12 /** Issues filed this long ago or later are counted for their outcome. */
13 export const OUTCOME_DAYS = 14;
14 /** Spend and passes are totalled over this many days. */
15 export const SPEND_DAYS = 7;
16 const LINE_MAX = 160;
17
18 export interface PlannerPass {
19 readonly at: string;
20 readonly state: string;
21 /** Issues the pass's actor opened while it ran. */
22 readonly opened: number;
23 /** The pass's own last message, first line, cut to one line. */
24 readonly said: string;
25 }
26
27 export interface PlannerOutcomes {
28 readonly filed: number;
29 readonly landed: number;
30 readonly dropped: number;
31 readonly split: number;
32 readonly open: number;
33 }
34
35 export interface PlannerCard {
36 readonly last: PlannerPass | null;
37 readonly passes: number;
38 readonly spentUsd: number;
39 readonly crewUsd: number;
40 readonly outcomes: PlannerOutcomes;
41 }
42
43 /** The first line of a summary, one line, never longer than a line of the card. */
44 export function oneLine(text: string): string {
45 const first = (text.split("\n").find((l) => l.trim() !== "") ?? "").trim();
46 return first.length > LINE_MAX ? `${first.slice(0, LINE_MAX - 1)}…` : first;
47 }
48
49 /** The planner's share of the crew's spend, as a whole percent; 0 when nothing was spent. */
50 export function sharePercent(planner: number, crew: number): number {
51 return crew > 0 ? Math.round((planner / crew) * 100) : 0;
52 }
53
54 const PLANNER_RUNS = `FROM run r JOIN repo p ON p.direction_issue_id = r.issue_id WHERE r.kind = 'agent'`;
55
56 export function plannerCard(db: Database, now = new Date()): PlannerCard {
57 const since = new Date(now.getTime() - SPEND_DAYS * DAY_MS).toISOString();
58 // One statement: the last pass with what it opened, the week's totals and the outcomes.
59 const from = new Date(now.getTime() - OUTCOME_DAYS * DAY_MS).toISOString();
60 const t = db
61 .query<
62 {
63 at: string | null;
64 state: string | null;
65 summary: string | null;
66 opened: number | null;
67 n: number;
68 usd: number | null;
69 crew: number | null;
70 filed: number;
71 landed: number;
72 dropped: number;
73 split: number;
74 open: number;
75 },
76 [string, string, string]
77 >(
78 `SELECT l.created_at AS at, l.state, l.summary, l.opened,
79 (SELECT COUNT(*) ${PLANNER_RUNS} AND r.created_at >= ?1) AS n,
80 (SELECT SUM(r.cost_usd) ${PLANNER_RUNS} AND r.created_at >= ?1) AS usd,
81 (SELECT SUM(cost_usd) FROM run WHERE kind = 'agent' AND created_at >= ?1) AS crew,
82 o.*
83 FROM (SELECT COUNT(*) AS filed,
84 COALESCE(SUM(i.state = 'closed' AND i.close_reason = 'done'), 0) AS landed,
85 COALESCE(SUM(i.state = 'closed' AND i.close_reason = 'dropped'), 0) AS dropped,
86 COALESCE(SUM(i.state = 'closed' AND i.close_reason = 'split'), 0) AS split,
87 COALESCE(SUM(i.state = 'open'), 0) AS open
88 FROM issue i
89 WHERE i.kind = 'issue' AND i.created_at >= ?2
90 AND i.author_id IN (SELECT DISTINCT r.actor_id ${PLANNER_RUNS} AND r.actor_id IS NOT NULL)) o
91 LEFT JOIN (SELECT r.created_at, r.state, r.summary,
92 (SELECT COUNT(*) FROM issue i
93 WHERE i.kind = 'issue' AND r.actor_id IS NOT NULL AND r.started_at IS NOT NULL
94 AND i.author_id = r.actor_id AND i.created_at >= r.started_at
95 AND i.created_at <= COALESCE(r.finished_at, ?3)) AS opened
96 ${PLANNER_RUNS}
97 ORDER BY r.created_at DESC LIMIT 1) l ON 1`,
98 )
99 .get(since, from, now.toISOString());
100 return {
101 last:
102 t?.at == null
103 ? null
104 : { at: t.at, state: t.state ?? "", opened: t.opened ?? 0, said: oneLine(t.summary ?? "") },
105 passes: t?.n ?? 0,
106 spentUsd: t?.usd ?? 0,
107 crewUsd: t?.crew ?? 0,
108 outcomes: {
109 filed: t?.filed ?? 0,
110 landed: t?.landed ?? 0,
111 dropped: t?.dropped ?? 0,
112 split: t?.split ?? 0,
113 open: t?.open ?? 0,
114 },
115 };
116 }
117
118 /**
119 * The card as label and value rows, one fact each: the web page and the terminal screen draw the
120 * same rows. Empty when the planner has never run and filed nothing.
121 */
122 export function plannerRows(c: PlannerCard, now = new Date()): [string, string][] {
123 if (c.last === null && c.outcomes.filed === 0) return [];
124 const o = c.outcomes;
125 const rows: [string, string][] =
126 c.last === null
127 ? [["Last pass", "none yet"]]
128 : [
129 ["Last pass", `${agoWords(c.last.at, now.getTime())} (${c.last.state})`],
130 ["Opened", String(c.last.opened)],
131 ...(c.last.said === "" ? [] : ([["Said", c.last.said]] as [string, string][])),
132 ];
133 rows.push(
134 [`Last ${SPEND_DAYS} days`, `${c.passes} passes, $${c.spentUsd.toFixed(2)}: ${sharePercent(c.spentUsd, c.crewUsd)}% of the crew's spend`],
135 [`Filed in ${OUTCOME_DAYS} days`, `${o.filed}: ${o.landed} landed, ${o.dropped} dropped, ${o.split} split, ${o.open} open`],
136 );
137 return rows;
138 }
src/crew/reserve.ts +12
@@ -35,3 +35,15 @@ export function reserveWords(reserve: Reserve): string {
3535 export function short(reserve: Reserve): boolean {
3636 return reserve.startable < reserve.target;
3737 }
38
39 /**
40 * Whether the planner is owed a pass: the reserve is down to half its
41 * target. Asked at one below the target, the planner ran every twenty
42 * minutes to open one issue each time, and a pass costs the same to set up
43 * whether it opens one issue or five (2026-11-09: 11 passes in four hours,
44 * most a top-up of one). Half lets the map run down between passes and
45 * fills it back in one; a thin map's three is still asked at two.
46 */
47 export function due(reserve: Reserve): boolean {
48 return reserve.startable <= Math.ceil(reserve.target / 2);
49 }
src/crew/runner.ts +4 −1
@@ -181,6 +181,7 @@ import { budgetLimit, budgetVerdict, cutOffBy, isOwnForge } from "./forge_budget
181181 import { boxesOf, landedBoxes } from "./box_pass.ts";
182182 import { reviewRange } from "./review_range.ts";
183183 import { heldNow, stuckOf } from "./held.ts";
184 import { reserveOf } from "./reserve.ts";
184185 import { resumeDecision } from "./resume.ts";
185186 import { owed } from "./team_share.ts";
186187 import { pauseReason } from "./pacing.ts";
@@ -1501,7 +1502,8 @@ async function work(
15011502 ? { earlierParks: parkReasons(app.db, repo, issue.id) }
15021503 : {}),
15031504 // A planning run is given what the crew handed over (`parks.ts`),
1504 // what holds the ready list when nothing on it can start (`held.ts`).
1505 // what holds the ready list when nothing on it can start (`held.ts`),
1506 // and the standing reserve it keeps (`reserve.ts`).
15051507 ...(brief.role === "planner" && issue.id === repo.directionIssueId
15061508 ? {
15071509 parkedTwice: [
@@ -1516,6 +1518,7 @@ async function work(
15161518 return {
15171519 landed: landedBoxes(held.by.landed),
15181520 stuck: stuckOf(held),
1521 reserve: reserveOf(held.startable.length, repo.autonomySlots),
15191522 };
15201523 })(),
15211524 owed: owed(app.db, repo.id),
src/tui/screens/planner.ts deleted −42
@@ -1,42 +0,0 @@
1 /**
2 * The planner's card in the terminal (#16231): the same rows as Settings → Crew → Planner, from
3 * `plannerRows`. A forge admin's, like the page: it spans every repository's direction.
4 */
5
6 import { plannerCard, plannerRows } from "../../crew/planner_card.ts";
7 import type { Ctx, Screen } from "../app/app.ts";
8 import type { Session } from "../session.ts";
9 import { style } from "../term/style.ts";
10 import { wrap } from "../term/width.ts";
11 import type { PaletteEntry } from "./entries.ts";
12
13 /** The screen's lines, plain data; nothing for anyone but an admin. */
14 export function plannerLines(f: Session, now = new Date()): string[] {
15 if (f.user?.isAdmin !== true) return [];
16 const rows = plannerRows(plannerCard(f.app.db, now), now);
17 return rows.length === 0 ? ["The planner has not run yet."] : rows.map(([k, v]) => `${k}: ${v}`);
18 }
19
20 export function plannerScreen(f: Session, ctx: Ctx): Screen {
21 const lines = plannerLines(f);
22 return {
23 title: "Planner",
24 keys: [],
25 render(area, s) {
26 const c = ctx.theme.c;
27 const shown = lines.flatMap((l) => wrap(l, Math.max(20, area.w - 2)));
28 shown.slice(0, area.h).forEach((l, i) => s.text(area.x + 1, area.y + i, l, style(c.fg, c.bg), area.x + area.w));
29 },
30 key: () => false,
31 };
32 }
33
34 export const entry: PaletteEntry = {
35 rank: 855,
36 id: "planner",
37 title: "Planner",
38 hint: "its last pass, its spend this week and what became of what it filed",
39 after: ["crewbudgets"],
40 offered: (f) => f.user?.isAdmin === true,
41 run: (session, ctx) => ctx.push(plannerScreen(session, ctx)),
42 };
src/web/pages/crew.ts −2
@@ -11,7 +11,6 @@ import { crewTop, TOP_HELP } from "../crew_top.ts";
1111 import { sshOn } from "../../settings/ssh.ts";
1212 import { USERNAME_PATTERN } from "../username_pattern.ts";
1313 import { budgetsCard } from "../studio/crew_budgets.ts";
14 import { plannerCardView } from "../studio/planner_card.ts";
1514 import { crewKeyField } from "../studio/crew_key.ts";
1615 import { fundingOf, fundingWords } from "../../spawn/funding.ts";
1716 import {
@@ -697,7 +696,6 @@ function crewView(
697696 ], helpAsked(ctx.request.url))}
698697 ${budgetsCard(ctx)}
699698 ${knobsCard(ctx)}
700 ${plannerCardView(ctx)}
701699 ${when(spending.length > 0, () =>
702700 spendingCard(spending, forgeCeiling(ctx.app.config) ?? undefined),
703701 )}
src/web/studio/planner_card.ts deleted −19
@@ -1,19 +0,0 @@
1 /**
2 * Settings → Crew → Planner (#16231): the last pass, the planner's share of the week's spend and
3 * what became of the issues it filed, one fact a row. The rows come from `crew/planner_card.ts`,
4 * the same ones the terminal shows. The Crew page is the admin's, so the card spans every
5 * repository's direction.
6 */
7
8 import { plannerCard, plannerRows } from "../../crew/planner_card.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { html, type Html } from "../html.ts";
11
12 const row = ([label, value]: [string, string]): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`;
13
14 export function plannerCardView(ctx: Ctx, now = new Date()): Html | null {
15 const rows = plannerRows(plannerCard(ctx.app.db, now), now);
16 return rows.length === 0
17 ? null
18 : html`<section class="settings-block" id="planner"><h2>Planner</h2><dl class="status">${rows.map(row)}</dl></section>`;
19 }
test/brief-neutral.test.ts +2 −1
@@ -47,6 +47,7 @@ const planner = {
4747 boxes: [{ number: 2, title: "Closes", boxes: ["one", "two"] }],
4848 landed: [{ number: 10, title: "Landed", boxes: ["left"] }],
4949 owed: [{ team: { slug: "design", dial: 20, charter: "looks" }, open: 0, today: 1 }],
50 reserve: { startable: 1, target: 4 },
5051 };
5152
5253 const texts = (): Record<string, string> => {
@@ -100,7 +101,7 @@ describe("briefs are neutral across model families", () => {
100101 expect(built[`task:${reason}`]?.length ?? 0).toBeGreaterThan(50);
101102 expect(built[`planner:${reason}`]?.length ?? 0).toBeGreaterThan(50);
102103 }
103 expect(built["planner:assigned"]).not.toContain("standing reserve");
104 expect(built["planner:assigned"]).toContain("standing reserve");
104105 expect(built["planner:assigned"]).toContain("Limb #5");
105106 expect(built["planner:assigned"]).toContain("Teams own");
106107 expect(built["planner:assigned"]).toContain("Parked twice");
test/crew-held.test.ts +9 −7
@@ -27,7 +27,7 @@ import { createUser, getUserByName, type User } from "../src/core/users.ts";
2727 import { driveRepo } from "../src/crew/autonomy.ts";
2828 import { taskPrompt } from "../src/crew/brief.ts";
2929 import { ISSUE_RUN_CAP } from "../src/crew/guard.ts";
30 import { heldCounts, heldNow, heldWords, stuckOf } from "../src/crew/held.ts";
30 import { heldCounts, heldNow, heldWords, replannable, stuckOf } from "../src/crew/held.ts";
3131 import { PARK_NOTE } from "../src/crew/parks.ts";
3232 import { hunt, keyPart } from "../src/crew/sentinel.ts";
3333 import { HELD_TTL_MS, readHeld } from "../src/flow/held.ts";
@@ -324,6 +324,7 @@ describe("the tick says why each ready issue cannot start", () => {
324324 const held = heldNow(app, fresh());
325325 expect(held.by.done_on_main.map((i) => i.number)).toEqual([done.number]);
326326 expect(held.by.stalled).toHaveLength(0);
327 expect(replannable(held)).toHaveLength(0);
327328 expect(heldWords(held)).toBe("done_on_main=1");
328329 expect(stuckOf(held)).toBeUndefined();
329330
@@ -332,7 +333,7 @@ describe("the tick says why each ready issue cannot start", () => {
332333 ran(fresh(), done, mason, "declined: it is not there", 0);
333334 const again = heldNow(app, fresh());
334335 expect(again.by.done_on_main).toHaveLength(0);
335 expect(again.by.stalled.map((i) => i.number)).toEqual([done.number]);
336 expect(replannable(again).map((i) => i.number)).toEqual([done.number]);
336337 });
337338
338339 test("an issue the crew found done on main is held as done_on_main, not replannable", async () => {
@@ -362,16 +363,17 @@ describe("the tick says why each ready issue cannot start", () => {
362363 const named = (h: keyof typeof held.by) => held.by[h].map((i) => i.number);
363364 expect(named("done_on_main")).toContain(done.number);
364365 expect(named("stalled")).not.toContain(done.number);
366 expect(replannable(held).map((i) => i.number)).not.toContain(done.number);
365367 // A later park is a newer word: it is the planner's to re-plan again.
366368 expect(named("done_on_main")).not.toContain(reparked.number);
367 expect(named("stalled")).toContain(reparked.number);
369 expect(replannable(held).map((i) => i.number)).toContain(reparked.number);
368370 // A person's comment after the done note does not make it startable.
369371 expect(held.startable.map((r) => r.issue.number)).not.toContain(spoken.number);
370372 expect(named("done_on_main")).toContain(spoken.number);
371373 expect(heldWords(held)).toContain("done_on_main=");
372374 });
373375
374 test("nothing startable with a slot free is no reason to ask the planner; a pass asked for another reason is told the breakdown (#16231)", async () => {
376 test("nothing startable with a slot free asks the planner once, with the breakdown, whatever the plate", async () => {
375377 const { repo, atlas, mason } = await crewed(app, alice, "stuck");
376378 const fresh = () => getRepoById(app.db, repo.id)!;
377379 // The map ran dry: the planner's first pass, an hour ago.
@@ -389,10 +391,10 @@ describe("the tick says why each ready issue cannot start", () => {
389391 expect(held.startable).toHaveLength(0);
390392 expect(heldWords(held)).toBe("stalled=4 run_cap=1");
391393
392 expect(await driveRepo(app, fresh())).toBe("idle");
393 expect(getIssueById(app.db, direction.id)!.assigneeId).toBeNull();
394 expect(await driveRepo(app, fresh())).toBe("planned");
395 expect(getIssueById(app.db, direction.id)!.assigneeId).toBe(atlas.id);
394396
395 // A pass asked for another reason is given the breakdown in its brief.
397 // The pass the crew would start, given the breakdown in its brief.
396398 const told = stuckOf(heldNow(app, fresh()));
397399 expect(told?.held).toBe("stalled=4 run_cap=1");
398400 const brief = taskPrompt({
test/crew-reserve.test.ts +36 −38
@@ -1,8 +1,8 @@
11 /**
2 * The standing reserve (#3237) is what the tick line reports, `reserve=startable/target`. Since
3 * #16231 a short reserve is no reason to run a planner: a direction nobody has planned from, a
4 * person's word or edit on it, and a hand-over are. Only a pass that did not end well waits out
5 * the 20-minute floor.
2 * The standing reserve (#3237): the planner is asked whenever fewer issues
3 * can start than two per builder slot, not only when the map runs dry; its
4 * brief names the target; the tick line says `reserve=startable/target`;
5 * and only a pass that did not end well waits out the 20-minute floor.
66 */
77 import { seatAs } from "./helpers/seat.ts";
88 import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from "bun:test";
@@ -20,8 +20,8 @@ import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
2020 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2121 import { serve, type Servers } from "../src/http/server.ts";
2222 import { autonomyTick, driveRepo, settleAgentRun } from "../src/crew/autonomy.ts";
23 import { systemPrompt, taskPrompt } from "../src/crew/brief.ts";
24 import { reserveOf, reserveTarget, reserveWords } from "../src/crew/reserve.ts";
23 import { taskPrompt } from "../src/crew/brief.ts";
24 import { due, reserveOf, reserveTarget, reserveWords } from "../src/crew/reserve.ts";
2525 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
2626
2727 describe("the reserve's size", () => {
@@ -32,9 +32,20 @@ describe("the reserve's size", () => {
3232 expect(reserveTarget(0)).toBe(3);
3333 expect(reserveWords(reserveOf(5, 7))).toBe("5/14");
3434 });
35
36 test("the planner is due at half the target, not one below it", () => {
37 expect(due(reserveOf(7, 7))).toBe(true);
38 expect(due(reserveOf(8, 7))).toBe(false);
39 expect(due(reserveOf(13, 7))).toBe(false);
40 expect(due(reserveOf(2, 2))).toBe(true);
41 expect(due(reserveOf(3, 2))).toBe(false);
42 // A thin map of three is still asked at two: there is no half to run down.
43 expect(due(reserveOf(2, 1))).toBe(true);
44 expect(due(reserveOf(3, 1))).toBe(false);
45 });
3546 });
3647
37 describe("a planner asked for words, not for a short reserve (#16231)", () => {
48 describe("a planner that keeps a standing reserve", () => {
3849 let dataDir: string;
3950 let app: App;
4051 let servers: Servers;
@@ -149,27 +160,25 @@ describe("a planner asked for words, not for a short reserve (#16231)", () => {
149160 await rm(dataDir, { recursive: true, force: true });
150161 });
151162
152 test("a direction nobody has planned from is owed its first pass; a full plate holds it", async () => {
163 test("a full reserve with every slot busy is not a reason to plan", async () => {
153164 expect(await driveRepo(app, fresh())).toBe("full");
165 expect(fresh().directionIssueId).toBeNull();
166 });
167
168 test("7 slots, 5 startable: the planner is asked, with target 14", async () => {
154169 for (const issue of free.splice(0, 9)) close(issue);
155170 listen();
156171 expect(await driveRepo(app, fresh())).toBe("planned");
157172 const direction = getIssueById(app.db, fresh().directionIssueId!)!;
158173 expect(direction.assigneeId).toBe(atlas.id);
159 expect(lines.some((l) => l.includes("a person's direction; planner asked"))).toBe(true);
174 const asked = lines.find((l) => l.includes("reserve is short; planner asked"));
175 expect(asked).toContain("ready=5");
176 expect(asked).toContain("reserve=5/14");
160177 });
161178
162 test("7 slots, 5 startable after a pass: a short reserve is no reason to ask the planner", async () => {
163 planningRun("ok", "opened #30");
164 listen();
165 expect(await driveRepo(app, fresh(), minutesOn(1))).toBe("full");
166 expect(lines.some((l) => l.includes("planner asked"))).toBe(false);
167 expect(getIssueById(app.db, fresh().directionIssueId!)!.assigneeId).toBeNull();
168 });
169
170 test("the planner's brief asks for no reserve and no explanation on the direction", () => {
179 test("the planner's brief names the reserve and asks why when it is left short", () => {
171180 const direction = getIssueById(app.db, fresh().directionIssueId!)!;
172 const input = {
181 const brief = taskPrompt({
173182 agent: getAgentByName(app.db, "atlas")!,
174183 repo: fresh(),
175184 issue: direction,
@@ -177,17 +186,18 @@ describe("a planner asked for words, not for a short reserve (#16231)", () => {
177186 forgeUrl: "http://forge.test",
178187 isApp: false,
179188 resuming: false,
180 role: "planner" as const,
181 reason: "assigned" as const,
189 role: "planner",
190 reason: "assigned",
182191 comments: [],
183192 reviews: [],
184193 reviewComments: [],
185194 since: direction.createdAt,
186 };
187 const brief = taskPrompt(input) + systemPrompt(input);
188 expect(brief).not.toContain("standing reserve");
189 expect(brief).not.toContain("say why in a comment");
190 expect(brief).toContain("Write no explanation on the direction issue");
195 reserve: reserveOf(5, 7),
196 });
197 expect(brief).toContain("standing reserve of 14 startable issues");
198 expect(brief).toContain("5 can start now: plan at least 9 more");
199 expect(brief).toContain(`If you finish with fewer than 14 startable, say why in a comment on #${direction.number}`);
200 expect(brief).not.toContain("at least three ready issues");
191201 });
192202
193203 test("the tick line says reserve=startable/target", async () => {
@@ -223,16 +233,4 @@ describe("a planner asked for words, not for a short reserve (#16231)", () => {
223233 expect(lines.some((l) => l.includes("planned recently"))).toBe(true);
224234 expect(await driveRepo(app, fresh(), minutesOn(21))).toBe("planned");
225235 });
226
227 test("a person's comment on the direction asks for a pass: the one trigger left (#16231)", async () => {
228 const direction = planningRun("ok", "opened #30");
229 // The pass ended after every earlier word on the direction.
230 const ended = new Date(Date.now() + 5_000).toISOString();
231 app.db.query("UPDATE run SET started_at = ?2, finished_at = ?2, created_at = ?2 WHERE issue_id = ?1").run(direction.id, ended);
232 expect(await driveRepo(app, fresh(), minutesOn(1))).toBe("full");
233 expect(addComment(app, alice, fresh(), direction, "Plan the renderer next.").ok).toBe(true);
234 app.db.query("UPDATE comment SET created_at = ?2 WHERE issue_id = ?1 AND body = 'Plan the renderer next.'")
235 .run(direction.id, new Date(Date.parse(ended) + 1000).toISOString());
236 expect(await driveRepo(app, fresh(), minutesOn(1))).toBe("planned");
237 });
238236 });
test/pages-budget.test.ts +1 −1
@@ -56,7 +56,7 @@ quietLogs();
5656 const DEFAULT = { statements: 60, git: 8 };
5757 /** Pages that cost more today, with the most they may: lower these, never raise them. */
5858 const HEAVIER: Record<string, { statements?: number; git?: number }> = {
59 "/settings/crew": { statements: 69 }, // +1 over main's 68: the Planner card reads the last pass, the week and the outcomes in one statement (#16231); the crew's top (#16230): 11 over the 57 the page cost before it, each section one bounded read or a few (now: the visible repositories, their apps and open counts, the live runs; accounts: the credentials in one read, the week's ledger, the standings' three; failed-early: one); the week's card is read once for the panel and the member records
59 "/settings/crew": { statements: 68 }, // the crew's top (#16230): 11 over the 57 the page cost before it, each section one bounded read or a few (now: the visible repositories, their apps and open counts, the live runs; accounts: the credentials in one read, the week's ledger, the standings' three; failed-early: one); the week's card is read once for the panel and the member records
6060 "/:owner/:name/issues/:number": { statements: 71 }, // +1: whether the repository is archived, so its pages say noindex (#14305)
6161 "/next": { statements: 90 }, // a new page: measured 90 warm over the fixture's repositories, one ranking per administered repository, at most GROUPS_MAX = 5 (#15870)
6262 "/:owner/:name/next": { statements: 63 }, // -3 (#15913): the waiting offers and outsider reports ride the page's own writer check, the open-pull ceiling and count are one statement; -6 (#15940): the page's repository read once per request, the palette lists skip counts, the runs tab reuses the app read; +2: the waiting offers and the decision check beside the reports (#15887); +1: the size limits of held issues, one read of both (#15845); +2: the waiting outsider reports, the decider check and the list (#15840); +1: whether the repository is archived (#14305); +1: the wallet row, one read of the monthly cap (#13529); +1: the growth line, one read for the week, the open counts and the planner pause (#12290, #12867)
test/palette-roster.test.ts −2
@@ -224,7 +224,6 @@ test("a site-admin person is offered the whole roster", () => {
224224 ["codes", "Gift codes", "make a code that gives a plan for free, and revoke one"],
225225 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
226226 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
227 ["planner", "Planner", "its last pass, its spend this week and what became of what it filed"],
228227 ["cloud", "Cloud accounts", "provider tokens, what they are used for, today's calls"],
229228 ["pinned", "Pinned forges", "deploy, update and roll back a forge on your cloud"],
230229 ["experiments", "Experiments", "what each cloud machine costs and answers"],
@@ -339,7 +338,6 @@ test("a site-admin agent is offered the roster without the person-only entries",
339338 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
340339 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
341340 ["plan-row", "Plan", "this forge's plan, its last backup, and where its owner manages billing"],
342 ["planner", "Planner", "its last pass, its spend this week and what became of what it filed"],
343341 ["cloud", "Cloud accounts", "provider tokens, what they are used for, today's calls"],
344342 ["pinned", "Pinned forges", "deploy, update and roll back a forge on your cloud"],
345343 ["experiments", "Experiments", "what each cloud machine costs and answers"],
test/planner-card.test.ts deleted −121
@@ -1,121 +0,0 @@
1 /**
2 * The planner's card on the Crew page (#16231): its last pass in one line, its share of the week's
3 * spend, and what became of the issues it filed.
4 */
5 import { seatAs } from "./helpers/seat.ts";
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { getUserByName, createUser, type User } from "../src/core/users.ts";
15 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
16 import { plannerCard, plannerRows, oneLine, sharePercent } from "../src/crew/planner_card.ts";
17 import type { Ctx } from "../src/http/context.ts";
18 import { plannerLines } from "../src/tui/screens/planner.ts";
19 import type { Session } from "../src/tui/session.ts";
20 import { plannerCardView } from "../src/web/studio/planner_card.ts";
21
22 describe("the planner's numbers", () => {
23 test("one line, cut; a share of nothing is 0", () => {
24 expect(oneLine("\n Opened #5 and #6.\nThen a long explanation")).toBe("Opened #5 and #6.");
25 expect(oneLine("x".repeat(300)).length).toBe(160);
26 expect(sharePercent(1, 4)).toBe(25);
27 expect(sharePercent(1, 0)).toBe(0);
28 });
29
30 let dataDir: string;
31 let app: App;
32 let alice: User;
33 let atlas: User;
34 let mason: User;
35
36 beforeAll(async () => {
37 dataDir = await mkdtemp(join(tmpdir(), "forge-planner-card-"));
38 app = createApp({ dataDir, port: 0 });
39 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
40 if (!a.ok) throw new Error(a.error);
41 alice = a.value;
42 for (const name of ["atlas", "mason"]) {
43 const made = await createAgent(app, alice, { username: name });
44 if (!made.ok) throw new Error(String(made.error));
45 }
46 atlas = getUserByName(app.db, "atlas")!;
47 mason = getUserByName(app.db, "mason")!;
48 });
49
50 afterAll(async () => {
51 app.close();
52 await rm(dataDir, { recursive: true, force: true });
53 });
54
55 test("nothing before a pass; then the pass, its spend against the crew's, and the outcomes of what it filed", async () => {
56 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
57 if (!made.ok) throw new Error(String(made.error));
58 const repo = made.value;
59 expect(addToCrew(app, alice, repo, "atlas").ok).toBe(true);
60 expect(addToCrew(app, alice, repo, "mason").ok).toBe(true);
61 seatAs(app.db, repo.id, atlas.id, "planner");
62 expect(plannerCard(app.db).last).toBeNull();
63
64 const direction = openIssue(app, alice, repo, { title: "Direction" });
65 if (!direction.ok) throw new Error(String(direction.error));
66 app.db.query("UPDATE repo SET direction_issue_id = ?2 WHERE id = ?1").run(repo.id, direction.value.id);
67
68 const run = (issueId: string, actor: User, usd: number, summary: string) => {
69 const id = createRun(app.db, { repoId: repo.id, kind: "agent", issueId, actorId: actor.id, reason: "assigned" }).id;
70 claimRun(app.db, id);
71 return finishRun(app.db, id, { state: "ok", summary, costUsd: usd });
72 };
73 const filed = ["a", "b", "c", "d"].map((t) => {
74 const o = openIssue(app, atlas, repo, { title: `Filed ${t}` });
75 if (!o.ok) throw new Error(String(o.error));
76 return o.value;
77 });
78 run(direction.value.id, atlas, 1, "Opened #2 to #5.\nA long explanation follows.");
79 // The pass ran while the issues were opened.
80 app.db
81 .query("UPDATE run SET started_at = ?2, finished_at = ?3 WHERE issue_id = ?1")
82 .run(direction.value.id, new Date(Date.now() - 60_000).toISOString(), new Date(Date.now() + 60_000).toISOString());
83 run(filed[0]!.id, mason, 3, "opened pull");
84 const close = app.db.query("UPDATE issue SET state = 'closed', close_reason = ?2, closed_at = ?3 WHERE id = ?1");
85 const at = new Date().toISOString();
86 close.run(filed[0]!.id, "done", at);
87 close.run(filed[1]!.id, "dropped", at);
88 close.run(filed[2]!.id, "split", at);
89
90 const card = plannerCard(app.db);
91 expect(card.last?.said).toBe("Opened #2 to #5.");
92 expect(card.last?.opened).toBe(4);
93 expect(card.passes).toBe(1);
94 expect(sharePercent(card.spentUsd, card.crewUsd)).toBe(25);
95 expect(card.outcomes).toEqual({ filed: 4, landed: 1, dropped: 1, split: 1, open: 1 });
96 });
97
98 test("the page: absent when empty, one fact a row, a hostile summary escaped", async () => {
99 const empty = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-planner-empty-")), port: 0 });
100 try {
101 expect(plannerCardView({ app: empty } as unknown as Ctx)).toBeNull();
102 } finally {
103 empty.close();
104 }
105 app.db.query("UPDATE run SET summary = ?1 WHERE kind = 'agent' AND summary LIKE 'Opened #2%'").run(
106 `<script>alert(1)</script>\nsecond line`,
107 );
108 const out = String(plannerCardView({ app } as unknown as Ctx));
109 expect(out).not.toContain("<script>");
110 expect(out).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
111 for (const label of ["Last pass", "Opened", "Said", "Last 7 days", "Filed in 14 days"]) expect(out).toContain(`<dt>${label}</dt>`);
112 expect(out).not.toContain("Asked only when");
113 });
114
115 test("the terminal shows the same rows to an admin and nothing to anyone else", () => {
116 const rows = plannerRows(plannerCard(app.db)).map(([k, v]) => `${k}: ${v}`);
117 expect(plannerLines({ app, user: alice } as unknown as Session)).toEqual(rows);
118 expect(plannerLines({ app, user: atlas } as unknown as Session)).toEqual([]);
119 expect(plannerLines({ app } as unknown as Session)).toEqual([]);
120 });
121 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs