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 #1360

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +1114 −9
README.md +11
@@ -356,6 +356,17 @@ crosses.
356356 `docs/FOLLOWING.md` is a fork that keeps up with its parent: where it
357357 stands, taking updates, and the crew's part when both sides moved.
358358
359 Cards that need a person can be handed to the decider: the "Let the decider"
360 tap on a card (`POST /asks/decide`), `POST /api/v1/asks/decide` with
361 `{"items":[…],"by":"decider"}` (an `rw` credential), the MCP tool of the same
362 name, or a standing rule per app, "Decisions here" in the app's autonomy
363 settings (`me`, `decider`, `decider_tell`). It only closes or sets aside,
364 through the bulk action, so a receipt and a day's undo come with it; an unsure
365 answer stays with the owner. The ledger row (`GET …/decisions`) carries the
366 card, direction, whether this app is pinned or muted, spend and evidence, never
367 the owner's other apps or recent calls. The terminal has no asks list or
368 autonomy settings yet, so it has no counterpart.
369
359370 `docs/FLEET.md` is one change across many repositories, runs or issues: a
360371 query, a dry-run plan of every row before → after, a receipt, and undo.
361372
docs/PLANNING.md +14
@@ -504,6 +504,20 @@ place, and `by` says which answered. Nothing a decider says is acted on
504504 outside the choices the forge wrote down, which is what makes its answers
505505 safe to act on without a person.
506506
507 **Let the decider (cards that need a person).** A hand-over, a stopped or
508 green pull, or a review can be handed to the decider with a third tap, "Let
509 the decider", or by a standing rule per repository (Settings, "Decisions
510 here": me / the decider / the decider, and tell me the unsure ones;
511 `core/decider_rule.ts`). One call per card (`crew/decide_card.ts`), none when
512 a rule answers (a muted app's card is set aside). Its context is curated —
513 the direction, pinned and muted apps, the day's spend against the ceiling,
514 the owner's last ten calls on the repository, and the card's own evidence —
515 and stored on the `card` ledger row beside its reason and confidence. It
516 answers `close`, `defer` or `ask`; below 0.75 it is unsure and the card stays
517 with the owner (under the plain rule, it is set aside). It never ships. What
518 it closes or sets aside is a bulk receipt, undone for a day like any other.
519 `decide` on MCP and `POST /api/v1/asks/decide` take `by: "decider"`.
520
507521 Where it decides today:
508522
509523 - **Routing** (`crew/route.ts`): who takes what was told, its size (tiny,
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 +180
@@ -0,0 +1,180 @@
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 CardChoice,
22 } from "../crew/decide_card.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import { pendingCards, type PendingCard } from "../web/studio/asks.ts";
25 import { applyAsksBulk, type Skipped } from "./asks_bulk.ts";
26 import type { FleetError } from "./fleet.ts";
27
28 /** The most cards one request hands over. */
29 export const DECIDE_MAX = 20;
30
31 export interface CardResult {
32 readonly item: string;
33 /** What came of the card: closed, set aside, or left with the person. */
34 readonly act: CardChoice;
35 readonly p: number;
36 readonly by: string;
37 readonly reason: string;
38 /** The bulk receipt to undo, when the decider acted. */
39 readonly operation?: string;
40 }
41
42 export interface Decided {
43 readonly results: CardResult[];
44 readonly skipped: Skipped[];
45 }
46
47 export async function decideCards(
48 app: App,
49 actor: User | undefined,
50 items: unknown,
51 standing: Exclude<DeciderRule, "me"> | undefined = undefined,
52 ): Promise<Result<Decided, FleetError>> {
53 if (!actor)
54 return err({ code: "unauthorized", message: "sign in to hand over cards" });
55 const list = Array.isArray(items)
56 ? items.filter((i): i is string => typeof i === "string")
57 : [];
58 if (list.length === 0 || list.length !== (items as unknown[]).length)
59 return err({ code: "bad_action", message: "items is a list of ask ids" });
60 if (list.length > DECIDE_MAX)
61 return err({
62 code: "too_many",
63 message: `at most ${DECIDE_MAX} cards at once`,
64 });
65 const db = app.db;
66 const cards = new Map(
67 pendingCards(db, actor, listReposVisibleTo(db, actor, { limit: 200 })).map(
68 (c) => [c.id, c],
69 ),
70 );
71 const results: CardResult[] = [];
72 const skipped: Skipped[] = [];
73 for (const item of new Set(list)) {
74 const card = cards.get(item);
75 if (card === undefined) {
76 skipped.push({ item, reason: "it no longer asks you, or a decider cannot answer it" });
77 continue;
78 }
79 results.push(await decideOne(app, actor, card, standing));
80 }
81 return ok({ results, skipped });
82 }
83
84 /** One card answered and written to the ledger. */
85 async function decideOne(
86 app: App,
87 actor: User,
88 card: PendingCard,
89 standing: Exclude<DeciderRule, "me"> | undefined,
90 ): Promise<CardResult> {
91 const db = app.db;
92 const item = card.id;
93 const context = cardContext(db, {
94 kind: card.kind,
95 repo: card.repo,
96 pull: card.pull,
97 issue: card.issue,
98 viewerId: actor.id,
99 });
100 const answer = await decideCard(app.config.decider, context);
101 // What is done: a sure answer as given; an unsure one is the person's —
102 // except under the plain standing rule, which sets the card aside.
103 let act: CardChoice = answer.choice;
104 if (act !== "ask" && !answer.sure) act = standing === "decider" ? "defer" : "ask";
105 let reason = answer.reason;
106 if (answer.choice !== "ask" && !answer.sure && answer.by !== "rule")
107 reason += act === "ask" ? "; unsure, so it is yours" : "; unsure, so set aside";
108 let operation: string | undefined;
109 if (act !== "ask") {
110 const done = await applyAsksBulk(
111 app,
112 actor,
113 act === "close" ? "close" : "dismiss",
114 [item],
115 );
116 if (done.ok && done.value.rows.some((r) => r.outcome === "ok"))
117 operation = done.value.id;
118 else {
outdated

This full context is what ends up in the public ledger row. Whatever is redacted has to be redacted here, or wherever decisions are serialised.

119 act = "ask";
120 reason += "; it could not be done, so it is yours";
121 }
122 }
123 // No decider answered and no rule: a miss, noted as such (by "none", left
124 // out of the tally) so a sweep waits for the card to change before asking.
125 const missed = answer.by === "rule" && answer.choice === "ask";
126 const subject = (card.pull ?? card.issue)!;
127 recordDecision(db, {
128 kind: "card",
129 repoId: card.repo.id,
130 issueId: subject.id,
131 state: {
132 item,
133 context: ledgerContext(context),
134 reason,
135 said: answer.choice,
136 standing: standing ?? null,
137 operation: operation ?? null,
138 since: card.since,
139 },
140 answer: act,
141 p: answer.p,
142 by: missed ? "none" : answer.by,
143 ms: answer.ms,
144 });
145 return {
146 item,
147 act,
148 p: answer.p,
149 by: answer.by,
150 reason,
151 ...(operation === undefined ? {} : { operation }),
152 };
153 }
154
155 /** Cards a sweep answers at most, so a long backlog costs a few calls a tick. */
156 const SWEEP_MAX = 10;
157
158 /**
159 * The standing rules at work: for each repository ruled to the decider,
160 * answer the cards that wait on its owner and were not answered since they
161 * last changed. A tick's work, never a request's.
162 */
163 export async function sweepStandingCards(app: App): Promise<number> {
164 let handled = 0;
165 for (const { repoId, rule } of ruledRepos(app.db)) {
166 const repo = getRepoById(app.db, repoId);
167 const actor = repo
168 ? getUserById(app.db, repo.autonomyBy ?? repo.ownerId)
169 : undefined;
170 if (!repo || !actor || actor.kind !== "user") continue;
171 for (const card of pendingCards(app.db, actor, [repo])) {
172 if (handled >= SWEEP_MAX) return handled;
173 const last = latestDecision(app.db, (card.pull ?? card.issue)!.id, "card");
174 if (last !== undefined && last.createdAt >= card.since) continue;
175 const done = await decideOne(app, actor, card, rule);
176 if (done.by !== "rule" || done.act !== "ask") handled++;
177 }
178 }
179 return handled;
180 }
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 +48 −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,44 @@ 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 }
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 stay out.
59 */
60 export const ledgerContext = (
61 context: CardContext,
62 ): Omit<CardContext, "ownerLastTen"> => {
63 const { ownerLastTen: _private, ...rest } = context;
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 },
outdated

