Review passes: keep a smaller pass record and drop it when the run ends, re-ask a lost report with the pass prompt when it starts fresh, withdraw orphan pass calls, count only queued passes against runner room, count uncited-verdict candidates as unsure, record a changed tree before the reset

This commit is contained in:
aiongg committed 2026-12-01 16:35:15 +00:00
1 parent 35f0b61ea1
commit 60734ac3c9
4 files changed
+69 -33

No files matched your search

+2
View File
@@ -348,6 +348,8 @@ export async function endRun(db: Db, id: number, end: RunEnd, o: { at: string; t
ended_at: o.at, end_kind: end.end === "fault" || end.end === "stopped" || end.end === "unread" ? "infra" : end.end, outcome: end.end === "outcome" ? end.outcome : null,
layer: end.end === "infra" ? end.layer : end.end === "stopped" ? STOP_LAYERS.stopped : end.end === "unread" ? UNREAD_LAYER : own ? "harness" : null, fault: own ? "own" : null, error, end_data: endData,
...(o.turns !== undefined && { turns: o.turns }), ...(o.cost !== undefined && { cost: o.cost }), transcript: o.transcript ?? null,
// A run the task goes on from (a stop, an infra end) keeps its passes record for the next try; any other end drops it.
...(end.end !== "stopped" && end.end !== "infra" && { pass_record: null }),
}).where("id", "=", id).where("ended_at", "is", null))).changes === 1);
}
+9 -4
View File
@@ -335,7 +335,7 @@ export function applyVerdicts(raw: Record<string, unknown>, listed: readonly Mer
else findings.push({ title: c.title, detail: c.detail, class: null, ...(c.file && { file: c.file }), ...(c.line && { line: c.line }) });
}
const count = (v: Verdict): number => [...verdicts.values()].filter((x) => x === v).length;
return { report: { ...raw, findings }, rejected: count("rejected"), unsure: count("unsure"), unjudged };
return { report: { ...raw, findings }, rejected: count("rejected"), unsure: count("unsure") + listed.filter((c) => covered.has(c.id) && !verdicts.has(c.id)).length, unjudged };
}
/** One area of a review for coverage: its changed files, and what each of its passes that returned a report did not read. */
@@ -428,7 +428,7 @@ type PassDone = { call: PassCall; got?: Candidate[]; unread?: string[] };
* and with `merged` the integrator goes on with the same candidates.
*/
type SavedReview = {
run: Omit<RunSpec, "files">; done: Record<string, PassDone>;
run: Omit<RunSpec, "files" | "passes">; done: Record<string, PassDone>;
merged?: { listed: Merged[]; total: number; calls: PassCall[]; unread: { area?: number; files: string[] }[] };
};
const savedReview = (v: unknown): SavedReview | null => (obj(v) && obj((v as SavedReview).run) ? v as SavedReview : null);
@@ -442,7 +442,12 @@ export async function reviewPasses(db: Db, c: PassContext, base: KindModule): Pr
if (c.task.scope !== "full") return null;
const saved = savedReview(c.saved);
let run: RunSpec;
if (saved) run = { ...saved.run, files: saved.run.plan ? areaFiles(saved.run.plan, c.input.diff ?? "") : [] };
// The passes are not kept: each area's files are in the plan, and the specs are rebuilt from the plan or the configuration alone.
if (saved) {
const r = saved.run;
const names = c.input.diff !== null ? diffIndex(c.input.diff).map((e) => e.path) : [];
run = { ...r, passes: r.plan ? planPasses(r.plan) : r.config.specialists ? passSpecs(r.config.specialists, names) : [], files: r.plan ? areaFiles(r.plan, c.input.diff ?? "") : [] };
}
else {
const cfg = await readConfig(db, [SETTINGS.reviewVariant.name]);
const v = variantOf(cfg.reviewVariant);
@@ -452,7 +457,7 @@ export async function reviewPasses(db: Db, c: PassContext, base: KindModule): Pr
run = spec;
}
const conf = run.config;
const state: SavedReview = saved ?? { run: { name: run.name, config: conf, passes: run.passes, ...(run.plan && { plan: run.plan }) }, done: {} };
const state: SavedReview = saved ?? { run: { name: run.name, config: conf, ...(run.plan && { plan: run.plan }) }, done: {} };
if (!saved) await c.save(state);
if (run.plan?.tier === "small") return smallRun(c, base, run);
if (conf.tools.ra) return { end: failed(`review variant ${run.name} asks for the rust-analyzer tools, which this AutoCraft does not have yet`) };
+34 -14
View File
@@ -19,6 +19,7 @@ import {
savePassRecord, sessionsOf, taskStops, updateSession,
} from "../data/task/index.ts";
import { adoptCall, ASK_PROMPT, loadCalls, withdrawCalls } from "../data/runners/index.ts";
import { liveBoundCalls, loadWorkspaces } from "../data/build/index.ts";
import { loadQuiet } from "../data/security/index.ts";
import { awaitCall, type Outcome as CallOutcome } from "../remote/calls.ts";
import { queueWorkspaceCall, type WorkspaceCallRequest } from "../build/workspace-call.ts";
@@ -72,7 +73,9 @@ const SHA = /^[0-9a-f]{40}$/;
*/
export type TurnRequest = {
db: Db; session: ItemSession; task: Task; run: TaskRun; workspace: WorkspaceRef;
prompt: string; resume: string | null; readOnly: boolean; adopt?: string; queued?: (callId: string) => Promise<void>;
prompt: string; resume: string | null; readOnly: boolean; adopt?: string;
/** The prompt of the fresh call a resumed turn falls back to when its session's runner never takes the resume (`prompt` continues a session; this one starts it). */
fresh?: string; queued?: (callId: string) => Promise<void>;
/** The call gets the repo's reference documentation tools. */
reference?: boolean;
/** The catalogue prompt, model and effort the turn runs with in place of the task's own (a review variant's passes). */
@@ -554,15 +557,21 @@ export async function runTask(db: Db, task: Task, run: TaskRun, kind: KindModule
let passTurns = 0;
const passContext = (at: WorkspaceRef, s: ItemSession, input: SessionInput, files: InputFile[], base: string, book: PassBook): PassCtx => {
const docs = files.filter(isDocFile), placedFiles: InputFile[] = [];
const placed = new Map<string, number>();
// The passes whose calls are queued count against a runner's room; a leased one is already in the view's leases.
const placedCalls = new Map<string, { call: string; login: string }>();
const placedQueued = async (): Promise<Map<string, number>> => {
const states = await loadCalls(db, [...placedCalls.values()].map((x) => Number(x.call)));
const n = new Map<string, number>();
for (const x of placedCalls.values()) if (states.get(Number(x.call))?.state === "queued") n.set(x.login, (n.get(x.login) ?? 0) + 1);
return n;
};
const own = run.runner?.login ?? null;
let router: ReturnType<typeof loadPassRouter> | null = null;
const routed = async (as: TurnAs, fresh: boolean): Promise<{ login: string; as: TurnAs } | null> => {
if (fresh || !router) router = loadPassRouter(db, task, own, placed);
if (fresh || !router) router = loadPassRouter(db, task, own, await placedQueued());
const p = (await router)(tierOfModel(as.model));
return p && { login: p.login, as: p.tier === tierOfModel(as.model) ? as : { ...as, model: TIER_MODEL[p.tier] } };
};
const count = (login: string, n: number) => placed.set(login, (placed.get(login) ?? 0) + n);
return {
task, input, saved: book.record.plan, save: book.save,
place: async (more) => {
@@ -573,7 +582,7 @@ export async function runTask(db: Db, task: Task, run: TaskRun, kind: KindModule
// Once per try whose passes ran (here, or before a restart): the record says when it was done.
restoreTree: async () => {
if (book.record.restored || (passTurns === 0 && !Object.keys(book.record.calls).length)) return false;
const changed = (await w.restoreTree?.(db, at, base)) ?? false;
const changed = (await w.restoreTree?.(db, at, base, async () => { book.record.treeChanged = true; await book.flush(); })) ?? false;
await w.placeInputs(db, at, input, [...files, ...placedFiles]);
book.record.restored = true;
if (changed) book.record.treeChanged = true;
@@ -582,6 +591,13 @@ export async function runTask(db: Db, task: Task, run: TaskRun, kind: KindModule
},
turn: async (text, as, resume = null, o = {}) => {
await stopIfEnded();
// A pass call queued just before a restart whose id never reached the record is no one's: it is withdrawn before the integrator's call joins the workspace.
if (!o.sibling && Object.keys(book.record.calls).length) {
const known = new Set(Object.values(book.record.calls).map((c) => Number(c.call)));
const ws = (await loadWorkspaces(db, { ids: [Number(at.id)] })).get(Number(at.id));
const orphans = ws ? (await liveBoundCalls(db, [ws])).get(Number(at.id))?.filter((c) => !c.alone && !known.has(c.id)) ?? [] : [];
if (orphans.length) await withdrawCalls(db, orphans.map((c) => ({ id: c.id, reason: "withdrawn: a review pass call the restart left without a record" })));
}
// Sequential passes run the item's code between turns, which could rewrite the maintainers' documents; siblings get them once, before the integrator.
if (passTurns++ > 0 && docs.length && !o.sibling) await w.placeInputs(db, at, input, docs);
const started = Date.now();
@@ -590,6 +606,7 @@ export async function runTask(db: Db, task: Task, run: TaskRun, kind: KindModule
const earlier = resume === null && key !== undefined ? book.take(key) : null;
const was: EarlierCall = earlier ? await earlierOf(db, earlier.call) : "ended";
let adopt = was === "open" ? earlier!.call : undefined;
const fresh = was === "read" ? withNotes(text, at) : undefined;
const from = was === "read" ? earlier!.call : resume;
const prompt = was === "read" ? LOST_REPLY_MESSAGE : resume === null ? withNotes(text, at) : text;
// The call taken back or continued, with the runner and model it ran on.
@@ -598,18 +615,21 @@ export async function runTask(db: Db, task: Task, run: TaskRun, kind: KindModule
let r: TurnReply;
for (let reroutes = 0; ; reroutes++) {
const where = to;
if (where) count(where.login, 1);
const queued = key === undefined ? undefined : async (id: string): Promise<void> => await book.note(key, id, where?.login, where?.as.model);
if (key !== undefined && where && adopt !== undefined) placedCalls.set(key, { call: adopt, login: where.login });
const queued = key === undefined ? undefined : async (id: string): Promise<void> => {
await book.note(key, id, where?.login, where?.as.model);
if (where) placedCalls.set(key, { call: id, login: where.login });
};
try {
r = await deps.turn({
db, session: s, task, run, workspace: at, prompt, resume: from, readOnly: !task.pushes, as: where?.as ?? as, ...(queued && { queued }), ...(adopt !== undefined && { adopt }),
db, session: s, task, run, workspace: at, prompt, resume: from, readOnly: !task.pushes, as: where?.as ?? as, ...(queued && { queued }), ...(adopt !== undefined && { adopt }), ...(fresh !== undefined && { fresh }),
...(input.reference && { reference: true }), ...(where && { sibling: { login: where.login } }),
});
break;
} catch (e) {
if (!where || from !== null || reroutes >= PASS_REROUTES || !(e instanceof InfraError && e.cause instanceof GivenBackError)) throw e;
} finally {
if (where) count(where.login, -1);
if (key !== undefined) placedCalls.delete(key);
}
to = await routed(as, true);
adopt = undefined;
@@ -1093,10 +1113,10 @@ export async function turnCallRequest(db: Db, p: SessionPrompt, o: TurnRequest,
async function turnCall(db: Db, p: SessionPrompt, o: TurnRequest): Promise<TurnReply> {
const { login, lane } = turnLane(o);
const tier: Tier = tierOfModel(p.model);
const queue = async (parent: string | null): Promise<number> => {
const queue = async (parent: string | null, prompt = o.prompt): Promise<number> => {
let id: number;
try {
id = await queueWorkspaceCall(db, await turnCallRequest(db, p, o, parent));
id = await queueWorkspaceCall(db, await turnCallRequest(db, p, { ...o, prompt }, parent));
} catch (e) {
// The workspace is held by other calls (a review's passes still running beside the integrator): a wait for them, not a fault.
if (e instanceof BuildError && e.status === 409) throw new InfraError("workspace", e.message, { cause: e });
@@ -1109,8 +1129,8 @@ async function turnCall(db: Db, p: SessionPrompt, o: TurnRequest): Promise<TurnR
if (await withdrawIfStopped(db, o.task.id, id)) throw new TaskStoppedError(o.task.id, (await loadTask(db, o.task.id))?.state ?? null);
return id;
};
const queued = async (parent: string | null): Promise<number> => {
const n = await queue(parent);
const queued = async (parent: string | null, prompt?: string): Promise<number> => {
const n = await queue(parent, prompt);
await o.queued?.(String(n));
return n;
};
@@ -1128,7 +1148,7 @@ async function turnCall(db: Db, p: SessionPrompt, o: TurnRequest): Promise<TurnR
id = await queued(o.resume);
out = await awaitCall(db, id, wait);
if (out.state === "unclaimed" && o.resume !== null) {
id = await queued(null);
id = await queued(null, o.fresh);
out = await awaitCall(db, id, wait);
}
}
+24 -15
View File
@@ -230,26 +230,35 @@ export async function placeInputs(db: Db, ws: WorkspaceRef, input: SessionInput,
}
/**
* The shell that puts /work/src back at commit `$1`: tracked changes, a moved HEAD and untracked files dropped (ignored files,
* build output and installed dependencies among them, stay). Prints `changed` first when the tree was not at `$1`. A lock a
* killed call left behind is removed first; nothing else runs in the tree while this does.
* The shells that put /work/src back at commit `$1`: the first prints `changed` when the tree was not at `$1` (HEAD moved, tracked
* changes or untracked files); the second drops tracked changes, a moved HEAD and untracked files (ignored files, build output
* and installed dependencies stay). A lock a killed call left behind is removed first; nothing else runs in the tree meanwhile.
*/
const RESTORE_SH = `set -e
const CHECK_SH = `set -e
rm -f .git/index.lock
if [ "$(git rev-parse HEAD)" != "$1" ] || ! git diff --quiet --no-ext-diff "$1" -- || [ -n "$(git ls-files --others --exclude-standard | head -n 1)" ]; then echo changed; fi`;
const RESET_SH = `set -e
rm -f .git/index.lock
if [ "$(git rev-parse HEAD)" != "$1" ] || ! git diff --quiet --no-ext-diff "$1" -- || [ -n "$(git ls-files --others --exclude-standard | head -n 1)" ]; then echo changed; fi
git reset --quiet --hard "$1"
git clean -fdq`;
/**
* Puts the workspace's tree back at `base`, dropping what calls changed in it (restoreTree's shell), and says whether it had
* changed. A transport failure is infra (layer pod), any other failure infra on the workspace layer.
* Puts the workspace's tree back at `base`, dropping what calls changed in it, and says whether it had changed. `changed` runs
* after the check and before the reset, so a restart between them still finds the change recorded. A transport failure is infra
* (layer pod), any other failure infra on the workspace layer.
*/
export async function restoreTree(db: Db, ws: WorkspaceRef, base: string, api?: KubeApi): Promise<boolean> {
const r = await execWs(db, api ?? clusterApi(db), Number(ws.id), ["run", "120", "--", "sh", "-c", RESTORE_SH, "restore", base], { tool: "restore", args: { base }, timeoutMs: 130_000 });
if (r.header?.kind !== "status" || r.header.state !== "exited" || r.header.exit !== 0) {
throw new InfraError(r.transport ? "pod" : "workspace", `the tree could not be put back at ${base.slice(0, 8)}: ${r.error ?? describeHeader(r.header)} ${r.output.trim().split("\n").pop()?.slice(0, 200) ?? ""}`.trim());
}
return /^changed$/m.test(r.output);
export async function restoreTree(db: Db, ws: WorkspaceRef, base: string, api?: KubeApi, changed?: () => Promise<void>): Promise<boolean> {
const run = async (sh: string): Promise<string> => {
const r = await execWs(db, api ?? clusterApi(db), Number(ws.id), ["run", "120", "--", "sh", "-c", sh, "restore", base], { tool: "restore", args: { base }, timeoutMs: 130_000 });
if (r.header?.kind !== "status" || r.header.state !== "exited" || r.header.exit !== 0) {
throw new InfraError(r.transport ? "pod" : "workspace", `the tree could not be put back at ${base.slice(0, 8)}: ${r.error ?? describeHeader(r.header)} ${r.output.trim().split("\n").pop()?.slice(0, 200) ?? ""}`.trim());
}
return r.output;
};
const was = /^changed$/m.test(await run(CHECK_SH));
if (was) await changed?.();
await run(RESET_SH);
return was;
}
type DiffEntry = GateInput["diff"][number];
@@ -354,7 +363,7 @@ export type WorkspaceDeps = {
workspaceAsIs?(db: Db, session: ItemSession, id: string): Promise<WorkspaceRef | null>;
placeInputs(db: Db, ws: WorkspaceRef, input: SessionInput, files: InputFile[]): Promise<void>;
/** Puts the tree back at `base` and says whether it had changed (restoreTree); a fake without it has a tree nothing changes. */
restoreTree?(db: Db, ws: WorkspaceRef, base: string): Promise<boolean>;
restoreTree?(db: Db, ws: WorkspaceRef, base: string, changed?: () => Promise<void>): Promise<boolean>;
readChange(db: Db, ws: WorkspaceRef, base: string, message: string): Promise<ReadChange | null>;
releaseWorkspace(db: Db, ws: WorkspaceRef): Promise<void>;
};
@@ -362,7 +371,7 @@ export const workspaceDeps: WorkspaceDeps = {
workspaceFor: (db, s, seed, stop) => workspaceFor(db, s, seed, { db, api: clusterApi(db), log: () => {}, ...(stop && { stop }) }),
workspaceAsIs: (db, s, id) => workspaceAsIs(db, s, id),
placeInputs: (db, ws, input, files) => placeInputs(db, ws, input, files),
restoreTree: (db, ws, base) => restoreTree(db, ws, base),
restoreTree: (db, ws, base, changed) => restoreTree(db, ws, base, undefined, changed),
readChange: (db, ws, base, message) => readChange(db, ws, base, message),
releaseWorkspace,
};