Classify asks an item's due priority and area questions in its one Jev request

A classify request carries priority.jev's impact question when the item's
priority is due, and areas.jev's area question when an issue's area is due
(a pull request's area state adds its paths, so it stays a request of its
own). The answers are settled and stored as the prioritize step and the
area pass do (Haiku where Jev is unsure), and the Plan holds the prioritize
step back while the item's classify Jev call is due, so the two never ask
Jev the same item at once. The request's usage is split over the three
steps' rows in proportion to the request each would have sent alone.

Non-OK Jev API statuses are counted per classify chunk in the job log, and
a failed Workers AI response keeps its retry and rate-limit headers in the
run's error.
This commit is contained in:
aiongg committed 2026-11-25 01:07:04 +00:00
1 parent 55ea620fd5
commit cfdaaae353
13 files changed
+331 -69

No files matched your search

+8 -1
View File
@@ -29,6 +29,13 @@ function readToken(path: string): string {
const fail = (code: number, status: number | null, message: string): JevProc => ({ code, stdout: "", stderr: `jev: ${status === null ? "" : `API error status=${status}: `}${message}\n` });
/** The retry and rate-limit headers of a response, as ` (name: value; ...)`, or "" when it has none: they say which limit a 429 hit. */
export function limitHeaders(h: Headers): string {
const kept: string[] = [];
h.forEach((v, k) => { if (k === "retry-after" || /ratelimit/.test(k)) kept.push(`${k}: ${v.slice(0, 80)}`); });
return kept.length ? ` (${kept.sort().join("; ")})` : "";
}
/** Sends a request in the `jev ask` format (`{state, questions, model?}` as JSON text) to Workers AI. */
export async function askJevCloudflare(cfg: JevCloudflareConfig, body: string, timeoutMs: number, base = "https://api.cloudflare.com"): Promise<JevProc> {
let token: string;
@@ -54,7 +61,7 @@ export async function askJevCloudflare(cfg: JevCloudflareConfig, body: string, t
if (!res.ok) {
let detail = "";
try { detail = ((JSON.parse(text) as { errors?: { message?: string }[] }).errors ?? []).map((x) => x.message).filter(Boolean).join("; "); } catch { /* no detail */ }
return fail(1, res.status, detail.slice(0, 200) || res.statusText);
return fail(1, res.status, `${detail.slice(0, 200) || res.statusText}${limitHeaders(res.headers)}`);
}
let parsed: unknown;
try { parsed = JSON.parse(text); } catch { return { code: 0, stdout: text, stderr: "" }; }
+17
View File
@@ -135,3 +135,20 @@ export function jevFailure(r: { code: number | null; stderr: string }): { kind:
if (/api key/i.test(line)) return { kind: "account", reason: "key rejected" };
return null;
}
// Statuses of Jev API responses that were not OK, counted in this process since the last take: a job logs them per chunk, so a
// provider's request rate limit (status 429) shows in the job log.
const statuses = new Map<string, number>();
/** Counts the API status a failed `jev ask` printed (`jev: API error status=<N> ...`), if any. */
export function noteJevStatus(stderr: string): void {
const status = /API error status=(\d+)/.exec(stderr)?.[1];
if (status !== undefined) statuses.set(status, (statuses.get(status) ?? 0) + 1);
}
/** The counts by status since the last take, and starts counting again. */
export function takeJevStatuses(): Map<string, number> {
const out = new Map(statuses);
statuses.clear();
return out;
}
+8 -4
View File
@@ -210,7 +210,7 @@ export type TieredStep<It, JV, HV, C = void, B = It[]> = {
onJevFailure: "haiku" | "haiku-when-unavailable";
};
export type TieredOpts<It, C> = {
export type TieredOpts<It, C, JV = unknown> = {
ctx?: C;
/** Jev call width (default: the Jev parallelism setting). */
jevWidth?: number | (() => Promise<number>);
@@ -221,6 +221,8 @@ export type TieredOpts<It, C> = {
/** Start the first Haiku batch alone (a failure that stops all calls then shows early). */
first?: boolean;
cancelled?: () => Promise<boolean>;
/** Jev answers already given by ref (asked in another request: src/classify/run.ts runJev); these items are not sent to Jev. */
given?: ReadonlyMap<string, JV>;
};
export type TieredResult<JV, HV> = {
@@ -235,10 +237,12 @@ export type TieredResult<JV, HV> = {
skipped: Set<string>;
};
export async function runTiered<It, JV, HV, C = void, B = It[]>(db: Db, tier: TieredStep<It, JV, HV, C, B>, items: It[], opts: TieredOpts<It, C> = {}): Promise<TieredResult<JV, HV>> {
export async function runTiered<It, JV, HV, C = void, B = It[]>(db: Db, tier: TieredStep<It, JV, HV, C, B>, items: It[], opts: TieredOpts<It, C, JV> = {}): Promise<TieredResult<JV, HV>> {
const out: TieredResult<JV, HV> = { jev: new Map(), haiku: new Map(), alone: new Set(), asked: new Set(), skipped: new Set() };
if (await jevAvailable(db)) {
await pool(items.map((x) => async () => {
for (const x of items) if (opts.given?.has(tier.ref(x))) out.jev.set(tier.ref(x), opts.given.get(tier.ref(x))!);
const toJev = items.filter((x) => !out.jev.has(tier.ref(x)));
if (toJev.length && await jevAvailable(db)) {
await pool(toJev.map((x) => async () => {
if (!await jevAvailable(db)) return;
const r = await runModelStep(db, tier.jev, x, { ctx: opts.ctx, usage: opts.jevUsage?.(x), cancelled: opts.cancelled });
out.jev.set(tier.ref(x), r.ok ? r.value : null);
+13 -4
View File
@@ -6,7 +6,7 @@ import type { Area, AreaItem } from "../areas/types.ts";
import { parsePairReply, type DupePair, type PairAnswer } from "../dupes/pair.ts";
import { carryTexts, lintComparison, parseIssueComparison, parsePrComparison, type CompareIssues, type ComparePrs, type IssueComparison, type PrComparison } from "../dupes/group.ts";
import { jevImpact, parseHaikuImpacts, SURE, type Impact, type JevImpactAnswers } from "../priority/score.ts";
import { renderAreaJev, renderReferenceJev } from "../prompts/index.ts";
import { renderAreaJev, renderClassifyJev, renderReferenceJev, type ClassifyExtras } from "../prompts/index.ts";
import type { ReferenceLintInput } from "../replylint.ts";
import type { ClaudeStep, JevStep, TieredStep } from "./step.ts";
import { parseRefereeReply, type Referee } from "../classify/parse.ts";
@@ -42,10 +42,19 @@ export const CLASSIFY_HAIKU: ClaudeStep<Item[], Verdict[]> = {
return { value: verdicts, rest: leftOf(todo, refOf, missing) };
},
};
export const CLASSIFY_JEV: JevStep<Item, Verdict> = {
/** A classify.jev request: the item, and the questions of priority.jev and areas.jev due for it (renderClassifyJev). */
export type ClassifyAsk = { item: Item } & ClassifyExtras;
/** The verdict, and an answer (null: none valid) for each extra question asked. */
export type ClassifyAnswer = { verdict: Verdict; impact?: JevImpact | null; area?: AreaAnswer | null };
export const CLASSIFY_JEV: JevStep<ClassifyAsk, ClassifyAnswer> = {
provider: "jev", id: "classify.jev",
request: (item) => ({ item }),
parse: (answers, item) => single(answers ? jevVerdict(refOf(item), answers as JevAnswers) : null),
request: (x) => ({ item: x.item, body: renderClassifyJev(x.item, x) }),
// The verdict decides whether the reply counts; an extra answer that is not valid is left to its own step.
parse: (answers, x, ctx) => {
const verdict = answers ? jevVerdict(refOf(x.item), answers as JevAnswers) : null;
if (!verdict) return null;
return { value: { verdict, ...(x.impact && { impact: jevImpact(answers as JevImpactAnswers) }), ...(x.areas && { area: ctx.code === 0 ? jevAreaChoice(answers, x.areas) : null }) } };
},
};
// Priority: Jev's level, Haiku where Jev is under SURE or gave none.
+43 -6
View File
@@ -13,10 +13,11 @@ import { runTiered } from "../agents/step.ts";
import { AREAS } from "../agents/steps.ts";
import { pilotExpr } from "../pilot.ts";
import { cachedDiff, ghDiff, splitDiff } from "../review/diff.ts";
import { settles } from "./parse.ts";
import { settles, type AreaAnswer } from "./parse.ts";
import { currentList, setItemArea } from "./store.ts";
import { AREA_PATHS_MAX, type Area, type AreaItem } from "./types.ts";
import type { Db } from "../db/index.ts";
import * as kx from "../db/kx.ts";
const CHUNK = 40;
@@ -48,8 +49,10 @@ type Due = AreaItem & { head: string | null; version: number };
* Open items of repos with an area list that need an answer. Without `rescan`: never asked, or asked against an older
* list version and unassigned. With `rescan`: also the ones answered "none of these" for the current version.
* Operator-assigned items are never due. Items of repos no Task Runner takes come after the rest before the limit (takersFirst).
* `refs`: only these items. `first`: these items come first and are not counted against the limit.
*/
export async function dueForArea(db: Db, opts: { repo?: string; limit: number; rescan?: boolean }): Promise<Due[]> {
export async function dueForArea(db: Db, opts: { repo?: string; limit: number; rescan?: boolean; refs?: readonly string[]; first?: ReadonlySet<string> }): Promise<Due[]> {
if (opts.refs && !opts.refs.length) return [];
const due: Due[] = await db.all(db.k.selectFrom("items as i").innerJoin("tracked_repos as t", "t.name", "i.repo")
.innerJoin(db.k.selectFrom("area_lists").select(["repo", (eb) => eb.fn.max<number>("version").as("v")]).groupBy("repo").as("l"), (j) => j.onRef("l.repo", "=", "i.repo"))
.leftJoin("item_areas as a", (j) => j.onRef("a.repo", "=", "i.repo").onRef("a.number", "=", "i.number"))
@@ -59,12 +62,38 @@ export async function dueForArea(db: Db, opts: { repo?: string; limit: number; r
.where("i.state", "=", "OPEN")
.where((eb) => notOwnIntegrationExpr(db, eb, "i")).where((eb) => pilotExpr(db, eb, "i"))
.$if(!!opts.repo, (q) => q.where("i.repo", "=", opts.repo!))
.$if(!!opts.refs, (q) => q.where(kx.refIn(db, "i", opts.refs!)))
.where((eb) => eb.or([
eb("a.number", "is", null),
eb.and([eb("a.source", "<>", "operator"), eb.or([eb("a.list_version", "<>", eb.ref("l.v")), ...(opts.rescan ? [eb("a.area", "is", null)] : [])])]),
]))
.orderBy("t.pipeline", "desc").orderBy("i.updated_at", (o) => o.desc().nullsLast()).orderBy("i.repo").orderBy("i.number"));
return (await takersFirst(db, due, (x) => [x.repo], (x) => [x], "areas.haiku")).slice(0, opts.limit);
const ordered = await takersFirst(db, due, (x) => [x.repo], (x) => [x], "areas.haiku");
const first = opts.first;
if (!first?.size) return ordered.slice(0, opts.limit);
return [...ordered.filter((x) => first.has(refOf(x))), ...ordered.filter((x) => !first.has(refOf(x))).slice(0, opts.limit)];
}
/** A repo's list as an area question asks it: its areas and the version they belong to. */
export type AskedList = { areas: Area[]; version: number };
/**
* The current list of each of `refs` that is due for an area answer and whose area question can ride along in its classify request
* (an issue: its area state is the classify state, src/prompts renderClassifyJev), by ref.
*/
export async function areaListsDue(db: Db, refs: readonly { repo: string; number: number; kind: "pr" | "issue" }[]): Promise<Map<string, AskedList>> {
const out = new Map<string, AskedList>();
const due = await dueForArea(db, { limit: Infinity, refs: refs.filter((x) => x.kind === "issue").map(refOf) });
const lists = new Map<string, AskedList | null>();
for (const x of due) {
if (!lists.has(x.repo)) {
const l = await currentList(db, x.repo);
lists.set(x.repo, l && { areas: l.areas, version: l.version });
}
const l = lists.get(x.repo);
if (l) out.set(refOf(x), l);
}
return out;
}
export type AssignParams = {
@@ -77,6 +106,8 @@ export type AssignParams = {
cancelled?: () => Promise<boolean>;
progress?: (line: string) => Promise<void>;
log?: (line: string) => void;
/** Jev answers already given by ref (asked in the item's classify request), with the list version they were asked against; these items go first and are not counted against `limit`. */
given?: ReadonlyMap<string, { answer: AreaAnswer; version: number }>;
};
export type AssignResult = { due: number; jev: number; haiku: number; none: number; left: number };
@@ -103,11 +134,17 @@ async function assignRepo(db: Db, repo: string, due: Due[], p: AssignParams, r:
await jobItem(db, x.repo, x.number, area === null ? "fits none of the areas" : `assigned area ${area}`, p.log);
};
for (let i = 0; i < due.length && !await p.cancelled?.(); i += CHUNK) {
// With neither model available there is nothing to ask, so no diff is fetched.
if (!await jevAvailable(db) && await freeSlots(db) <= 0 && !p.paths) { p.log?.(`areas: no model available for ${repo}`); break; }
// With neither model available there is nothing to ask, so no diff is fetched; answers already given are still stored.
const given = new Map<string, AreaAnswer>();
for (const x of due.slice(i, i + CHUNK)) {
const g = p.given?.get(refOf(x));
if (g && g.version === version) given.set(refOf(x), g.answer);
}
if (!given.size && !await jevAvailable(db) && await freeSlots(db) <= 0 && !p.paths) { p.log?.(`areas: no model available for ${repo}`); break; }
const chunk = await withPaths(due.slice(i, i + CHUNK), p.paths ?? diffPaths(db));
const t = await runTiered(db, AREAS, chunk, {
ctx: { repo, areas: list.areas },
given,
cancelled: p.cancelled,
jevUsage: (x) => ({ run: p.usageRun, agent: `areas-jev-${refOf(x)}`, stage: "areas", model: "jev-latest", items: () => 1, keepEarlier: true }),
haikuUsage: (_batch, n) => ({ run: p.usageRun, agent: `areas-haiku-${repo}-${String(n).padStart(3, "0")}`, stage: "areas", keepEarlier: true }),
@@ -124,7 +161,7 @@ async function assignRepo(db: Db, repo: string, due: Due[], p: AssignParams, r:
/** Assigns areas to the due items. Returns counts; `left` is the due items that got no answer in this pass. */
export async function assignAreas(db: Db, p: AssignParams): Promise<AssignResult> {
const due = await dueForArea(db, { repo: p.repo, limit: p.limit, rescan: p.rescan });
const due = await dueForArea(db, { repo: p.repo, limit: p.limit, rescan: p.rescan, first: p.given && new Set(p.given.keys()) });
const r: AssignResult = { due: due.length, jev: 0, haiku: 0, none: 0, left: 0 };
const byRepo = new Map<string, Due[]>();
for (const x of due) byRepo.set(x.repo, [...(byRepo.get(x.repo) ?? []), x]);
+55 -11
View File
@@ -7,7 +7,7 @@ import type { ItemRef } from "../../web/src/api/types.ts";
import { createHash } from "node:crypto";
import { jevParallel } from "../agents/accounts.ts";
import { askJevCloudflare, jevCloudflareConfig } from "../agents/jev-cloudflare.ts";
import { JEV_UNREADABLE_SUMMARY, jevAvailable, jevEnv, jevFailure, markJevUnavailable, markJevUnreadable, markJevWorking } from "../agents/jev.ts";
import { JEV_UNREADABLE_SUMMARY, jevAvailable, jevEnv, jevFailure, markJevUnavailable, markJevUnreadable, markJevWorking, noteJevStatus } from "../agents/jev.ts";
import { accountConfigDir, itemRepos, NoTakerError, poolRoom, repoBatches, startClaudeRun, type PoolRoom, startJevRun, tryStartFollowUp, isHalt, type Started } from "../agents/call.ts";
import { touchStore, type KeptSession, type SessionAsk } from "../prepush/resume.ts";
import { finishRun, packText, setRunProgress } from "../agents/runs.ts";
@@ -36,8 +36,9 @@ import { holdCheckouts } from "../sandbox/checkout.ts";
import { sessionStore } from "../sandbox/session-store.ts";
import { defaultWorkspace } from "../sandbox/workspace.ts";
import { runModelStep } from "../agents/step.ts";
import { CLASSIFY_HAIKU, CLASSIFY_JEV } from "../agents/steps.ts";
import { CLAUDE_PROMPTS, JEV_ARGS, JEV_USD_PER_INPUT_TOKEN, JEV_PROMPTS, claudeArgs, claudeParts, claudePromptOf, jevPromptOf, joinParts, renderClaude, renderJev, type ClaudeInput, type ClaudePromptId, type JevPromptId } from "../prompts/index.ts";
import { CLASSIFY_HAIKU, CLASSIFY_JEV, type ClassifyAnswer, type JevImpact } from "../agents/steps.ts";
import type { AreaAnswer } from "../areas/parse.ts";
import { CLAUDE_PROMPTS, JEV_ARGS, JEV_USD_PER_INPUT_TOKEN, JEV_PROMPTS, claudeArgs, claudeParts, claudePromptOf, jevPromptOf, joinParts, renderAreaJev, renderClaude, renderJev, type ClassifyExtras, type ClaudeInput, type ClaudePromptId, type JevPromptId } from "../prompts/index.ts";
import { stripMarks } from "../prompts/harness.ts";
import type { DupePair } from "../dupes/pair.ts";
import { flagsOf, jevVerdict, parseHaikuReply, parseRef, refOf, type Item, type JevAnswers, type Verdict } from "./parse.ts";
@@ -867,6 +868,7 @@ export async function askJev(id: JevPromptId, item: Item | DupePair | { ref: str
} catch { /* the caller reports an unreadable answer */ }
// A step that sums its retries into one row (usage option of runModelStep) saves nothing here.
if (tokens && perCallUsage) await saveUsage(db, String(runId), "jev", id.split(".")[0]!, JEV_PROMPTS[id].models[0]!, 1, { ...tokens, cost: tokens.input * JEV_USD_PER_INPUT_TOKEN }, start, now());
noteJevStatus(r.stderr);
const outage = jevFailure(r);
if (outage) await markJevUnavailable(db, outage.kind, outage.reason);
else if (r.code === 0 && tokens) await markJevWorking(db, Date.parse(start));
@@ -909,26 +911,68 @@ export async function runHaiku(db: Db, runId: string, items: Item[], batchSize =
* have ended (also after a failure), in one write each. `hashes` (by ref) are stored as the verdicts' input_hash. Returns the
* refs whose verdict was saved.
*/
export async function runJev(db: Db, runId: string, items: Item[], width?: number, hashes?: ReadonlyMap<string, string>): Promise<Set<string>> {
/** Answers of the extra questions a chunk's classify requests carried (renderClassifyJev), by ref; only valid ones. */
export type JevExtraAnswers = { impact: Map<string, JevImpact>; area: Map<string, AreaAnswer> };
export type JevRun = { saved: Set<string> } & JevExtraAnswers;
/** Usage agent names of an item's classify request: classify's row, and the rows of the extra steps it asks for. */
export const jevAgents = (ref: string, extra?: ClassifyExtras): string[] => [`jev-${ref}`, ...(extra?.impact ? [`priority-jev-${ref}`] : []), ...(extra?.areas ? [`areas-jev-${ref}`] : [])];
/**
* The usage row of a classify request split into one row per step it asked for, each step's share in proportion to the length of
* the request it would have sent alone; the classify row keeps the rounding remainder, so the rows add up to the call. A share's
* items count is 1 when that step's answer was valid.
*/
function splitUsage(row: UsageRow, item: Item, extra: ClassifyExtras, a: ClassifyAnswer | null): UsageRow[] {
const ref = refOf(item);
const parts = [
{ agent: `jev-${ref}`, stage: row.stage, items: row.items, len: renderJev("classify.jev", item).length },
...(extra.impact ? [{ agent: `priority-jev-${ref}`, stage: "priority", items: a?.impact ? 1 : 0, len: renderJev("priority.jev", item).length }] : []),
...(extra.areas ? [{ agent: `areas-jev-${ref}`, stage: "areas", items: a?.area ? 1 : 0, len: renderAreaJev(item, extra.areas).length }] : []),
];
if (parts.length === 1) return [row];
const total = parts.reduce((n, x) => n + x.len, 0);
const share = (n: number, len: number) => Math.floor((n * len) / total);
const rows = parts.map((x) => {
const input = share(row.u.input, x.len), output = share(row.u.output, x.len);
return { ...row, agent: x.agent, stage: x.stage, items: x.items, u: { ...row.u, input, output } };
});
const first = rows[0]!;
first.u = { ...first.u, input: row.u.input - rows.slice(1).reduce((n, r) => n + r.u.input, 0), output: row.u.output - rows.slice(1).reduce((n, r) => n + r.u.output, 0) };
for (const r of rows) r.u = { ...r.u, cost: r.u.input * JEV_USD_PER_INPUT_TOKEN };
return rows;
}
/**
* Jev classifies `items`, one request per item. `extras`: the questions of priority.jev and areas.jev due for an item, asked in
* the same request; their valid answers are returned for the caller to settle and store, and the request's usage is split over
* the steps (splitUsage).
*/
export async function runJev(db: Db, runId: string, items: Item[], width?: number, hashes?: ReadonlyMap<string, string>, extras?: ReadonlyMap<string, ClassifyExtras>): Promise<JevRun> {
if (width === undefined) width = await jevParallel(db);
// Read once per chunk; a failed call reads it again, since a call that fails is how an outage shows.
let up = await jevAvailable(db);
const sinkUsage: UsageRow[] = [], verdicts: { v: Verdict; hash?: string }[] = [];
let saved: Set<string>;
const out: JevRun = { saved: new Set(), impact: new Map(), area: new Map() };
try {
await pool(items.map((item) => async () => {
// Once a call shows Jev is unavailable, the items still waiting are left for Haiku.
if (!up) return;
const ref = refOf(item);
const r = await runModelStep(db, CLASSIFY_JEV, item, { available: async () => up, usage: { run: runId, agent: `jev-${ref}`, stage: "classify", sink: sinkUsage, items: (ok) => (ok ? 1 : 0), withoutUsage: true, skipWhen: async (x) => !x.ok && !(up = await jevAvailable(db)) } });
if (r.ok) verdicts.push({ v: r.value, ...(hashes?.has(ref) && { hash: hashes.get(ref)! }) });
else if (up = await jevAvailable(db)) console.error(`jev: no valid answer for ${ref}`);
const ref = refOf(item), extra = extras?.get(ref) ?? {};
const mine: UsageRow[] = [];
const r = await runModelStep(db, CLASSIFY_JEV, { item, ...extra }, { available: async () => up, usage: { run: runId, agent: `jev-${ref}`, stage: "classify", sink: mine, items: (ok) => (ok ? 1 : 0), withoutUsage: true, skipWhen: async (x) => !x.ok && !(up = await jevAvailable(db)) } });
for (const row of mine) sinkUsage.push(...splitUsage(row, item, extra, r.ok ? r.value : null));
if (r.ok) {
verdicts.push({ v: r.value.verdict, ...(hashes?.has(ref) && { hash: hashes.get(ref)! }) });
if (r.value.impact) out.impact.set(ref, r.value.impact);
if (r.value.area) out.area.set(ref, r.value.area);
} else if (up = await jevAvailable(db)) console.error(`jev: no valid answer for ${ref}`);
}), width);
} finally {
await saveUsages(db, sinkUsage);
saved = await saveVerdicts(db, "jev", runId, verdicts);
out.saved = await saveVerdicts(db, "jev", runId, verdicts);
}
return saved;
return out;
}
/** A failed CLI result in words: the turn limit by name, else the CLI's text. */
+6 -2
View File
@@ -94,6 +94,9 @@ const WAITS: Partial<Record<ItemState, string>> = {
"waiting-haiku": "Haiku's second opinion", "scope-open": "a scope answer", "scope-due": "the scope question to be asked",
};
/** The item has no priority row at its current text hash; the prioritize step asks it unless a classify request does. */
export const priorityDue = (f: ItemFacts): boolean => f.inScope && !f.integration && f.priorityHash !== f.embedHash;
export function decideItem(f: ItemFacts): ItemPlan {
const state = itemState(f);
const c = f.classification;
@@ -110,8 +113,9 @@ export function decideItem(f: ItemFacts): ItemPlan {
const backoff = !!c.referee?.failedAt && Date.parse(c.referee.failedAt) > f.now - RECOMMEND_RETRY_MS;
// Not while Jev or Haiku is due again: the referee would judge the verdicts they are about to replace.
if (f.run && live && !f.draft && state === "referee-due" && !backoff && !jevDue && !haikuDue) actions.push(act("referee", null, { source: c.referee ? "opus" : "sonnet" }));
// prioritize: no priority row at the current text hash.
if (live && f.priorityHash !== f.embedHash) actions.push(act("prioritize", null));
// prioritize: no priority row at the current text hash. Not while Jev's classify call is due: that request asks the impact
// question too and settles the priority (src/runner/classify.ts), so the two steps never ask Jev the same item at once.
if (priorityDue(f) && !(f.run && live && jevDue)) actions.push(act("prioritize", null));
// embed: every open item, with no scope test.
if (f.embeddedHash !== f.embedHash) actions.push(act("embed", null));
// dupes: items to scan, pairs to check, groups to ask.
+36 -18
View File
@@ -6,7 +6,7 @@
// recomputed from the mirror's reach signals on every pass, without a model.
import { takersFirst } from "../agents/call.ts";
import { runTiered } from "../agents/step.ts";
import { PRIORITY } from "../agents/steps.ts";
import { PRIORITY, type JevImpact } from "../agents/steps.ts";
import { type Item, refOf } from "../classify/parse.ts";
import { fillEmbedHashes } from "../itemhash.ts";
import { reachOfOpenItems } from "./reach.ts";
@@ -19,7 +19,7 @@ import { batches, excluded } from "../db/kx.ts";
const JEV_CHUNK = 40;
const now = () => new Date().toISOString();
type Due = Item & { hash: string };
export type Due = Item & { hash: string };
/** The items the Plans send to rating: no priority row, or one made at other text. */
async function dueItems(db: Db): Promise<Due[]> {
@@ -71,6 +71,25 @@ export async function rescore(db: Db, nowMs: number = Date.now()): Promise<numbe
export type PrioritizeOptions = { limit: number; onSent?: (n: number) => void; cancelled?: () => Promise<boolean>; log?: (line: string) => void };
export type PrioritizeResult = { due: number; sent: number; jev: number; haiku: number; saved: number; rescored: number; haikuAlone: number };
/** Rates one chunk: Jev (skipped for the items in `given`, answered in another request), Haiku where it is unsure, then saves. */
async function rateChunk(db: Db, all: Due[], res: PrioritizeResult, log: (line: string) => void, given?: ReadonlyMap<string, JevImpact>): Promise<void> {
const t = await runTiered(db, PRIORITY, all, given ? { given } : {});
// An item whose Haiku batch no Task Runner could take is left for a later pass, unsaved.
const chunk = all.filter((x) => !t.skipped.has(refOf(x)));
res.sent += chunk.length;
const verdicts = new Map<string, Verdict>();
for (const item of chunk) {
const ref = refOf(item), v = t.jev.get(ref) ?? null;
verdicts.set(ref, { jev: v, haiku: t.haiku.get(ref) ?? null });
if (v) res.jev++;
if (t.haiku.has(ref)) res.haiku++;
}
res.haikuAlone += t.alone.size;
const saved = await save(db, chunk, verdicts);
for (const item of chunk) if (saved.has(refOf(item))) res.saved++;
else log(`prioritize: no valid answer for ${refOf(item)}`);
}
export async function runPrioritize(db: Db, opts: PrioritizeOptions): Promise<PrioritizeResult> {
const log = opts.log ?? (() => {});
await fillEmbedHashes(db);
@@ -80,29 +99,28 @@ export async function runPrioritize(db: Db, opts: PrioritizeOptions): Promise<Pr
log(`prioritize: ${due} items due, taking ${todo.length}`);
const res: PrioritizeResult = { due, sent: 0, jev: 0, haiku: 0, saved: 0, rescored: 0, haikuAlone: 0 };
for (let i = 0; i < todo.length && !await opts.cancelled?.(); i += JEV_CHUNK) {
const all = todo.slice(i, i + JEV_CHUNK);
const t = await runTiered(db, PRIORITY, all);
// An item whose Haiku batch no Task Runner could take is left for a later pass, unsaved.
const chunk = all.filter((x) => !t.skipped.has(refOf(x)));
res.sent += chunk.length;
await rateChunk(db, todo.slice(i, i + JEV_CHUNK), res, log);
opts.onSent?.(res.sent);
const verdicts = new Map<string, Verdict>();
for (const item of chunk) {
const ref = refOf(item), v = t.jev.get(ref) ?? null;
verdicts.set(ref, { jev: v, haiku: t.haiku.get(ref) ?? null });
if (v) res.jev++;
if (t.haiku.has(ref)) res.haiku++;
}
res.haikuAlone += t.alone.size;
const saved = await save(db, chunk, verdicts);
for (const item of chunk) if (saved.has(refOf(item))) res.saved++;
else log(`prioritize: no valid answer for ${refOf(item)}`);
}
res.rescored = await rescore(db);
if (res.haikuAlone) log(`Jev unavailable: Haiku rated ${res.haikuAlone} items`);
return res;
}
/**
* Settles and stores the priority of items whose Jev impact answer came in another request (the classify job asks it with the
* type, src/runner/classify.ts), as runPrioritize does: Haiku decides where Jev is unsure. `hash`: the item's text hash when the
* question was asked. The saved rows make the items no longer due for the prioritize step.
*/
export async function prioritizeAnswered(db: Db, items: readonly Due[], given: ReadonlyMap<string, JevImpact>, opts: { cancelled?: () => Promise<boolean>; log?: (line: string) => void } = {}): Promise<PrioritizeResult> {
const todo = items.filter((x) => given.has(refOf(x)));
const res: PrioritizeResult = { due: todo.length, sent: 0, jev: 0, haiku: 0, saved: 0, rescored: 0, haikuAlone: 0 };
for (let i = 0; i < todo.length && !await opts.cancelled?.(); i += JEV_CHUNK) await rateChunk(db, todo.slice(i, i + JEV_CHUNK), res, opts.log ?? (() => {}), given);
// New rows get their reach now, as a prioritize pass gives its own.
if (res.saved) res.rescored = await rescore(db);
return res;
}
export const commands = {
prioritize: {
summary: "prioritize [--limit N]: Jev (Haiku where unsure) rates the level (P0-P4) of open items without a priority, then recomputes all reach",
+28 -8
View File
@@ -152,7 +152,7 @@ const JEV: JevPrompt = {
id: "classify.jev",
stage: "Classify",
runner: "jev",
purpose: "First sort: the type label with a probability per label, and a yes-probability for each flag, one item per call.",
purpose: "First sort: the type label with a probability per label, and a yes-probability for each flag, one item per call. The same request also asks priority.jev's impact question when the item's priority is due, and areas.jev's area question when an issue's area is due, so an item takes one Jev request.",
models: ["jev-latest"],
placeholders: { item: `The item as one JSON string (the request's state) with ${ITEM_FIELDS}.` },
request: {
@@ -169,7 +169,7 @@ const JEV: JevPrompt = {
},
},
output: `{"answers": {"type": {"choice", "confidence", "probabilities": {label: p}}, "security": {"noul": p}, "needs_decision": {"noul": p}}, "usage": {"input_tokens", "output_tokens"}}`,
validation: "The answer is kept only when type.choice is one of the six labels and both noul answers are numbers. Each flag is a yes from its own noul (security 0.9, needs_decision 0.8), a no below 0.3, and unsure in between; when Jev is unsure, Haiku's answer decides. The probabilities are stored with the verdict. A call without a valid answer is made once more; after that the item is logged and stays unclassified.",
validation: "The answer is kept only when type.choice is one of the six labels and both noul answers are numbers. Each flag is a yes from its own noul (security 0.9, needs_decision 0.8), a no below 0.3, and unsure in between; when Jev is unsure, Haiku's answer decides. The probabilities are stored with the verdict. A call without a valid answer is made once more; after that the item is logged and stays unclassified. Impact and area answers in the same reply are read and settled as priority.jev and areas.jev read theirs; one that is not valid leaves its question to its own step. The reply's tokens are split over the three steps' usage rows in proportion to the length of the request each step would have sent alone.",
limits: { perCall: 1, attempts: 2, timeoutSeconds: 600 },
};
@@ -770,7 +770,7 @@ const PRIORITY_JEV: JevPrompt = {
id: "priority.jev",
stage: "Priority",
runner: "jev",
purpose: "Priority level of an open issue or pull request (P0 to P4, P4 = backlog) with a probability per level, one item per call.",
purpose: "Priority level of an open issue or pull request (P0 to P4, P4 = backlog) with a probability per level, one item per call. In a classify job the question goes in the item's classify.jev request when both are due, and the answer is settled and stored as here.",
models: ["jev-latest"],
placeholders: { item: `The item as one JSON string (the request's state) with ${ITEM_FIELDS}.` },
request: {
@@ -1092,7 +1092,7 @@ const AREAS_JEV: JevPrompt = {
id: "areas.jev",
stage: "Classify",
runner: "jev",
purpose: "Names the area of the app an item belongs to, among the repo's area list plus \"none of these\" (the list's names and descriptions fill the question's criteria), one item per call. Asked only for repos that have an area list.",
purpose: "Names the area of the app an item belongs to, among the repo's area list plus \"none of these\" (the list's names and descriptions fill the question's criteria), one item per call. Asked only for repos that have an area list. In a classify job an issue's question goes in its classify.jev request when both are due (a pull request's state adds its paths, so it is asked on its own).",
models: ["jev-latest"],
placeholders: { item: `The item as one JSON string (the request's state) with ${AREA_ITEM_FIELDS}.` },
request: {
@@ -1624,13 +1624,33 @@ export function withoutRepoDir<T>(input: T): T {
/** An item for the area prompts: the classifier's view plus, for pull requests, the changed paths. */
export const areaItemInput = (i: AreaItem): Record<string, unknown> => ({ ...itemInput(i), ...(i.kind === "pr" && i.paths && { paths: i.paths.slice(0, AREA_PATHS_MAX) }) });
/** The request body for areas.jev: the registered request with the repo's list as the question's criteria. */
export function renderAreaJev(item: AreaItem, areas: Area[]): string {
const req = JEV_PROMPTS["areas.jev"].request;
/** The area question of areas.jev with the repo's list as its criteria. */
function areaQuestion(areas: Area[]): JevQuestion {
const criteria: Record<string, string> = {};
for (const a of areas) criteria[a.name] = a.description;
criteria[NONE_OF_THESE] = "No area of the list fits the item well.";
return JSON.stringify({ ...req, state: JSON.stringify(areaItemInput(item)), questions: { area: { ...req.questions.area!, criteria } } });
return { ...JEV_PROMPTS["areas.jev"].request.questions.area!, criteria };
}
/** The request body for areas.jev: the registered request with the repo's list as the question's criteria. */
export function renderAreaJev(item: AreaItem, areas: Area[]): string {
const req = JEV_PROMPTS["areas.jev"].request;
return JSON.stringify({ ...req, state: JSON.stringify(areaItemInput(item)), questions: { area: areaQuestion(areas) } });
}
/** The other per-item questions a classify.jev request carries: priority.jev's impact, and areas.jev's area against the repo's list. */
export type ClassifyExtras = { impact?: boolean; areas?: Area[] };
/**
* The request body of classify.jev, with the questions of priority.jev and areas.jev added when they are due for the same item:
* Jev answers independent questions over one state in one request. The state is classify's (itemInput); an area question rides
* along only where areaItemInput gives the same state, which is every issue (a pull request's area state adds its paths).
*/
export function renderClassifyJev(item: Item, extras: ClassifyExtras = {}): string {
const req = JEV_PROMPTS["classify.jev"].request;
if (extras.areas && item.kind !== "issue") throw new Error("an area question rides along only on an issue, whose area state is the classify state");
const questions = { ...req.questions, ...(extras.impact && JEV_PROMPTS["priority.jev"].request.questions), ...(extras.areas && { area: areaQuestion(extras.areas) }) };
return JSON.stringify({ ...req, state: JSON.stringify(itemInput(item)), questions });
}
const itemValues = (items: Item[]) => ({ items: untrustedJson(items.map(itemInput)) });
+50 -14
View File
@@ -11,14 +11,17 @@
import { refOf, type Item } from "../classify/parse.ts";
import { takersFirst } from "../agents/call.ts";
import { freeSlots } from "../agents/accounts.ts";
import { jevAvailable } from "../agents/jev.ts";
import { haikuBatches, runHaiku, runJev } from "../classify/run.ts";
import { jevAvailable, takeJevStatuses } from "../agents/jev.ts";
import { haikuBatches, jevAgents, runHaiku, runJev, type JevExtraAnswers } from "../classify/run.ts";
import { prioritizeAnswered } from "../priority/index.ts";
import { priorityDue } from "../core/decide-item.ts";
import type { ClassifyExtras } from "../prompts/index.ts";
import { fillClassHashes } from "../itemhash.ts";
import { itemPlans, itemsOf, plannedItems, type ItemPlans, type PlannedItem } from "../core/select-items.ts";
import { startedRefs } from "../pilot.ts";
import type { StepContext } from "./steps.ts";
import { latestRun } from "../classify/settled.ts";
import { assignAreas, type AssignResult } from "../areas/assign.ts";
import { areaListsDue, assignAreas, type AskedList, type AssignResult } from "../areas/assign.ts";
import type { Db } from "../db/index.ts";
import { batches, excluded } from "../db/kx.ts";
@@ -32,8 +35,9 @@ const JEV_CHUNK = 40, HAIKU_PER_CALL = 25;
/**
* runJev and runHaiku write one token_usage row per agent name (`jev-<ref>`,
* `haiku-NN`) with INSERT OR REPLACE. Rows from earlier passes with those
* runJev and runHaiku write one token_usage row per agent name (`jev-<ref>`, and
* `priority-jev-<ref>` and `areas-jev-<ref>` for the questions a classify request
* carries for those steps; `haiku-NN`) with INSERT OR REPLACE. Rows from earlier passes with those
* names are renamed first so their cost stays on record.
*/
async function keepUsage(db: Db, run: string, agents: string[]): Promise<void> {
@@ -66,18 +70,44 @@ const sliceGuard = (ctx: StepContext): (() => boolean) => {
};
};
export async function jevPass(ctx: StepContext, run: string, todo: Item[], hashes: Map<string, string>, t: Tally, more: () => boolean): Promise<Set<string>> {
/** What the Jev pass got: the items it classified, and the valid impact and area answers their requests carried. */
export type JevPassResult = { done: Set<string> } & JevExtraAnswers;
export async function jevPass(ctx: StepContext, run: string, todo: Item[], hashes: Map<string, string>, t: Tally, more: () => boolean, extras?: ReadonlyMap<string, ClassifyExtras>): Promise<JevPassResult> {
const { db } = ctx;
const done = new Set<string>();
const out: JevPassResult = { done: new Set(), impact: new Map(), area: new Map() };
for (let i = 0; i < todo.length && !await ctx.cancelled() && await jevAvailable(db) && more(); i += JEV_CHUNK) {
const chunk = todo.slice(i, i + JEV_CHUNK);
await keepUsage(db, run, chunk.map((x) => `jev-${refOf(x)}`));
await keepUsage(db, run, chunk.flatMap((x) => jevAgents(refOf(x), extras?.get(refOf(x)))));
t.sent(chunk.length);
for (const ref of await runJev(db, run, chunk, undefined, hashes)) done.add(ref);
t.answered("jev", done.size);
const r = await runJev(db, run, chunk, undefined, hashes, extras);
for (const ref of r.saved) out.done.add(ref);
for (const [ref, a] of r.impact) out.impact.set(ref, a);
for (const [ref, a] of r.area) out.area.set(ref, a);
t.answered("jev", out.done.size);
const limited = takeJevStatuses();
await ctx.progress(`Jev: ${Math.min(i + JEV_CHUNK, todo.length)} of ${todo.length} items`);
if (limited.size) ctx.log(`Jev responses that were not OK in this chunk: ${[...limited].map(([status, n]) => `${n} with status ${status}`).join(", ")}`);
}
return done;
return out;
}
/**
* The questions of priority.jev and areas.jev that are due for the items of `todo`, to ask in their classify requests (one Jev
* request per item), with the priority text hash of each item asked for its impact. Priority is due from the item's Plan facts
* (the Plan holds back the prioritize step while this request is due); an area question rides along on an issue only.
*/
async function classifyExtras(db: Db, plans: ClassifyPlans, todo: readonly Item[]): Promise<{ extras: Map<string, ClassifyExtras>; priority: Map<string, string>; lists: Map<string, AskedList> }> {
const facts = new Map(plans.items.map((p) => [`${p.facts.repo}#${p.facts.number}`, p.facts]));
const lists = await areaListsDue(db, todo);
const extras = new Map<string, ClassifyExtras>(), priority = new Map<string, string>();
for (const x of todo) {
const ref = refOf(x), f = facts.get(ref), list = lists.get(ref);
const impact = !!f && priorityDue(f);
if (impact) priority.set(ref, f.embedHash);
if (impact || list) extras.set(ref, { ...(impact && { impact }), ...(list && { areas: list.areas }) });
}
return { extras, priority, lists };
}
/**
@@ -174,7 +204,8 @@ async function pass(ctx: StepContext, run: string, mode: "new" | "all"): Promise
const todo = (await takersFirst(ctx.db, due, (x) => [x.repo], (x) => [x])).slice(0, limit);
ctx.log(`run ${run}: ${open} open items, ${due.length} due for Jev, taking ${todo.length}`);
const t = tally(ctx), more = sliceGuard(ctx);
const jevDone = await jevPass(ctx, run, todo, hashes, t, more);
const ask = await classifyExtras(ctx.db, plans, todo);
const jevRes = await jevPass(ctx, run, todo, hashes, t, more, ask.extras), jevDone = jevRes.done;
// Items Jev did not answer because it is unavailable go to Haiku, which settles them.
const alone = await ctx.cancelled() || await jevAvailable(ctx.db) ? [] : todo.filter((x) => !jevDone.has(refOf(x)));
const haikuAlone = alone.length ? await haikuOnlyPass(ctx, run, alone, hashes, t, more) : 0;
@@ -184,10 +215,15 @@ async function pass(ctx: StepContext, run: string, mode: "new" | "all"): Promise
ctx.log(`Haiku: ${unsure.length} items where Jev is unsure of the type (under ${SURE * 100} %) or of a flag`);
const haiku = await haikuPass(ctx, run, unsure, t, "haiku", more);
const jev = jevDone.size, left = due.length - jev - haikuAlone;
// Impact answers the classify requests carried are settled and stored whatever the time, as the prioritize step would.
const prio = await ctx.cancelled() || !jevRes.impact.size ? null : await prioritizeAnswered(ctx.db, todo.filter((x) => jevRes.impact.has(refOf(x))).map((x) => ({ ...x, hash: ask.priority.get(refOf(x))! })), jevRes.impact, { cancelled: ctx.cancelled, log: ctx.log });
if (prio) ctx.log(`Priority from the classify requests: ${prio.saved} of ${prio.due} items saved (${prio.haiku} by Haiku where Jev was unsure)`);
// Items of repos with an area list that were not asked against its current version; Jev's answers share the job's limit with the type pass.
// Past the slice the areas wait for a job with time left, since the planner queues classify-new only while Jev has items due;
// the job that clears the last of them asks them whatever its time.
const areas = await ctx.cancelled() || (ctx.timeUp() && left > 0) ? { due: 0, jev: 0, haiku: 0, none: 0, left: 0 } : await assignAreas(ctx.db, { limit: Math.min(limit, AREAS_PER_CLASSIFY_JOB), usageRun: run, cancelled: ctx.cancelled, progress: ctx.progress, log: ctx.log });
// the job that clears the last of them asks them whatever its time. Answers the classify requests carried are stored in any case.
const given = new Map([...jevRes.area].map(([ref, answer]) => [ref, { answer, version: ask.lists.get(ref)!.version }]));
const areaLimit = ctx.timeUp() && left > 0 ? 0 : Math.min(limit, AREAS_PER_CLASSIFY_JOB);
const areas = await ctx.cancelled() || (!areaLimit && !given.size) ? { due: 0, jev: 0, haiku: 0, none: 0, left: 0 } : await assignAreas(ctx.db, { limit: areaLimit, given, usageRun: run, cancelled: ctx.cancelled, progress: ctx.progress, log: ctx.log });
return { areas, jev, due: due.length, haiku, haikuDue: unsure.length, haikuAlone, aloneDue: alone.length, left, asked: t.asked() };
}
+43
View File
@@ -0,0 +1,43 @@
// A classify job asks an item's due priority and area questions in the item's one Jev request, and stores their answers as the
// prioritize step and the area pass would: the item is then no longer due for either. Jev is faked (setRunner).
import assert from "node:assert/strict";
import { afterEach, test } from "node:test";
import { setRunner } from "../src/classify/run.ts";
import { classifyNew } from "../src/runner/classify.ts";
import { editAreas } from "../src/areas/store.ts";
import { plannedItems } from "../src/core/select-items.ts";
import type { StepContext } from "../src/runner/steps.ts";
import { world, type World } from "./world-db.ts";
let current: World | null = null;
afterEach(() => current?.close());
test("one Jev request per item answers its type, priority and area, and the other steps see them done", async () => {
const w = (current = await (await world()).repo());
await w.issue(1);
await w.db.run(w.db.k.insertInto("items").values({ repo: "app", number: 2, kind: "issue", state: "OPEN", title: "Export drops the alpha channel", body: "Saving a PNG loses transparency.", author: "someone", created_at: "2026-11-01T00:00:00Z", updated_at: "2026-11-01T00:00:00Z" }));
await editAreas(w.db, "app", { op: "replace", areas: [{ name: "Export", description: "Saving files" }, { name: "Text", description: "Type tools" }] }, null);
const bodies: string[] = [];
const restore = setRunner(async (_cmd, _args, stdin) => {
bodies.push(stdin);
const answers = {
type: { choice: "bugfix", probabilities: { bugfix: 0.97 } }, security: { noul: 0.01 }, needs_decision: { noul: 0.02 },
impact: { choice: "P1", probabilities: { P1: 0.95 } }, area: { choice: "Export", probabilities: { Export: 0.96 } },
};
return { code: 0, stderr: "", stdout: JSON.stringify({ answers, usage: { input_tokens: 900, output_tokens: 3 } }) };
});
const ctx: StepContext = {
db: w.db, job: { id: 1, requestedBy: "pipeline", startedAt: new Date().toISOString(), resumes: 0 }, params: { limit: 50 },
progress: async () => {}, log: () => {}, usageRun: () => {}, handled: () => {}, acted: () => {},
cancelled: async () => false, stopping: async () => false, timeUp: () => false,
};
try { await classifyNew(ctx); } finally { restore(); }
const asked = bodies.map((b) => JSON.parse(b) as { state: string; questions: Record<string, unknown> }).filter((b) => b.state.includes("app#2"));
assert.equal(asked.length, 1, "one request for the new item");
assert.ok("impact" in asked[0]!.questions && "area" in asked[0]!.questions, "it carries the impact and area questions");
const prio = await w.db.get(w.db.k.selectFrom("item_priority").select(["impact", "model"]).where("number", "=", 2));
assert.deepEqual(prio, { impact: "P1", model: "jev" });
const area = await w.db.get(w.db.k.selectFrom("item_areas").select(["area", "source"]).where("number", "=", 2));
assert.deepEqual(area, { area: "Export", source: "jev" });
assert.ok(!(await plannedItems(w.db, "prioritize")).some((p) => p.facts.number === 2), "prioritize no longer has the item");
});
+2
View File
@@ -51,6 +51,8 @@ const rows: Row[] = [
// ---- prioritize, embed
{ name: "no priority row", facts: { priorityHash: null }, expect: { state: "classified", actions: ["prioritize"] } },
{ name: "priority made at older text", facts: { priorityHash: "old" }, expect: { state: "classified", actions: ["prioritize"] } },
{ name: "no priority row while Jev's classify call is due: that request asks the impact", facts: { priorityHash: null, classification: { jev: jev({ changed: true }) } }, expect: { state: "classified", actions: ["classify"] } },
{ name: "no priority row while only Haiku's classify call is due: prioritize asks it", facts: { priorityHash: null, classification: { status: "waiting", label: null, jev: jev({ unsure: true }) } }, expect: { state: "waiting-haiku", actions: ["classify", "prioritize"] } },
{ name: "no vector for the current model", facts: { embeddedHash: null }, expect: { state: "classified", actions: ["embed"] } },
{ name: "vector of older text: embed again, no scan until it is current", facts: { embeddedHash: "old", scannedHash: null }, expect: { state: "classified", actions: ["embed"] } },
{ name: "embed does not depend on scope", facts: { inScope: false, embeddedHash: null }, expect: { state: "classified", actions: ["embed"] } },
+22 -1
View File
@@ -56,10 +56,31 @@ test("runJev saves a chunk's verdicts and usage together, with the input hash",
const restore = setRunner(async () => ({ code: 0, stderr: "", stdout: JSON.stringify({ answers, usage: { input_tokens: 10, output_tokens: 1 } }) }));
try {
const items = [1, 2, 3].map((number) => ({ repo: "a", number, kind: "pr" as const, title: "t", body: "b", lines_changed: 1, files_changed: 1, author_association: null }));
const saved = await runJev(db, "run1", items, 3, new Map([["a#1", "h1"], ["a#3", "h3"]]));
const { saved } = await runJev(db, "run1", items, 3, new Map([["a#1", "h1"], ["a#3", "h3"]]));
assert.deepEqual([...saved].sort(), ["a#1", "a#2", "a#3"]);
} finally { restore(); }
const rows = await db.all(db.k.selectFrom("classifications").select(["number", "input_hash"]).orderBy("number"));
assert.deepEqual(rows.map((r) => r.input_hash), ["h1", null, "h3"]);
assert.equal((await db.all(db.k.selectFrom("token_usage").select("agent"))).length, 3);
});
test("a classify request that also asks the impact and area questions splits its usage over the three steps", async () => {
const db = await fresh();
const bodies: string[] = [];
const restore = setRunner(async (_cmd: string, _args: string[], stdin: string) => {
bodies.push(stdin);
return { code: 0, stderr: "", stdout: JSON.stringify({ answers: { ...answers, impact: { choice: "P2", probabilities: { P2: 0.95 } }, area: { choice: "Export", probabilities: { Export: 0.6 } } }, usage: { input_tokens: 1001, output_tokens: 7 } }) };
});
let r: Awaited<ReturnType<typeof runJev>>;
try {
const item = { repo: "a", number: 1, kind: "issue" as const, title: "t", body: "b", lines_changed: null, files_changed: null, author_association: null };
r = await runJev(db, "run1", [item], 1, undefined, new Map([["a#1", { impact: true, areas: [{ name: "Export", description: "Saving files" }] }]]));
} finally { restore(); }
assert.equal(bodies.length, 1, "one request for the item");
assert.equal(r.impact.get("a#1")?.impact, "P2", "the impact answer is returned for priority to settle");
const rows = await db.all(db.k.selectFrom("token_usage").select(["stage", "input_tokens as i", "output_tokens as o"]));
assert.deepEqual(rows.map((x) => x.stage).sort(), ["areas", "classify", "priority"]);
assert.ok(rows.every((x) => (x.i ?? 0) > 0), "every step pays a share");
assert.equal(rows.reduce((n, x) => n + (x.i ?? 0), 0), 1001, "the shares add up to the call");
assert.equal(rows.reduce((n, x) => n + (x.o ?? 0), 0), 7);
});