High: these are the names of the owner's pinned and muted repositories across the whole forge. They are stored in the ledger row's state, and GET /api/v1/repos/:owner/:name/decisions serves that to every reader of this repository. Store whether this app is pinned or muted, not the list.

92 direction: clip(repo.autonomyDirection, 600),
93 apps: {
94 pinned: pinnedRepoIds(db, viewerId).has(repo.id),
95 muted: mutedRepos(db, viewerId).has(repo.id),
outdated

The owner's own recent actions are stored in state too, and readable through the public decisions API. Either redact them there or limit them to admins.

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
@@ -92,6 +92,7 @@ import {
9292 milestonesJson,
9393 } from "../web/pages/milestones.ts";
9494 import { appsOf, asksAnswer } from "../web/studio/asks.ts";
95 import { decideCards } from "../actions/decide_cards.ts";
9596 import { applyAsksBulk, previewAsksBulk } from "../actions/asks_bulk.ts";
9697 import type { Ctx, Handler } from "./context.ts";
9798 import {
@@ -449,6 +450,25 @@ const TOOLS: readonly Tool[] = [
449450 return answer.ok ? good(answer.value) : bad(answer.error.code, answer.error.message);
450451 },
451452 },
453 {
454 name: "decide",
455 description:
456 '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.',
457 inputSchema: {
458 type: "object",
459 properties: {
460 by: { type: "string", enum: ["decider"] },
461 items: { type: "array", items: { type: "string" }, maxItems: 20 },
462 },
463 required: ["by", "items"],
464 },
465 writes: true,
466 async run(ctx, user, args) {
467 if (args["by"] !== "decider") return bad("invalid", 'by is "decider"');
468 const done = await decideCards(ctx.app, user, args["items"]);
469 return done.ok ? good(done.value) : bad(done.error.code, done.error.message);
470 },
471 },
452472 {
453473 name: "seal",
454474 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 +21
@@ -20,7 +20,9 @@ import { reviewersOf, waitsForPerson } from "../../crew/review.ts";
2020 import { tokenReturns } from "../../core/returns.ts";
2121 import { returnsRepos } from "../../actions/returns.ts";
2222 import {
23 cardTally,
2324 listDecisionsForRepos,
25 type CardTally,
2426 type Decision,
2527 type DecisionKind,
2628 } from "../../core/decisions.ts";
@@ -115,8 +117,19 @@ const KIND_WORDS: Record<DecisionKind, string> = {
115117 lean: "which way",
116118 // Never listed (`listDecisionsForRepos` leaves guards out); named for the type.
117119 guard: "not started",
120 card: "a card for you",
118121 };
119122
123 /** "the decider closed 4, deferred 2, asked you about 1" — what it did, never a zero. */
124 export function deciderWords(t: CardTally): string {
125 const parts = [
126 t.closed > 0 ? `closed ${t.closed}` : "",
127 t.deferred > 0 ? `deferred ${t.deferred}` : "",
128 t.asked > 0 ? `asked you about ${t.asked}` : "",
129 ].filter((p) => p !== "");
130 return `the decider ${parts.join(", ")}`;
131 }
132
120133 const money = (n: number): string => `$${n.toFixed(2)}`;
121134
122135 /** A wait, in the unit a person reads it in. */
@@ -960,6 +973,14 @@ function today(ctx: Ctx, scope: BoardScope): Html {
960973 </a>
961974 </li>`;
962975 });
976 // What the decider did with the cards that needed the owner, today.
977 const tally = cardTally(db, [...scope.ownerFacts], since);
978 if (tally.closed + tally.deferred + tally.asked > 0)
979 rows.unshift(
980 html`<li class="muted small board-decider">
981 ${deciderWords(tally)}
982 </li>`,
983 );
963984 return region(
964985 "today",
965986 "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 +202
@@ -0,0 +1,202 @@
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 { 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 ["apps", "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("cards that do not ask, or are not decidable, are skipped", async () => {
197 const done = await decideCards(app, alice, ["parked:nope", "paused:nope"]);
198 expect(done.ok && done.value.skipped).toHaveLength(2);
199 expect((await decideCards(app, alice, "x")).ok).toBe(false);
200 expect((await decideCards(app, undefined, ["a"])).ok).toBe(false);
201 });
202 });
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
@@ -162,6 +162,7 @@ describe("the forge over MCP", () => {
162162 "edit",
163163 "asks",
164164 "asks_act",
165 "decide",
165166 "seal",
166167 "now",
167168 "stop",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs