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

Let the decider: a card that needs a person can be handed to a decision model with curated context, per card or by a standing rule per app #1547

Closed opened this in answer to
Closed without merging

scout/forge:scout/1151-let-the-decider-a-card-that-needs-a-pers → main 8 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
21 files changed +1261 −9
README.md +11
@@ -381,6 +381,17 @@ crosses.
381381 `docs/FOLLOWING.md` is a fork that keeps up with its parent: where it
382382 stands, taking updates, and the crew's part when both sides moved.
383383
384 Cards that need a person can be handed to the decider: the "Let the decider"
385 tap on a card (`POST /asks/decide`), `POST /api/v1/asks/decide` with
386 `{"items":[…],"by":"decider"}` (an `rw` credential), the MCP tool of the same
387 name, or a standing rule per app, "Decisions here" in the app's autonomy
388 settings (`me`, `decider`, `decider_tell`). It only closes or sets aside,
389 through the bulk action, so a receipt and a day's undo come with it; an unsure
390 answer stays with the owner. The ledger row (`GET …/decisions`) carries the
391 card, direction, whether this app is pinned or muted, spend and evidence, never
392 the owner's other apps or recent calls. The terminal has no asks list or
393 autonomy settings yet, so it has no counterpart.
394
384395 `docs/FLEET.md` is one change across many repositories, runs or issues: a
385396 query, a dry-run plan of every row before → after, a receipt, and undo.
386397
docs/PLANNING.md +14
@@ -509,6 +509,20 @@ place, and `by` says which answered. Nothing a decider says is acted on
509509 outside the choices the forge wrote down, which is what makes its answers
510510 safe to act on without a person.
511511
512 **Let the decider (cards that need a person).** A hand-over, a stopped or
513 green pull, or a review can be handed to the decider with a third tap, "Let
514 the decider", or by a standing rule per repository (Settings, "Decisions
515 here": me / the decider / the decider, and tell me the unsure ones;
516 `core/decider_rule.ts`). One call per card (`crew/decide_card.ts`), none when
517 a rule answers (a muted app's card is set aside). Its context is curated —
518 the direction, pinned and muted apps, the day's spend against the ceiling,
519 the owner's last ten calls on the repository, and the card's own evidence —
520 and stored on the `card` ledger row beside its reason and confidence. It
521 answers `close`, `defer` or `ask`; below 0.75 it is unsure and the card stays
522 with the owner (under the plain rule, it is set aside). It never ships. What
523 it closes or sets aside is a bulk receipt, undone for a day like any other.
524 `decide` on MCP and `POST /api/v1/asks/decide` take `by: "decider"`.
525
512526 Where it decides today:
513527
514528 - **Routing** (`crew/route.ts`): who takes what was told, its size (tiny,
scripts/gate.ts +2
@@ -86,6 +86,8 @@ export const GATE: readonly string[] = [
8686 "test/session-settle.test.ts",
8787 "test/landing.test.ts",
8888 "test/decide.test.ts",
89 "test/decide-cards.test.ts",
90 "test/decide-doors.test.ts",
8991 "test/ledger.test.ts",
9092 "test/capacity.test.ts",
9193 "test/guard-new-accounts.test.ts",
src/actions/asks_bulk.ts +5 −1
@@ -9,6 +9,7 @@
99 */
1010
1111 import type { App } from "../app.ts";
12 import { markCardUndone } from "../core/decisions.ts";
1213 import { listOperations, type Operation } from "../core/fleet_ops.ts";
1314 import type { User } from "../core/users.ts";
1415 import { err, ok, type Result } from "../kernel/result.ts";
@@ -191,5 +192,8 @@ export async function undoAsksBulk(
191192 const op = ownAsksOperation(app, actor, operationId);
192193 if (op === undefined)
193194 return err({ code: "not_found", message: "no such operation here" });
194 return undoFleetOp(app, actor, op.id);
195 const undone = await undoFleetOp(app, actor, op.id);
196 // A card the decider answered is no longer answered (`core/decisions.ts`).
197 if (undone.ok) markCardUndone(app.db, op.id);
198 return undone;
195199 }
src/actions/decide_cards.ts added +261
@@ -0,0 +1,261 @@
1 /**
2 * Cards that need a person, handed to the decider: by a tap on one card
3 * ("Let the decider"), or by a repository's standing rule
4 * (`core/decider_rule.ts`). The answer is a close or a setting-aside done
5 * as a bulk action on the card (`actions/asks_bulk.ts`) — the same access
6 * check, the same receipt, the same undo for a day — and a row in the
7 * decision ledger carrying the context the decider saw, its reason and its
8 * confidence. An unsure answer leaves the card with the person.
9 */
10
11 import type { App } from "../app.ts";
12 import type { DeciderRule } from "../core/decider_rule.ts";
13 import { ruledRepos } from "../core/decider_rule.ts";
14 import { latestDecision, recordDecision } from "../core/decisions.ts";
15 import { getRepoById, listReposVisibleTo } from "../core/repos.ts";
16 import { getUserById, type User } from "../core/users.ts";
17 import {
18 cardContext,
19 ledgerContext,
20 decideCard,
21 type CardAnswer,
22 type CardChoice,
23 type CardContext,
24 } from "../crew/decide_card.ts";
25 import { err, ok, type Result } from "../kernel/result.ts";
26 import { pendingCards, type PendingCard } from "../web/studio/asks.ts";
27 import { applyAsksBulk, type Skipped } from "./asks_bulk.ts";
28 import type { FleetError } from "./fleet.ts";
29
30 /** The most cards one request hands over. */
31 export const DECIDE_MAX = 20;
32
33 export interface CardResult {
34 readonly item: string;
35 /** What came of the card: closed, set aside, or left with the person. */
36 readonly act: CardChoice;
37 readonly p: number;
38 readonly by: string;
39 readonly reason: string;
40 /** The bulk receipt to undo, when the decider acted. */
41 readonly operation?: string;
42 }
43
44 export interface Decided {
45 readonly results: CardResult[];
46 readonly skipped: Skipped[];
47 }
48
49 export async function decideCards(
50 app: App,
51 actor: User | undefined,
52 items: unknown,
53 standing: Exclude<DeciderRule, "me"> | undefined = undefined,
54 ): Promise<Result<Decided, FleetError>> {
55 if (!actor)
56 return err({ code: "unauthorized", message: "sign in to hand over cards" });
57 const list = Array.isArray(items)
58 ? items.filter((i): i is string => typeof i === "string")
59 : [];
60 if (list.length === 0 || list.length !== (items as unknown[]).length)
61 return err({ code: "bad_action", message: "items is a list of ask ids" });
62 if (list.length > DECIDE_MAX)
63 return err({
64 code: "too_many",
65 message: `at most ${DECIDE_MAX} cards at once`,
66 });
67 const db = app.db;
68 const cards = new Map(
69 pendingCards(db, actor, listReposVisibleTo(db, actor, { limit: 200 })).map(
70 (c) => [c.id, c],
71 ),
72 );
73 const results: CardResult[] = [];
74 const skipped: Skipped[] = [];
75 for (const item of new Set(list)) {
76 const card = cards.get(item);
77 if (card === undefined) {
78 skipped.push({ item, reason: "it no longer asks you, or a decider cannot answer it" });
79 continue;
80 }
81 results.push(await decideOne(app, actor, card, standing));
82 }
83 return ok({ results, skipped });
84 }
85
86 /** One card as the decider judged it, not yet acted on. */
87 interface Judged {
88 readonly card: PendingCard;
89 readonly context: CardContext;
90 readonly answer: CardAnswer;
91 readonly act: CardChoice;
92 readonly reason: string;
93 }
94
95 /** Ask the decider about one card: what it would do, and why. */
96 async function judge(
97 app: App,
98 actor: User,
99 card: PendingCard,
100 standing: Exclude<DeciderRule, "me"> | undefined,
101 ): Promise<Judged> {
102 const context = cardContext(app.db, {
103 kind: card.kind,
104 repo: card.repo,
105 pull: card.pull,
106 issue: card.issue,
107 viewerId: actor.id,
108 });
109 const answer = await decideCard(app.config.decider, context);
110 // What is done: a sure answer as given; an unsure one is the person's —
111 // except under the plain standing rule, which sets the card aside.
112 let act: CardChoice = answer.choice;
113 if (act !== "ask" && !answer.sure) act = standing === "decider" ? "defer" : "ask";
114 let reason = answer.reason;
115 if (answer.choice !== "ask" && !answer.sure && answer.by !== "rule")
116 reason += act === "ask" ? "; unsure, so it is yours" : "; unsure, so set aside";
117 return { card, context, answer, act, reason };
118 }
119
120 /** Write one judged card to the ledger, with the receipt that did it (if any). */
121 function record(
122 app: App,
123 j: Judged,
124 act: CardChoice,
125 reason: string,
126 operation: string | undefined,
127 standing: Exclude<DeciderRule, "me"> | undefined,
128 ): CardResult {
129 const { card, context, answer } = j;
130 const item = card.id;
131 // No decider answered and no rule: a miss, noted as such (by "none", left
132 // out of the tally) so a sweep waits for the card to change before asking.
133 const missed = answer.by === "rule" && answer.choice === "ask";
134 const subject = (card.pull ?? card.issue)!;
135 recordDecision(app.db, {
136 kind: "card",
137 repoId: card.repo.id,
138 issueId: subject.id,
139 state: {
140 item,
141 context: ledgerContext(context),
142 reason,
143 said: answer.choice,
144 standing: standing ?? null,
145 operation: operation ?? null,
146 since: card.since,
147 },
148 answer: act,
149 p: answer.p,
150 by: missed ? "none" : answer.by,
151 ms: answer.ms,
152 });
153 return {
154 item,
155 act,
156 p: answer.p,
157 by: answer.by,
158 reason,
159 ...(operation === undefined ? {} : { operation }),
160 };
161 }
162
163 /** The bulk verb an act is done as. */
164 const verbOf = (act: CardChoice): "close" | "dismiss" =>
165 act === "close" ? "close" : "dismiss";
166
167 /** One card answered and written to the ledger. */
168 async function decideOne(
outdated

Medium: autonomyBy may be another admin. The receipts then belong to them, and the owner can't undo anything (ownAsksOperation checks actorId). Act as the owner whose cards these are.

169 app: App,
170 actor: User,
171 card: PendingCard,
172 standing: Exclude<DeciderRule, "me"> | undefined,
173 ): Promise<CardResult> {
174 const j = await judge(app, actor, card, standing);
175 let { act, reason } = j;
outdated

High: every card here gets its own bulk receipt, but the page only keeps an undo for the latest one (latestUndoable). Collect the sweep's closes and set-asides into one applyAsksBulk call per owner, and record that operation id on each ledger row.

176 let operation: string | undefined;
177 if (act !== "ask") {
178 const done = await applyAsksBulk(app, actor, verbOf(act), [card.id]);
179 if (done.ok && done.value.rows.some((r) => r.outcome === "ok"))
180 operation = done.value.id;
181 else {
182 act = "ask";
183 reason += "; it could not be done, so it is yours";
184 }
185 }
186 return record(app, j, act, reason, operation, standing);
187 }
188
189 /** One owner's judged cards in a sweep, and the rule each came under. */
190 interface Owned {
191 readonly actor: User;
192 readonly judged: Judged[];
193 readonly rule: Map<string, Exclude<DeciderRule, "me">>;
194 }
195
196 /** Cards a sweep answers at most, so a long backlog costs a few calls a tick. */
197 const SWEEP_MAX = 10;
198
199 /**
200 * The standing rules at work: for each repository ruled to the decider,
201 * answer the cards that wait on its owner and were not answered since they
202 * last changed. A tick's work, never a request's.
203 */
204 export async function sweepStandingCards(app: App): Promise<number> {
205 let handled = 0;
206 // Judged cards, by the owner whose they are: each owner's closes and
207 // set-asides are done together, one receipt each, so one link undoes them.
208 const byOwner = new Map<string, Owned>();
209 const missed: { j: Judged; rule: Exclude<DeciderRule, "me"> }[] = [];
210 outer: for (const { repoId, rule } of ruledRepos(app.db)) {
211 const repo = getRepoById(app.db, repoId);
212 // The cards are the owner's, so the receipts are too.
213 const actor = repo ? getUserById(app.db, repo.ownerId) : undefined;
214 if (!repo || !actor || actor.kind !== "user") continue;
215 for (const card of pendingCards(app.db, actor, [repo])) {
216 if (handled >= SWEEP_MAX) break outer;
217 const last = latestDecision(app.db, (card.pull ?? card.issue)!.id, "card");
218 if (last !== undefined && last.createdAt >= card.since) continue;
219 const j = await judge(app, actor, card, rule);
220 if (j.answer.by !== "rule" || j.act !== "ask") handled++;
221 if (j.act === "ask") {
222 missed.push({ j, rule });
223 continue;
224 }
225 const own: Owned = byOwner.get(actor.id) ?? { actor, judged: [], rule: new Map() };
226 own.judged.push(j);
227 own.rule.set(card.id, rule);
228 byOwner.set(actor.id, own);
229 }
230 }
231 for (const { j, rule } of missed) record(app, j, "ask", j.reason, undefined, rule);
232 for (const { actor, judged, rule } of byOwner.values()) {
233 for (const verb of ["close", "dismiss"] as const) {
234 const group = judged.filter((j) => verbOf(j.act) === verb);
235 if (group.length === 0) continue;
236 const done = await applyAsksBulk(
237 app,
238 actor,
239 verb,
240 group.map((j) => j.card.id),
241 );
242 const okIds = new Set(
243 done.ok
244 ? done.value.rows.filter((r) => r.outcome === "ok").map((r) => r.targetId)
245 : [],
246 );
247 for (const j of group) {
248 const did = okIds.has((j.card.pull ?? j.card.issue)!.id);
249 record(
250 app,
251 j,
252 did ? j.act : "ask",
253 did ? j.reason : `${j.reason}; it could not be done, so it is yours`,
254 did && done.ok ? done.value.id : undefined,
255 rule.get(j.card.id),
256 );
257 }
258 }
259 }
260 return handled;
261 }
src/core/decider_rule.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * Who decides a card that needs a person, per repository: the owner (`me`,
3 * the default and no row), the decider, or the decider with the unsure ones
4 * left on the board for the owner. Pure data; the settings route owes the
5 * admin check.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 export type DeciderRule = "me" | "decider" | "decider_tell";
11
12 export const DECIDER_RULES: readonly DeciderRule[] = [
13 "me",
14 "decider",
15 "decider_tell",
16 ];
17
18 export const isDeciderRule = (value: unknown): value is DeciderRule =>
19 typeof value === "string" && (DECIDER_RULES as readonly string[]).includes(value);
20
21 export function getDeciderRule(db: Database, repoId: string): DeciderRule {
22 const row = db
23 .query<{ rule: string }, [string]>(
24 "SELECT rule FROM decider_rule WHERE repo_id = ?1",
25 )
26 .get(repoId);
27 return isDeciderRule(row?.rule) ? row.rule : "me";
28 }
29
30 export function setDeciderRule(
31 db: Database,
32 repoId: string,
33 rule: DeciderRule,
34 ): void {
35 if (rule === "me") {
36 db.query("DELETE FROM decider_rule WHERE repo_id = ?1").run(repoId);
37 return;
38 }
39 db.query(
40 `INSERT INTO decider_rule (repo_id, rule) VALUES (?1, ?2)
41 ON CONFLICT (repo_id) DO UPDATE SET rule = excluded.rule`,
42 ).run(repoId, rule);
43 }
44
45 /** Every repository that is not ruled by its owner, with its rule. */
46 export function ruledRepos(
47 db: Database,
48 ): { repoId: string; rule: Exclude<DeciderRule, "me"> }[] {
49 return db
50 .query<{ repo_id: string; rule: Exclude<DeciderRule, "me"> }, []>(
51 "SELECT repo_id, rule FROM decider_rule",
52 )
53 .all()
54 .map((r) => ({ repoId: r.repo_id, rule: r.rule }));
55 }
src/core/decisions.ts +77 −1
@@ -16,7 +16,13 @@ import { id as newId } from "../kernel/id.ts";
1616 * `lean` was which option on a studio ask card a careful owner would pick.
1717 * Nothing records one any more; older ledgers still hold rows of it, and the
1818 * summaries that read them keep the word. */
19 export type DecisionKind = "next" | "land" | "retry" | "lean" | "guard";
19 export type DecisionKind =
20 | "next"
21 | "land"
22 | "retry"
23 | "lean"
24 | "guard"
25 | "card";
2026
2127 export interface Decision {
2228 readonly id: string;
@@ -291,3 +297,73 @@ export function listDecidedIn(
291297 .all(limit, ...repoIds)
292298 .map(toDecision);
293299 }
300
301 /**
302 * A card the decider answered, taken back: the bulk receipt that did it
303 * was undone, so the ledger row says so and the tally stops counting it.
304 */
305 export function markCardUndone(db: Database, operationId: string): void {
306 db.query(
307 `UPDATE decision
308 SET outcome = 'undone', outcome_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
309 WHERE kind = 'card' AND outcome IS NULL
310 AND json_extract(state, '$.operation') = ?1`,
311 ).run(operationId);
312 }
313
314 export interface CardTally {
315 readonly closed: number;
316 readonly deferred: number;
317 readonly asked: number;
318 }
319
320 /** What the decider did with cards since a moment, undone ones left out. */
321 export function cardTally(
322 db: Database,
323 repoIds: readonly string[],
324 since: string,
325 ): CardTally {
326 const unique = [...new Set(repoIds)].slice(0, 400);
327 const n = { close: 0, defer: 0, ask: 0 } as Record<string, number>;
328 if (unique.length > 0)
329 for (const r of db
330 .query<{ answer: string; n: number }, (string | number)[]>(
331 `SELECT answer, COUNT(*) AS n FROM decision
332 WHERE kind = 'card' AND by != 'none' AND created_at >= ?1
333 AND (outcome IS NULL OR outcome != 'undone')
334 AND repo_id IN (${unique.map((_, i) => `?${i + 2}`).join(",")})
335 GROUP BY answer`,
336 )
337 .all(since, ...unique))
338 n[r.answer] = r.n;
339 return { closed: n["close"]!, deferred: n["defer"]!, asked: n["ask"]! };
340 }
341
342 /**
343 * The newest receipt, by what it did ("close" or "defer"), of the decider's
344 * cards since a moment — what the board's tally links to. Undone ones left out.
345 */
346 export function cardReceipts(
347 db: Database,
348 repoIds: readonly string[],
349 since: string,
350 ): { close?: string; defer?: string } {
351 const unique = [...new Set(repoIds)].slice(0, 400);
352 const found: { close?: string; defer?: string } = {};
353 if (unique.length === 0) return found;
354 const rows = db
355 .query<{ answer: string; op: string }, (string | number)[]>(
356 `SELECT answer, json_extract(state, '$.operation') AS op FROM decision
357 WHERE kind = 'card' AND answer IN ('close','defer') AND created_at >= ?1
358 AND (outcome IS NULL OR outcome != 'undone')
359 AND json_extract(state, '$.operation') IS NOT NULL
360 AND repo_id IN (${unique.map((_, i) => `?${i + 2}`).join(",")})
361 ORDER BY created_at DESC, id DESC`,
362 )
363 .all(since, ...unique);
364 for (const r of rows) {
365 const k = r.answer === "close" ? "close" : "defer";
366 found[k] ??= r.op;
367 }
368 return found;
369 }
src/core/schema.ts +9
@@ -1595,6 +1595,15 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — who decides a card that needs a person, per repository (#1151):
1599 // `me` (no row), `decider`, or `decider_tell`. A repository with no row
1600 // is ruled by its owner.
1601 `
1602 CREATE TABLE decider_rule (
1603 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE,
1604 rule TEXT NOT NULL CHECK (rule IN ('decider','decider_tell'))
1605 );
1606 `,
15981607 ];
15991608
16001609 /**
src/crew/decide_card.ts added +188
@@ -0,0 +1,188 @@
1 /**
2 * The decider, one level up: a card that needs a person — a hand-over, a
3 * green pull, a stopped one, a review — answered by a small-model call
4 * instead, from a context curated for the purpose and nothing more (the
5 * direction, whether the owner pinned or muted this app, the day's spend, the owner's
6 * last ten calls here, and the card's own evidence). The context is the
7 * ledger row's `state`, so a person can read why it answered as it did.
8 *
9 * It only ever answers with an act the owner can undo for a day: `close`
10 * (a hand-over or stopped pull), `defer` (set the card aside; the work
11 * stays), or `ask` (it needs a person after all). Shipping is never an
12 * answer: a merge is not undone.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { listInteractions, mutedRepos } from "../core/interactions.ts";
17 import { listComments, type Issue } from "../core/issues.ts";
18 import { pinnedRepoIds } from "../core/pins.ts";
19 import type { Pull } from "../core/pulls.ts";
20 import type { Repo } from "../core/repos.ts";
21 import { listReviews } from "../core/reviews.ts";
22 import { latestRunsForIssues } from "../core/runs.ts";
23 import { spentTodayForRepos } from "./autonomy.ts";
24 import { decideOr, certain, type Decider } from "./decide.ts";
25
26 export type CardKind = "look" | "review" | "stopped" | "parked";
27
28 export const isCardKind = (kind: string): kind is CardKind =>
29 kind === "look" || kind === "review" || kind === "stopped" || kind === "parked";
30
31 export type CardChoice = "close" | "defer" | "ask";
32
33 /** Below this probability an answer is unsure, and the card is not acted on by it. */
34 export const SURE = 0.75;
35
36 export interface CardInput {
37 readonly kind: CardKind;
38 readonly repo: Repo;
39 readonly pull?: Pull | undefined;
40 readonly issue?: Issue | undefined;
41 readonly viewerId: string;
42 }
43
44 /** What the decider is shown, as it is stored on the ledger row. */
45 export interface CardContext {
46 readonly card: { kind: CardKind; title: string; app: string };
47 readonly direction: string;
48 readonly apps: { pinned: boolean; muted: boolean };
49 readonly spend: { todayUsd: number; ceilingUsd: number };
50 readonly ownerLastTen: { did: string; at: string }[];
51 readonly evidence: { park?: string[]; check?: string; review?: string };
52 }
53
54 const clip = (text: string, n: number): string => text.slice(0, n);
55
56 /**
57 * What the ledger keeps of the context: the decisions API serves a row to
58 * every reader of the repository, so the owner's own recent calls and pins and mutes stay out.
59 */
60 export const ledgerContext = (
61 context: CardContext,
62 ): Omit<CardContext, "ownerLastTen" | "apps"> => {
63 const { ownerLastTen: _last, apps: _apps, ...rest } = context;
outdated

Low: apps.pinned and apps.muted are the owner's private preferences, and the decisions API serves them to every reader of a public repository. Strip apps here as well.

64 return rest;
65 };
66
67 /** The curated context for one card: this and nothing else. */
68 export function cardContext(db: Database, input: CardInput): CardContext {
69 const { repo, viewerId } = input;
70 const subject = input.pull ?? input.issue;
71 const spent = spentTodayForRepos(db, [repo.id]).get(repo.id) ?? 0;
72 const evidence: CardContext["evidence"] = {};
73 if (input.kind === "parked" && input.issue !== undefined) {
74 evidence.park = listComments(db, input.issue.id)
75 .slice(-3)
76 .map((c) => clip(c.body, 300));
77 }
78 if (input.pull !== undefined) {
79 const check = latestRunsForIssues(db, [input.pull.id]).get(input.pull.id);
80 if (check !== undefined)
81 evidence.check = clip(`${check.state}: ${check.summary}`, 400);
82 const review = listReviews(db, input.pull.id).at(-1);
83 if (review !== undefined)
84 evidence.review = clip(`${review.state}: ${review.body}`, 400);
85 }
86 return {
87 card: {
88 kind: input.kind,
89 title: clip(subject?.title ?? "", 200),
90 app: `${repo.ownerName}/${repo.name}`,
91 },
92 direction: clip(repo.autonomyDirection, 600),
93 apps: {
94 pinned: pinnedRepoIds(db, viewerId).has(repo.id),
95 muted: mutedRepos(db, viewerId).has(repo.id),
96 },
97 spend: { todayUsd: spent, ceilingUsd: repo.autonomyCeilingUsd },
98 ownerLastTen: listInteractions(db, viewerId, 200)
99 .filter(
100 (i) =>
101 i.repoId === repo.id &&
102 (i.kind === "shipped" || i.kind === "dismissed" || i.kind === "told"),
103 )
104 .slice(0, 10)
105 .map((i) => ({ did: i.kind, at: i.createdAt })),
106 evidence,
107 };
108 }
109
110 const OPTIONS: Readonly<Record<CardKind, readonly CardChoice[]>> = {
111 parked: ["close", "defer", "ask"],
112 stopped: ["close", "defer", "ask"],
113 look: ["defer", "ask"],
114 review: ["defer", "ask"],
115 };
116
117 const DESCRIBE: Readonly<Record<CardChoice, string>> = {
118 close: "it no longer matters: close it, losing nothing worth keeping",
119 defer: "it can wait: set the card aside, and the work stays as it is",
120 ask: "it needs the owner's judgment, or the evidence is not enough to say",
121 };
122
123 export interface CardAnswer {
124 readonly choice: CardChoice;
125 readonly p: number;
126 readonly by: string;
127 readonly ms: number;
128 readonly reason: string;
129 /** Whether the decider is sure enough to act on its choice. */
130 readonly sure: boolean;
131 }
132
133 /**
134 * The answer a rule gives with no call, if one does: a muted app's cards
135 * do not matter (the owner said so), so they are set aside.
136 */
137 export function ruleAnswer(context: CardContext): CardAnswer | undefined {
138 if (context.apps.muted)
139 return {
140 choice: "defer",
141 p: 1,
142 by: "rule",
143 ms: 0,
144 reason: "the app is muted",
145 sure: true,
146 };
147 return undefined;
148 }
149
150 /**
151 * One small-model call for one card, or none: a rule that answers, or no
152 * decider at all, is `ask` — the owner decides, as before.
153 */
154 export async function decideCard(
155 decider: Decider | undefined,
156 context: CardContext,
157 ): Promise<CardAnswer> {
158 const rule = ruleAnswer(context);
159 if (rule !== undefined) return rule;
160 const options = OPTIONS[context.card.kind];
161 const decided = await decideOr(
162 decider,
163 context as unknown as Record<string, unknown>,
164 {
165 card: {
166 options,
167 about:
168 "A card needs its owner. Choose close, defer or ask. Use the owner's direction, what they pinned and muted, the day's spend against its ceiling, their last decisions here, and the card's evidence. Prefer ask when unsure.",
169 describe: Object.fromEntries(options.map((o) => [o, DESCRIBE[o]])),
170 },
171 },
172 () => ({ card: certain(options, "ask") }),
173 );
174 const answer = decided.answers.card;
175 const choice = answer.choice as CardChoice;
176 const sure = decided.by !== "rule" && answer.p >= SURE;
177 return {
178 choice,
179 p: answer.p,
180 by: decided.by,
181 ms: decided.ms,
182 sure,
183 reason:
184 decided.by === "rule"
185 ? "no decider answered"
186 : `${decided.by} chose ${choice} at ${answer.p.toFixed(2)}`,
187 };
188 }
src/http/feed.ts +15
@@ -25,6 +25,7 @@ import {
2525 undoAsksBulk,
2626 previewAsksBulk,
2727 } from "../actions/asks_bulk.ts";
28 import { decideCards } from "../actions/decide_cards.ts";
2829 import type { FleetError } from "../actions/fleet.ts";
2930 import type { Handler } from "./context.ts";
3031 import type { Router } from "./router.ts";
@@ -91,6 +92,20 @@ export function feedRoutes(router: Router<Handler>): void {
9192 return json({ preview: false, ...op.value }, 201);
9293 });
9394
95 // Hand cards to the decider (`actions/decide_cards.ts`): it answers each
96 // now, in the ledger, and what it closed or set aside is undone like a
97 // bulk action (below).
98 router.add("POST", "/api/v1/asks/decide", async (ctx) => {
99 const denied = requireScope(ctx, "rw");
100 if (denied) return denied;
101 const input = await body(ctx.request);
102 if (input.by !== undefined && input.by !== "decider")
103 return apiError("invalid_by", 422, 'by is "decider"');
104 const done = await decideCards(ctx.app, ctx.auth.user, input.items);
105 if (!done.ok) return bulkError(done.error);
106 return json(done.value, 201);
107 });
108
94109 // Undo a bulk action on asks — only an asks operation: anything else a
95110 // fleet operation did takes an admin credential at /api/v1/fleet/ops.
96111 router.add("POST", "/api/v1/asks/bulk/:id/undo", async (ctx) => {
src/http/mcp.ts +20
@@ -103,6 +103,7 @@ import {
103103 milestonesJson,
104104 } from "../web/pages/milestones.ts";
105105 import { appsOf, asksAnswer } from "../web/studio/asks.ts";
106 import { decideCards } from "../actions/decide_cards.ts";
106107 import { applyAsksBulk, previewAsksBulk } from "../actions/asks_bulk.ts";
107108 import type { Ctx, Handler } from "./context.ts";
108109 import {
@@ -524,6 +525,25 @@ const TOOLS: readonly Tool[] = [
524525 return answer.ok ? good(answer.value) : bad(answer.error.code, answer.error.message);
525526 },
526527 },
528 {
529 name: "decide",
530 description:
531 'Hand cards that need you to the decider (`by: "decider"`). `items` are ask ids from `asks` (a row\'s `items`): a hand-over, a stopped pull, a green pull, a review. For each it makes one small-model call (none when a rule already answers) and answers now: close it, set it aside, or leave it with you when it is unsure. Every answer is a row in the decision ledger with its reason, confidence and the context it saw; what it closed or set aside can be undone for a day (POST /api/v1/asks/bulk/<id>/undo with the returned operation). It never ships.',
532 inputSchema: {
533 type: "object",
534 properties: {
535 by: { type: "string", enum: ["decider"] },
536 items: { type: "array", items: { type: "string" }, maxItems: 20 },
537 },
538 required: ["by", "items"],
539 },
540 writes: true,
541 async run(ctx, user, args) {
542 if (args["by"] !== "decider") return bad("invalid", 'by is "decider"');
543 const done = await decideCards(ctx.app, user, args["items"]);
544 return done.ok ? good(done.value) : bad(done.error.code, done.error.message);
545 },
546 },
527547 {
528548 name: "seal",
529549 description:
src/http/server.ts +2
@@ -188,6 +188,7 @@ import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
188188 import { askedPage } from "../web/studio/asked_page.ts";
189189 import {
190190 asksBulkSubmit,
191 asksDecideSubmit,
191192 asksBulkUndo,
192193 asksListen,
193194 asksPage,
@@ -573,6 +574,7 @@ export function buildRouter(): Router<Handler> {
573574 // One screen for "is everything fine?": what asks the viewer (docs/STUDIO.md).
574575 router.add("GET", "/asks", asksPage);
575576 router.add("POST", "/asks/bulk", asksBulkSubmit);
577 router.add("POST", "/asks/decide", asksDecideSubmit);
576578 router.add("POST", "/asks/bulk/:id/undo", asksBulkUndo);
577579 router.add("POST", "/asks/listen", asksListen);
578580 // What people asked of the crew, and what became of it (core/asked.ts).
src/main.ts +6
@@ -34,6 +34,7 @@ import { graphInstagram } from "./crew/instagram.ts";
3434 import { peopleOnCrews } from "./core/agents.ts";
3535 import { startNotifier } from "./crew/notify.ts";
3636 import { sweepStaleAsks } from "./crew/stale_asks.ts";
37 import { sweepStandingCards } from "./actions/decide_cards.ts";
3738 import { recordAskLedger } from "./web/studio/asks.ts";
3839 import { startPromptRoutine } from "./crew/prompts.ts";
3940 import { pruneTokens } from "./core/tokens.ts";
@@ -324,6 +325,11 @@ runSync(app); // one pass on boot: a forge that was down has fetching to do
324325 // expired: what asked each person, and how it ended.
325326 const tickAsks = async (): Promise<void> => {
326327 await sweepStaleAsks(app);
328 try {
329 await sweepStandingCards(app);
330 } catch (error) {
331 app.log.error("standing decider rules failed", { error: String(error) });
332 }
327333 try {
328334 recordAskLedger(app.db);
329335 } catch (error) {
src/web/pages/board.ts +36
@@ -20,7 +20,10 @@ import { reviewersOf, waitsForPerson } from "../../crew/review.ts";
2020 import { tokenReturns } from "../../core/returns.ts";
2121 import { returnsRepos } from "../../actions/returns.ts";
2222 import {
23 cardReceipts,
24 cardTally,
2325 listDecisionsForRepos,
26 type CardTally,
2427 type Decision,
2528 type DecisionKind,
2629 } from "../../core/decisions.ts";
@@ -117,8 +120,33 @@ const KIND_WORDS: Record<DecisionKind, string> = {
117120 lean: "which way",
118121 // Never listed (`listDecisionsForRepos` leaves guards out); named for the type.
119122 guard: "not started",
123 card: "a card for you",
120124 };
121125
126 /** "the decider closed 4, deferred 2, asked you about 1" — what it did, never a zero. */
127 export function deciderWords(t: CardTally): string {
128 const parts = [
129 t.closed > 0 ? `closed ${t.closed}` : "",
130 t.deferred > 0 ? `deferred ${t.deferred}` : "",
131 t.asked > 0 ? `asked you about ${t.asked}` : "",
132 ].filter((p) => p !== "");
133 return `the decider ${parts.join(", ")}`;
134 }
135
136 /** The same sentence, the closed and deferred words linked to their receipt and its Undo. */
137 function deciderLine(t: CardTally, op: { close?: string; defer?: string }) {
138 const link = (id: string | undefined, text: string) =>
139 id === undefined
140 ? text
141 : html`<a href="/?op=${encodeURIComponent(id)}#asks-bulk-result">${text}</a>`;
142 const parts = [
143 t.closed > 0 ? link(op.close, `closed ${t.closed}`) : "",
144 t.deferred > 0 ? link(op.defer, `deferred ${t.deferred}`) : "",
145 t.asked > 0 ? `asked you about ${t.asked}` : "",
146 ].filter((p) => p !== "");
147 return html`the decider ${parts.flatMap((p, i) => (i === 0 ? [p] : [", ", p]))}`;
148 }
149
122150 const money = (n: number): string => `$${n.toFixed(2)}`;
123151
124152 /** A wait, in the unit a person reads it in. */
@@ -971,6 +999,14 @@ function today(ctx: Ctx, scope: BoardScope): Html {
971999 </a>
9721000 </li>`;
9731001 });
1002 // What the decider did with the cards that needed the owner, today.
1003 const tally = cardTally(db, [...scope.ownerFacts], since);
1004 if (tally.closed + tally.deferred + tally.asked > 0)
1005 rows.unshift(
1006 html`<li class="muted small board-decider">
1007 ${deciderLine(tally, cardReceipts(db, [...scope.ownerFacts], since))}
1008 </li>`,
1009 );
9741010 return region(
9751011 "today",
9761012 "4",
src/web/pages/settings.ts +5
@@ -8,6 +8,7 @@
88 * same-origin POST and every one of them says what happened.
99 */
1010
11 import { isDeciderRule, setDeciderRule } from "../../core/decider_rule.ts";
1112 import {
1213 deleteAppEnvVar,
1314 disableApp,
@@ -1748,6 +1749,7 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
17481749 const slots = Number(field(form, "slots"));
17491750 if (
17501751 !isAutonomy(mode) ||
1752 (field(form, "decides") !== "" && !isDeciderRule(field(form, "decides"))) ||
17511753 !Number.isFinite(ceiling) ||
17521754 ceiling < 0 ||
17531755 !Number.isInteger(slots) ||
@@ -1766,6 +1768,9 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
17661768 autonomySlots: slots,
17671769 autonomyBy: mode === "off" ? null : (ctx.auth.user?.id ?? null),
17681770 });
1771 // The select is optional: a form posted without it leaves the rule alone.
1772 const decides = field(form, "decides");
1773 if (updated.ok && isDeciderRule(decides)) setDeciderRule(ctx.app.db, repo.id, decides);
17691774 return flashTo(ctx, `${base}/settings#autonomy`, {
17701775 ...(updated.ok
17711776 ? {
src/web/studio/asks.ts +53 −7
@@ -46,6 +46,7 @@ import {
4646 spentTodayForRepos,
4747 } from "../../crew/autonomy.ts";
4848 import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts";
49 import { isCardKind, type CardKind } from "../../crew/decide_card.ts";
4950 import { CHECK_FAILED_LIMIT } from "../../crew/dispatch.ts";
5051 import { isStalePull, mergesAgainSince } from "../../crew/stale_asks.ts";
5152 import { waitsForPerson, type ReviewWait } from "../../crew/review.ts";
@@ -552,6 +553,32 @@ function waitingOn(
552553 return notDismissed(db, user, scoredFor(db, user, repos));
553554 }
554555
556 /** A card the decider may answer: what it is about, no wording or picture. */
557 export interface PendingCard {
558 readonly id: string;
559 readonly kind: CardKind;
560 readonly repo: Repo;
561 readonly pull?: Pull | undefined;
562 readonly issue?: Issue | undefined;
563 readonly since: string;
564 }
565
566 /**
567 * The cards waiting on this person that a decider may answer (a hand-over,
568 * a green or stopped pull, a review) — not a ceiling or a planner's decline.
569 */
570 export function pendingCards(
571 db: Database,
572 user: User,
573 repos: readonly Repo[],
574 ): PendingCard[] {
575 return waitingOn(db, user, repos).flatMap((c) =>
576 isCardKind(c.kind)
577 ? [{ id: c.id, kind: c.kind, repo: c.repo, pull: c.pull, issue: c.issue, since: c.since }]
578 : [],
579 );
580 }
581
555582 /** How an ask that is no longer asked ended, when nobody dismissed it. */
556583 function endOf(
557584 db: Database,
@@ -850,6 +877,7 @@ export function decisionsFor(
850877 }
851878 /** The id of the form a row's own button submits (see `decisionForm`). */
852879 const askFormId = (d: Decision): string => `ask-${d.id}`;
880 const deciderFormId = (d: Decision): string => `decide-${d.id}`;
853881
854882 /**
855883 * The form behind a row's landing button — its own post, exactly as it was.
@@ -858,20 +886,36 @@ const askFormId = (d: Decision): string => `ask-${d.id}`;
858886 */
859887 export function decisionForm(d: Decision): Html | null {
860888 const pull = d.pull;
861 if (pull === undefined) return null;
862889 const base = repoBase(d.repo);
863890 const own = html`id="${askFormId(d)}" method="post" hidden`;
891 const decider = isCardKind(d.kind)
892 ? html`<form id="${deciderFormId(d)}" method="post" action="/asks/decide" hidden>
893 <input type="hidden" name="item" value="${d.id}" />
894 </form>`
895 : null;
896 if (pull === undefined) return decider;
864897 if (d.kind === "stopped")
865898 return html`<form ${own} action="${base}/pulls/${pull.number}/state">
866 <input type="hidden" name="state" value="closed" />
867 </form>`;
899 <input type="hidden" name="state" value="closed" />
900 </form>${decider}`;
868901 if (d.kind === "look" || d.kind === "review")
869902 return html`<form ${own} action="${base}/pulls/${pull.number}/ship">
870 <input type="hidden" name="pull" value="${pull.number}" />
871 </form>`;
872 return null;
903 <input type="hidden" name="pull" value="${pull.number}" />
904 </form>${decider}`;
905 return decider;
873906 }
874907
908 /** The third tap: the card handed to the decider (`actions/decide_cards.ts`). */
909 const deciderTap = (d: Decision): Html | null =>
910 isCardKind(d.kind)
911 ? btn("Let the decider", { size: "sm", form: deciderFormId(d) })
912 : null;
913
914 const tap = (d: Decision): Html[] => {
915 const t = deciderTap(d);
916 return t === null ? [] : [t];
917 };
918
875919 /**
876920 * The actions on one ask, on one line: a button for what lands (submitting
877921 * the row's own form, `decisionForm`), links for what needs a look or a
@@ -903,6 +947,7 @@ export function decisionButtons(ctx: Ctx, d: Decision): { primary: Html; others:
903947 others: [
904948 btn("Close", { size: "sm", form: askFormId(d) }),
905949 btn("See", { href: changeHref(base, pull.number), size: "sm" }),
950 ...tap(d),
906951 ],
907952 };
908953 if ((d.kind === "look" || d.kind === "review") && pull)
@@ -914,6 +959,7 @@ export function decisionButtons(ctx: Ctx, d: Decision): { primary: Html; others:
914959 href: `${changeHref(base, pull.number)}#comment-body`,
915960 size: "sm",
916961 }),
962 ...tap(d),
917963 ],
918964 };
919965 if (d.kind === "declined" && d.issue)
@@ -932,7 +978,7 @@ export function decisionButtons(ctx: Ctx, d: Decision): { primary: Html; others:
932978 size: "sm",
933979 variant: "primary",
934980 }),
935 others: [],
981 others: [...tap(d)],
936982 };
937983 return {
938984 primary: btn("Settings", { href: `${base}/settings/autonomy`, size: "sm" }),
src/web/studio/asks_page.ts +27
@@ -15,6 +15,7 @@ import {
1515 previewAsksBulk,
1616 type Skipped,
1717 } from "../../actions/asks_bulk.ts";
18 import { decideCards } from "../../actions/decide_cards.ts";
1819 import type { FleetValue } from "../../core/fleet_ops.ts";
1920 import { removeMutes } from "../../core/interactions.ts";
2021 import type { Ctx } from "../../http/context.ts";
@@ -599,6 +600,32 @@ export async function asksBulkUndo(ctx: Ctx): Promise<Response> {
599600 return redirect(`/?op=${op.value.id}#asks-bulk-result`);
600601 }
601602
603 /**
604 * POST /asks/decide — hand one card to the decider. If it acts, its receipt
605 * lands here with an Undo; if it is unsure, the card stays and says so.
606 */
607 export async function asksDecideSubmit(ctx: Ctx): Promise<Response> {
608 if (!ctx.auth.user) return signInFirst(ctx);
609 const form = await readForm(ctx, "rw");
610 if (form instanceof Response) return form;
611 const items = form.getAll("item").filter((i): i is string => typeof i === "string");
612 const done = await decideCards(ctx.app, ctx.auth.user, items);
613 if (!done.ok) return await asksScreen(ctx, nothingDone(done.error.message));
614 const first = done.value.results[0];
615 if (first?.operation !== undefined)
616 return redirect(`/?op=${first.operation}#asks-bulk-result`);
617 return await asksScreen(ctx, {
618 banner: card(
619 html`<p>
620 ${first === undefined
621 ? "That card no longer asks you."
622 : html`The decider left it with you: ${first.reason}.`}
623 </p>`,
624 { id: "asks-bulk-result" },
625 ),
626 });
627 }
628
602629 /** POST /asks/listen — take back the viewer's own mute of the repositories named. */
603630 export async function asksListen(ctx: Ctx): Promise<Response> {
604631 if (!ctx.auth.user) return signInFirst(ctx);
src/web/studio/crew.ts +20
@@ -25,6 +25,7 @@
2525 * prompts, labels, webhooks, deletion — sits beneath them, an admin's.
2626 */
2727
28 import { getDeciderRule } from "../../core/decider_rule.ts";
2829 import { listAllAgents, listCrew } from "../../actions/crew.ts";
2930 import { CREW_ROLES, listCrewRoles, type CrewRole } from "../../core/agents.ts";
3031 import { getAppByRepo } from "../../core/apps.ts";
@@ -282,6 +283,7 @@ function autonomyCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html
282283 </dd>`
283284 : null}
284285 </dl>`;
286 const deciderRule = getDeciderRule(ctx.app.db, repo.id);
285287 const form = !admin
286288 ? null
287289 : html`<form method="post" action="${base}/settings/autonomy">
@@ -340,6 +342,24 @@ ${repo.autonomyDirection}</textarea
340342 type: "number",
341343 hint: "Agent runs at once here. This is the WIP limit.",
342344 })}
345 ${selectField({
346 label: "Decisions here",
347 name: "decides",
348 hint: "Who answers a card that needs a person (a hand-over, a green or stopped pull, a review). The decider closes or sets aside what it is sure of, in the ledger, undoable for a day; it never ships.",
349 options: [
350 { value: "me", label: "Me", selected: deciderRule === "me" },
351 {
352 value: "decider",
353 label: "The decider",
354 selected: deciderRule === "decider",
355 },
356 {
357 value: "decider_tell",
358 label: "The decider, and tell me the ones it was unsure of",
359 selected: deciderRule === "decider_tell",
360 },
361 ],
362 })}
343363 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
344364 </form>`;
345365 // An autonomous repository with no reviewer lands nothing an agent wrote
test/decide-cards.test.ts added +222
@@ -0,0 +1,222 @@
1 /**
2 * Let the decider (#1151): a card that needs a person, answered by a
3 * small-model call from a curated context — by a tap, or by a repository's
4 * standing rule — closed or set aside as a bulk action that can be undone,
5 * with the context it saw on the ledger row. An unsure answer is the
6 * owner's.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { sweepStandingCards, decideCards } from "../src/actions/decide_cards.ts";
15 import { undoAsksBulk } from "../src/actions/asks_bulk.ts";
16 import { addComment, openIssue } from "../src/actions/issues.ts";
17 import { createRepo } from "../src/actions/repos.ts";
18 import { setDeciderRule } from "../src/core/decider_rule.ts";
19 import { cardReceipts, cardTally, listDecisions } from "../src/core/decisions.ts";
20 import { recordInteraction } from "../src/core/interactions.ts";
21 import type { Repo } from "../src/core/repos.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { BREAKER_NOTE } from "../src/crew/breaker.ts";
24 import type { Decider } from "../src/crew/decide.ts";
25 import { deciderWords } from "../src/web/pages/board.ts";
26 import { askLinesFor } from "../src/web/studio/asks.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 describe("letting the decider answer cards", () => {
32 let dataDir = "";
33 let app: App;
34 let alice: User;
35 let said: { choice: string; p: number } = { choice: "close", p: 0.95 };
36 let calls = 0;
37 let shown: unknown;
38
39 const decider: Decider = {
40 name: "fake",
41 async decide(state, questions) {
42 calls++;
43 shown = state;
44 const options = questions["card"]!.options;
45 const probabilities = Object.fromEntries(
46 options.map((o) => [o, o === said.choice ? said.p : 0]),
47 );
48 return { card: { choice: said.choice, p: said.p, probabilities } } as never;
49 },
50 };
51
52 const items = (): string[] => askLinesFor(app.db, alice).flatMap((r) => r.items);
53
54 let n = 0;
55 const handOver = (repo: Repo, title = `Stuck ${++n}`) => {
56 const made = openIssue(app, alice, repo, { title });
57 if (!made.ok) throw new Error(String(made.error));
58 addComment(app, alice, repo, made.value, BREAKER_NOTE);
59 return made.value;
60 };
61
62 const repoNamed = async (name: string): Promise<Repo> => {
63 const made = await createRepo(app, alice, { name, visibility: "private" });
64 if (!made.ok) throw new Error(String(made.error));
65 return made.value;
66 };
67
68 beforeAll(async () => {
69 dataDir = await mkdtemp(join(tmpdir(), "forge-decide-cards-"));
70 app = createApp({ dataDir, port: 0, decider });
71 const a = await createUser(app.db, {
72 trusted: true,
73 username: "alice",
74 email: "[email protected]",
75 password: "a-long-decider-passphrase",
76 adminIfFirst: true,
77 });
78 if (!a.ok) throw new Error(a.error);
79 alice = a.value;
80 }, 30_000);
81
82 afterAll(async () => {
83 await rm(dataDir, { recursive: true, force: true });
84 });
85
86 test("a hand-over on a repository ruled 'decider' is answered without a person, and the row carries the context", async () => {
87 const repo = await repoNamed("shelved");
88 setDeciderRule(app.db, repo.id, "decider");
89 const issue = handOver(repo);
90 expect(items()).toContain(`parked:${issue.id}`);
91 said = { choice: "close", p: 0.95 };
92 calls = 0;
93 expect(await sweepStandingCards(app)).toBe(1);
94 expect(calls).toBe(1);
95 // The card left the board, and the issue is closed.
96 expect(items()).not.toContain(`parked:${issue.id}`);
97 const row = listDecisions(app.db, repo.id, { kind: "card" })[0]!;
98 expect(row.answer).toBe("close");
99 expect(row.by).toBe("fake");
100 expect(row.p).toBe(0.95);
101 const state = row.state as { context: any; reason: string; operation: string };
102 expect(state.reason).toContain("fake chose close");
103 expect(state.context.card.title).toBe(issue.title);
104 expect(Object.keys(state.context).sort()).toEqual(
105 ["card", "direction", "evidence", "spend"].sort(),
106 );
107 expect(state.context.evidence.park.length).toBeGreaterThan(0);
108 // What the decider saw is the context stored.
109 expect((shown as any).card.app).toBe("alice/shelved");
110 // Swept once: a second tick does not ask again.
111 expect(await sweepStandingCards(app)).toBe(0);
112 expect(calls).toBe(1);
113 });
114
115 test("undo restores the card and the ledger says so", async () => {
116 const repo = await repoNamed("undoable");
117 const issue = handOver(repo);
118 said = { choice: "defer", p: 0.9 };
119 const done = await decideCards(app, alice, [`parked:${issue.id}`]);
120 if (!done.ok) throw new Error(done.error.message);
121 const result = done.value.results[0]!;
122 expect(result.act).toBe("defer");
123 expect(items()).not.toContain(`parked:${issue.id}`);
124 const undone = await undoAsksBulk(app, alice, result.operation!);
125 expect(undone.ok).toBe(true);
126 expect(items()).toContain(`parked:${issue.id}`);
127 const row = listDecisions(app.db, repo.id, { kind: "card" })[0]!;
128 expect(row.outcome).toBe("undone");
129 expect(cardTally(app.db, [repo.id], "1970-01-01T00:00:00Z")).toEqual({
130 closed: 0,
131 deferred: 0,
132 asked: 0,
133 });
134 });
135
136 test("an unsure answer reaches the owner: the card stays, and the ledger says asked", async () => {
137 const repo = await repoNamed("unsure");
138 setDeciderRule(app.db, repo.id, "decider_tell");
139 const issue = handOver(repo);
140 said = { choice: "close", p: 0.5 };
141 expect(await sweepStandingCards(app)).toBe(1);
142 expect(items()).toContain(`parked:${issue.id}`);
143 const row = listDecisions(app.db, repo.id, { kind: "card" })[0]!;
144 expect(row.answer).toBe("ask");
145 expect((row.state as { said: string }).said).toBe("close");
146 // The same by hand: a tap on an unsure decider leaves the card too.
147 const other = handOver(repo);
148 const tapped = await decideCards(app, alice, [`parked:${other.id}`]);
149 expect(tapped.ok && tapped.value.results[0]!.act).toBe("ask");
150 expect(items()).toContain(`parked:${other.id}`);
151 expect(
152 cardTally(app.db, [repo.id], "1970-01-01T00:00:00Z").asked,
153 ).toBe(2);
154 });
155
156 test("under the plain rule an unsure answer is set aside, not asked", async () => {
157 const repo = await repoNamed("quietly");
158 setDeciderRule(app.db, repo.id, "decider");
159 const issue = handOver(repo);
160 said = { choice: "close", p: 0.5 };
161 await sweepStandingCards(app);
162 expect(items()).not.toContain(`parked:${issue.id}`);
163 expect(listDecisions(app.db, repo.id, { kind: "card" })[0]!.answer).toBe("defer");
164 });
165
166 test("a muted app's card is set aside by rule, with no call", async () => {
167 const repo = await repoNamed("muted");
168 recordInteraction(app.db, {
169 viewerId: alice.id,
170 itemId: `repo:${repo.id}`,
171 kind: "muted",
172 repoId: repo.id,
173 actorId: null,
174 });
175 const issue = handOver(repo);
176 calls = 0;
177 const done = await decideCards(app, alice, [`parked:${issue.id}`]);
178 expect(calls).toBe(0);
179 expect(done.ok && done.value.results[0]).toMatchObject({ act: "defer", by: "rule" });
180 expect(items()).not.toContain(`parked:${issue.id}`);
181 });
182
183 test("a repository ruled to me is never swept, and the line says what the decider did", async () => {
184 const repo = await repoNamed("mine");
185 const issue = handOver(repo);
186 calls = 0;
187 await sweepStandingCards(app);
188 expect(calls).toBe(0);
189 expect(items()).toContain(`parked:${issue.id}`);
190 expect(deciderWords({ closed: 4, deferred: 2, asked: 1 })).toBe(
191 "the decider closed 4, deferred 2, asked you about 1",
192 );
193 expect(deciderWords({ closed: 1, deferred: 0, asked: 0 })).toBe("the decider closed 1");
194 });
195
196 test("a sweep is one receipt, linked from the board, and one undo takes all of it back", async () => {
197 const repo = await repoNamed("swept");
198 setDeciderRule(app.db, repo.id, "decider");
199 const issues = [handOver(repo), handOver(repo), handOver(repo)];
200 said = { choice: "close", p: 0.95 };
201 expect(await sweepStandingCards(app)).toBe(3);
202 const rows = listDecisions(app.db, repo.id, { kind: "card" });
203 const ops = new Set(rows.map((r) => (r.state as { operation: string }).operation));
204 expect(rows).toHaveLength(3);
205 expect(ops.size).toBe(1);
206 const [op] = [...ops];
207 // The board's tally links to it, and it is the owner's.
208 expect(cardReceipts(app.db, [repo.id], "1970-01-01T00:00:00Z").close).toBe(op!);
209 const undone = await undoAsksBulk(app, alice, op!);
210 expect(undone.ok).toBe(true);
211 for (const i of issues) expect(items()).toContain(`parked:${i.id}`);
212 expect(listDecisions(app.db, repo.id, { kind: "card" }).every((r) => r.outcome === "undone")).toBe(true);
213 expect(cardReceipts(app.db, [repo.id], "1970-01-01T00:00:00Z").close).toBeUndefined();
214 });
215
216 test("cards that do not ask, or are not decidable, are skipped", async () => {
217 const done = await decideCards(app, alice, ["parked:nope", "paused:nope"]);
218 expect(done.ok && done.value.skipped).toHaveLength(2);
219 expect((await decideCards(app, alice, "x")).ok).toBe(false);
220 expect((await decideCards(app, undefined, ["a"])).ok).toBe(false);
221 });
222 });
test/decide-doors.test.ts added +232
@@ -0,0 +1,232 @@
1 /**
2 * Let the decider (#1151), the doors: the card form, the API, the
3 * settings select and the board's tally line — and what the ledger
4 * shows to a reader of the repository (never another app's name).
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { sweepStandingCards } from "../src/actions/decide_cards.ts";
13 import { addComment, openIssue } from "../src/actions/issues.ts";
14 import { enableApp } from "../src/actions/apps.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { getDeciderRule, setDeciderRule } from "../src/core/decider_rule.ts";
17 import { pin } from "../src/core/pins.ts";
18 import type { Repo } from "../src/core/repos.ts";
19 import { createToken } from "../src/core/tokens.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { BREAKER_NOTE } from "../src/crew/breaker.ts";
22 import type { Decider } from "../src/crew/decide.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { askLinesFor } from "../src/web/studio/asks.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26
27 quietLogs();
28
29 const PASSWORD = "a-long-decider-passphrase";
30
31 describe("the decider's doors", () => {
32 let dataDir = "";
33 let app: App;
34 let servers: Servers;
35 let alice: User;
36 let bob: User;
37 let aliceRw = "";
38 let aliceRo = "";
39 let bobRw = "";
40 let cookie = "";
41 let said = { choice: "close", p: 0.95 };
42 let repo: Repo;
43
44 const decider: Decider = {
45 name: "fake",
46 async decide(_state, questions) {
47 const options = questions["card"]!.options;
48 const probabilities = Object.fromEntries(
49 options.map((o) => [o, o === said.choice ? said.p : 0]),
50 );
51 return { card: { choice: said.choice, p: said.p, probabilities } } as never;
52 },
53 };
54
55 const items = (): string[] => askLinesFor(app.db, alice).flatMap((r) => r.items);
56 let n = 0;
57 const handOver = (target: Repo) => {
58 const made = openIssue(app, alice, target, { title: `Stuck ${++n}` });
59 if (!made.ok) throw new Error(String(made.error));
60 addComment(app, alice, target, made.value, BREAKER_NOTE);
61 return made.value;
62 };
63 const post = (path: string, fields: [string, string][], origin: string | null = servers.url) =>
64 fetch(`${servers.url}${path}`, {
65 method: "POST",
66 headers: {
67 cookie: `${cookie}; forge_mode=studio`,
68 ...(origin === null ? {} : { origin }),
69 },
70 body: new URLSearchParams(fields),
71 redirect: "manual",
72 });
73 const api = async (token: string | null, payload: unknown) => {
74 const res = await fetch(`${servers.url}/api/v1/asks/decide`, {
75 method: "POST",
76 headers: {
77 ...(token === null ? {} : { authorization: `Bearer ${token}` }),
78 "content-type": "application/json",
79 },
80 body: JSON.stringify(payload),
81 });
82 return { status: res.status, body: (await res.json()) as any };
83 };
84
85 beforeAll(async () => {
86 dataDir = await mkdtemp(join(tmpdir(), "forge-decide-doors-"));
87 app = createApp({ dataDir, port: 0, decider });
88 servers = await serve(app);
89 const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
90 const b = await createUser(app.db, { trusted: true, username: "bob", email: "[email protected]", password: PASSWORD });
91 if (!a.ok || !b.ok) throw new Error("users");
92 alice = a.value;
93 bob = b.value;
94 aliceRw = createToken(app.db, alice.id, "rw", "rw").token;
95 aliceRo = createToken(app.db, alice.id, "ro", "ro").token;
96 bobRw = createToken(app.db, bob.id, "rw", "rw").token;
97 const res = await fetch(`${servers.url}/signin`, {
98 method: "POST",
99 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
100 redirect: "manual",
101 });
102 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
103 const made = await createRepo(app, alice, { name: "doors", visibility: "public" });
104 if (!made.ok) throw new Error(String(made.error));
105 repo = made.value;
106 // The board lists apps: this repository is one.
107 const seeded = await commitToBranch(app, alice, repo, {
108 message: "Start",
109 files: [
110 { path: "package.json", content: '{"name":"doors","scripts":{"start":"bun run server.ts"}}\n' },
111 { path: "server.ts", content: "Bun.serve({ port: Number(process.env.PORT), fetch: () => new Response('ok') });\n" },
112 ],
113 });
114 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
115 const enabled = await enableApp(app, alice, repo, { slug: "doors" });
116 if (!enabled.ok) throw new Error(String(enabled.error));
117 }, 30_000);
118
119 afterAll(async () => {
120 await servers.stop();
121 await rm(dataDir, { recursive: true, force: true });
122 });
123
124 test("the card form refuses a foreign origin, then closes with a receipt", async () => {
125 const issue = handOver(repo);
126 const id = `parked:${issue.id}`;
127 said = { choice: "close", p: 0.95 };
128 const foreign = await post("/asks/decide", [["item", id]], "https://evil.example");
129 expect(foreign.status).toBeGreaterThanOrEqual(400);
130 expect(items()).toContain(id);
131 const done = await post("/asks/decide", [["item", id]]);
132 expect(done.status).toBe(303);
133 expect(done.headers.get("location")).toStartWith("/?op=");
134 expect(items()).not.toContain(id);
135 });
136
137 test("the card form says when the decider is unsure, and the card stays", async () => {
138 const issue = handOver(repo);
139 const id = `parked:${issue.id}`;
140 said = { choice: "close", p: 0.4 };
141 const res = await post("/asks/decide", [["item", id]]);
142 expect(res.status).toBe(200);
143 expect(await res.text()).toContain("The decider left it with you");
144 expect(items()).toContain(id);
145 });
146
147 test("the API: by is validated, a credential is needed, and it must write", async () => {
148 const issue = handOver(repo);
149 const id = `parked:${issue.id}`;
150 expect((await api(null, { items: [id] })).status).toBe(401);
151 expect((await api(aliceRo, { items: [id] })).status).toBe(403);
152 const bad = await api(aliceRw, { items: [id], by: "someone" });
153 expect(bad.status).toBe(422);
154 expect(bad.body.error).toBe("invalid_by");
155 expect(items()).toContain(id);
156 said = { choice: "defer", p: 0.9 };
157 const ok = await api(aliceRw, { items: [id], by: "decider" });
158 expect(ok.status).toBe(201);
159 expect(ok.body.results[0]).toMatchObject({ act: "defer", by: "fake" });
160 expect(items()).not.toContain(id);
161 // Someone who is not asked by the card cannot hand it over.
162 const other = handOver(repo);
163 const theirs = await api(bobRw, { items: [`parked:${other.id}`] });
164 expect(theirs.status).toBe(201);
165 expect(theirs.body.skipped).toHaveLength(1);
166 });
167
168 test("the settings select: an admin sets the rule, a non-admin cannot, a bad value is refused", async () => {
169 const path = "/alice/doors/settings/autonomy";
170 const fields = (decides: string): [string, string][] => [
171 ["autonomy", "off"], ["ceiling", "1"], ["slots", "1"], ["direction", ""], ["decides", decides],
172 ];
173 expect((await post(path, fields("decider"))).status).toBe(303);
174 expect(getDeciderRule(app.db, repo.id)).toBe("decider");
175 await post(path, fields("bogus"));
176 expect(getDeciderRule(app.db, repo.id)).toBe("decider");
177 const bobPost = await fetch(`${servers.url}${path}`, {
178 method: "POST",
179 headers: { authorization: `Bearer ${bobRw}`, origin: servers.url },
180 body: new URLSearchParams(fields("me")),
181 redirect: "manual",
182 });
183 expect(bobPost.status).not.toBe(303);
184 expect(getDeciderRule(app.db, repo.id)).toBe("decider");
185 setDeciderRule(app.db, repo.id, "me");
186 });
187
188 test("the ledger of a public app does not name another app, and the board says what the decider did", async () => {
189 const secret = await createRepo(app, alice, { name: "secret-client-app", visibility: "private" });
190 if (!secret.ok) throw new Error(String(secret.error));
191 pin(app.db, alice.id, secret.value.id);
192 setDeciderRule(app.db, repo.id, "decider");
193 handOver(repo);
194 said = { choice: "close", p: 0.95 };
195 expect(await sweepStandingCards(app)).toBeGreaterThan(0);
196 const res = await fetch(`${servers.url}/api/v1/repos/alice/doors/decisions`, {
197 headers: { authorization: `Bearer ${bobRw}` },
198 });
199 const text = await res.text();
200 expect(text).toContain('"card"');
201 expect(text).not.toContain("secret-client-app");
202 expect(text).not.toContain("ownerLastTen");
203 const board = await fetch(`${servers.url}/board`, {
204 headers: { cookie: `${cookie}; forge_mode=studio` },
205 });
206 const html = await board.text();
207 expect(html).toContain("the decider closed");
208 });
209
210 test("a failing decider is asked once per card state, not on every tick", async () => {
211 setDeciderRule(app.db, repo.id, "decider");
212 handOver(repo);
213 let calls = 0;
214 const failing: Decider = {
215 name: "down",
216 async decide() {
217 calls++;
218 throw new Error("model down");
219 },
220 };
221 const was = app.config.decider;
222 (app.config as { decider?: Decider | undefined }).decider = failing;
223 try {
224 await sweepStandingCards(app);
225 const first = calls;
226 await sweepStandingCards(app);
227 expect(calls).toBe(first);
228 } finally {
229 (app.config as { decider?: Decider | undefined }).decider = was;
230 }
231 });
232 });
test/mcp.test.ts +1
@@ -164,6 +164,7 @@ describe("the forge over MCP", () => {
164164 "edit",
165165 "asks",
166166 "asks_act",
167 "decide",
167168 "seal",
168169 "now",
169170 "stop",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs