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

The decider can be compared with SubQ Snap in the background, off by default, and decides nothing #17795

opened this

Merged 7h 55m ago, live in production

snap-shadow → main 0 commits 1 thread · 1 unresolved

  • Merged. snap-shadow was merged into main as c0cee92.

Review

Sign in to review this change.
20 files changed +923 −29
docs/features/decider-shadow.md added +24
@@ -0,0 +1,24 @@
1 ---
2 topic: Tell the crew
3 row: A second decider, in shadow
4 ---
5 # SubQ Snap beside the decider
6
7 After a `next` or `retry` decision is made and recorded, the forge can ask SubQ's decision model the
8 same question and keep its answer for a comparison. Nothing the forge does reads that answer.
9
10 - **Switch**: the limit `decider.shadow_per_day` on `/admin/limits` (MCP: `limits`). It is 0, off,
11 until a forge admin sets it.
12 - **What leaves the forge**: what the decider already gets, for public, unsealed work in repositories
13 owned by the person who saved the connection named `subq`. A `retry` decision holds the last lines
14 of a check's log, which its page shows to writers and the crew alone. SubQ's terms say it keeps
15 inputs for up to 60 days and does not train its foundational models on them.
16 - **It stops by itself** when the service answers 401, 402 or 403. Saving the limit again resumes it.
17 - **Kept** for 90 days, then the `retention-telemetry` job removes them.
18 - **The connection is found by its name**: without one named `subq` nothing is sent, and the report says so.
19 - **Report**: the terminal's Decider screen while the switch is on, and the MCP tool
20 `decider_shadow`. `action: replay` first says what up to 500 past decisions would cost;
21 starting or ending one takes `dryRun: false` and an admin token. Both are on the MCP tool alone, on
22 purpose: a replay sends past decisions out and costs money, and is run rarely. The terminal shows the report.
23 - **What it cannot say**: who was right on `next`, where only the issue picked has an outcome, or on a
24 `stop`, whose other try was never what it asked.
src/core/migration-pins/20261203033319-decision-shadow.pin added +1
@@ -0,0 +1,1 @@
1 4b67621057d3d7d85d005ad6379bff17c12f7a3466fd1fcd0cb02a722bf20b81
src/core/migrations/20261203033319-decision-shadow.ts added +20
@@ -0,0 +1,20 @@
1 // What a second decider said to a decision already made and recorded (`crew/snap.ts`): read for a
2 // comparison only, never to decide. `source` is live (asked after the decision), replay (a past one)
3 // or repeat (a replayed one asked twice). An `error` is a status code or a word, never a body. Additive.
4 export default `
5 CREATE TABLE decision_shadow (
6 id TEXT PRIMARY KEY,
7 decision_id TEXT NOT NULL REFERENCES decision(id) ON DELETE CASCADE,
8 source TEXT NOT NULL CHECK (source IN ('live', 'replay', 'repeat')),
9 model TEXT NOT NULL,
10 answer TEXT,
11 p REAL,
12 probabilities TEXT,
13 ms INTEGER NOT NULL DEFAULT 0,
14 input_tokens INTEGER NOT NULL DEFAULT 0,
15 error TEXT,
16 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
17 );
18 CREATE INDEX decision_shadow_decision ON decision_shadow(decision_id, source);
19 CREATE INDEX decision_shadow_at ON decision_shadow(created_at);
20 `;
src/crew/conversation_ask.ts +1
@@ -252,6 +252,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
252252 subscription_add: (a) => `Add the Claude login ${val(a, "name")} to the crew's pool`,
253253 subscription_budget: (a) =>
254254 a["usd"] === null ? `Clear subscription ${own(val(a, "id"))} lifetime budget` : `Set subscription ${own(val(a, "id"))} lifetime budget to ${dollars(a["usd"])}`,
255 decider_shadow: (a) => (val(a, "action") === "stop" ? "End the replay of past decisions to SubQ Snap" : "Send up to 500 past decisions to SubQ Snap, check log lines among them"),
255256 subscription_headroom: (a) => `Leave ${val(a, "percent")}% of each window of subscription ${val(a, "id")} for people`,
256257 talk_watch: (a) => `Watch ${val(a, "target")} and wake your agent when ${val(a, "kind").replace(/_/g, " ")}`,
257258 subscription_wake: (a) => `Use the resting subscription ${val(a, "id")} again now`,
src/crew/conversation_confirm.ts +2
@@ -72,6 +72,8 @@ export const ASKING: Readonly<Record<string, Asking>> = {
7272 subscription_add: { undo: () => "`subscription_delete` with its id removes it" },
7373 subscription_budget: { undo: () => "`subscription_budget` with the old `usd` sets it back" },
7474 subscription_headroom: {},
75 // What it sends leaves the forge for good.
76 decider_shadow: {},
7577 subscription_wake: {},
7678 // A watch wakes the agent without the owner: starting one is the owner's yes (#16557).
7779 talk_watch: { asks: (a) => a["action"] === "add" },
src/crew/dispatch.ts +27 −24
@@ -1488,6 +1488,32 @@ export interface CheckJudgement {
14881488 const RETRY_OPTIONS = ["again", "stop"];
14891489 const CAUSE_OPTIONS = ["change", "environment", "base"];
14901490
1491 /** What is asked of a red check; a replay of past ones (`snap.ts`) asks the same words. */
1492 export const RETRY_QUESTIONS = {
1493 retry: {
1494 options: RETRY_OPTIONS,
1495 about:
1496 "The check failed. Is another automatic try by the agent worth its cost, or should a person look?",
1497 describe: {
1498 again:
1499 "Try again: the failure reads as something the agent can fix from the log.",
1500 stop: "Stop: the failure repeats an earlier one, or is beyond what another run would fix.",
1501 },
1502 },
1503 cause: {
1504 options: CAUSE_OPTIONS,
1505 about:
1506 "Why the repository's check failed, judging from the end of its log.",
1507 describe: {
1508 change:
1509 "The code under test is wrong: a failing assertion, a type error, a bug the change introduced.",
1510 environment:
1511 "The place it ran failed, not the code: a timeout, a network error, a missing tool, a flaky runner, a full disk.",
1512 base: "The base branch itself is broken; the change is not what fails.",
1513 },
1514 },
1515 };
1516
14911517 /**
14921518 * Whose fault the failure is, and whether to try again — asked together,
14931519 * of one log tail, in one round trip, because the answers are only useful
@@ -1537,30 +1563,7 @@ export async function judgeFailedCheck(
15371563 },
15381564 log: tail,
15391565 },
1540 {
1541 retry: {
1542 options: RETRY_OPTIONS,
1543 about:
1544 "The check failed. Is another automatic try by the agent worth its cost, or should a person look?",
1545 describe: {
1546 again:
1547 "Try again: the failure reads as something the agent can fix from the log.",
1548 stop: "Stop: the failure repeats an earlier one, or is beyond what another run would fix.",
1549 },
1550 },
1551 cause: {
1552 options: CAUSE_OPTIONS,
1553 about:
1554 "Why the repository's check failed, judging from the end of its log.",
1555 describe: {
1556 change:
1557 "The code under test is wrong: a failing assertion, a type error, a bug the change introduced.",
1558 environment:
1559 "The place it ran failed, not the code: a timeout, a network error, a missing tool, a flaky runner, a full disk.",
1560 base: "The base branch itself is broken; the change is not what fails.",
1561 },
1562 },
1563 },
1566 RETRY_QUESTIONS,
15641567 () => ({
15651568 retry: certain(RETRY_OPTIONS, "again"),
15661569 cause: certain(CAUSE_OPTIONS, "change"),
src/crew/ledger.ts +3
@@ -19,6 +19,7 @@ import {
1919 type Questions,
2020 type State,
2121 } from "./decide.ts";
22 import { shadowDecision } from "./snap.ts";
2223
2324 export interface Recorded<Q extends Questions> extends Decided<Q> {
2425 readonly decision: Decision;
@@ -43,5 +44,7 @@ export async function decideAndRecord<Q extends Questions>(
4344 by: decided.by,
4445 ms: decided.ms,
4546 });
47 // Off unless the limit is set, and never awaited: the decision above is made and recorded.
48 shadowDecision(app, decision, about.repo, about.issue, state, questions);
4649 return { ...decided, decision };
4750 }
src/crew/next_pick.ts +5 −2
@@ -78,6 +78,10 @@ export async function withoutRetired(
7878 return kept;
7979 }
8080
81 /** What is asked about the ready issues; a replay of past ones (`snap.ts`) asks the same words. */
82 export const NEXT_ABOUT =
83 "Which of these ready issues moves the direction forward most right now? Prefer what unblocks others and what the direction names.";
84
8185 export async function nextOf(
8286 app: App,
8387 repo: Repo,
@@ -103,8 +107,7 @@ export async function nextOf(
103107 {
104108 next: {
105109 options,
106 about:
107 "Which of these ready issues moves the direction forward most right now? Prefer what unblocks others and what the direction names.",
110 about: NEXT_ABOUT,
108111 describe,
109112 },
110113 },
src/crew/snap.ts added +379
@@ -0,0 +1,379 @@
1 /**
2 * SubQ Snap as a second decider, in shadow: after a decision is made and recorded, the same state and
3 * questions go to Snap and what it says is kept beside the decision (`decision_shadow`). Nothing the
4 * forge does reads it. Off until an admin sets `decider.shadow_per_day` above 0.
5 *
6 * What leaves the forge is what the decider already gets, and only for `next` and `retry` decisions of
7 * public, unsealed work in repositories the saved `subq` connection's creator owns. A `retry` state
8 * holds the last lines of a check's log, which its page shows to writers and the crew alone; the limit
9 * says so where it is set. The key is the connection's, opened for each call and sent to its host only.
10 *
11 * It stops by itself: after an answer of 401, 402 or 403 nothing more is sent until an admin saves the
12 * limit again. The connection is found by its name: without one called `subq` nothing is sent, and the
13 * report says so. A slow or failed call costs the shadow and nothing else.
14 */
15
16 import type { Database } from "bun:sqlite";
17 import type { App } from "../app.ts";
18 import { connectionKey } from "../core/connections.ts";
19 import type { Decision } from "../core/decisions.ts";
20 import type { Issue } from "../core/issues.ts";
21 import { getRepoById, type Repo } from "../core/repos.ts";
22 import { id as newId } from "../kernel/id.ts";
23 import { createLog } from "../kernel/log.ts";
24 import { outboundFetch } from "../kernel/outbound.ts";
25 import { sliced } from "../kernel/breathe.ts";
26 import { background } from "../perf/jobs.ts";
27 import { limitValue, storeKey } from "../settings/limits.ts";
28 import { typeSafeAnswers, typeSafeRequest, type Answer, type Questions, type State } from "./decide.ts";
29
30 const log = createLog("snap");
31
32 export const SNAP_MODEL = "subq-snap-1.2";
33 /** What 1M input tokens cost, USD; output is free (docs.subq.ai, 2026-12-02). */
34 export const SNAP_USD_PER_M = 0.04;
35 /** The saved connection's name. */
36 const CONNECTION = "subq";
37 /** The kinds that carry a decider's answer about a repository today. */
38 export const SHADOW_KINDS = ["next", "retry"] as const;
39 type ShadowKind = (typeof SHADOW_KINDS)[number];
40 const LIVE_TIMEOUT_MS = 5_000;
41 const LIVE_AT_ONCE = 2;
42 /** The most of a reply that is read: one answer is under 1 KB. */
43 const REPLY_MAX = 32 * 1024;
44 const REFUSED = new Set(["401", "402", "403"]);
45
46 /** How a call goes out; a test hands its own. */
47 export const snapFetch: { fetch: typeof outboundFetch } = { fetch: outboundFetch };
48
49 interface Connection {
50 readonly id: string;
51 readonly ownerId: string;
52 readonly base: string;
53 }
54
55 /** The saved `subq` connection, with the person who made it; undefined without one. */
56 function snapConnection(db: Database): Connection | undefined {
57 const row = db
58 .query<{ id: string; created_by: string | null; api_base: string | null }, [string]>(
59 "SELECT id, created_by, api_base FROM subscription WHERE lower(name) = ?1 AND protocol = 'openai' ORDER BY created_at LIMIT 1",
60 )
61 .get(CONNECTION);
62 if (row === null || row.created_by === null || row.api_base === null) return undefined;
63 return { id: row.id, ownerId: row.created_by, base: row.api_base.replace(/\/+$/, "") };
64 }
65
66 /** Why nothing can be sent, when it is the connection; undefined when there is one to send on. */
67 export const shadowUnconnected = (db: Database): string | undefined =>
68 snapConnection(db) === undefined ? `no connection named ${CONNECTION} (OpenAI-compatible, with a base URL and a person who made it)` : undefined;
69
70 /** Whether a decision about this work may be sent: public, unsealed, its owner's own, of a kind asked. */
71 export function maySend(connection: { readonly ownerId: string }, kind: string, repo: Repo, issue: Pick<Issue, "sealed"> | undefined): boolean {
72 return (
73 (SHADOW_KINDS as readonly string[]).includes(kind) &&
74 repo.visibility === "public" &&
75 repo.sealedFor === null &&
76 !repo.quarantined &&
77 repo.ownerId === connection.ownerId &&
78 issue?.sealed !== true
79 );
80 }
81
82 /** Why a call failed, in a word that holds nothing the other side wrote. */
83 class SnapError extends Error {
84 constructor(readonly code: string) {
85 super(`snap: ${code}`);
86 }
87 }
88
89 interface Said {
90 readonly answer: Answer;
91 readonly tokens: number;
92 }
93
94 /** The reply's JSON, read no further than `REPLY_MAX`; longer, cut short or not JSON is `bad_body`. */
95 async function replyOf(response: Response): Promise<unknown> {
96 const reader = response.body?.getReader();
97 try {
98 const chunks: Uint8Array[] = [];
99 let size = 0;
100 for (let part = await reader?.read(); part !== undefined && !part.done; part = await reader?.read()) {
101 size += part.value.byteLength;
102 if (size > REPLY_MAX) throw new SnapError("bad_body");
103 chunks.push(part.value);
104 }
105 return JSON.parse(Buffer.concat(chunks).toString("utf8"));
106 } catch {
107 await reader?.cancel().catch(() => {});
108 throw new SnapError("bad_body");
109 }
110 }
111
112 async function ask(app: App, connection: Connection, kind: ShadowKind, state: State, questions: Questions, signal: AbortSignal): Promise<Said> {
113 const key = connectionKey(app.db, app.config.dataDir, connection.id);
114 if (key === undefined || key === "") throw new SnapError("no_key");
115 let response: Response;
116 try {
117 response = await snapFetch.fetch(`${connection.base}/systemone`, {
118 method: "POST",
119 headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json" },
120 body: JSON.stringify(typeSafeRequest(state, questions, SNAP_MODEL)),
121 signal,
122 });
123 } catch {
124 throw new SnapError(signal.aborted ? "timeout" : "unreachable");
125 }
126 if (!response.ok) {
127 await response.body?.cancel().catch(() => {});
128 throw new SnapError(String(response.status));
129 }
130 const body = (await replyOf(response)) as { answers?: Record<string, unknown>; usage?: { input_tokens?: unknown } } | null;
131 if (body?.answers?.[kind] === undefined) throw new SnapError("no_answer");
132 const tokens = body.usage?.input_tokens;
133 return { answer: typeSafeAnswers(body, questions)[kind]!, tokens: typeof tokens === "number" && tokens > 0 ? Math.round(tokens) : 0 };
134 }
135
136 type Source = "live" | "replay" | "repeat";
137
138 function keep(db: Database, decisionId: string, source: Source, ms: number, said: Said | { readonly error: string }): void {
139 const a = "answer" in said ? said : undefined;
140 db.query(
141 `INSERT INTO decision_shadow (id, decision_id, source, model, answer, p, probabilities, ms, input_tokens, error)
142 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)`,
143 ).run(
144 newId(),
145 decisionId,
146 source,
147 SNAP_MODEL,
148 a?.answer.choice ?? null,
149 a?.answer.p ?? null,
150 a === undefined ? null : JSON.stringify(a.answer.probabilities),
151 Math.round(ms),
152 a?.tokens ?? 0,
153 "error" in said ? said.error : null,
154 );
155 }
156
157 /** Ask once and keep what came of it; the error's word when it failed. */
158 async function askAndKeep(app: App, connection: Connection, decisionId: string, kind: ShadowKind, state: State, questions: Questions, source: Source, signal: AbortSignal): Promise<string | undefined> {
159 const started = performance.now();
160 try {
161 const said = await ask(app, connection, kind, state, questions, signal);
162 keep(app.db, decisionId, source, performance.now() - started, said);
163 return undefined;
164 } catch (error) {
165 const code = error instanceof SnapError ? error.code : "failed";
166 if (!app.closing.signal.aborted) keep(app.db, decisionId, source, performance.now() - started, { error: code });
167 return code;
168 }
169 }
170
171 /** The refusal that stopped the shadow, until an admin saves the limit again; undefined while it may go on. */
172 export function shadowStopped(db: Database): string | undefined {
173 const since = db.query<{ at: string }, [string]>("SELECT updated_at AS at FROM forge_setting WHERE key = ?1").get(storeKey("decider.shadow_per_day"))?.at ?? "";
174 return db
175 .query<{ error: string }, [string]>("SELECT error FROM decision_shadow WHERE created_at > ?1 AND error IN ('401', '402', '403') ORDER BY created_at DESC LIMIT 1")
176 .get(since)?.error;
177 }
178
179 const inFlight = new WeakMap<App, number>();
180
181 /**
182 * After `decision` is recorded: the same question to Snap, in the background, when all of it is
183 * allowed. It never throws: a read that fails here costs the shadow, not the decision just made.
184 */
185 export function shadowDecision(app: App, decision: Decision, repo: Repo, issue: Issue | undefined, state: State, questions: Questions): void {
186 try {
187 startShadow(app, decision, repo, issue, state, questions);
188 } catch (error) {
189 log.warn("the shadow decider was not asked", { error: error instanceof Error ? error.message : String(error) });
190 }
191 }
192
193 function startShadow(app: App, decision: Decision, repo: Repo, issue: Issue | undefined, state: State, questions: Questions): void {
194 const perDay = limitValue(app.db, "decider.shadow_per_day");
195 // A rule's answer is not a decider's: there is nothing to compare Snap with.
196 if (perDay === 0 || decision.by === "rule") return;
197 const connection = snapConnection(app.db);
198 if (connection === undefined || !maySend(connection, decision.kind, repo, issue)) return;
199 const running = inFlight.get(app) ?? 0;
200 // Full is dropped, never queued: a burst of decisions must not become a backlog.
201 if (running >= LIVE_AT_ONCE || shadowStopped(app.db) !== undefined) return;
202 const day = new Date().toISOString().slice(0, 10);
203 const today = app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM decision_shadow WHERE source = 'live' AND created_at >= ?1").get(day)!.n;
204 if (today >= perDay) return;
205 inFlight.set(app, running + 1);
206 void background(
207 "decider-shadow",
208 async () => {
209 try {
210 const signal = AbortSignal.any([app.closing.signal, AbortSignal.timeout(LIVE_TIMEOUT_MS)]);
211 const code = await askAndKeep(app, connection, decision.id, decision.kind as ShadowKind, state, questions, "live", signal);
212 if (code !== undefined && REFUSED.has(code)) log.warn("the shadow decider stopped: the service refused the key or its credit", { status: code });
213 } finally {
214 inFlight.set(app, (inFlight.get(app) ?? 1) - 1);
215 }
216 },
217 undefined,
218 app,
219 );
220 }
221
222 /** How long what Snap said is kept: a comparison over a quarter. `retention-telemetry` ends it. */
223 export const SHADOW_KEEP_DAYS = 90;
224 const PRUNE_ROWS = 200;
225
226 /** One slice of the prune: the oldest rows past the window. */
227 export function pruneShadows(db: Database, now: number, rows = PRUNE_ROWS): { readonly deleted: number; readonly more: boolean } {
228 const cut = new Date(now - SHADOW_KEEP_DAYS * 86_400_000).toISOString();
229 const gone = db.query("DELETE FROM decision_shadow WHERE id IN (SELECT id FROM decision_shadow WHERE created_at < ?1 ORDER BY created_at LIMIT ?2)").run(cut, rows).changes;
230 return { deleted: gone, more: gone === rows };
231 }
232
233 // ---- the replay ----
234
235 export const REPLAY_MAX = 500;
236 /** How many of them are asked twice, to see how much an answer varies. */
237 export const REPEATS = 50;
238 const REPLAY_AT_ONCE = 2;
239 const REPLAY_TIMEOUT_MS = 15_000;
240 const TRIES = 4;
241
242 interface Past {
243 readonly id: string;
244 readonly kind: ShadowKind;
245 readonly state: State;
246 readonly questions: Questions;
247 }
248
249 /** The question a past decision was asked, rebuilt; undefined when its state does not hold enough. */
250 export function questionsOf(kind: ShadowKind, state: unknown, words: { readonly retry: Questions; readonly nextAbout: string }): Questions | undefined {
251 if (kind === "retry") return words.retry;
252 const ready = (state as { ready?: unknown } | null)?.ready;
253 if (!Array.isArray(ready) || ready.length < 2) return undefined;
254 const describe: Record<string, string> = {};
255 for (const r of ready as { number?: unknown; title?: unknown; sealed?: unknown; holdsUp?: unknown }[]) {
256 if (typeof r?.number !== "number") return undefined;
257 const holds = typeof r.holdsUp === "number" && r.holdsUp > 0 ? ` (holds up ${r.holdsUp})` : "";
258 describe[String(r.number)] = `#${r.number} ${r.sealed === true ? "(sealed)" : String(r.title ?? "")}${holds}`;
259 }
260 return { next: { options: Object.keys(describe), about: words.nextAbout, describe } };
261 }
262
263 /** Past decisions with a known outcome, half of each kind, in an order their ids fix and no time does. */
264 async function pastDecisions(app: App, connection: Connection): Promise<Past[]> {
265 // Loaded when a replay is asked for: the two modules reach the crew's own, which import the ledger.
266 const [{ RETRY_QUESTIONS }, { NEXT_ABOUT }] = await Promise.all([import("./dispatch.ts"), import("./next_pick.ts")]);
267 const words = { retry: RETRY_QUESTIONS, nextAbout: NEXT_ABOUT };
268 const out: Past[] = [];
269 const turn = sliced();
270 for (const kind of SHADOW_KINDS) {
271 const rows = app.db
272 .query<{ id: string; repo_id: string; state: string }, [string, string, number]>(
273 `SELECT d.id, d.repo_id, d.state FROM decision d JOIN repo r ON r.id = d.repo_id LEFT JOIN issue i ON i.id = d.issue_id
274 WHERE d.kind = ?1 AND d.by = 'typesafe' AND d.outcome IS NOT NULL AND r.owner_id = ?2 AND r.visibility = 'public'
275 AND r.sealed_for IS NULL AND COALESCE(i.sealed, 0) = 0
276 AND NOT EXISTS (SELECT 1 FROM decision_shadow s WHERE s.decision_id = d.id AND s.source = 'replay' AND s.error IS NULL)
277 ORDER BY substr(d.id, -8) LIMIT ?3`,
278 )
279 .all(kind, connection.ownerId, REPLAY_MAX / SHADOW_KINDS.length);
280 for (const r of rows) {
281 if (turn.due()) await turn.breathe();
282 const repo = getRepoById(app.db, r.repo_id);
283 if (repo === undefined || !maySend(connection, kind, repo, undefined)) continue;
284 let state: unknown;
285 try {
286 state = JSON.parse(r.state);
287 } catch {
288 continue;
289 }
290 const questions = questionsOf(kind, state, words);
291 if (questions !== undefined) out.push({ id: r.id, kind, state: state as State, questions });
292 }
293 }
294 return out;
295 }
296
297 export interface ReplayPlan {
298 readonly decisions: number;
299 readonly repeats: number;
300 readonly tokens: number;
301 readonly usd: number;
302 }
303
304 const tokensOf = (p: Past): number => Math.ceil(JSON.stringify(typeSafeRequest(p.state, p.questions, SNAP_MODEL)).length / 4);
305
306 /** The ones asked twice: as many of each kind. */
307 const twiceOf = (past: readonly Past[]): Past[] => SHADOW_KINDS.flatMap((kind) => past.filter((p) => p.kind === kind).slice(0, REPEATS / SHADOW_KINDS.length));
308
309 const planOf = (past: readonly Past[]): ReplayPlan => {
310 const again = twiceOf(past);
311 const tokens = [...past, ...again].reduce((n, p) => n + tokensOf(p), 0);
312 return { decisions: past.length, repeats: again.length, tokens, usd: (tokens / 1e6) * SNAP_USD_PER_M };
313 };
314
315 export type ReplayError = "no_connection" | "running";
316 interface Replay {
317 readonly total: number;
318 done: number;
319 readonly stop: AbortController;
320 }
321 const replays = new WeakMap<App, Replay>();
322
323 /** What a replay would send and cost; nothing is sent. The tokens are a guess: four characters each. */
324 export async function planReplay(app: App): Promise<ReplayPlan | ReplayError> {
325 const connection = snapConnection(app.db);
326 return connection === undefined ? "no_connection" : planOf(await pastDecisions(app, connection));
327 }
328
329 /** Send past decisions to Snap, two at a time, behind the caller. A refused key or spent credit ends it. */
330 export async function startReplay(app: App): Promise<ReplayPlan | ReplayError> {
331 const connection = snapConnection(app.db);
332 if (connection === undefined) return "no_connection";
333 if (replays.has(app)) return "running";
334 const past = await pastDecisions(app, connection);
335 // Asked again after the await: two starts at once must not both run.
336 if (replays.has(app)) return "running";
337 const work: { p: Past; source: Source }[] = [...past.map((p) => ({ p, source: "replay" as const })), ...twiceOf(past).map((p) => ({ p, source: "repeat" as const }))];
338 const replay: Replay = { total: work.length, done: 0, stop: new AbortController() };
339 replays.set(app, replay);
340 const over = AbortSignal.any([app.closing.signal, replay.stop.signal]);
341 let next = 0;
342 const worker = async (): Promise<void> => {
343 for (let w = work[next++]; w !== undefined && !over.aborted; w = work[next++]) {
344 for (let attempt = 1; attempt <= TRIES && !over.aborted; attempt++) {
345 const code = await askAndKeep(app, connection, w.p.id, w.p.kind, w.p.state, w.p.questions, w.source, AbortSignal.any([over, AbortSignal.timeout(REPLAY_TIMEOUT_MS)]));
346 if (code !== undefined && REFUSED.has(code)) replay.stop.abort();
347 if (code === undefined || !(code === "429" || code.startsWith("5"))) break;
348 // The service sends no Retry-After: double the wait, with some of it left to chance.
349 await Bun.sleep(500 * 2 ** attempt * (0.5 + Math.random()));
350 }
351 replay.done++;
352 }
353 };
354 void background(
355 "decider-replay",
356 async () => {
357 try {
358 await Promise.all(Array.from({ length: REPLAY_AT_ONCE }, worker));
359 } finally {
360 replays.delete(app);
361 }
362 },
363 undefined,
364 app,
365 );
366 return planOf(past);
367 }
368
369 /** End a running replay; whether there was one. */
370 export function stopReplay(app: App): boolean {
371 const replay = replays.get(app);
372 replay?.stop.abort();
373 return replay !== undefined;
374 }
375
376 export const replayRunning = (app: App): { readonly done: number; readonly total: number } | undefined => {
377 const r = replays.get(app);
378 return r === undefined ? undefined : { done: r.done, total: r.total };
379 };
src/crew/snap_report.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * What the shadow decider's answers say beside the decider's (`snap.ts`), and what they cannot.
3 *
4 * Two comparisons are fair. Agreement: the same decision, two answers. And, among `retry` decisions the
5 * decider answered `again`, whether Snap would have said `stop` where the pull's next check went red:
6 * there the try was made, so its result is known. A `stop` shows nothing of the try it was against, and
7 * a `next` has an outcome only for the issue that was picked, so neither says who was right. The next
8 * check is read from the runs and not from the ledger's outcome, which a preview's deploy writes too.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import { SHADOW_KINDS, SNAP_USD_PER_M, shadowStopped, shadowUnconnected } from "./snap.ts";
13
14 /** The newest rows a report reads: a whole replay and some weeks of live answers. */
15 const ROWS = 2_000;
16
17 interface Row {
18 kind: string;
19 source: string;
20 jev: string;
21 jev_p: number;
22 snap: string | null;
23 probabilities: string | null;
24 ms: number;
25 tokens: number;
26 error: string | null;
27 decision_id: string;
28 /** The state of the pull's next check after a retry answered `again`; null when there is none. */
29 next_check: string | null;
30 }
31
32 const pct = (n: number, of: number): string => (of === 0 ? "none" : `${Math.round((100 * n) / of)}%`);
33 const at = (sorted: readonly number[], q: number): number => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
34 const chance = (r: Row, option: string): number => {
35 try {
36 const p = (JSON.parse(r.probabilities ?? "{}") as Record<string, unknown>)[option];
37 return typeof p === "number" ? p : 0;
38 } catch {
39 return 0;
40 }
41 };
42
43 /** How often a forecast of `green` came true, by how sure it was. */
44 function calibration(said: readonly { readonly p: number; readonly green: boolean }[]): string {
45 const bands: readonly (readonly [number, number])[] = [[0, 0.5], [0.5, 0.7], [0.7, 0.9], [0.9, 1.01]];
46 return bands
47 .map(([lo, hi]) => {
48 const inBand = said.filter((s) => s.p >= lo && s.p < hi);
49 return `${Math.round(lo * 100)}-${Math.min(100, Math.round(hi * 100))}% sure: green ${pct(inBand.filter((s) => s.green).length, inBand.length)} of ${inBand.length}`;
50 })
51 .join("; ");
52 }
53
54 /** The report's lines, the limits of each comparison among them. */
55 export function shadowReport(db: Database): string[] {
56 const rows = db
57 .query<Row, [number]>(
58 `SELECT d.kind, s.source, d.answer AS jev, d.p AS jev_p, s.answer AS snap, s.probabilities, s.ms, s.input_tokens AS tokens,
59 s.error, s.decision_id,
60 CASE WHEN d.kind = 'retry' AND d.answer = 'again' THEN
61 (SELECT r.state FROM run r WHERE r.issue_id = d.issue_id AND r.kind = 'check' AND r.state IN ('ok', 'failed')
62 AND r.created_at > d.created_at ORDER BY r.id LIMIT 1) END AS next_check
63 FROM decision_shadow s JOIN decision d ON d.id = s.decision_id ORDER BY s.created_at DESC LIMIT ?1`,
64 )
65 .all(ROWS);
66 const unconnected = shadowUnconnected(db);
67 const note = unconnected === undefined ? [] : [`Nothing is sent: ${unconnected}.`];
68 if (rows.length === 0) return [...note, "Snap has not been asked anything yet."];
69 const lines: string[] = [...note];
70 if (rows.length === ROWS) lines.push(`Only the newest ${ROWS} answers are read.`);
71 const answered = rows.filter((r) => r.error === null && r.snap !== null);
72 for (const kind of SHADOW_KINDS) {
73 for (const source of ["live", "replay"]) {
74 const of = answered.filter((r) => r.kind === kind && r.source === source);
75 if (of.length === 0) continue;
76 const same = of.filter((r) => r.snap === r.jev).length;
77 lines.push(`${kind}, ${source}: the same answer ${pct(same, of.length)} of ${of.length}.${source === "replay" ? " A replay asks today's words about a past state, not the question as it was." : ""}`);
78 if (kind !== "retry") continue;
79 const tried = of.flatMap((r) => (r.next_check === null ? [] : [{ r, green: r.next_check === "ok" }]));
80 const red = tried.filter((t) => !t.green);
81 const green = tried.filter((t) => t.green);
82 lines.push(
83 `retry, ${source}, where the decider said again and the pull's next check is known (${tried.length}): of ${red.length} that went red Snap said stop to ${pct(red.filter((t) => t.r.snap === "stop").length, red.length)}; of ${green.length} that went green, to ${pct(green.filter((t) => t.r.snap === "stop").length, green.length)}.`,
84 ` Snap's chance of again: ${calibration(tried.map((t) => ({ p: chance(t.r, "again"), green: t.green })))}`,
85 ` The decider's: ${calibration(tried.map((t) => ({ p: t.r.jev_p, green: t.green })))}`,
86 );
87 }
88 }
89 const first = new Map(answered.filter((r) => r.source === "replay").map((r) => [r.decision_id, r]));
90 const twice = answered.filter((r) => r.source === "repeat" && first.has(r.decision_id));
91 if (twice.length > 0) {
92 const moved = twice.filter((r) => first.get(r.decision_id)!.snap !== r.snap).length;
93 lines.push(`Asked twice (${twice.length}): Snap changed its answer ${pct(moved, twice.length)} of the time.`);
94 }
95 const ms = answered.map((r) => r.ms).sort((a, b) => a - b);
96 const tokens = rows.reduce((n, r) => n + r.tokens, 0);
97 const failed = rows.filter((r) => r.error !== null);
98 lines.push(`Time: p50 ${at(ms, 0.5)} ms, p95 ${at(ms, 0.95)} ms over ${ms.length} answers. Cost: ${tokens} input tokens, about $${((tokens / 1e6) * SNAP_USD_PER_M).toFixed(3)}.`);
99 if (failed.length > 0) lines.push(`No answer ${failed.length} times: ${[...new Set(failed.map((r) => r.error))].join(", ")}.`);
100 const stopped = shadowStopped(db);
101 if (stopped !== undefined) lines.push(`Stopped: the service answered ${stopped}. Saving the limit decider.shadow_per_day again lets it go on.`);
102 if (answered.some((r) => r.kind === "retry"))
103 lines.push("A builder's rework nearly always came between a retry answer and the next check, so that check judges the rework, not the state Snap was shown.");
104 lines.push("Not answered here: who was right on next (only the issue picked has an outcome), or on a stop (the try it was against was not what it asked).");
105 return lines;
106 }
src/http/mcp/tools/decider_shadow.ts added +36
@@ -0,0 +1,36 @@
1 import { SNAP_MODEL, planReplay, replayRunning, startReplay, stopReplay, type ReplayError } from "../../../crew/snap.ts";
2 import { shadowReport } from "../../../crew/snap_report.ts";
3 import { scopeAllows } from "../../../core/tokens.ts";
4 import { bad, good, type Tool } from "../shared.ts";
5
6 const REFUSED: Record<ReplayError, string> = {
7 no_connection: "no saved connection named subq with a key and an owner",
8 running: "a replay is running: action stop with dryRun: false ends it",
9 };
10
11 export const tool: Tool = {
12 name: "decider_shadow",
13 doc: "`{ action?, dryRun? }` (forge admin): SubQ Snap compared with the decider. No action is the report. `action: replay` says what 500 past decisions would cost, and sends them with `dryRun: false` and an admin token; `action: stop` ends it, the same way. The live shadow is the limit `decider.shadow_per_day`",
14 description: "Admin: Snap beside the decider: report, `replay`, `stop`.",
15 inputSchema: {
16 type: "object",
17 properties: { action: { type: "string", enum: ["report", "replay", "stop"] }, dryRun: { type: "boolean" } },
18 },
19 writes: true,
20 adminOnly: true,
21 dryByDefault: true,
22 readsWithout: "action",
23 async run(ctx, _user, args) {
24 const action = args["action"] ?? "report";
25 if (action === "report") return good({ report: shadowReport(ctx.app.db), ...(replayRunning(ctx.app) === undefined ? {} : { replay: replayRunning(ctx.app) }) });
26 // The report and the plans are reads; what sends or ends a replay is an admin token's.
27 const does = args["dryRun"] === false;

This refusal is correct, but no test would fail without it. Add the cases listed in point 1 of the review body.

28 if (does && !scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "starting or ending a replay needs an admin token");
29 if (action === "stop" && !does) return good({ says: "This would end the replay. Send dryRun: false to do it." });
30 if (action === "stop") return good({ says: stopReplay(ctx.app) ? "The replay ends after the calls in flight." : "No replay was running." });
31 const plan = does ? await startReplay(ctx.app) : await planReplay(ctx.app);
32 if (typeof plan === "string") return bad(plan, REFUSED[plan]);
33 const what = `${plan.decisions} past decisions, ${plan.repeats} of them twice, to ${SNAP_MODEL}: about ${plan.tokens} input tokens, $${plan.usd.toFixed(3)}. A retry decision holds the last lines of a check's log.`;
34 return good({ says: does ? `Sending ${what}` : `Would send ${what} Send dryRun: false to start.`, ...plan });
35 },
36 };
src/http/mcp/tools/index.ts +1
@@ -57,6 +57,7 @@ export { tool as crew_accounts } from "./crew_accounts.ts";
5757 export { tool as crew_devices } from "./crew_devices.ts";
5858 export { tool as cut_wave } from "./cut_wave.ts";
5959 export { tool as data } from "./data.ts";
60 export { tool as decider_shadow } from "./decider_shadow.ts";
6061 export { tool as decisions_by } from "./decisions_by.ts";
6162 export { tool as desk } from "./desk.ts";
6263 export { tool as detach } from "./detach.ts";
src/settings/limits.ts +10 −1
@@ -80,7 +80,8 @@ export type LimitKey =
8080 | "retention.deploy_pull_days"
8181 | "sampler.rows_per_source"
8282 | "boards.query_rows_max"
83 | "security.sweep_max_usd";
83 | "security.sweep_max_usd"
84 | "decider.shadow_per_day";
8485
8586 export interface LimitDef {
8687 readonly label: string;
@@ -432,6 +433,14 @@ export const LIMITS: Record<LimitKey, LimitDef> = {
432433 max: 10_000,
433434 reason: "An offer becomes a pull a person must read, so one address may send only a few an hour; the per-minute limit stops a burst, this one stops a drip.",
434435 },
436 "decider.shadow_per_day": {
437 label: "Decisions a day also sent to SubQ Snap, for comparison only",
438 unit: "calls, 0 is off",
439 default: 0,
440 min: 0,
441 max: 20_000,
442 reason: "Each one sends what the decider saw, a check log's last lines among it, to a second company; only public, unsealed work of the saved subq connection's owner goes.",
443 },
435444 "model_review.auto": {
436445 label: "Weekly model review applies a cheaper model on its own",
437446 unit: "0 asks first, 1 applies",
src/system/retention.ts +3 −1
@@ -53,6 +53,7 @@ import {
5353 TICK_ROWS,
5454 } from "./retention_events.ts";
5555 import { pruneSamples, ROW_CAP } from "./retention_samples.ts";
56 import { pruneShadows } from "../crew/snap.ts";
5657 import { pruneTelemetry, type Cursor } from "./retention_telemetry.ts";
5758 import { pruneGameCommands } from "./retention_games.ts";
5859 import { giveBack } from "./retention_vacuum.ts";
@@ -191,7 +192,8 @@ export function retentionJobs(app: App): Retention {
191192 withoutWaiting(db, () => {
192193 const t = pruneTelemetry(db, now, walked);
193194 const g = pruneGameCommands(db, now);
194 return { deleted: t.deleted + g.deleted, more: t.more || g.more };
195 const s = pruneShadows(db, now);
196 return { deleted: t.deleted + g.deleted + s.deleted, more: t.more || g.more || s.more };
195197 }),
196198 );
197199 return r === undefined ? { did: 0, more: false } : { did: r.deleted, more: r.more };
src/tui/screens/decider.ts +7 −1
@@ -18,6 +18,8 @@ import {
1818 } from "../../core/decisions.ts";
1919 import { efficiencyForRepos, perShippedWords } from "../../core/efficiency.ts";
2020 import { deciderSentence } from "../../story/words.ts";
21 import { shadowReport } from "../../crew/snap_report.ts";
22 import { limitValue } from "../../settings/limits.ts";
2123 import { getIssuesByIds } from "../../core/issues.ts";
2224 import { getReposByIds } from "../../core/repos.ts";
2325 import type { User } from "../../core/users.ts";
@@ -66,6 +68,10 @@ export function efficiencyLines(app: App, viewer: User | undefined, now = new Da
6668 return more <= 0 ? lines : [...lines.slice(0, COST_LINES), `+${more} more app${more === 1 ? "" : "s"}`];
6769 }
6870
71 /** What Snap's shadow says beside the decider (`crew/snap_report.ts`), to a forge admin while it is on. */
72 export const shadowLines = (app: App, viewer: User | undefined): string[] =>
73 viewer?.isAdmin === true && limitValue(app.db, "decider.shadow_per_day") > 0 ? shadowReport(app.db) : [];
74
6975 /** The ledger rows behind one pile's count today, newest first. */
7076 export function deciderRows(app: App, viewer: User | undefined, pile: DeciderPile, now = new Date()): DeciderRow[] {
7177 const db: Database = app.db;
@@ -97,7 +103,7 @@ export function deciderScreen(f: Session, ctx: Ctx, first: DeciderPile = "closed
97103 let costs: string[] = [];
98104 const read = (): void => {
99105 line = deciderLine(f.app, f.user);
100 costs = efficiencyLines(f.app, f.user);
106 costs = [...efficiencyLines(f.app, f.user), ...shadowLines(f.app, f.user)];
101107 rows = deciderRows(f.app, f.user, pile);
102108 state.clamp(rows.length);
103109 };
test/conversation-ask.test.ts +5
@@ -280,6 +280,11 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
280280 { id: "s1", usd: null },
281281 "Clear subscription s1's lifetime budget.",
282282 ],
283 [
284 "decider_shadow",
285 { action: "replay", dryRun: false },
286 "Send up to 500 past decisions to SubQ Snap, check log lines among them.",
287 ],
283288 [
284289 "subscription_headroom",
285290 { id: "s1", percent: 20 },
test/decider-shadow.test.ts added +289
@@ -0,0 +1,289 @@
1 /**
2 * SubQ Snap in shadow (crew/snap.ts): off by default, sent only for public, unsealed work of the
3 * connection's owner, never waited for, never deciding, and stopped by a refused key.
4 */
5 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { openIssue } from "../src/actions/issues.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { saveConnection } from "../src/core/connections.ts";
13 import { getDecision, recordDecision, setOutcome } from "../src/core/decisions.ts";
14 import { getIssueById, type Issue } from "../src/core/issues.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { certain, type Answer, type Answers, type Decider, type Questions } from "../src/crew/decide.ts";
19 import { decideAndRecord } from "../src/crew/ledger.ts";
20 import { planReplay, pruneShadows, questionsOf, replayRunning, SHADOW_KEEP_DAYS, shadowStopped, snapFetch, startReplay } from "../src/crew/snap.ts";
21 import { shadowReport } from "../src/crew/snap_report.ts";
22 import { serve } from "../src/http/server.ts";
23 import { setLimit } from "../src/settings/limits.ts";
24 import { shadowLines } from "../src/tui/screens/decider.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { promote } from "./helpers/members.ts";
27 import { pollUntil } from "./helpers/poll.ts";
28
29 quietLogs();
30
31 const KEY = "subq-key-for-the-test";
32 const QUESTIONS = { retry: { options: ["again", "stop"], about: "try?" }, cause: { options: ["change", "base"] } };
33 const jev: Decider = {
34 name: "typesafe",
35 async decide<Q extends Questions>(_state: unknown, questions: Q): Promise<Answers<Q>> {
36 const out: Record<string, Answer> = {};
37 for (const [k, v] of Object.entries(questions)) out[k] = { choice: v.options[0]!, p: 0.8, probabilities: { [v.options[0]!]: 0.8 } };
38 return out as Answers<Q>;
39 },
40 };
41 const real = snapFetch.fetch;
42
43 let dataDir: string;
44 let app: App;
45 let alice: User;
46 let bob: User;
47 let repos: { mine: Repo; secret: Repo; theirs: Repo };
48 let calls: { url: string; auth: string; body: unknown }[] = [];
49 let answer: () => Response | Promise<Response>;
50
51 const snapSays = (choice: string, p = 0.9) => () =>
52 Response.json({ answers: { retry: { type: "choice", choice, probabilities: { again: choice === "again" ? p : 1 - p, stop: choice === "stop" ? p : 1 - p }, confidence: p }, next: { type: "choice", choice: "2", probabilities: { "1": 0.3, "2": 0.7 } } }, usage: { input_tokens: 1000, output_tokens: 0 } });
53 const issue = (repo: Repo, by: User, o: { sealed?: boolean } = {}): Issue => {
54 const made = openIssue(app, by, repo, { title: "a red pull", ...o });
55 if (!made.ok) throw new Error(String(made.error));
56 return getIssueById(app.db, made.value.id)!;
57 };
58 const decide = (repo: Repo, about: Issue) =>
59 decideAndRecord(app, { kind: "retry", repo, issue: about }, { log: ["red"] }, QUESTIONS, () => ({ retry: certain(["again", "stop"], "again"), cause: certain(["change", "base"], "change") }));
60 interface ShadowRow {
61 decision_id: string;
62 source: string;
63 answer: string | null;
64 p: number | null;
65 probabilities: string | null;
66 error: string | null;
67 }
68 const shadows = (): ShadowRow[] => app.db.query<ShadowRow, []>("SELECT * FROM decision_shadow ORDER BY created_at, id").all();
69 const on = (n = 100) => setLimit(app.db, "decider.shadow_per_day", n, alice.id);
70
71 beforeAll(async () => {
72 dataDir = mkdtempSync(join(tmpdir(), "forge-decider-shadow-"));
73 app = createApp({ dataDir, port: 0, decider: jev });
74 const mk = async (username: string): Promise<User> => {
75 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: username === "alice" });
76 if (!r.ok) throw new Error(r.error);
77 return r.value;
78 };
79 alice = await mk("alice");
80 bob = await mk("bob");
81 // A guest may not own a repository; bob owns one.
82 promote(app.db, bob);
83 const repo = async (by: User, name: string, visibility: "public" | "private"): Promise<Repo> => {
84 const r = await createRepo(app, by, { name, visibility });
85 if (!r.ok) throw new Error(String(r.error));
86 return r.value;
87 };
88 repos = { mine: await repo(alice, "mine", "public"), secret: await repo(alice, "secret", "private"), theirs: await repo(bob, "theirs", "public") };
89 const saved = saveConnection(app.db, dataDir, { name: "subq", protocol: "openai", base: "https://api.subq.example/v1", key: KEY, scope: "forge", userId: alice.id, models: [], said: "ok" });
90 if (!saved.ok) throw new Error(String(saved.error));
91 snapFetch.fetch = async (url, init) => {
92 calls.push({ url, auth: new Headers(init?.headers).get("authorization") ?? "", body: JSON.parse(String(init?.body)) });
93 return answer();
94 };
95 }, 60_000);
96 afterAll(() => {
97 snapFetch.fetch = real;
98 app.close();
99 rmSync(dataDir, { recursive: true, force: true });
100 });
101 beforeEach(() => {
102 app.db.run("DELETE FROM decision_shadow");
103 calls = [];
104 answer = snapSays("stop");
105 setLimit(app.db, "decider.shadow_per_day", null, alice.id);
106 });
107
108 test("off by default: nothing is sent", async () => {
109 await decide(repos.mine, issue(repos.mine, alice));
110 expect(calls).toEqual([]);
111 expect(shadowLines(app, alice)).toEqual([]);
112 });
113
114 test("on: the same state and questions go to the connection's host with its key, and the decision is as it was", async () => {
115 on();
116 const made = await decide(repos.mine, issue(repos.mine, alice));
117 // The forge's own answer stands, whatever Snap says.
118 expect(made.answers.retry.choice).toBe("again");
119 await pollUntil(() => shadows().length === 1, "the shadow's row");
120 expect(calls).toHaveLength(1);
121 expect(calls[0]!.url).toBe("https://api.subq.example/v1/systemone");
122 expect(calls[0]!.auth).toBe(`Bearer ${KEY}`);
123 expect(calls[0]!.body).toMatchObject({ model: "subq-snap-1.2", state: { log: ["red"] }, questions: { retry: { type: "choice", criteria: { again: null, stop: null } } } });
124 const row = shadows()[0]!;
125 expect(row).toMatchObject({ decision_id: made.decision.id, source: "live", answer: "stop", p: 0.9, input_tokens: 1000, error: null });
126 expect(JSON.parse(row.probabilities ?? "{}")).toMatchObject({ stop: 0.9 });
127 expect(getDecision(app.db, made.decision.id)).toMatchObject({ answer: "again", by: "typesafe", p: 0.8 });
128 expect(JSON.stringify(shadows())).not.toContain(KEY);
129 });
130
131 test("a shadow that cannot start costs no decision", async () => {
132 on();
133 app.db.run("ALTER TABLE decision_shadow RENAME TO decision_shadow_away");
134 try {
135 const made = await decide(repos.mine, issue(repos.mine, alice));
136 expect(made.answers.retry.choice).toBe("again");
137 expect(getDecision(app.db, made.decision.id)?.answer).toBe("again");
138 expect(calls).toEqual([]);
139 } finally {
140 app.db.run("ALTER TABLE decision_shadow_away RENAME TO decision_shadow");
141 }
142 });
143
144 test("private, sealed and other people's work is never sent", async () => {
145 on();
146 await decide(repos.secret, issue(repos.secret, alice));
147 await decide(repos.theirs, issue(repos.theirs, bob));
148 await decide(repos.mine, issue(repos.mine, alice, { sealed: true }));
149 expect(calls).toEqual([]);
150 });
151
152 test("a slow Snap holds no decision, two calls are the most at once, and the day's limit ends it", async () => {
153 on(3);
154 const gate = Promise.withResolvers<void>();
155 answer = async () => {
156 await gate.promise;
157 return snapSays("again")();
158 };
159 for (let i = 0; i < 4; i++) await decide(repos.mine, issue(repos.mine, alice));
160 expect(calls).toHaveLength(2);
161 expect(shadows()).toEqual([]);
162 gate.resolve();
163 await pollUntil(() => shadows().length === 2, "both rows");
164 for (let i = 0; i < 3; i++) {
165 await decide(repos.mine, issue(repos.mine, alice));
166 await pollUntil(() => shadows().length === 3, "the third row");
167 }
168 expect(calls).toHaveLength(3);
169 });
170
171 test("a refused key or spent credit stops it until the limit is saved again; a body is never kept", async () => {
172 on();
173 answer = () => Response.json({ detail: { error_type: "x", message: "SECRET WORDS" } }, { status: 402 });
174 await decide(repos.mine, issue(repos.mine, alice));
175 await pollUntil(() => shadows().length === 1, "the refusal");
176 expect(shadows()[0]).toMatchObject({ error: "402", answer: null });
177 expect(JSON.stringify(shadows())).not.toContain("SECRET WORDS");
178 expect(shadowStopped(app.db)).toBe("402");
179 await decide(repos.mine, issue(repos.mine, alice));
180 expect(calls).toHaveLength(1);
181 expect(shadowReport(app.db).join("\n")).toContain("Stopped: the service answered 402");
182 on();
183 expect(shadowStopped(app.db)).toBeUndefined();
184 });
185
186 test("a replay says its cost first, asks past decisions with an outcome, and reports only what is fair", async () => {
187 const past = (kind: "retry" | "next", answered: string, state: unknown, outcome: string | undefined, repo = repos.mine) => {
188 const about = issue(repo, repo === repos.theirs ? bob : alice);
189 const d = recordDecision(app.db, { kind, repoId: repo.id, issueId: about.id, state, answer: answered, p: 0.8, by: "typesafe", ms: 1 });
190 if (outcome !== undefined) setOutcome(app.db, d.id, outcome);
191 return { d, about };
192 };
193 const tried = past("retry", "again", { log: ["red"] }, "green");
194 // The ledger says green, as a deploy may; the pull's own next check went red.
195 app.db.query("INSERT INTO run (id, repo_id, kind, issue_id, state, created_at) VALUES ('zz-check', ?1, 'check', ?2, 'failed', strftime('%Y-%m-%dT%H:%M:%fZ','now','+1 minute'))").run(repos.mine.id, tried.about.id);
196 past("next", "1", { ready: [{ number: 1, title: "one", holdsUp: 2 }, { number: 2, title: "two", holdsUp: 0 }] }, "shipped");
197 past("retry", "again", { log: [] }, undefined);
198 past("retry", "again", { log: [] }, "green", repos.theirs);
199 const plan = await planReplay(app);
200 expect(calls).toEqual([]);
201 expect(plan).toMatchObject({ decisions: 2, repeats: 2 });
202 if (typeof plan === "string") throw new Error(plan);
203 expect(plan.usd).toBeGreaterThan(0);
204 expect(await startReplay(app)).toMatchObject({ decisions: 2 });
205 expect(await startReplay(app)).toBe("running");
206 await pollUntil(() => replayRunning(app) === undefined, "the replay's end");
207 expect(shadows().map((s) => s.source).sort()).toEqual(["repeat", "repeat", "replay", "replay"]);
208 const report = shadowReport(app.db).join("\n");
209 expect(report).toContain("retry, replay: the same answer 0% of 1");
210 expect(report).toContain("next, replay: the same answer 0% of 1");
211 expect(report).toContain("of 1 that went red Snap said stop to 100%");
212 expect(report).toContain("Asked twice (2): Snap changed its answer 0% of the time");
213 expect(report).toContain("4000 input tokens, about $0.000");
214 expect(report).toContain("Not answered here: who was right on next");
215 expect(report).toContain("A builder's rework nearly always came between a retry answer and the next check");
216 });
217
218 test("a past next question is rebuilt from its ready list; one with too little in it is left out", () => {
219 const words = { retry: QUESTIONS, nextAbout: "which?" };
220 const ready = [{ number: 7, title: "seven", holdsUp: 1 }, { number: 8, sealed: true, title: "never said" }];
221 expect(questionsOf("next", { ready }, words)).toEqual({ next: { options: ["7", "8"], about: "which?", describe: { "7": "#7 seven (holds up 1)", "8": "#8 (sealed)" } } });
222 expect(questionsOf("next", { ready: ready.slice(0, 1) }, words)).toBeUndefined();
223 expect(questionsOf("next", "text", words)).toBeUndefined();
224 });
225
226 test("a connection renamed away sends nothing, and the report says why", async () => {
227 on();
228 app.db.run("UPDATE subscription SET name = 'other' WHERE name = 'subq'");
229 try {
230 await decide(repos.mine, issue(repos.mine, alice));
231 expect(calls).toEqual([]);
232 expect(shadowReport(app.db)[0]).toContain("Nothing is sent: no connection named subq");
233 expect(await planReplay(app)).toBe("no_connection");
234 } finally {
235 app.db.run("UPDATE subscription SET name = 'subq' WHERE name = 'other'");
236 }
237 expect(shadowReport(app.db).join("")).not.toContain("Nothing is sent");
238 });
239
240 test("rows past the window go, a slice at a time, and newer ones stay", async () => {
241 on();
242 const { decision } = await decide(repos.mine, issue(repos.mine, alice));
243 await pollUntil(() => shadows().length === 1, "the row");
244 const now = Date.now();
245 const add = app.db.query("INSERT INTO decision_shadow (id, decision_id, source, model, created_at) VALUES (?1, ?2, 'live', 'm', ?3)");
246 for (let i = 0; i < 3; i++) add.run(`old${i}`, decision.id, new Date(now - (SHADOW_KEEP_DAYS + 1) * 86_400_000).toISOString());
247 expect(pruneShadows(app.db, now, 2)).toEqual({ deleted: 2, more: true });
248 expect(pruneShadows(app.db, now, 2)).toEqual({ deleted: 1, more: false });
249 expect(shadows()).toHaveLength(1);
250 });
251
252 test("a reply past the byte cap is bad_body, though its JSON holds an answer", async () => {
253 on();
254 const pad = "x".repeat(100_000);
255 answer = () => Response.json({ pad, answers: { retry: { choice: "stop" } } });
256 await decide(repos.mine, issue(repos.mine, alice));
257 await pollUntil(() => shadows().length === 1, "the refused reply's row");
258 expect(shadows()[0]).toMatchObject({ error: "bad_body", answer: null });
259 });
260
261 test("MCP: no tool for a non-admin; an admin's rw token reads and plans, and neither starts nor ends a replay", async () => {
262 const past = recordDecision(app.db, { kind: "retry", repoId: repos.mine.id, issueId: issue(repos.mine, alice).id, state: { log: ["red"] }, answer: "again", p: 0.8, by: "typesafe", ms: 1 });
263 setOutcome(app.db, past.id, "green");
264 const servers = await serve(app);
265 try {
266 const call = async (token: string, args: Record<string, unknown>): Promise<string> => {
267 const res = await fetch(`${servers.url}/mcp`, {
268 method: "POST",
269 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
270 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "decider_shadow", arguments: args } }),
271 });
272 return JSON.stringify(await res.json());
273 };
274 // An admin-scope token of an account that is no admin: the account is what is refused.
275 const bobs = createToken(app.db, bob.id, "t", "admin").token;
276 for (const args of [{}, { action: "report" }, { action: "replay" }, { action: "replay", dryRun: false }, { action: "stop", dryRun: false }])
277 expect(await call(bobs, args)).toContain("no tool named decider_shadow");
278 const rw = createToken(app.db, alice.id, "t", "rw").token;
279 for (const action of ["replay", "stop"]) expect(await call(rw, { action, dryRun: false })).toContain("forbidden: starting or ending a replay needs an admin token");
280 expect(await call(rw, { action: "replay" })).toContain("Would send ");
281 expect(await call(rw, { action: "stop" })).toContain("This would end the replay");
282 expect(await call(rw, {})).toContain("report");
283 // There was a past decision to send, and none went.
284 expect([calls, shadows(), replayRunning(app)]).toEqual([[], [], undefined]);
285 } finally {
286 servers.stop();
287 app.db.query("DELETE FROM decision WHERE id = ?1").run(past.id);
288 }
289 });
test/job-slices.test.ts +2
@@ -298,6 +298,8 @@ function jobs(): Record<string, () => unknown> {
298298 * on.
299299 */
300300 const UNTIMED: Record<string, string> = {
301 "decider-shadow": "one call to a second decider after a decision is recorded (crew/snap.ts): a few indexed reads, one insert and a network answer, at most two at once; decider-shadow.test.ts drives it with a fake",
302 "decider-replay": "an admin's replay of at most 500 past decisions (crew/snap.ts): network answers and one insert each, two at once; decider-shadow.test.ts drives it with a fake",
301303 "snapshot-gc": "one full Bun.gc(true) while a snapshot is cut (snapshot/settle.ts), as long as the process's own heap makes it, which a fixture's heap does not; snapshot-settle.test.ts drives it",
302304 "kept-log-flush": "every 2 s: one append of the buffered stall and minute lines to perf/loop.log, rotated past its size (perf/kept_log.ts); perf-kept-log.test.ts drives flush directly",
303305 "snapshot-cut-timeout": "a one-shot timer per file a snapshot cuts (snapshot/cut.ts), fired only when the cutter's worker has not answered within CUT_TIMEOUT_MS: it ends the worker and refuses the jobs it held; snapshot-cut.test.ts drives a silent worker to it",
test/mcp-forge-protocol.test.ts +1
@@ -187,6 +187,7 @@ describe("the forge over MCP: protocol", () => {
187187 "outsiders",
188188 "pane",
189189 "origins",
190 "decider_shadow",
190191 "decisions_by",
191192 "archive",
192193 "detach",
test/mcp-write-scope.test.ts +1
@@ -51,6 +51,7 @@ const ADMIN_ARGS: Record<string, Record<string, unknown>> = {
5151 * generic arguments would only read.
5252 */
5353 const WRITE_ARGS: Record<string, Record<string, unknown>> = {
54 decider_shadow: { action: "replay", dryRun: false },
5455 flow: { kind: "drift", action: "update", repo: "alice/game", pull: 1 },
5556 repo: { repo: "alice/game", action: "open", chapter: "v1", confirm: true },
5657 migrate_data: { repo: "alice/game", dump: "dump.sql", apply: true },

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs