From bd3647fdd613bf542016953933c7fdc850f4e011 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:17:51 -0800 Subject: [PATCH 01/31] test(server): scored model guidance outranks newer one-sample groups The card keeps the newest groups, so an unscored group and twenty one-sample groups leave a five-sample group off it. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 9aa12555fa57c..c8d5b988d9594 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -806,3 +806,74 @@ it.effect( ); }, ); + +it.effect("ranks scored guidance ahead of newer single samples and drops unscored groups", () => { + let calls = 0; + return Effect.gen(function* () { + const service = yield* ModelEvaluations.ModelEvaluations; + const rich = { instanceId, model: "rich-model" }; + for (let index = 0; index < 5; index++) { + const thread = ThreadId.make(`rich-thread-${index}`); + const id = RunId.make(`rich-run-${index}`); + yield* seed({ thread, run: id, model: rich }); + yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); + yield* TestClock.adjust("1 second"); + } + for (let index = 0; index < 20; index++) { + const thread = ThreadId.make(`thin-thread-${index}`); + const id = RunId.make(`thin-run-${index}`); + yield* seed({ + thread, + run: id, + model: { instanceId, model: `thin-model-${index}` }, + }); + yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); + yield* TestClock.adjust("1 second"); + } + const emptyRun = RunId.make("empty-run"); + yield* seed({ + thread: ThreadId.make("empty-thread"), + run: emptyRun, + model: { instanceId, model: "empty-model" }, + }); + yield* service.evaluateRun({ + threadId: ThreadId.make("empty-thread"), + runId: emptyRun, + runOutcome: "completed", + }); + const report = yield* service.list(scope); + assert.equal( + report.records.find((record) => record.runId === emptyRun)?.status, + "insufficient_evidence", + ); + assert.equal(report.guidance[0]?.modelSelection.model, "rich-model"); + assert.equal(report.guidance[0]?.sampleCount, 5); + assert.equal(report.guidance[1]?.modelSelection.model, "thin-model-19"); + assert.equal(report.guidance.length, 20); + assert.isFalse(report.guidance.some((group) => group.sampleCount === 0)); + assert.isFalse(report.guidance.some((group) => group.modelSelection.model === "empty-model")); + assert.isFalse(report.guidance.some((group) => group.modelSelection.model === "thin-model-0")); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls += 1; + if (calls < 26) return Effect.succeed(verdict(request.packet)); + const output = verdict(request.packet); + return Effect.succeed({ + ...output, + outcome: "insufficient_evidence", + confidence: "low", + scores: { + taskCompletion: null, + correctness: null, + instructionFollowing: null, + verification: null, + }, + strengths: [], + weaknesses: [], + promptAdvice: [], + }); + }), + ), + ); +}); From 49f36868e14db6fae262a8bbbe2437dbac952757 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:20:01 -0800 Subject: [PATCH 02/31] fix(server): rank model guidance by scored samples Newest one-sample groups filled the card before older groups with more scores. Drop groups with no scored samples, then keep the largest groups, newest first. Co-authored-by: Cursor --- .../src/modelEvaluations/ModelEvaluations.ts | 141 ++++++++++-------- 1 file changed, 76 insertions(+), 65 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 14576aa3c6a39..29bc5752c581d 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -77,73 +77,84 @@ function summarize( group.push(record); groups.set(key, group); } - return [...groups.values()].slice(0, GUIDANCE_LIMIT).map((group) => { - const first = group[0]!; - const scored = group.filter((record) => record.status === "scored"); - const meanScores = { - taskCompletion: null, - correctness: null, - instructionFollowing: null, - verification: null, - } as ModelEvaluationGuidance["meanScores"]; - const scoreCounts = { - taskCompletion: 0, - correctness: 0, - instructionFollowing: 0, - verification: 0, - }; - for (const dimension of DIMENSIONS) { - const values = scored.flatMap((record) => record.verdict?.scores[dimension] ?? []); - scoreCounts[dimension] = values.length; - Object.assign(meanScores, { - [dimension]: - values.length === 0 - ? null - : values.reduce((sum, value) => sum + value, 0) / values.length, - }); - } - const prompts = scored.map((record) => record.promptChars).toSorted((a, b) => a - b); - const observations = (field: "strengths" | "weaknesses" | "promptAdvice") => - [ - ...new Set( - scored.flatMap( - (record) => - record.verdict?.[field].map((observation) => - observation.text.replace(/\s+/g, " ").trim().slice(0, 240), - ) ?? [], + return [...groups.values()] + .map((group) => { + const first = group[0]!; + const scored = group.filter((record) => record.status === "scored"); + const meanScores = { + taskCompletion: null, + correctness: null, + instructionFollowing: null, + verification: null, + } as ModelEvaluationGuidance["meanScores"]; + const scoreCounts = { + taskCompletion: 0, + correctness: 0, + instructionFollowing: 0, + verification: 0, + }; + for (const dimension of DIMENSIONS) { + const values = scored.flatMap((record) => record.verdict?.scores[dimension] ?? []); + scoreCounts[dimension] = values.length; + Object.assign(meanScores, { + [dimension]: + values.length === 0 + ? null + : values.reduce((sum, value) => sum + value, 0) / values.length, + }); + } + const prompts = scored.map((record) => record.promptChars).toSorted((a, b) => a - b); + const observations = (field: "strengths" | "weaknesses" | "promptAdvice") => + [ + ...new Set( + scored.flatMap( + (record) => + record.verdict?.[field].map((observation) => + observation.text.replace(/\s+/g, " ").trim().slice(0, 240), + ) ?? [], + ), ), + ].slice(0, 3); + return { + scope: first.scope, + modelSelection: first.modelSelection, + evaluatorSelection: first.evaluatorSelection, + rubricVersion: first.rubricVersion, + taskCategory: first.verdict!.taskCategory, + sampleCount: scored.length, + insufficientEvidenceCount: group.length - scored.length, + meanScores, + scoreCounts, + confidence: + scored.filter((record) => record.verdict?.confidence !== "low").length >= 5 + ? "observed" + : "provisional", + promptChars: { + min: prompts[0] ?? 0, + median: + prompts.length === 0 + ? 0 + : ((prompts[Math.floor((prompts.length - 1) / 2)] ?? 0) + + (prompts[Math.floor(prompts.length / 2)] ?? 0)) / + 2, + max: prompts.at(-1) ?? 0, + }, + strengths: observations("strengths"), + weaknesses: observations("weaknesses"), + promptAdvice: observations("promptAdvice"), + latestAt: group.reduce( + (latest, record) => (record.at > latest ? record.at : latest), + group[0]!.at, ), - ].slice(0, 3); - return { - scope: first.scope, - modelSelection: first.modelSelection, - evaluatorSelection: first.evaluatorSelection, - rubricVersion: first.rubricVersion, - taskCategory: first.verdict!.taskCategory, - sampleCount: scored.length, - insufficientEvidenceCount: group.length - scored.length, - meanScores, - scoreCounts, - confidence: - scored.filter((record) => record.verdict?.confidence !== "low").length >= 5 - ? "observed" - : "provisional", - promptChars: { - min: prompts[0] ?? 0, - median: - prompts.length === 0 - ? 0 - : ((prompts[Math.floor((prompts.length - 1) / 2)] ?? 0) + - (prompts[Math.floor(prompts.length / 2)] ?? 0)) / - 2, - max: prompts.at(-1) ?? 0, - }, - strengths: observations("strengths"), - weaknesses: observations("weaknesses"), - promptAdvice: observations("promptAdvice"), - latestAt: first.at, - }; - }); + }; + }) + .filter((group) => group.sampleCount > 0) + .toSorted( + (left, right) => + right.sampleCount - left.sampleCount || + (left.latestAt < right.latestAt ? 1 : left.latestAt > right.latestAt ? -1 : 0), + ) + .slice(0, GUIDANCE_LIMIT); } export class ModelEvaluationPassError extends Schema.TaggedError()( From 4682d06f96792af98dc4e21d1e34d98e7b05296c Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:25:15 -0800 Subject: [PATCH 03/31] test(server): quality-neutral model options share one guidance group fastMode, serviceTier, contextWindow, and ultracode each open their own group, including fastMode false against an omitted fastMode. Effort values, judges, and turn versus subagent stay separate. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 48 ++++++++++++++----- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index c8d5b988d9594..97ff8cb9679d1 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -520,15 +520,33 @@ it.effect( ); it.effect( - "keeps model options and judges separate, counts observed scores, and expires old guidance", + "pools latency and capacity options, and keeps effort, judges, scope, and observed scores separate", () => Effect.gen(function* () { const service = yield* ModelEvaluations.ModelEvaluations; const settings = yield* ServerSettings.ServerSettingsService; - for (let index = 0; index < 8; index++) { + const cases: ReadonlyArray<{ + readonly options: NonNullable; + readonly subagent?: boolean; + readonly switchJudge?: boolean; + }> = [ + { options: [] }, + { options: [{ id: "fastMode", value: true }] }, + { options: [{ id: "fastMode", value: false }] }, + { options: [{ id: "serviceTier", value: "priority" }] }, + { options: [{ id: "contextWindow", value: "1m" }] }, + { options: [{ id: "ultracode", value: true }] }, + { options: [{ id: "effort", value: "high" }] }, + { options: [{ id: "effort", value: "low" }] }, + { options: [{ id: "reasoningEffort", value: "high" }] }, + { options: [{ id: "reasoning_effort", value: "medium" }] }, + { options: [], switchJudge: true }, + { options: [], subagent: true }, + ]; + for (const [index, entry] of cases.entries()) { const id = RunId.make(`group-run-${index}`); const thread = ThreadId.make(`group-thread-${index}`); - if (index === 6) + if (entry.switchJudge) yield* settings.updateSettings({ modelEvaluationModelSelection: { instanceId: ProviderInstanceId.make("codex"), @@ -538,25 +556,31 @@ it.effect( yield* seed({ thread, run: id, - subagent: index === 7, - model: { - ...modelSelection, - options: index === 5 ? [{ id: "effort", value: "high" }] : [], - }, + subagent: entry.subagent, + model: { ...modelSelection, options: entry.options }, }); yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); } const report = yield* service.list(scope); - assert.equal(report.guidance.length, 4); - const learned = report.guidance.find((group) => group.sampleCount === 5)!; + const groupsWith = (id: string) => + report.guidance.filter((group) => + (group.modelSelection.options ?? []).some((option) => option.id === id), + ); + assert.equal(report.guidance.length, 7); + const learned = report.guidance.find((group) => group.sampleCount === 6)!; assert.equal(learned.confidence, "observed"); assert.equal(learned.meanScores.taskCompletion, 3); - assert.equal(learned.scoreCounts.taskCompletion, 5); + assert.equal(learned.scoreCounts.taskCompletion, 6); assert.equal(learned.scoreCounts.verification, 0); assert.equal(learned.strengths.length, 1); + assert.equal(learned.scope, "turn"); + assert.equal(groupsWith("effort").length, 2); + assert.equal(groupsWith("reasoningEffort").length, 1); + assert.equal(groupsWith("reasoning_effort").length, 1); + assert.equal(report.guidance.filter((group) => group.scope === "subagent").length, 1); yield* settings.updateSettings({ enableModelEvaluations: false }); assert.deepEqual(yield* service.guidance(scope), []); - assert.equal((yield* service.list(scope)).records.length, 8); + assert.equal((yield* service.list(scope)).records.length, cases.length); yield* TestClock.adjust("91 days"); assert.deepEqual((yield* service.list(scope)).guidance, []); }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), From dccd7b12cd42273e375b414652668d31efb40d80 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:29:59 -0800 Subject: [PATCH 04/31] fix(server): group model guidance by output-quality options fastMode, serviceTier, contextWindow, and ultracode were splitting one model into singleton groups. The selection key keeps effort, reasoningEffort, and reasoning_effort. Co-authored-by: Cursor --- apps/server/src/modelEvaluations/ModelEvaluations.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 29bc5752c581d..1148819eb3853 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -51,11 +51,16 @@ const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(MessageId const decodeSelection = Schema.decodeUnknownEffect(Schema.fromJsonString(ModelSelection)); const isModelEvaluationError = Schema.is(ModelEvaluationError); +// fastMode, serviceTier, contextWindow, and ultracode change latency, billing, or capacity, not output quality. +const QUALITY_OPTION_IDS = new Set(["effort", "reasoningEffort", "reasoning_effort"]); + function selectionKey(selection: ModelSelection) { return JSON.stringify({ instanceId: selection.instanceId, model: selection.model, - options: (selection.options ?? []).toSorted((a, b) => a.id.localeCompare(b.id)), + options: (selection.options ?? []) + .filter((option) => QUALITY_OPTION_IDS.has(option.id)) + .toSorted((left, right) => left.id.localeCompare(right.id)), }); } From 7bea4a3a238d2ca4fc006e7fdf7e194db5fb84a0 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:32:07 -0800 Subject: [PATCH 05/31] test(server): automated wakes are not judged as user prompts A command, monitor, group, or delegated-task wake is scored as if the user asked for that work. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 97ff8cb9679d1..8397d9de5c596 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { EventId, MessageId, + NodeId, ProjectId, ProviderInstanceId, ServerProvider, @@ -112,6 +113,7 @@ const seed = Effect.fn("test.seedEvaluationRun")(function* ( readonly subagent?: boolean; readonly existingThread?: OrchestrationV2AppThread; readonly requestedAt?: DateTime.Utc; + readonly notification?: OrchestrationV2ConversationMessage["notification"]; } = {}, ) { const project = options.project ?? projectId; @@ -217,6 +219,9 @@ const seed = Effect.fn("test.seedEvaluationRun")(function* ( : "I am DeepSeek on OpenCode. Added the named export; existing callers remain compatible.", streaming: false, attachments: [], + ...(role === "user" && options.notification !== undefined + ? { notification: options.notification } + : {}), createdAt: role === "user" ? (options.requestedAt ?? at) @@ -901,3 +906,34 @@ it.effect("ranks scored guidance ahead of newer single samples and drops unscore ), ); }); + +it.effect.each(["command", "monitor", "group", "delegated_task"] as const)( + "records a %s wake as skipped and does not judge it", + (kind) => { + const calls: string[] = []; + return Effect.gen(function* () { + yield* seed({ + notification: { + source: + kind === "delegated_task" ? { kind, taskIds: [NodeId.make("wake-task")] } : { kind }, + outcome: "completed", + summary: "Background work finished", + }, + }); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.deepEqual(calls, []); + const record = (yield* service.list(scope)).records[0]!; + assert.equal(record.status, "skipped"); + assert.match(record.reason ?? "", /automated wake/); + assert.deepEqual((yield* service.list(scope)).guidance, []); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push("judge"); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); + }, +); From 952da84fa88f2944b28ff0ed8d972862bde7e875 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:34:30 -0800 Subject: [PATCH 06/31] fix(server): skip automated wakes instead of scoring them Command, monitor, group, and delegated-task wakes were judged as user prompts. A request with a notification is recorded as skipped and is not sent to the evaluator. Co-authored-by: Cursor --- .../server/src/modelEvaluations/ModelEvaluations.ts | 13 +++++++++---- .../provider-core/src/server/modelEvaluation.ts | 1 + 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 1148819eb3853..6206b001e851e 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -466,17 +466,22 @@ const make = Effect.gen(function* () { runOutcome, }); const evidence = build(records); + const automatedWake = records.messages.some( + (message) => message.id === records.run.userMessageId && message.notification !== undefined, + ); const attributed = records.run.providerInstanceId === records.run.modelSelection.instanceId && (yield* attributionKnown(threadId, runId, records.run.modelSelection)); let status: ModelEvaluationRecord["status"] = "skipped"; - let reason: string | null = "The run has no complete request and final response to evaluate."; + let reason: string | null = automatedWake + ? "The request was an automated wake, not a user prompt. No model score was recorded." + : "The run has no complete request and final response to evaluate."; let verdict: ModelEvaluationRecord["verdict"] = null; - if (!attributed) + if (!automatedWake && !attributed) reason = "The executed model could not be attributed to one stable model selection."; - if (!settled) + if (!automatedWake && !settled) reason = "The run could not finish checkpoint finalization. No model score was recorded."; - if (evidence !== null && attributed && settled) { + if (!automatedWake && evidence !== null && attributed && settled) { const generated = yield* Effect.gen(function* () { const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-model-evaluation-" }); return yield* textGeneration.generateModelEvaluation({ diff --git a/packages/provider-core/src/server/modelEvaluation.ts b/packages/provider-core/src/server/modelEvaluation.ts index 1722d292ea839..1447851d0c859 100644 --- a/packages/provider-core/src/server/modelEvaluation.ts +++ b/packages/provider-core/src/server/modelEvaluation.ts @@ -197,6 +197,7 @@ export function buildModelEvaluationEvidence(input: { .filter((item) => item.threadId === input.run.threadId && item.runId === input.run.id) .toSorted((a, b) => a.ordinal - b.ordinal); const requestMessage = messageById.get(input.run.userMessageId); + if (requestMessage?.notification !== undefined) return null; const requestItem = items.find( (item) => item.type === "user_message" && item.messageId === input.run.userMessageId, ); From 656d10a11efaa169d0e8fd08cd0c75e55a3c163c Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:36:00 -0800 Subject: [PATCH 07/31] test(server): a failed evaluation records a bounded cause Every evaluator failure is stored as one generic sentence, so a timeout cannot be told from a payload or a response body. Co-authored-by: Cursor --- .../src/modelEvaluations/ModelEvaluations.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 8397d9de5c596..15746cd4d4b0a 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -372,6 +372,13 @@ it.effect.each(["provider-error", "unsupported-citation", "abstention", "missing 0, ); if (kind !== "abstention") assert.isNull(record.verdict); + if (kind === "provider-error") { + assert.include(record.reason ?? "", "TextGenerationError"); + assert.include(record.reason ?? "", "Codex CLI request timed out."); + assert.notInclude(record.reason ?? "", "TAIL_SECRET"); + assert.notInclude(record.reason ?? "", "FULL_MODEL_RESPONSE"); + assert.notInclude(record.reason ?? "", "x".repeat(200)); + } }).pipe( Effect.provide( makeLayer((request) => { @@ -379,7 +386,8 @@ it.effect.each(["provider-error", "unsupported-citation", "abstention", "missing return Effect.fail( new TextGenerationError({ operation: "generateModelEvaluation", - detail: "Do not persist this provider payload.", + detail: `Codex CLI request timed out.${"x".repeat(500)}TAIL_SECRET`, + cause: "FULL_MODEL_RESPONSE", }), ); const output = verdict(request.packet); From 548608be284a8f3064f53da2f90d4a3843ab508a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:38:31 -0800 Subject: [PATCH 08/31] fix(server): record why a model evaluation failed Evaluator failures all stored one sentence, so a timeout looked like every other failure. The record keeps the error tag and a short detail, and leaves out the cause payload. Co-authored-by: Cursor --- .../src/modelEvaluations/ModelEvaluations.ts | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 6206b001e851e..70e801b54c4c6 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -54,6 +54,14 @@ const isModelEvaluationError = Schema.is(ModelEvaluationError); // fastMode, serviceTier, contextWindow, and ultracode change latency, billing, or capacity, not output quality. const QUALITY_OPTION_IDS = new Set(["effort", "reasoningEffort", "reasoning_effort"]); +const EVALUATOR_FAILURE_DETAIL_LIMIT = 120; + +function evaluatorFailureReason(error: { readonly _tag: string; readonly detail: string }) { + const detail = error.detail.replace(/\s+/g, " ").trim().slice(0, EVALUATOR_FAILURE_DETAIL_LIMIT); + const named = detail.length === 0 ? error._tag : `${error._tag}: ${detail}`; + return `The evaluator could not complete this evaluation (${named}). No model score was recorded.`; +} + function selectionKey(selection: ModelSelection) { return JSON.stringify({ instanceId: selection.instanceId, @@ -491,17 +499,21 @@ const make = Effect.gen(function* () { }); }).pipe( Effect.scoped, - Effect.catchTags({ TextGenerationError: () => Effect.succeed(null) }), + Effect.map((verdict) => ({ verdict, failure: null })), + Effect.catchTags({ + TextGenerationError: (error) => + Effect.succeed({ verdict: null, failure: evaluatorFailureReason(error) }), + }), ); - if (generated === null) { + if (generated.failure !== null) { status = "failed"; - reason = "The evaluator could not complete this evaluation. No model score was recorded."; - } else if (!validateModelEvaluationVerdict(generated, evidence.packet)) { + reason = generated.failure; + } else if (!validateModelEvaluationVerdict(generated.verdict, evidence.packet)) { status = "failed"; reason = "The evaluator returned unsupported scores or evidence references. No model score was recorded."; } else { - verdict = generated; + verdict = generated.verdict; status = verdict.outcome; reason = null; } From aab869e803f71a1fc7ebfb37c8aaa6e04e1a34d0 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:42:26 -0800 Subject: [PATCH 09/31] fix(server): keep model guidance types exact Chaining the guidance sort widened confidence to string, and the grouping test passed an undefined subagent flag. Co-authored-by: Cursor --- .../server/src/modelEvaluations/ModelEvaluations.test.ts | 2 +- apps/server/src/modelEvaluations/ModelEvaluations.ts | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 15746cd4d4b0a..10c28ad5e1526 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -569,7 +569,7 @@ it.effect( yield* seed({ thread, run: id, - subagent: entry.subagent, + ...(entry.subagent ? { subagent: true } : {}), model: { ...modelSelection, options: entry.options }, }); yield* service.evaluateRun({ threadId: thread, runId: id, runOutcome: "completed" }); diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 70e801b54c4c6..251e2a91c8bf5 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -128,6 +128,10 @@ function summarize( ), ), ].slice(0, 3); + const confidence: ModelEvaluationGuidance["confidence"] = + scored.filter((record) => record.verdict?.confidence !== "low").length >= 5 + ? "observed" + : "provisional"; return { scope: first.scope, modelSelection: first.modelSelection, @@ -138,10 +142,7 @@ function summarize( insufficientEvidenceCount: group.length - scored.length, meanScores, scoreCounts, - confidence: - scored.filter((record) => record.verdict?.confidence !== "low").length >= 5 - ? "observed" - : "provisional", + confidence, promptChars: { min: prompts[0] ?? 0, median: From 4b730487836e4253ac959faae311c9051d7675ba Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:57:05 -0800 Subject: [PATCH 10/31] test(server): a settled delegated child never returns to model guidance Co-Authored-By: Claude Opus 5.5 --- .../modelEvaluations/ModelEvaluations.test.ts | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 10c28ad5e1526..525d0c47050e6 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -5,6 +5,7 @@ import { MessageId, NodeId, ProjectId, + ProviderDriverKind, ProviderInstanceId, ServerProvider, RunId, @@ -945,3 +946,158 @@ it.effect.each(["command", "monitor", "group", "delegated_task"] as const)( ); }, ); + +const childDriver = ProviderDriverKind.make("claude"); + +function delegatedChild( + id: string, + status: OrchestrationV2TurnItem["status"], + result: string | null, + ordinal: number, +): Extract { + return { + id: TurnItemId.make(id), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status, + title: "Delegated child", + startedAt: at, + completedAt: status === "pending" || status === "running" || status === "waiting" ? null : at, + updatedAt: at, + type: "subagent", + subagentId: NodeId.make(id), + origin: "app_owned", + driver: childDriver, + providerInstanceId: instanceId, + childThreadId: null, + prompt: "Check the export.", + result, + }; +} + +const recordChild = ( + id: string, + status: OrchestrationV2TurnItem["status"], + result: string | null, + ordinal: number, +) => + persist({ + id: EventId.make(`child:${id}:${status}:${ordinal}`), + type: "turn-item.updated", + threadId, + runId, + occurredAt: at, + payload: delegatedChild(id, status, result, ordinal), + }); + +const packetsWith = (calls: ReadonlyArray[0]>, token: string) => + calls.filter((call) => JSON.stringify(call.packet).includes(token)); + +it.effect("scores a delegated child once that child settles", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + yield* seed(); + yield* recordChild("running-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-result-token").length, 0); + yield* recordChild("running-child", "completed", "child-result-token", 2); + assert.deepEqual((yield* service.list(scope)).records, []); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-result-token").length, 1); + const report = yield* service.list(scope); + assert.equal(report.records.length, 1); + assert.equal(report.records[0]?.status, "scored"); + assert.equal(report.guidance[0]?.sampleCount, 1); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-result-token").length, 1); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("waits to rescore until every delegated child has settled", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + yield* seed(); + yield* recordChild("child-a", "running", null, 2); + yield* recordChild("child-b", "running", null, 3); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + yield* recordChild("child-a", "completed", "child-a-token", 2); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-a-token").length, 0); + assert.deepEqual((yield* service.list(scope)).records, []); + yield* recordChild("child-b", "completed", "child-b-token", 3); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-a-token").length, 1); + assert.equal(packetsWith(calls, "child-b-token").length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("does not rescore a settled child when the exchange itself changed", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + const seeded = yield* seed(); + yield* recordChild("edited-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + yield* recordChild("edited-child", "completed", "child-edit-token", 2); + yield* persist({ + id: EventId.make("edited-final-answer"), + type: "message.updated", + threadId, + runId, + occurredAt: at, + payload: { ...seeded.messages[1]!, text: "The export was removed after review." }, + }); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "child-edit-token").length, 0); + assert.deepEqual((yield* service.list(scope)).records, []); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); + +it.effect("scores a turn whose delegated child already ended cancelled", () => { + const calls: Array[0]> = []; + return Effect.gen(function* () { + yield* seed(); + yield* recordChild("cancelled-child", "cancelled", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.equal(calls.length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer((request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }), + ), + ); +}); From 252509ace3c8fed94e92d1698dd2018001d58472 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:38:23 -0800 Subject: [PATCH 11/31] fix(server): score a turn again after its delegated children settle Judging the turn while a child was still running left a score that the child's result then marked stale, and the existing row blocked another pass. Hold the judge until every subagent item has left an active status, then replace that row from the settled evidence. Co-authored-by: Cursor --- .../ModelEvaluationSubagentRefresh.ts | 72 ++++++++ .../modelEvaluations/ModelEvaluations.test.ts | 36 +++- .../src/modelEvaluations/ModelEvaluations.ts | 167 +++++++++++++++++- .../modelEvaluationSchedule.ts | 9 +- apps/server/src/server.ts | 7 + .../src/server/modelEvaluation.test.ts | 39 ++++ .../src/server/modelEvaluation.ts | 11 ++ 7 files changed, 328 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts new file mode 100644 index 0000000000000..e9901a292b898 --- /dev/null +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts @@ -0,0 +1,72 @@ +import { + isOrchestrationV2WorkActive, + type OrchestrationV2DomainEvent, + type RunId, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as ModelEvaluations from "./ModelEvaluations.ts"; + +export class ModelEvaluationSubagentRefresh extends Context.Service< + ModelEvaluationSubagentRefresh, + { + readonly start: () => Effect.Effect; + } +>()("t3/modelEvaluations/ModelEvaluationSubagentRefresh") {} + +function settledSubagentRun( + event: OrchestrationV2DomainEvent, +): { readonly threadId: ThreadId; readonly runId: RunId } | undefined { + if (event.type !== "turn-item.updated" || event.payload.type !== "subagent") return undefined; + if (isOrchestrationV2WorkActive(event.payload.status)) return undefined; + const runId = event.runId ?? event.payload.runId; + if (runId === undefined || runId === null) return undefined; + return { threadId: event.threadId, runId }; +} + +const make = Effect.gen(function* () { + const evaluations = yield* ModelEvaluations.ModelEvaluations; + const orchestrator = yield* Orchestrator.OrchestratorV2; + + const start: ModelEvaluationSubagentRefresh["Service"]["start"] = () => + forkParked( + Effect.gen(function* () { + const after = yield* orchestrator.getLatestEventSequence(); + yield* evaluations + .enqueueSettledSubagentRefreshes() + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not refresh settled subagent evaluations", { cause }), + ), + ); + yield* Stream.runForEach(orchestrator.streamDomainEventsAfter(after), (event) => { + const run = settledSubagentRun(event); + if (run === undefined) return Effect.void; + return evaluations.enqueueSettledSubagentRefreshes({ runId: run.runId }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not refresh a settled subagent evaluation", { + threadId: run.threadId, + runId: run.runId, + cause, + }), + ), + ); + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("settled subagent evaluation refresh stopped", { cause }), + ), + ), + ); + + return { start } satisfies ModelEvaluationSubagentRefresh["Service"]; +}); + +export const layer = Layer.effect(ModelEvaluationSubagentRefresh, make); diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 525d0c47050e6..1cb88ee0542a7 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -1035,14 +1035,14 @@ it.effect("waits to rescore until every delegated child has settled", () => { yield* recordChild("child-b", "running", null, 3); const service = yield* ModelEvaluations.ModelEvaluations; yield* service.evaluateRun(input); - yield* recordChild("child-a", "completed", "child-a-token", 2); + yield* recordChild("child-a", "completed", "alpha-result", 2); yield* service.evaluateRun(input); - assert.equal(packetsWith(calls, "child-a-token").length, 0); + assert.equal(packetsWith(calls, "alpha-result").length, 0); assert.deepEqual((yield* service.list(scope)).records, []); - yield* recordChild("child-b", "completed", "child-b-token", 3); + yield* recordChild("child-b", "completed", "beta-result", 3); yield* service.evaluateRun(input); - assert.equal(packetsWith(calls, "child-a-token").length, 1); - assert.equal(packetsWith(calls, "child-b-token").length, 1); + assert.equal(packetsWith(calls, "alpha-result").length, 1); + assert.equal(packetsWith(calls, "beta-result").length, 1); assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); }).pipe( Effect.provide( @@ -1101,3 +1101,29 @@ it.effect("scores a turn whose delegated child already ended cancelled", () => { ), ); }); + +it.effect("enqueues one refresh after every delegated child settles", () => + Effect.gen(function* () { + yield* seed(); + yield* recordChild("queued-a", "running", null, 2); + yield* recordChild("queued-b", "running", null, 3); + const service = yield* ModelEvaluations.ModelEvaluations; + const sql = yield* SqlClient.SqlClient; + const refreshIds = () => + sql<{ effect_id: string }>` + SELECT effect_id FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`} + ORDER BY effect_id + `; + yield* service.evaluateRun(input); + yield* recordChild("queued-a", "completed", "queued-a-token", 2); + yield* service.enqueueSettledSubagentRefreshes({ runId }); + assert.deepEqual(yield* refreshIds(), []); + yield* recordChild("queued-b", "completed", "queued-b-token", 3); + yield* service.enqueueSettledSubagentRefreshes(); + yield* service.enqueueSettledSubagentRefreshes({ runId }); + const ids = yield* refreshIds(); + assert.equal(ids.length, 1); + assert.match(ids[0]!.effect_id, /:subagents:\d+$/); + }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), +); diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 251e2a91c8bf5..82c5aa335203a 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -4,15 +4,17 @@ import { ModelEvaluationError, ModelEvaluationRecord, ModelSelection, + RunId, + ThreadId, type ModelEvaluationGuidance, type ModelEvaluationReport, + type ModelEvaluationRunOutcome, type ProjectId, - type RunId, - type ThreadId, } from "@t3tools/contracts"; import { MODEL_EVALUATION_RUBRIC_VERSION, buildModelEvaluationEvidence, + modelEvaluationAwaitsSubagents, validateModelEvaluationVerdict, } from "@t3tools/provider-core/server/modelEvaluation"; import * as Context from "effect/Context"; @@ -62,6 +64,18 @@ function evaluatorFailureReason(error: { readonly _tag: string; readonly detail: return `The evaluator could not complete this evaluation (${named}). No model score was recorded.`; } +function refreshRunOutcome(status: string): ModelEvaluationRunOutcome | undefined { + switch (status) { + case "completed": + case "failed": + case "interrupted": + case "cancelled": + return status; + default: + return undefined; + } +} + function selectionKey(selection: ModelSelection) { return JSON.stringify({ instanceId: selection.instanceId, @@ -182,6 +196,9 @@ export class ModelEvaluations extends Context.Service< ModelEvaluations, { readonly enqueueRun: (input: RunInput) => Effect.Effect; + readonly enqueueSettledSubagentRefreshes: (input?: { + readonly runId: RunId; + }) => Effect.Effect; readonly evaluateRun: (input: RunInput) => Effect.Effect; readonly list: (input: { readonly projectId: ProjectId; @@ -346,6 +363,71 @@ const make = Effect.gen(function* () { `; return yield* Effect.forEach(rows, (row) => decodeRecord(row.payload_json)); }); + const settledSubagentRevisions = Effect.fn("ModelEvaluations.settledSubagentRevisions")( + function* (runId?: RunId) { + const after = DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { days: 90 })); + return yield* sql<{ + thread_id: string; + run_id: string; + run_status: string; + subagent_revision: number | null; + }>` + SELECT candidate.thread_id, candidate.run_id, candidate.run_status, candidate.subagent_revision + FROM ( + SELECT + evaluation.thread_id AS thread_id, + evaluation.run_id AS run_id, + run.status AS run_status, + ( + SELECT MAX(source.sequence) + FROM orchestration_events AS source + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + AND source.event_type = 'turn-item.updated' + AND json_extract(source.payload_json, '$.runId') = evaluation.run_id + AND json_extract(source.payload_json, '$.type') = 'subagent' + ) AS subagent_revision + FROM model_evaluations AS evaluation + JOIN orchestration_v2_projection_threads AS thread ON thread.thread_id = evaluation.thread_id + JOIN orchestration_v2_projection_runs AS run ON run.run_id = evaluation.run_id + WHERE thread.deleted_at IS NULL AND thread.archived_at IS NULL AND run.status <> 'rolled_back' + AND evaluation.evaluated_at >= ${after} + AND ${runId === undefined ? sql`1 = 1` : sql`evaluation.run_id = ${runId}`} + AND NOT EXISTS ( + SELECT 1 FROM orchestration_events AS source + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + AND source.event_type IN ('message.updated', 'turn-item.updated') + AND json_extract(source.payload_json, '$.runId') = evaluation.run_id + AND ( + source.event_type = 'message.updated' + OR json_extract(source.payload_json, '$.type') IN ( + 'user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool' + ) + ) + ) + AND NOT EXISTS ( + SELECT 1 FROM json_each(evaluation.source_message_ids) AS message + JOIN orchestration_events AS source + ON json_extract(source.payload_json, '$.id') = message.value + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' + AND source.sequence > evaluation.source_sequence + ) + AND NOT EXISTS ( + SELECT 1 FROM json_each(evaluation.source_message_ids) AS reference + LEFT JOIN orchestration_v2_projection_messages AS message ON message.message_id = reference.value + LEFT JOIN orchestration_v2_projection_runs AS source_run ON source_run.run_id = message.run_id + WHERE message.message_id IS NULL OR message.thread_id <> evaluation.thread_id + OR source_run.status = 'rolled_back' + OR (source_run.status = 'cancelled' AND json_extract(source_run.payload_json, '$.startedAt') IS NULL) + OR (${discardedRequest}) + ) + ) AS candidate + WHERE candidate.subagent_revision IS NOT NULL + `; + }, + ); const list: ModelEvaluations["Service"]["list"] = Effect.fn("ModelEvaluations.list")( function* ({ projectId }) { @@ -437,7 +519,14 @@ const make = Effect.gen(function* () { ); yield* requireProject(projectId); const previous = yield* sql`SELECT run_id FROM model_evaluations WHERE run_id = ${runId}`; - if (previous.length > 0) return; + const awaitsSubagents = modelEvaluationAwaitsSubagents(records.turnItems, runId); + let replacing = false; + if (previous.length > 0) { + if (awaitsSubagents) return; + const [revision] = yield* settledSubagentRevisions(runId); + if (revision === undefined) return; + replacing = true; + } const generation = yield* reset(projectId); if (DateTime.formatIso(records.run.requestedAt) <= generation.reset_at) return; const evaluatorSelection = @@ -490,7 +579,8 @@ const make = Effect.gen(function* () { reason = "The executed model could not be attributed to one stable model selection."; if (!automatedWake && !settled) reason = "The run could not finish checkpoint finalization. No model score was recorded."; - if (!automatedWake && evidence !== null && attributed && settled) { + if (!automatedWake && awaitsSubagents) reason = "Delegated work from this run is still open."; + if (!automatedWake && evidence !== null && attributed && settled && !awaitsSubagents) { const generated = yield* Effect.gen(function* () { const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-model-evaluation-" }); return yield* textGeneration.generateModelEvaluation({ @@ -564,7 +654,14 @@ const make = Effect.gen(function* () { }; yield* sql`INSERT INTO model_evaluations (run_id, project_id, thread_id, evaluated_at, source_sequence, source_message_ids, payload_json) VALUES (${runId}, ${projectId}, ${threadId}, ${record.at}, ${source.sourceSequence}, ${encodeIds(evidence?.sourceMessageIds ?? [])}, ${encodeRecord(record)}) - ON CONFLICT (run_id) DO NOTHING`; + ON CONFLICT (run_id) DO UPDATE SET + project_id = excluded.project_id, + thread_id = excluded.thread_id, + evaluated_at = excluded.evaluated_at, + source_sequence = excluded.source_sequence, + source_message_ids = excluded.source_message_ids, + payload_json = excluded.payload_json + WHERE ${replacing ? sql`1 = 1` : sql`0 = 1`}`; }), ), ); @@ -575,7 +672,65 @@ const make = Effect.gen(function* () { Effect.mapError((cause) => new ModelEvaluationPassError({ runId, cause })), ), ); - return ModelEvaluations.of({ enqueueRun, evaluateRun, list, clear, guidance }); + const enqueueSettledSubagentRefreshes: ModelEvaluations["Service"]["enqueueSettledSubagentRefreshes"] = + Effect.fn("ModelEvaluations.enqueueSettledSubagentRefreshes")( + function* (input) { + const current = yield* settings.getSettings; + if (!current.enableModelEvaluations) return; + const candidates = yield* settledSubagentRevisions(input?.runId); + const effects = yield* Effect.forEach(candidates, (candidate) => + Effect.gen(function* () { + const runOutcome = refreshRunOutcome(candidate.run_status); + if (runOutcome === undefined || candidate.subagent_revision === null) return []; + const runId = RunId.make(candidate.run_id); + const loaded = yield* projections + .getThreadRecords(ThreadId.make(candidate.thread_id), ["turnItems"], { + turnItemRunIds: [runId], + turnItemTypes: ["subagent"], + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning( + "Could not read subagent items for a model evaluation refresh", + { runId, cause }, + ).pipe(Effect.as(null)), + ), + ); + if (loaded === null || modelEvaluationAwaitsSubagents(loaded.turnItems, runId)) + return []; + return modelEvaluationEffects({ + settings: current, + threadId: ThreadId.make(candidate.thread_id), + runId, + runOutcome, + subagentRevision: candidate.subagent_revision, + }); + }), + ); + const pending = effects.flat(); + if (pending.length === 0) return; + yield* outbox.enqueue(pending); + yield* outbox.notifyAvailable(pending.length); + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ModelEvaluationPassError({ + runId: input?.runId ?? "subagent-refresh", + cause, + }), + ), + ), + ); + return ModelEvaluations.of({ + enqueueRun, + enqueueSettledSubagentRefreshes, + evaluateRun, + list, + clear, + guidance, + }); }); export const layer = Layer.effect(ModelEvaluations, make); diff --git a/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts b/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts index 675f560a16ce4..353d246965e47 100644 --- a/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts +++ b/apps/server/src/modelEvaluations/modelEvaluationSchedule.ts @@ -12,12 +12,17 @@ export function modelEvaluationEffects(input: { readonly threadId: ThreadId; readonly runId: RunId; readonly runOutcome: ModelEvaluationRunOutcome; + readonly subagentRevision?: number; }): ReadonlyArray { if (!input.settings.enableModelEvaluations) return []; + const id = + input.subagentRevision === undefined + ? `effect:model-evaluation.generate:${input.runId}` + : `effect:model-evaluation.generate:${input.runId}:subagents:${input.subagentRevision}`; return [ { - id: `effect:model-evaluation.generate:${input.runId}`, - commandId: CommandId.make(`command:effect:model-evaluation.generate:${input.runId}`), + id, + commandId: CommandId.make(`command:${id}`), threadId: input.threadId, request: { type: "model-evaluation.generate", diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1bc1265d18c61..7b5edfd711463 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -6,6 +6,7 @@ import * as HolographicMemory from "./project/knowledge/HolographicMemory.ts"; import * as ProjectKnowledge from "./project/knowledge/ProjectKnowledge.ts"; import * as AssistedLearning from "./project/knowledge/AssistedLearning.ts"; import * as ConversationSummaries from "./project/conversationSummaries/ConversationSummaries.ts"; +import * as ModelEvaluationSubagentRefresh from "./modelEvaluations/ModelEvaluationSubagentRefresh.ts"; import * as ModelEvaluations from "./modelEvaluations/ModelEvaluations.ts"; import * as ExternalHistory from "./project/externalHistory/ExternalHistory.ts"; import * as CodeIndexReactor from "./project/knowledge/CodeIndexReactor.ts"; @@ -748,6 +749,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* ModelEvaluationSubagentRefresh.ModelEvaluationSubagentRefresh; + yield* service.start(); + }), + ).pipe(Layer.provide(ModelEvaluationSubagentRefresh.layer)), Layer.effectDiscard( Effect.gen(function* () { const service = yield* GroupReactor.GroupReactor; diff --git a/packages/provider-core/src/server/modelEvaluation.test.ts b/packages/provider-core/src/server/modelEvaluation.test.ts index 0b7f6d0260857..07cb6db031cdd 100644 --- a/packages/provider-core/src/server/modelEvaluation.test.ts +++ b/packages/provider-core/src/server/modelEvaluation.test.ts @@ -19,6 +19,7 @@ import * as DateTime from "effect/DateTime"; import { buildModelEvaluationEvidence, buildModelEvaluationPrompt, + modelEvaluationAwaitsSubagents, validateModelEvaluationVerdict, } from "./modelEvaluation.ts"; @@ -427,3 +428,41 @@ it.each([ scenario === "empty-context", ); }); + +it("waits only while a delegated child is still active", () => { + const child = ( + status: + | "pending" + | "running" + | "waiting" + | "idle" + | "completed" + | "failed" + | "cancelled" + | "interrupted", + ) => ({ runId, type: "subagent" as const, status }); + expect(modelEvaluationAwaitsSubagents([child("running")], runId)).toBe(true); + expect(modelEvaluationAwaitsSubagents([child("pending"), child("waiting")], runId)).toBe(true); + expect( + modelEvaluationAwaitsSubagents( + [ + child("idle"), + child("completed"), + child("failed"), + child("cancelled"), + child("interrupted"), + ], + runId, + ), + ).toBe(false); + expect( + modelEvaluationAwaitsSubagents( + [ + child("completed"), + { runId, type: "command_execution" as const, status: "running" as const }, + ], + runId, + ), + ).toBe(false); + expect(modelEvaluationAwaitsSubagents([child("running")], RunId.make("other-run"))).toBe(false); +}); diff --git a/packages/provider-core/src/server/modelEvaluation.ts b/packages/provider-core/src/server/modelEvaluation.ts index 1447851d0c859..2f42f91e02651 100644 --- a/packages/provider-core/src/server/modelEvaluation.ts +++ b/packages/provider-core/src/server/modelEvaluation.ts @@ -1,5 +1,6 @@ import { type BlindModelEvaluationPacket, + isOrchestrationV2WorkActive, ModelEvaluationVerdict, type ModelEvaluationRunOutcome, type OrchestrationV2ConversationMessage, @@ -171,6 +172,16 @@ function evidenceText(item: OrchestrationV2TurnItem, redact: (text: string) => s } } +export function modelEvaluationAwaitsSubagents( + turnItems: ReadonlyArray>, + runId: OrchestrationV2Run["id"], +): boolean { + return turnItems.some( + (item) => + item.runId === runId && item.type === "subagent" && isOrchestrationV2WorkActive(item.status), + ); +} + export function buildModelEvaluationEvidence(input: { readonly run: Pick< OrchestrationV2Run, From 8d05906ab64277ad1984ea875d95d2c293aaed8c Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:15:06 -0800 Subject: [PATCH 12/31] test(server): a child that settles mid-evaluation leaves the turn unscored The first evaluation can read an active child and then drop the write when that child settles. Nothing queues a replacement score. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 1cb88ee0542a7..a15b131614dd6 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -55,12 +55,13 @@ const makeLayer = ( generate: Generate, enabled = true, published: ReadonlyArray = [], + readProviders: Effect.Effect> = Effect.succeed(published), ) => ModelEvaluations.layer.pipe( Layer.provide(Layer.mock(TextGeneration.TextGeneration)({ generateModelEvaluation: generate })), Layer.provide( Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed(published), + getProviders: readProviders, }), ), Layer.provideMerge( @@ -1127,3 +1128,49 @@ it.effect("enqueues one refresh after every delegated child settles", () => assert.match(ids[0]!.effect_id, /:subagents:\d+$/); }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), ); + +it.effect("scores a turn whose child settles before the evaluation is stored", () => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const release = yield* Deferred.make(); + const calls: Array[0]> = []; + const readProviders = Effect.gen(function* () { + yield* Deferred.succeed(reached, undefined); + yield* Deferred.await(release); + return []; + }); + return yield* Effect.gen(function* () { + yield* seed(); + yield* recordChild("racing-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + const sql = yield* SqlClient.SqlClient; + const fiber = yield* Effect.forkChild(service.evaluateRun(input)); + yield* Deferred.await(reached); + yield* recordChild("racing-child", "completed", "racing-child-token", 2); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(fiber); + const ids = yield* sql<{ effect_id: string }>` + SELECT effect_id FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`} + ORDER BY effect_id + `; + assert.equal(calls.length, 0); + assert.equal(ids.length, 1); + yield* service.evaluateRun(input); + assert.equal(packetsWith(calls, "racing-child-token").length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer( + (request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }, + true, + [], + readProviders, + ), + ), + ); + }), +); From 5c903ad53f67f12535722e9e134695a409f64b4d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:20:25 -0800 Subject: [PATCH 13/31] fix(server): retry a model evaluation when its snapshot goes stale A child can settle after the evaluation reads the run and before the write. The write drops that stale packet, and a run with no stored row is never scanned again. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 4 +-- .../src/modelEvaluations/ModelEvaluations.ts | 25 ++++++++++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index a15b131614dd6..2ad74f18122ae 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -1146,7 +1146,7 @@ it.effect("scores a turn whose child settles before the evaluation is stored", ( const sql = yield* SqlClient.SqlClient; const fiber = yield* Effect.forkChild(service.evaluateRun(input)); yield* Deferred.await(reached); - yield* recordChild("racing-child", "completed", "racing-child-token", 2); + yield* recordChild("racing-child", "completed", "settled-result-token", 2); yield* Deferred.succeed(release, undefined); yield* Fiber.join(fiber); const ids = yield* sql<{ effect_id: string }>` @@ -1157,7 +1157,7 @@ it.effect("scores a turn whose child settles before the evaluation is stored", ( assert.equal(calls.length, 0); assert.equal(ids.length, 1); yield* service.evaluateRun(input); - assert.equal(packetsWith(calls, "racing-child-token").length, 1); + assert.equal(packetsWith(calls, "settled-result-token").length, 1); assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); }).pipe( Effect.provide( diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 82c5aa335203a..35f3fb70f53ff 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -609,7 +609,7 @@ const make = Effect.gen(function* () { reason = null; } } - yield* settings.withSettingsSnapshot((current) => + const retry = yield* settings.withSettingsSnapshot((current) => sql.withTransaction( Effect.gen(function* () { if ( @@ -618,9 +618,9 @@ const make = Effect.gen(function* () { current.modelEvaluationModelSelection ?? current.textGenerationModelSelection, ) !== selectionKey(evaluatorSelection) ) - return; + return false; const latestGeneration = yield* reset(projectId); - if (latestGeneration.generation !== generation.generation) return; + if (latestGeneration.generation !== generation.generation) return false; const latest = yield* loadSource(threadId, runId); if ( latest === null || @@ -628,13 +628,24 @@ const make = Effect.gen(function* () { latest.run.status !== records.run.status || selectionKey(latest.run.modelSelection) !== selectionKey(records.run.modelSelection) ) - return; + return false; const latestEvidence = build(latest); if ( encodePacket(latestEvidence?.packet ?? null) !== encodePacket(evidence?.packet ?? null) - ) - return; + ) { + const revision = yield* sequence(threadId); + const effects = modelEvaluationEffects({ + settings: current, + threadId, + runId, + runOutcome, + subagentRevision: revision, + }); + if (effects.length === 0) return false; + yield* outbox.enqueue(effects); + return true; + } yield* requireProject(projectId); const record: ModelEvaluationRecord = { projectId, @@ -662,9 +673,11 @@ const make = Effect.gen(function* () { source_message_ids = excluded.source_message_ids, payload_json = excluded.payload_json WHERE ${replacing ? sql`1 = 1` : sql`0 = 1`}`; + return false; }), ), ); + if (retry) yield* outbox.notifyAvailable(1); }, (effect, { runId }) => effect.pipe( From 4d9dcebc0e803fc3d8252978b95d61817f5d46ca Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:21:57 -0800 Subject: [PATCH 14/31] test(server): a scored automated wake still feeds model guidance Rows scored before wakes were skipped stay in the guidance window. The card still treats them as user prompts. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 2ad74f18122ae..fde30fb31325c 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -917,6 +917,28 @@ it.effect("ranks scored guidance ahead of newer single samples and drops unscore ); }); +it.effect("leaves an already scored automated wake out of guidance", () => + Effect.gen(function* () { + yield* seed(); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + const sql = yield* SqlClient.SqlClient; + yield* sql` + UPDATE orchestration_v2_projection_messages + SET payload_json = json_set( + payload_json, + '$.notification', + json('{"source":{"kind":"command"},"outcome":"completed","summary":"Background work finished"}') + ) + WHERE message_id = ${`${runId}:user`} + `; + const report = yield* service.list(scope); + assert.deepEqual(report.guidance, []); + assert.deepEqual(report.records, []); + }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), +); + it.effect.each(["command", "monitor", "group", "delegated_task"] as const)( "records a %s wake as skipped and does not judge it", (kind) => { From d409383bed73564e947568f8955577bd25e0510e Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:26:18 -0800 Subject: [PATCH 15/31] fix(server): keep scored automated wakes out of model guidance Evaluations stored before wakes were skipped still match the guidance query. A scored or abstaining row whose request is a notification no longer enters that window. Co-authored-by: Cursor --- apps/server/src/modelEvaluations/ModelEvaluations.ts | 8 ++++++++ packages/provider-core/src/server/modelEvaluation.ts | 1 - 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 35f3fb70f53ff..27d45410efe36 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -334,6 +334,14 @@ const make = Effect.gen(function* () { WHERE evaluation.project_id = ${projectId} AND thread.project_id = ${projectId} AND thread.deleted_at IS NULL AND thread.archived_at IS NULL AND run.status <> 'rolled_back' AND evaluation.evaluated_at >= ${after} + AND ( + json_extract(evaluation.payload_json, '$.status') NOT IN ('scored', 'insufficient_evidence') + OR NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_messages AS request + WHERE request.message_id = json_extract(run.payload_json, '$.userMessageId') + AND json_extract(request.payload_json, '$.notification') IS NOT NULL + ) + ) AND NOT EXISTS ( SELECT 1 FROM orchestration_events AS source WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' diff --git a/packages/provider-core/src/server/modelEvaluation.ts b/packages/provider-core/src/server/modelEvaluation.ts index 2f42f91e02651..3a7bc1e8f280e 100644 --- a/packages/provider-core/src/server/modelEvaluation.ts +++ b/packages/provider-core/src/server/modelEvaluation.ts @@ -208,7 +208,6 @@ export function buildModelEvaluationEvidence(input: { .filter((item) => item.threadId === input.run.threadId && item.runId === input.run.id) .toSorted((a, b) => a.ordinal - b.ordinal); const requestMessage = messageById.get(input.run.userMessageId); - if (requestMessage?.notification !== undefined) return null; const requestItem = items.find( (item) => item.type === "user_message" && item.messageId === input.run.userMessageId, ); From a8ff1d8260e2361eceb27867f4241450e4b84d20 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:28:01 -0800 Subject: [PATCH 16/31] fix(server): use the model-evaluation event indexes for refresh lookups A subagent revision lookup constrained event_type with equality, so SQLite could not prove the partial index and scanned the stream index instead. Co-authored-by: Cursor --- apps/server/src/modelEvaluations/ModelEvaluations.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 27d45410efe36..9745ebd2d0e0a 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -388,9 +388,10 @@ const make = Effect.gen(function* () { run.status AS run_status, ( SELECT MAX(source.sequence) - FROM orchestration_events AS source + FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + AND source.event_type IN ('message.updated', 'turn-item.updated') AND source.event_type = 'turn-item.updated' AND json_extract(source.payload_json, '$.runId') = evaluation.run_id AND json_extract(source.payload_json, '$.type') = 'subagent' @@ -402,7 +403,7 @@ const make = Effect.gen(function* () { AND evaluation.evaluated_at >= ${after} AND ${runId === undefined ? sql`1 = 1` : sql`evaluation.run_id = ${runId}`} AND NOT EXISTS ( - SELECT 1 FROM orchestration_events AS source + SELECT 1 FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence AND source.event_type IN ('message.updated', 'turn-item.updated') @@ -416,7 +417,7 @@ const make = Effect.gen(function* () { ) AND NOT EXISTS ( SELECT 1 FROM json_each(evaluation.source_message_ids) AS message - JOIN orchestration_events AS source + JOIN orchestration_events AS source INDEXED BY model_evaluation_message_revision ON json_extract(source.payload_json, '$.id') = message.value WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' From 62092317bde97fd2d95e9825d6e4bc2741d0ce6d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:29:12 -0800 Subject: [PATCH 17/31] test(server): thinking options are pooled with latency settings Guidance groups effort, but a boolean thinking flag and thinking_level still share a group with fast mode and context window. Co-authored-by: Cursor --- apps/server/src/modelEvaluations/ModelEvaluations.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index fde30fb31325c..d7cb86fe79b68 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -555,6 +555,9 @@ it.effect( { options: [{ id: "effort", value: "low" }] }, { options: [{ id: "reasoningEffort", value: "high" }] }, { options: [{ id: "reasoning_effort", value: "medium" }] }, + { options: [{ id: "thinking", value: true }] }, + { options: [{ id: "thinking", value: false }] }, + { options: [{ id: "thinking_level", value: "high" }] }, { options: [], switchJudge: true }, { options: [], subagent: true }, ]; @@ -581,7 +584,7 @@ it.effect( report.guidance.filter((group) => (group.modelSelection.options ?? []).some((option) => option.id === id), ); - assert.equal(report.guidance.length, 7); + assert.equal(report.guidance.length, 10); const learned = report.guidance.find((group) => group.sampleCount === 6)!; assert.equal(learned.confidence, "observed"); assert.equal(learned.meanScores.taskCompletion, 3); @@ -592,6 +595,8 @@ it.effect( assert.equal(groupsWith("effort").length, 2); assert.equal(groupsWith("reasoningEffort").length, 1); assert.equal(groupsWith("reasoning_effort").length, 1); + assert.equal(groupsWith("thinking").length, 2); + assert.equal(groupsWith("thinking_level").length, 1); assert.equal(report.guidance.filter((group) => group.scope === "subagent").length, 1); yield* settings.updateSettings({ enableModelEvaluations: false }); assert.deepEqual(yield* service.guidance(scope), []); From 54f81b40b8fdda575f4557375f74f7b36d66c11a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:30:45 -0800 Subject: [PATCH 18/31] fix(server): group model guidance by every reasoning option Thinking and thinking_level change output quality, but the guidance key only knew three effort ids. Server and client now share one list. Co-authored-by: Cursor --- apps/server/src/modelEvaluations/ModelEvaluations.ts | 3 ++- packages/client-runtime/src/handoff.ts | 8 ++++---- packages/client-runtime/src/modelTraits.ts | 7 ++----- packages/client-runtime/src/state/threadExecution.ts | 10 ++-------- packages/shared/src/model.ts | 10 ++++++++++ 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 9745ebd2d0e0a..bc3402f628774 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -17,6 +17,7 @@ import { modelEvaluationAwaitsSubagents, validateModelEvaluationVerdict, } from "@t3tools/provider-core/server/modelEvaluation"; +import { REASONING_EFFORT_OPTION_IDS } from "@t3tools/shared/model"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -54,7 +55,7 @@ const decodeSelection = Schema.decodeUnknownEffect(Schema.fromJsonString(ModelSe const isModelEvaluationError = Schema.is(ModelEvaluationError); // fastMode, serviceTier, contextWindow, and ultracode change latency, billing, or capacity, not output quality. -const QUALITY_OPTION_IDS = new Set(["effort", "reasoningEffort", "reasoning_effort"]); +const QUALITY_OPTION_IDS = new Set(REASONING_EFFORT_OPTION_IDS); const EVALUATOR_FAILURE_DETAIL_LIMIT = 120; diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index 39b90e2414d0e..a1c47973176f1 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -12,13 +12,13 @@ import { import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, + REASONING_EFFORT_OPTION_IDS, } from "@t3tools/shared/model"; import { formatTokens } from "@t3tools/shared/usageFormat"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; -import { REASONING_EFFORT_OPTION_IDS } from "./state/threadExecution.ts"; export type HandoffTimelineRun = Pick< OrchestrationV2Run, @@ -137,9 +137,9 @@ function resolveEffort( const model = models?.find((candidate) => candidate.slug === selection.model); if (model === undefined) { // Pi states its effort as `thinking`; the catalog would otherwise mark it a reasoning control. - const value = [...REASONING_EFFORT_OPTION_IDS, "thinking"] - .map((id) => getModelSelectionStringOptionValue(selection, id)) - .find((candidate) => candidate !== undefined); + const value = REASONING_EFFORT_OPTION_IDS.map((id) => + getModelSelectionStringOptionValue(selection, id), + ).find((candidate) => candidate !== undefined); return value === undefined ? undefined : { value, label: value }; } const descriptor = model.capabilities?.optionDescriptors?.find(isReasoningSelect); diff --git a/packages/client-runtime/src/modelTraits.ts b/packages/client-runtime/src/modelTraits.ts index 6e84acf10fc0d..0732ee59cc6fa 100644 --- a/packages/client-runtime/src/modelTraits.ts +++ b/packages/client-runtime/src/modelTraits.ts @@ -4,13 +4,10 @@ import { getProviderOptionCurrentLabel, getProviderOptionCurrentValue, isClaudeUltrathinkPrompt, + REASONING_EFFORT_OPTION_IDS, } from "@t3tools/shared/model"; -import { REASONING_EFFORT_OPTION_IDS } from "./state/threadExecution.ts"; -const REASONING_DESCRIPTOR_IDS: ReadonlySet = new Set([ - ...REASONING_EFFORT_OPTION_IDS, - "thinking", -]); +const REASONING_DESCRIPTOR_IDS: ReadonlySet = new Set(REASONING_EFFORT_OPTION_IDS); /** The model's reasoning control: a known effort id, or a select its agent marked as reasoning. */ export function isReasoningControl(descriptor: ProviderOptionDescriptor): boolean { diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 4b1409821af5a..183d0350e595a 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -32,6 +32,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentLabel, getProviderOptionStatedValue, + REASONING_EFFORT_OPTION_IDS, resolveSelectableModel, withLegacyUltracodeEffort, } from "@t3tools/shared/model"; @@ -217,14 +218,7 @@ export function deriveReportedModelSelection(projection: ThreadStructure): Model return providerThread?.nativeMetadata?.modelSelection ?? null; } -export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray = [ - "reasoningEffort", - "effort", - "reasoning", - "variant", - "reasoning_effort", - "thinking_level", -]; +export { REASONING_EFFORT_OPTION_IDS }; export function formatModelSelectionEffort( selection: ModelSelection, diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index babe1347cc056..723f4b7e483be 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -14,6 +14,16 @@ import { copySorted } from "./Array.ts"; const DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make("codex"); +export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray = [ + "reasoningEffort", + "effort", + "reasoning", + "variant", + "reasoning_effort", + "thinking_level", + "thinking", +]; + export function modelSelectionCommandType( currentInstanceId: ProviderInstanceId, selection: ModelSelection, From 53a53a559ab1dc4136f959c9ad3f740a8182cdf3 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:32:18 -0800 Subject: [PATCH 19/31] test(server): a failed evaluation can store raw provider output The stored cause keeps Claude and Codex command text, including stderr, instead of a short classified reason. Co-authored-by: Cursor --- .../modelEvaluations/ModelEvaluations.test.ts | 139 ++++++++++-------- 1 file changed, 75 insertions(+), 64 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index d7cb86fe79b68..712e461dcc74e 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -352,71 +352,82 @@ it.effect( }, ); -it.effect.each(["provider-error", "unsupported-citation", "abstention", "missing-reply"] as const)( - "keeps %s separate from a low task score", - (kind) => - Effect.gen(function* () { - yield* seed({ missingReply: kind === "missing-reply" }); - const service = yield* ModelEvaluations.ModelEvaluations; - yield* service.evaluateRun(input); - const report = yield* service.list(scope); - const record = report.records[0]!; - assert.equal( - record.status, - kind === "missing-reply" - ? "skipped" - : kind === "abstention" - ? "insufficient_evidence" - : "failed", - ); - assert.equal( - report.guidance.reduce((sum, group) => sum + group.sampleCount, 0), - 0, - ); - if (kind !== "abstention") assert.isNull(record.verdict); - if (kind === "provider-error") { - assert.include(record.reason ?? "", "TextGenerationError"); - assert.include(record.reason ?? "", "Codex CLI request timed out."); - assert.notInclude(record.reason ?? "", "TAIL_SECRET"); - assert.notInclude(record.reason ?? "", "FULL_MODEL_RESPONSE"); - assert.notInclude(record.reason ?? "", "x".repeat(200)); - } - }).pipe( - Effect.provide( - makeLayer((request) => { - if (kind === "provider-error") - return Effect.fail( - new TextGenerationError({ - operation: "generateModelEvaluation", - detail: `Codex CLI request timed out.${"x".repeat(500)}TAIL_SECRET`, - cause: "FULL_MODEL_RESPONSE", - }), - ); - const output = verdict(request.packet); - if (kind === "unsupported-citation") - return Effect.succeed({ - ...output, - rationale: { text: "Unfounded claim", citations: ["E999"] }, - }); - if (kind === "abstention") - return Effect.succeed({ - ...output, - outcome: "insufficient_evidence", - confidence: "low", - scores: { - taskCompletion: null, - correctness: null, - instructionFollowing: null, - verification: null, - }, - strengths: [], - weaknesses: [], - promptAdvice: [], - }); - return Effect.succeed(output); - }), - ), +it.effect.each([ + "provider-error", + "provider-stderr", + "unsupported-citation", + "abstention", + "missing-reply", +] as const)("keeps %s separate from a low task score", (kind) => + Effect.gen(function* () { + yield* seed({ missingReply: kind === "missing-reply" }); + const service = yield* ModelEvaluations.ModelEvaluations; + yield* service.evaluateRun(input); + const report = yield* service.list(scope); + const record = report.records[0]!; + assert.equal( + record.status, + kind === "missing-reply" + ? "skipped" + : kind === "abstention" + ? "insufficient_evidence" + : "failed", + ); + assert.equal( + report.guidance.reduce((sum, group) => sum + group.sampleCount, 0), + 0, + ); + if (kind !== "abstention") assert.isNull(record.verdict); + if (kind === "provider-error" || kind === "provider-stderr") { + assert.include(record.reason ?? "", "TextGenerationError"); + assert.notInclude(record.reason ?? "", "Codex CLI request timed out"); + assert.notInclude(record.reason ?? "", "Claude CLI command failed"); + assert.notInclude(record.reason ?? "", "TAIL_SECRET"); + assert.notInclude(record.reason ?? "", "sk-live-SECRET"); + assert.notInclude(record.reason ?? "", "FULL_MODEL_RESPONSE"); + assert.notInclude(record.reason ?? "", "x".repeat(200)); + } + if (kind === "provider-error") assert.match(record.reason ?? "", /timed out/); + if (kind === "provider-stderr") assert.match(record.reason ?? "", /provider command failed/); + }).pipe( + Effect.provide( + makeLayer((request) => { + if (kind === "provider-error" || kind === "provider-stderr") + return Effect.fail( + new TextGenerationError({ + operation: "generateModelEvaluation", + detail: + kind === "provider-stderr" + ? "Claude CLI command failed: Error: leaked sk-live-SECRET from provider stderr" + : `Codex CLI request timed out.${"x".repeat(500)}TAIL_SECRET`, + cause: "FULL_MODEL_RESPONSE", + }), + ); + const output = verdict(request.packet); + if (kind === "unsupported-citation") + return Effect.succeed({ + ...output, + rationale: { text: "Unfounded claim", citations: ["E999"] }, + }); + if (kind === "abstention") + return Effect.succeed({ + ...output, + outcome: "insufficient_evidence", + confidence: "low", + scores: { + taskCompletion: null, + correctness: null, + instructionFollowing: null, + verification: null, + }, + strengths: [], + weaknesses: [], + promptAdvice: [], + }); + return Effect.succeed(output); + }), ), + ), ); it.effect.each(["clear", "disable", "edit", "move"] as const)( From 7dba64c9fcc1e33b11f132c826895eefff73ba8b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:43:42 -0800 Subject: [PATCH 20/31] test(server): one event-stream error stops subagent evaluation refresh The startup scan runs, then a dropped subscription ends the loop. A child that settles afterward is never queued. Co-authored-by: Cursor --- .../ModelEvaluationSubagentRefresh.test.ts | 53 ++++++++++++++ .../ModelEvaluationSubagentRefresh.ts | 71 +++++++++++-------- 2 files changed, 95 insertions(+), 29 deletions(-) create mode 100644 apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts new file mode 100644 index 0000000000000..7f8d56faae000 --- /dev/null +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts @@ -0,0 +1,53 @@ +import { assert, it } from "@effect/vitest"; +import { RunId, ThreadId, type OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { followSettledSubagentRefreshes } from "./ModelEvaluationSubagentRefresh.ts"; + +const runId = RunId.make("parent-run"); + +const settledChild = { + type: "turn-item.updated", + threadId: ThreadId.make("parent-thread"), + runId, + payload: { type: "subagent", status: "completed", runId }, +} as OrchestrationV2DomainEvent; + +it.effect("keeps refreshing after the event stream fails", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const started = yield* Deferred.make(); + const refreshed: Array = []; + let subscriptions = 0; + const fiber = yield* Effect.forkChild( + followSettledSubagentRefreshes({ + evaluations: { + enqueueSettledSubagentRefreshes: (input) => + Effect.sync(() => { + refreshed.push(input?.runId); + }), + }, + orchestrator: { + getLatestEventSequence: () => Deferred.succeed(started, undefined).pipe(Effect.as(0)), + streamDomainEventsAfter: () => { + subscriptions += 1; + return subscriptions === 1 + ? Stream.fail(new Error("subscription dropped")) + : Stream.fromQueue(events); + }, + }, + }), + ); + yield* Deferred.await(started); + yield* TestClock.adjust("1 second"); + yield* Queue.offer(events, settledChild); + yield* Effect.yieldNow; + assert.include(refreshed, runId); + yield* Fiber.interrupt(fiber); + }), +); diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts index e9901a292b898..46b55a87177f9 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts @@ -31,40 +31,53 @@ function settledSubagentRun( return { threadId: event.threadId, runId }; } +export const followSettledSubagentRefreshes = Effect.fn("ModelEvaluationSubagentRefresh.follow")( + function* (input: { + readonly evaluations: Pick< + ModelEvaluations.ModelEvaluations["Service"], + "enqueueSettledSubagentRefreshes" + >; + readonly orchestrator: Pick< + Orchestrator.OrchestratorV2["Service"], + "getLatestEventSequence" | "streamDomainEventsAfter" + >; + }) { + yield* Effect.gen(function* () { + const after = yield* input.orchestrator.getLatestEventSequence(); + yield* input.evaluations + .enqueueSettledSubagentRefreshes() + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not refresh settled subagent evaluations", { cause }), + ), + ); + yield* Stream.runForEach(input.orchestrator.streamDomainEventsAfter(after), (event) => { + const run = settledSubagentRun(event); + if (run === undefined) return Effect.void; + return input.evaluations.enqueueSettledSubagentRefreshes({ runId: run.runId }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not refresh a settled subagent evaluation", { + threadId: run.threadId, + runId: run.runId, + cause, + }), + ), + ); + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("settled subagent evaluation refresh stopped", { cause }), + ), + ); + }, +); + const make = Effect.gen(function* () { const evaluations = yield* ModelEvaluations.ModelEvaluations; const orchestrator = yield* Orchestrator.OrchestratorV2; const start: ModelEvaluationSubagentRefresh["Service"]["start"] = () => - forkParked( - Effect.gen(function* () { - const after = yield* orchestrator.getLatestEventSequence(); - yield* evaluations - .enqueueSettledSubagentRefreshes() - .pipe( - Effect.catchCause((cause) => - Effect.logWarning("Could not refresh settled subagent evaluations", { cause }), - ), - ); - yield* Stream.runForEach(orchestrator.streamDomainEventsAfter(after), (event) => { - const run = settledSubagentRun(event); - if (run === undefined) return Effect.void; - return evaluations.enqueueSettledSubagentRefreshes({ runId: run.runId }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Could not refresh a settled subagent evaluation", { - threadId: run.threadId, - runId: run.runId, - cause, - }), - ), - ); - }); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("settled subagent evaluation refresh stopped", { cause }), - ), - ), - ); + forkParked(followSettledSubagentRefreshes({ evaluations, orchestrator })); return { start } satisfies ModelEvaluationSubagentRefresh["Service"]; }); From 0b8e9d8ab936435c29668077b12edb9417ce6f20 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:45:12 -0800 Subject: [PATCH 21/31] fix(server): resume subagent evaluation refresh after a stream error A single dropped event subscription ended the refresh until the server restarted. The loop logs the failure and subscribes again from the latest cursor. Co-authored-by: Cursor --- .../ModelEvaluationSubagentRefresh.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts index 46b55a87177f9..80fce01dee722 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.ts @@ -5,8 +5,10 @@ import { type ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Schedule from "effect/Schedule"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -21,6 +23,12 @@ export class ModelEvaluationSubagentRefresh extends Context.Service< } >()("t3/modelEvaluations/ModelEvaluationSubagentRefresh") {} +const subscriptionBackoff = Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.minutes(1))), + ), +); + function settledSubagentRun( event: OrchestrationV2DomainEvent, ): { readonly threadId: ThreadId; readonly runId: RunId } | undefined { @@ -65,9 +73,10 @@ export const followSettledSubagentRefreshes = Effect.fn("ModelEvaluationSubagent ); }); }).pipe( - Effect.catchCause((cause) => + Effect.tapCause((cause) => Effect.logWarning("settled subagent evaluation refresh stopped", { cause }), ), + Effect.retry(subscriptionBackoff), ); }, ); From 93825c55abf8821990fcfb2cc9de532262167067 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:46:01 -0800 Subject: [PATCH 22/31] fix(server): store a classified cause when model evaluation fails Claude and Codex put command output in the error detail. The saved reason now keeps the error tag and a short cause, not that text. Co-authored-by: Cursor --- .../src/modelEvaluations/ModelEvaluations.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index bc3402f628774..040c0b3d8bdc9 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -57,12 +57,23 @@ const isModelEvaluationError = Schema.is(ModelEvaluationError); // fastMode, serviceTier, contextWindow, and ultracode change latency, billing, or capacity, not output quality. const QUALITY_OPTION_IDS = new Set(REASONING_EFFORT_OPTION_IDS); -const EVALUATOR_FAILURE_DETAIL_LIMIT = 120; +function evaluatorFailureCause(detail: string): string { + const text = detail.toLowerCase(); + if (text.includes("timed out")) return "timed out"; + if (text.includes("command failed")) return "provider command failed"; + if ( + text.includes("invalid structured output") || + text.includes("invalid evaluation events") || + text.includes("unexpected output") + ) + return "invalid output"; + if (text.includes("tool activity") || text.includes("tool work")) return "tool activity"; + if (text.includes("not available") || text.includes("enoent")) return "provider unavailable"; + return "provider request failed"; +} function evaluatorFailureReason(error: { readonly _tag: string; readonly detail: string }) { - const detail = error.detail.replace(/\s+/g, " ").trim().slice(0, EVALUATOR_FAILURE_DETAIL_LIMIT); - const named = detail.length === 0 ? error._tag : `${error._tag}: ${detail}`; - return `The evaluator could not complete this evaluation (${named}). No model score was recorded.`; + return `The evaluator could not complete this evaluation (${error._tag}: ${evaluatorFailureCause(error.detail)}). No model score was recorded.`; } function refreshRunOutcome(status: string): ModelEvaluationRunOutcome | undefined { From a600d3db3a841c96e7af644cdebc4765f85c7e1c Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:48:11 -0800 Subject: [PATCH 23/31] test(server): type the dropped subscription as a domain stream error Co-authored-by: Cursor --- .../ModelEvaluationSubagentRefresh.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts index 7f8d56faae000..dae1a34bec75c 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts @@ -7,6 +7,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { followSettledSubagentRefreshes } from "./ModelEvaluationSubagentRefresh.ts"; const runId = RunId.make("parent-run"); @@ -37,7 +38,11 @@ it.effect("keeps refreshing after the event stream fails", () => streamDomainEventsAfter: () => { subscriptions += 1; return subscriptions === 1 - ? Stream.fail(new Error("subscription dropped")) + ? Stream.fail( + new Orchestrator.OrchestratorDomainEventStreamError({ + cause: new Error("subscription dropped"), + }), + ) : Stream.fromQueue(events); }, }, From 978992fd7a33d1f27f92742c96c31482a6901947 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:01:58 -0800 Subject: [PATCH 24/31] test(server): the refresh test awaits the enqueue instead of yielding AGENTS.md rules out waiting on yieldNow; a Deferred completes when the refresh is queued. Co-Authored-By: Claude Opus 5.5 --- .../ModelEvaluationSubagentRefresh.test.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts index dae1a34bec75c..a0c6f44d9939d 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluationSubagentRefresh.test.ts @@ -23,15 +23,15 @@ it.effect("keeps refreshing after the event stream fails", () => Effect.gen(function* () { const events = yield* Queue.unbounded(); const started = yield* Deferred.make(); - const refreshed: Array = []; + const refreshed = yield* Deferred.make(); let subscriptions = 0; const fiber = yield* Effect.forkChild( followSettledSubagentRefreshes({ evaluations: { enqueueSettledSubagentRefreshes: (input) => - Effect.sync(() => { - refreshed.push(input?.runId); - }), + input?.runId === undefined + ? Effect.void + : Deferred.succeed(refreshed, input.runId).pipe(Effect.asVoid), }, orchestrator: { getLatestEventSequence: () => Deferred.succeed(started, undefined).pipe(Effect.as(0)), @@ -51,8 +51,7 @@ it.effect("keeps refreshing after the event stream fails", () => yield* Deferred.await(started); yield* TestClock.adjust("1 second"); yield* Queue.offer(events, settledChild); - yield* Effect.yieldNow; - assert.include(refreshed, runId); + assert.equal(yield* Deferred.await(refreshed), runId); yield* Fiber.interrupt(fiber); }), ); From 6fef5a035f315c0c179f79526c4537d3d17d79a0 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:02:28 -0800 Subject: [PATCH 25/31] perf(server): evaluation lookups use the whole event index Comparing json_extract to a TEXT column applies its affinity, so SQLite used only the index's stream_id column and scanned every thread event. A unary plus on the compared value lets the plan seek stream_id, the run or message id, and sequence, in the refresh query and in readRecords. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/modelEvaluations/ModelEvaluations.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 040c0b3d8bdc9..c408e64a8a0cd 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -359,7 +359,7 @@ const make = Effect.gen(function* () { WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence AND source.event_type IN ('message.updated', 'turn-item.updated') - AND json_extract(source.payload_json, '$.runId') = evaluation.run_id + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id AND (source.event_type = 'message.updated' OR json_extract(source.payload_json, '$.type') IN ('user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool', 'subagent')) ) AND NOT EXISTS ( @@ -403,9 +403,10 @@ const make = Effect.gen(function* () { FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + -- Matches the partial index's predicate; INDEXED BY fails without it. AND source.event_type IN ('message.updated', 'turn-item.updated') AND source.event_type = 'turn-item.updated' - AND json_extract(source.payload_json, '$.runId') = evaluation.run_id + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id AND json_extract(source.payload_json, '$.type') = 'subagent' ) AS subagent_revision FROM model_evaluations AS evaluation @@ -419,7 +420,7 @@ const make = Effect.gen(function* () { WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence AND source.event_type IN ('message.updated', 'turn-item.updated') - AND json_extract(source.payload_json, '$.runId') = evaluation.run_id + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id AND ( source.event_type = 'message.updated' OR json_extract(source.payload_json, '$.type') IN ( @@ -429,8 +430,8 @@ const make = Effect.gen(function* () { ) AND NOT EXISTS ( SELECT 1 FROM json_each(evaluation.source_message_ids) AS message - JOIN orchestration_events AS source INDEXED BY model_evaluation_message_revision - ON json_extract(source.payload_json, '$.id') = message.value + CROSS JOIN orchestration_events AS source INDEXED BY model_evaluation_message_revision + ON json_extract(source.payload_json, '$.id') = +message.value WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' AND source.sequence > evaluation.source_sequence From 787b466a5efed76f0947b467b223e28affaf72db Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:00:33 -0800 Subject: [PATCH 26/31] test(server): behaviour options, settling children and unavailable judges in model guidance Agent and mode options must keep their own guidance group, and a group shows the selection it ranked. A child that ends cancelled or idle mid-evaluation must still lead to a score. An unavailable judge must be recorded as such. The source-message check must seek the message-revision index. Co-Authored-By: Claude Opus 5.5 --- .../modelEvaluations/ModelEvaluations.test.ts | 127 ++++++++++++------ 1 file changed, 85 insertions(+), 42 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index 712e461dcc74e..e030074ac32dc 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -355,6 +355,7 @@ it.effect( it.effect.each([ "provider-error", "provider-stderr", + "provider-unavailable", "unsupported-citation", "abstention", "missing-reply", @@ -378,7 +379,11 @@ it.effect.each([ 0, ); if (kind !== "abstention") assert.isNull(record.verdict); - if (kind === "provider-error" || kind === "provider-stderr") { + if ( + kind === "provider-error" || + kind === "provider-stderr" || + kind === "provider-unavailable" + ) { assert.include(record.reason ?? "", "TextGenerationError"); assert.notInclude(record.reason ?? "", "Codex CLI request timed out"); assert.notInclude(record.reason ?? "", "Claude CLI command failed"); @@ -389,17 +394,24 @@ it.effect.each([ } if (kind === "provider-error") assert.match(record.reason ?? "", /timed out/); if (kind === "provider-stderr") assert.match(record.reason ?? "", /provider command failed/); + if (kind === "provider-unavailable") assert.match(record.reason ?? "", /provider unavailable/); }).pipe( Effect.provide( makeLayer((request) => { - if (kind === "provider-error" || kind === "provider-stderr") + if ( + kind === "provider-error" || + kind === "provider-stderr" || + kind === "provider-unavailable" + ) return Effect.fail( new TextGenerationError({ operation: "generateModelEvaluation", detail: kind === "provider-stderr" ? "Claude CLI command failed: Error: leaked sk-live-SECRET from provider stderr" - : `Codex CLI request timed out.${"x".repeat(500)}TAIL_SECRET`, + : kind === "provider-unavailable" + ? "The selected evaluator is unavailable. Choose an enabled, installed, authenticated provider that supports blind evaluation." + : `Codex CLI request timed out.${"x".repeat(500)}TAIL_SECRET`, cause: "FULL_MODEL_RESPONSE", }), ); @@ -546,7 +558,7 @@ it.effect( ); it.effect( - "pools latency and capacity options, and keeps effort, judges, scope, and observed scores separate", + "pools latency and capacity options, and keeps behavior, effort, judges, scope, and observed scores separate", () => Effect.gen(function* () { const service = yield* ModelEvaluations.ModelEvaluations; @@ -569,6 +581,8 @@ it.effect( { options: [{ id: "thinking", value: true }] }, { options: [{ id: "thinking", value: false }] }, { options: [{ id: "thinking_level", value: "high" }] }, + { options: [{ id: "agent", value: "plan" }] }, + { options: [{ id: "mode", value: "architect" }] }, { options: [], switchJudge: true }, { options: [], subagent: true }, ]; @@ -595,8 +609,9 @@ it.effect( report.guidance.filter((group) => (group.modelSelection.options ?? []).some((option) => option.id === id), ); - assert.equal(report.guidance.length, 10); + assert.equal(report.guidance.length, 12); const learned = report.guidance.find((group) => group.sampleCount === 6)!; + assert.deepEqual(learned.modelSelection, modelSelection); assert.equal(learned.confidence, "observed"); assert.equal(learned.meanScores.taskCompletion, 3); assert.equal(learned.scoreCounts.taskCompletion, 6); @@ -608,6 +623,8 @@ it.effect( assert.equal(groupsWith("reasoning_effort").length, 1); assert.equal(groupsWith("thinking").length, 2); assert.equal(groupsWith("thinking_level").length, 1); + assert.equal(groupsWith("agent").length, 1); + assert.equal(groupsWith("mode").length, 1); assert.equal(report.guidance.filter((group) => group.scope === "subagent").length, 1); yield* settings.updateSettings({ enableModelEvaluations: false }); assert.deepEqual(yield* service.guidance(scope), []); @@ -1167,48 +1184,74 @@ it.effect("enqueues one refresh after every delegated child settles", () => }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), ); -it.effect("scores a turn whose child settles before the evaluation is stored", () => - Effect.gen(function* () { - const reached = yield* Deferred.make(); - const release = yield* Deferred.make(); - const calls: Array[0]> = []; - const readProviders = Effect.gen(function* () { - yield* Deferred.succeed(reached, undefined); - yield* Deferred.await(release); - return []; - }); - return yield* Effect.gen(function* () { - yield* seed(); - yield* recordChild("racing-child", "running", null, 2); - const service = yield* ModelEvaluations.ModelEvaluations; - const sql = yield* SqlClient.SqlClient; - const fiber = yield* Effect.forkChild(service.evaluateRun(input)); - yield* Deferred.await(reached); - yield* recordChild("racing-child", "completed", "settled-result-token", 2); - yield* Deferred.succeed(release, undefined); - yield* Fiber.join(fiber); - const ids = yield* sql<{ effect_id: string }>` +it.effect.each(["completed", "cancelled", "idle"] as const)( + "scores a turn whose child ends %s before the evaluation is stored", + (settledStatus) => + Effect.gen(function* () { + const reached = yield* Deferred.make(); + const release = yield* Deferred.make(); + const calls: Array[0]> = []; + const readProviders = Effect.gen(function* () { + yield* Deferred.succeed(reached, undefined); + yield* Deferred.await(release); + return []; + }); + return yield* Effect.gen(function* () { + yield* seed(); + yield* recordChild("racing-child", "running", null, 2); + const service = yield* ModelEvaluations.ModelEvaluations; + const sql = yield* SqlClient.SqlClient; + const fiber = yield* Effect.forkChild(service.evaluateRun(input)); + yield* Deferred.await(reached); + yield* recordChild( + "racing-child", + settledStatus, + settledStatus === "completed" ? "settled-result-token" : null, + 2, + ); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(fiber); + const ids = yield* sql<{ effect_id: string }>` SELECT effect_id FROM orchestration_v2_effect_outbox WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`} ORDER BY effect_id `; - assert.equal(calls.length, 0); - assert.equal(ids.length, 1); - yield* service.evaluateRun(input); - assert.equal(packetsWith(calls, "settled-result-token").length, 1); - assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); - }).pipe( - Effect.provide( - makeLayer( - (request) => { - calls.push(request); - return Effect.succeed(verdict(request.packet)); - }, - true, - [], - readProviders, + assert.equal(calls.length, 0); + assert.equal(ids.length, 1); + yield* service.evaluateRun(input); + assert.equal(calls.length, 1); + if (settledStatus === "completed") + assert.equal(packetsWith(calls, "settled-result-token").length, 1); + assert.equal((yield* service.list(scope)).guidance[0]?.sampleCount, 1); + }).pipe( + Effect.provide( + makeLayer( + (request) => { + calls.push(request); + return Effect.succeed(verdict(request.packet)); + }, + true, + [], + readProviders, + ), + ), + ); + }), +); + +it.effect("checks every revised source message through the message-revision index", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const plan = yield* sql<{ detail: string }>`EXPLAIN QUERY PLAN + SELECT evaluation.run_id FROM model_evaluations AS evaluation + WHERE ${ModelEvaluations.sourceMessageRevised(sql)}`; + assert.isTrue( + plan.some((row) => + row.detail.includes( + "model_evaluation_message_revision (stream_id=? AND =? AND sequence>?)", ), ), + JSON.stringify(plan), ); - }), + }).pipe(Effect.provide(makeLayer((request) => Effect.succeed(verdict(request.packet))))), ); From e78b52e77e05b58eff9c39bb918e30b8107f363d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:01:38 -0800 Subject: [PATCH 27/31] fix(server): model guidance pools only quality-neutral options and retries settling children Guidance now drops fastMode, serviceTier, contextWindow and ultracode from a selection instead of keeping only effort options, so options like OpenCode agent and ACP mode still separate groups. The card shows that normalized selection. An evaluation retries when a delegated child settles while it runs, and an unavailable judge is classified as provider unavailable. Both evaluation lookups share one indexed source-message check. Co-Authored-By: Claude Opus 5.5 --- .../src/modelEvaluations/ModelEvaluations.ts | 84 +++++++++---------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index c408e64a8a0cd..5730d27987990 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -17,7 +17,6 @@ import { modelEvaluationAwaitsSubagents, validateModelEvaluationVerdict, } from "@t3tools/provider-core/server/modelEvaluation"; -import { REASONING_EFFORT_OPTION_IDS } from "@t3tools/shared/model"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -54,8 +53,13 @@ const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(MessageId const decodeSelection = Schema.decodeUnknownEffect(Schema.fromJsonString(ModelSelection)); const isModelEvaluationError = Schema.is(ModelEvaluationError); -// fastMode, serviceTier, contextWindow, and ultracode change latency, billing, or capacity, not output quality. -const QUALITY_OPTION_IDS = new Set(REASONING_EFFORT_OPTION_IDS); +// These change latency, billing, or capacity, not output quality. +const QUALITY_NEUTRAL_OPTION_IDS = new Set([ + "fastMode", + "serviceTier", + "contextWindow", + "ultracode", +]); function evaluatorFailureCause(detail: string): string { const text = detail.toLowerCase(); @@ -68,7 +72,12 @@ function evaluatorFailureCause(detail: string): string { ) return "invalid output"; if (text.includes("tool activity") || text.includes("tool work")) return "tool activity"; - if (text.includes("not available") || text.includes("enoent")) return "provider unavailable"; + if ( + /unavailable|not available|not installed|no provider instance|does not support|enoent/.test( + text, + ) + ) + return "provider unavailable"; return "provider request failed"; } @@ -76,7 +85,7 @@ function evaluatorFailureReason(error: { readonly _tag: string; readonly detail: return `The evaluator could not complete this evaluation (${error._tag}: ${evaluatorFailureCause(error.detail)}). No model score was recorded.`; } -function refreshRunOutcome(status: string): ModelEvaluationRunOutcome | undefined { +function settledRunOutcome(status: string): ModelEvaluationRunOutcome | undefined { switch (status) { case "completed": case "failed": @@ -88,16 +97,27 @@ function refreshRunOutcome(status: string): ModelEvaluationRunOutcome | undefine } } +function qualitySelection(selection: ModelSelection): ModelSelection { + const options = (selection.options ?? []) + .filter((option) => !QUALITY_NEUTRAL_OPTION_IDS.has(option.id)) + .toSorted((left, right) => left.id.localeCompare(right.id)); + const base = { instanceId: selection.instanceId, model: selection.model }; + return options.length === 0 ? base : { ...base, options }; +} + function selectionKey(selection: ModelSelection) { - return JSON.stringify({ - instanceId: selection.instanceId, - model: selection.model, - options: (selection.options ?? []) - .filter((option) => QUALITY_OPTION_IDS.has(option.id)) - .toSorted((left, right) => left.id.localeCompare(right.id)), - }); + return JSON.stringify(qualitySelection(selection)); } +export const sourceMessageRevised = (sql: SqlClient.SqlClient) => sql`EXISTS ( + SELECT 1 FROM json_each(evaluation.source_message_ids) AS message + CROSS JOIN orchestration_events AS source INDEXED BY model_evaluation_message_revision + ON json_extract(source.payload_json, '$.id') = +message.value + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' + AND source.sequence > evaluation.source_sequence +)`; + function summarize( records: ReadonlyArray, ): ReadonlyArray { @@ -160,8 +180,8 @@ function summarize( : "provisional"; return { scope: first.scope, - modelSelection: first.modelSelection, - evaluatorSelection: first.evaluatorSelection, + modelSelection: qualitySelection(first.modelSelection), + evaluatorSelection: qualitySelection(first.evaluatorSelection), rubricVersion: first.rubricVersion, taskCategory: first.verdict!.taskCategory, sampleCount: scored.length, @@ -362,14 +382,7 @@ const make = Effect.gen(function* () { AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id AND (source.event_type = 'message.updated' OR json_extract(source.payload_json, '$.type') IN ('user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool', 'subagent')) ) - AND NOT EXISTS ( - SELECT 1 FROM json_each(evaluation.source_message_ids) AS message - JOIN orchestration_events AS source - ON json_extract(source.payload_json, '$.id') = message.value - WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' - AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' - AND source.sequence > evaluation.source_sequence - ) + AND NOT ${sourceMessageRevised(sql)} AND NOT EXISTS ( SELECT 1 FROM json_each(evaluation.source_message_ids) AS reference LEFT JOIN orchestration_v2_projection_messages AS message ON message.message_id = reference.value @@ -428,14 +441,7 @@ const make = Effect.gen(function* () { ) ) ) - AND NOT EXISTS ( - SELECT 1 FROM json_each(evaluation.source_message_ids) AS message - CROSS JOIN orchestration_events AS source INDEXED BY model_evaluation_message_revision - ON json_extract(source.payload_json, '$.id') = +message.value - WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' - AND source.stream_id = evaluation.thread_id AND source.event_type = 'message.updated' - AND source.sequence > evaluation.source_sequence - ) + AND NOT ${sourceMessageRevised(sql)} AND NOT EXISTS ( SELECT 1 FROM json_each(evaluation.source_message_ids) AS reference LEFT JOIN orchestration_v2_projection_messages AS message ON message.message_id = reference.value @@ -529,16 +535,9 @@ const make = Effect.gen(function* () { const records = source.records; if (records === null) return; const projectId = records.thread.projectId; - const runOutcome = - records.run.status === "completed" || - records.run.status === "failed" || - records.run.status === "interrupted" || - records.run.status === "cancelled" - ? records.run.status - : requestedOutcome; - const settled = ["completed", "failed", "interrupted", "cancelled"].includes( - records.run.status, - ); + const settledOutcome = settledRunOutcome(records.run.status); + const runOutcome = settledOutcome ?? requestedOutcome; + const settled = settledOutcome !== undefined; yield* requireProject(projectId); const previous = yield* sql`SELECT run_id FROM model_evaluations WHERE run_id = ${runId}`; const awaitsSubagents = modelEvaluationAwaitsSubagents(records.turnItems, runId); @@ -654,7 +653,8 @@ const make = Effect.gen(function* () { const latestEvidence = build(latest); if ( encodePacket(latestEvidence?.packet ?? null) !== - encodePacket(evidence?.packet ?? null) + encodePacket(evidence?.packet ?? null) || + modelEvaluationAwaitsSubagents(latest.turnItems, runId) !== awaitsSubagents ) { const revision = yield* sequence(threadId); const effects = modelEvaluationEffects({ @@ -715,7 +715,7 @@ const make = Effect.gen(function* () { const candidates = yield* settledSubagentRevisions(input?.runId); const effects = yield* Effect.forEach(candidates, (candidate) => Effect.gen(function* () { - const runOutcome = refreshRunOutcome(candidate.run_status); + const runOutcome = settledRunOutcome(candidate.run_status); if (runOutcome === undefined || candidate.subagent_revision === null) return []; const runId = RunId.make(candidate.run_id); const loaded = yield* projections From 0e37cbc866c046a8a14438cb0e3d8734e64d7782 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:02:32 -0800 Subject: [PATCH 28/31] revert(client-runtime): keep the reasoning option list where it was The server no longer reads this list, so moving it to packages/shared and adding Pi's thinking option is outside this change. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/handoff.ts | 8 ++++---- packages/client-runtime/src/modelTraits.ts | 7 +++++-- packages/client-runtime/src/state/threadExecution.ts | 10 ++++++++-- packages/shared/src/model.ts | 10 ---------- 4 files changed, 17 insertions(+), 18 deletions(-) diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index a1c47973176f1..39b90e2414d0e 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -12,13 +12,13 @@ import { import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, - REASONING_EFFORT_OPTION_IDS, } from "@t3tools/shared/model"; import { formatTokens } from "@t3tools/shared/usageFormat"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; +import { REASONING_EFFORT_OPTION_IDS } from "./state/threadExecution.ts"; export type HandoffTimelineRun = Pick< OrchestrationV2Run, @@ -137,9 +137,9 @@ function resolveEffort( const model = models?.find((candidate) => candidate.slug === selection.model); if (model === undefined) { // Pi states its effort as `thinking`; the catalog would otherwise mark it a reasoning control. - const value = REASONING_EFFORT_OPTION_IDS.map((id) => - getModelSelectionStringOptionValue(selection, id), - ).find((candidate) => candidate !== undefined); + const value = [...REASONING_EFFORT_OPTION_IDS, "thinking"] + .map((id) => getModelSelectionStringOptionValue(selection, id)) + .find((candidate) => candidate !== undefined); return value === undefined ? undefined : { value, label: value }; } const descriptor = model.capabilities?.optionDescriptors?.find(isReasoningSelect); diff --git a/packages/client-runtime/src/modelTraits.ts b/packages/client-runtime/src/modelTraits.ts index 0732ee59cc6fa..6e84acf10fc0d 100644 --- a/packages/client-runtime/src/modelTraits.ts +++ b/packages/client-runtime/src/modelTraits.ts @@ -4,10 +4,13 @@ import { getProviderOptionCurrentLabel, getProviderOptionCurrentValue, isClaudeUltrathinkPrompt, - REASONING_EFFORT_OPTION_IDS, } from "@t3tools/shared/model"; +import { REASONING_EFFORT_OPTION_IDS } from "./state/threadExecution.ts"; -const REASONING_DESCRIPTOR_IDS: ReadonlySet = new Set(REASONING_EFFORT_OPTION_IDS); +const REASONING_DESCRIPTOR_IDS: ReadonlySet = new Set([ + ...REASONING_EFFORT_OPTION_IDS, + "thinking", +]); /** The model's reasoning control: a known effort id, or a select its agent marked as reasoning. */ export function isReasoningControl(descriptor: ProviderOptionDescriptor): boolean { diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 183d0350e595a..4b1409821af5a 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -32,7 +32,6 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentLabel, getProviderOptionStatedValue, - REASONING_EFFORT_OPTION_IDS, resolveSelectableModel, withLegacyUltracodeEffort, } from "@t3tools/shared/model"; @@ -218,7 +217,14 @@ export function deriveReportedModelSelection(projection: ThreadStructure): Model return providerThread?.nativeMetadata?.modelSelection ?? null; } -export { REASONING_EFFORT_OPTION_IDS }; +export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray = [ + "reasoningEffort", + "effort", + "reasoning", + "variant", + "reasoning_effort", + "thinking_level", +]; export function formatModelSelectionEffort( selection: ModelSelection, diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index 723f4b7e483be..babe1347cc056 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -14,16 +14,6 @@ import { copySorted } from "./Array.ts"; const DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make("codex"); -export const REASONING_EFFORT_OPTION_IDS: ReadonlyArray = [ - "reasoningEffort", - "effort", - "reasoning", - "variant", - "reasoning_effort", - "thinking_level", - "thinking", -]; - export function modelSelectionCommandType( currentInstanceId: ProviderInstanceId, selection: ModelSelection, From 8f44414833f15165bb33664ed464de2e0e34d8a3 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:03:35 -0800 Subject: [PATCH 29/31] docs: model evaluations describe pooled options, wakes and delegated work Co-Authored-By: Claude Opus 5.5 --- docs/user/model-evaluations.md | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/docs/user/model-evaluations.md b/docs/user/model-evaluations.md index 319c350f7d512..8de3cfb7b6647 100644 --- a/docs/user/model-evaluations.md +++ b/docs/user/model-evaluations.md @@ -18,29 +18,35 @@ which keeps account authentication while disabling custom instructions and exten After a task ends, T3 Code gives the judge the request, relevant conversation context, and available outcome evidence with model and provider labels removed. The same process covers subagent threads -run through T3's orchestration. Model names mentioned inside free-form text may be harder to remove -completely, and tool output keeps its structure and any token, cost, or timing figures a tool -reports. Those can hint at which harness ran the task, so blind evaluation reduces identity cues -without guaranteeing anonymity. +run through T3's orchestration. A task that delegated work is evaluated once that delegated work +finishes, so its result counts. A turn started by an automated wake, such as a finished background +command, is recorded as skipped rather than scored, because it was not a request you wrote. Model +names mentioned inside free-form text may be harder to remove completely, and tool output keeps its +structure and any token, cost, or timing figures a tool reports. Those can hint at which harness ran +the task, so blind evaluation reduces identity cues without guaranteeing anonymity. The judge scores task completion, correctness, instruction following, and verification from 0 to 4. When the evidence cannot establish a score, that dimension stays unscored. A claim that tests passed is not the same as a recorded test result. Failed evaluation calls and insufficient evidence remain -visible in recent evaluations, instead of becoming poor performance scores for the evaluated model. +visible in recent evaluations with a short cause, such as a timeout or an unavailable judge, instead +of becoming poor performance scores for the evaluated model. ## Inspect and use guidance Choose a project under **Learned guidance** to see its recent evaluations and accumulated strengths, limitations, and prompting advice. Results stay within that project and environment. T3 keeps -separate groups for different model options, task categories, top-level versus subagent tasks, -judges, and scoring rubrics, so a change of judge does not silently mix two scales. +separate groups for different task categories, top-level versus subagent tasks, judges, scoring +rubrics, and model options that can change the answer, such as reasoning effort or agent mode, so a +change of judge does not silently mix two scales. Options that only change speed, cost, or context +size, such as fast mode, share one group. Guidance reflects up to 200 observations from the past 90 days. The displayed sample counts show how much evidence supports each score. Small samples remain provisional, and all guidance is an aid to judgment rather than a guarantee about future tasks. Observed prompt lengths describe past requests; they do not measure a model's maximum context window or establish an ideal prompt length. -Agents using T3's orchestration can retrieve this guidance when choosing models and framing delegated -tasks. Your explicit model choice still wins. Turning evaluations off stops new evaluation calls -and use of the guidance while leaving saved history available to inspect. **Clear project history** -removes that project's scores and learned guidance; later tasks can collect new observations. +Agents using T3's orchestration can retrieve this guidance when choosing models and framing +delegated tasks. Groups backed by more scored tasks come first. Your explicit model choice still +wins. Turning evaluations off stops new evaluation calls and use of the guidance while leaving saved +history available to inspect. **Clear project history** removes that project's scores and learned +guidance; later tasks can collect new observations. From 127af66fddf70abd9be5b1d242775a6758fff52e Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:14:29 -0800 Subject: [PATCH 30/31] docs: model evaluations give the judge-scale reason its own sentence Co-Authored-By: Claude Opus 5.5 --- docs/user/model-evaluations.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/user/model-evaluations.md b/docs/user/model-evaluations.md index 8de3cfb7b6647..86b96ad44ed65 100644 --- a/docs/user/model-evaluations.md +++ b/docs/user/model-evaluations.md @@ -36,9 +36,9 @@ of becoming poor performance scores for the evaluated model. Choose a project under **Learned guidance** to see its recent evaluations and accumulated strengths, limitations, and prompting advice. Results stay within that project and environment. T3 keeps separate groups for different task categories, top-level versus subagent tasks, judges, scoring -rubrics, and model options that can change the answer, such as reasoning effort or agent mode, so a -change of judge does not silently mix two scales. Options that only change speed, cost, or context -size, such as fast mode, share one group. +rubrics, and model options that can change the answer, such as reasoning effort or agent mode. A +change of judge or rubric starts a new group, so two scoring scales are never mixed. Options that only +change speed, cost, or context size, such as fast mode, share one group. Guidance reflects up to 200 observations from the past 90 days. The displayed sample counts show how much evidence supports each score. Small samples remain provisional, and all guidance is an From 293af03934612391210645c1955235ddfc52aa17 Mon Sep 17 00:00:00 2001 From: Zack Jackson <25274700+ScriptedAlchemy@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:35:42 -0800 Subject: [PATCH 31/31] fix(server): keep edited evidence out of evaluation retries --- .../modelEvaluations/ModelEvaluations.test.ts | 5 +++ .../src/modelEvaluations/ModelEvaluations.ts | 40 +++++++++++++------ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts index e030074ac32dc..12eed453cd4ed 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.test.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.test.ts @@ -482,6 +482,11 @@ it.effect.each(["clear", "disable", "edit", "move"] as const)( yield* (yield* SqlClient.SqlClient)`SELECT run_id FROM model_evaluations`, [], ); + assert.deepEqual( + yield* (yield* SqlClient.SqlClient)`SELECT effect_id FROM orchestration_v2_effect_outbox + WHERE effect_id LIKE ${`effect:model-evaluation.generate:${runId}:subagents:%`}`, + [], + ); if (action === "clear") { yield* service.evaluateRun(input); assert.deepEqual((yield* service.list(scope)).records, []); diff --git a/apps/server/src/modelEvaluations/ModelEvaluations.ts b/apps/server/src/modelEvaluations/ModelEvaluations.ts index 5730d27987990..7b064cb1ca802 100644 --- a/apps/server/src/modelEvaluations/ModelEvaluations.ts +++ b/apps/server/src/modelEvaluations/ModelEvaluations.ts @@ -118,6 +118,20 @@ export const sourceMessageRevised = (sql: SqlClient.SqlClient) => sql`EXISTS ( AND source.sequence > evaluation.source_sequence )`; +const nonSubagentSourceRevised = (sql: SqlClient.SqlClient) => sql`EXISTS ( + SELECT 1 FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision + WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' + AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence + AND source.event_type IN ('message.updated', 'turn-item.updated') + AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id + AND ( + source.event_type = 'message.updated' + OR json_extract(source.payload_json, '$.type') IN ( + 'user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool' + ) + ) +)`; + function summarize( records: ReadonlyArray, ): ReadonlyArray { @@ -428,19 +442,7 @@ const make = Effect.gen(function* () { WHERE thread.deleted_at IS NULL AND thread.archived_at IS NULL AND run.status <> 'rolled_back' AND evaluation.evaluated_at >= ${after} AND ${runId === undefined ? sql`1 = 1` : sql`evaluation.run_id = ${runId}`} - AND NOT EXISTS ( - SELECT 1 FROM orchestration_events AS source INDEXED BY model_evaluation_source_revision - WHERE source.application_event_version = 2 AND source.aggregate_kind = 'thread' - AND source.stream_id = evaluation.thread_id AND source.sequence > evaluation.source_sequence - AND source.event_type IN ('message.updated', 'turn-item.updated') - AND json_extract(source.payload_json, '$.runId') = +evaluation.run_id - AND ( - source.event_type = 'message.updated' - OR json_extract(source.payload_json, '$.type') IN ( - 'user_message', 'assistant_message', 'command_execution', 'file_change', 'dynamic_tool' - ) - ) - ) + AND NOT ${nonSubagentSourceRevised(sql)} AND NOT ${sourceMessageRevised(sql)} AND NOT EXISTS ( SELECT 1 FROM json_each(evaluation.source_message_ids) AS reference @@ -656,6 +658,18 @@ const make = Effect.gen(function* () { encodePacket(evidence?.packet ?? null) || modelEvaluationAwaitsSubagents(latest.turnItems, runId) !== awaitsSubagents ) { + if ( + encodeIds(latestEvidence?.sourceMessageIds ?? []) !== + encodeIds(evidence?.sourceMessageIds ?? []) + ) + return false; + const [changes] = yield* sql<{ revised: number }>` + WITH evaluation(thread_id, run_id, source_sequence, source_message_ids) AS ( + VALUES (${threadId}, ${runId}, ${source.sourceSequence}, ${encodeIds(evidence?.sourceMessageIds ?? [])}) + ) + SELECT ${nonSubagentSourceRevised(sql)} OR ${sourceMessageRevised(sql)} AS revised + FROM evaluation`; + if (changes!.revised !== 0) return false; const revision = yield* sequence(threadId); const effects = modelEvaluationEffects({ settings: current,