From a700dcc5d51656a4a7b4830d78fae909d6ecd601 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:53:10 -0800 Subject: [PATCH 01/27] test(server): reproduce peer reply summary attribution --- .../ConversationSummaries.test.ts | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index a286802f16670..657a43465789b 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -464,6 +464,47 @@ it.effect( }, ); +it.effect("attributes peer replies to their speaker in summary model input", () => { + const model = citing(); + return Effect.gen(function* () { + yield* seed; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const peer = item(1); + if (peer.type !== "assistant_message") return yield* Effect.die("Expected a peer reply"); + yield* projections.apply({ + id: EventId.make("peer-reply-attribution"), + type: "turn-item.updated", + threadId, + providerInstanceId: instanceId, + occurredAt: at, + payload: { ...peer, speaker: { label: "Astra", model: "gpt-6-astra" } }, + }); + yield* summarize; + assert.deepEqual(model.calls[0]?.messages[1], { + ref: "M2", + role: "user", + text: `[Historical peer_reply; speaker=Astra (gpt-6-astra); thread=summary-thread; run=summary-run; item=item-1; provider-thread=none; status=completed]\n${rawText(1)}`, + }); + assert.deepEqual(model.calls[0]?.messages[3], { + ref: "M4", + role: "assistant", + text: rawText(3), + }); + const summary = yield* onlySummary; + const service = yield* ConversationSummaries.ConversationSummaries; + const expansion = yield* service.expand({ + ...scope, + summaryId: summary.id, + offset: 1, + limit: 1, + }); + assert.equal( + expansion.sources[0]?.result.state === "available" ? expansion.sources[0].result.text : null, + rawText(1), + ); + }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); +}); + it.effect("negotiates ranged summary responses while preserving legacy whole-message reads", () => { const model = citing(); return Effect.gen(function* () { From b71f68c2d372e0a9d5ec40a1f8128ad55321d9c4 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 01:59:36 -0800 Subject: [PATCH 02/27] fix(server): attribute peer replies in conversation summaries --- .../ConversationSummaries.ts | 29 +++++++++++++++---- .../provider-core/src/server/handoffBudget.ts | 2 +- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 9143dce1eef99..d419b0431073d 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -19,6 +19,7 @@ import { type KnowledgeSourceUnavailableReason, type MessageId, type OrchestrationV2ConversationMessage, + type OrchestrationV2HistoricalMessage, type OrchestrationV2RunStatus, type OrchestrationV2UserMessageInputIntent, type ProjectId, @@ -31,6 +32,10 @@ import { summaryToolText, summaryToolTypes, } from "@t3tools/provider-core/server/conversationEvidence"; +import { + historicalMessage, + renderHistoricalMessage, +} from "@t3tools/provider-core/server/handoffBudget"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline"; import * as Context from "effect/Context"; @@ -816,7 +821,7 @@ const make = Effect.gen(function* () { const records = yield* projections .getThreadRecords(threadId, ["messages", "turnItems"], { messageRoles: ["user", "assistant"], - turnItemTypes: summaryToolTypes, + turnItemTypes: [...summaryToolTypes, "assistant_message"], turnItemStatuses: finalizedToolStatuses, }) .pipe(Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) })); @@ -922,8 +927,13 @@ const make = Effect.gen(function* () { createdAt: message.createdAt, }); } + const peerReplies = new Map(); for (const item of records.turnItems) { if (item.runId !== null && excluded.has(item.runId)) continue; + if (item.type === "assistant_message" && item.speaker !== undefined) { + const historical = historicalMessage(item); + if (historical !== null) peerReplies.set(item.messageId, historical); + } const text = summaryToolText(item); if (text === null) continue; all.push({ @@ -1080,11 +1090,18 @@ const make = Effect.gen(function* () { const summarizeLeaf = (chunk: ReadonlyArray) => publish({ - messages: chunk.map((source) => ({ - role: source.role, - text: source.text, - ...(source.ref.range === undefined ? {} : { range: source.ref.range }), - })), + messages: chunk.map((source) => { + const peer = + source.ref.kind === "message" ? peerReplies.get(source.ref.messageId) : undefined; + return { + role: peer?.role ?? source.role, + text: + peer === undefined + ? source.text + : renderHistoricalMessage({ ...peer, text: source.text }), + ...(source.ref.range === undefined ? {} : { range: source.ref.range }), + }; + }), sources: chunk.map((source) => source.ref), ranges: chunk.map((source) => source.ref), position: leafPosition(DateTime.formatIso(chunk[0]!.createdAt), chunk[0]!.ref), diff --git a/packages/provider-core/src/server/handoffBudget.ts b/packages/provider-core/src/server/handoffBudget.ts index 1e8ba7473c5bc..40a168e026ee3 100644 --- a/packages/provider-core/src/server/handoffBudget.ts +++ b/packages/provider-core/src/server/handoffBudget.ts @@ -304,7 +304,7 @@ export function historicalMessage( }; } -function renderHistoricalMessage(message: OrchestrationV2HistoricalMessage): string { +export function renderHistoricalMessage(message: OrchestrationV2HistoricalMessage): string { const source = message.speaker === undefined ? `${message.role}; ${message.kind}` From fe56ee303f7ec220632adc2f3dcce5b05a0103e1 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:43:13 -0800 Subject: [PATCH 03/27] test(server): peer replies must be named in summary input A seat model's reply is still handed to the summarizer as the user, and to assisted learning as the assistant. These tests require a peer role that carries the speaker. Co-authored-by: Cursor --- .../ConversationSummaries.test.ts | 25 ++++++-- .../knowledge/AssistedLearning.test.ts | 49 ++++++++++++++ evals/conversation-summaries/cases.ts | 64 +++++++++++++++++++ evals/conversation-summaries/grade.ts | 53 +++++++++++---- evals/conversation-summaries/run.test.ts | 45 ++++++++++++- .../src/conversationSummaries/index.test.ts | 41 ++++++++++++ .../contracts/src/conversationSummaries.ts | 5 ++ .../src/server/textGeneration.ts | 22 ++----- .../src/server/textGenerationPrompts.test.ts | 49 +++++++++++++- .../src/server/textGenerationPrompts.ts | 36 +++++++---- 10 files changed, 340 insertions(+), 49 deletions(-) create mode 100644 packages/client-runtime/src/conversationSummaries/index.test.ts diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 657a43465789b..66e60955c58cd 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -482,8 +482,9 @@ it.effect("attributes peer replies to their speaker in summary model input", () yield* summarize; assert.deepEqual(model.calls[0]?.messages[1], { ref: "M2", - role: "user", - text: `[Historical peer_reply; speaker=Astra (gpt-6-astra); thread=summary-thread; run=summary-run; item=item-1; provider-thread=none; status=completed]\n${rawText(1)}`, + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: rawText(1), }); assert.deepEqual(model.calls[0]?.messages[3], { ref: "M4", @@ -498,10 +499,22 @@ it.effect("attributes peer replies to their speaker in summary model input", () offset: 1, limit: 1, }); - assert.equal( - expansion.sources[0]?.result.state === "available" ? expansion.sources[0].result.text : null, - rawText(1), - ); + const peerSource = expansion.sources[0]?.result; + assert.equal(peerSource?.state, "available"); + if (peerSource?.state !== "available") return yield* Effect.die("Expected the peer source"); + assert.equal(peerSource.role, "assistant"); + assert.deepEqual(peerSource.speaker, { label: "Astra", model: "gpt-6-astra" }); + assert.equal(peerSource.text, rawText(1)); + const agentPage = yield* service.expand({ + ...scope, + summaryId: summary.id, + offset: 3, + limit: 1, + }); + const agentSource = agentPage.sources[0]?.result; + if (agentSource?.state !== "available") return yield* Effect.die("Expected the agent source"); + assert.equal(agentSource.role, "assistant"); + assert.equal(agentSource.speaker, undefined); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); diff --git a/apps/server/src/project/knowledge/AssistedLearning.test.ts b/apps/server/src/project/knowledge/AssistedLearning.test.ts index b2ef4358861b4..955d638bfd13e 100644 --- a/apps/server/src/project/knowledge/AssistedLearning.test.ts +++ b/apps/server/src/project/knowledge/AssistedLearning.test.ts @@ -11,6 +11,7 @@ import { RunId, TextGenerationError, ThreadId, + TurnItemId, type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -315,6 +316,54 @@ it.effect("saves a settled run's cited facts exactly once, recallable without re }).pipe(Effect.provide(makeLayer(model.generate))); }); +it.effect("sends a peer reply as that peer, not as the assistant", () => { + const model = scripted([{ candidates: [] }]); + const text = "Done. I converted the handlers to snake_case keys."; + return Effect.gen(function* () { + yield* seedRun; + const projections = yield* ProjectionStore.ProjectionStoreV2; + yield* projections.apply({ + id: EventId.make("peer-reply"), + type: "turn-item.updated", + threadId, + providerInstanceId, + occurredAt: at, + payload: { + id: TurnItemId.make("learning-peer-item"), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed", + title: null, + startedAt: at, + completedAt: at, + updatedAt: at, + type: "assistant_message", + messageId: MessageId.make("learning-reply"), + text, + streaming: false, + speaker: { label: "Astra", model: "gpt-6-astra" }, + }, + }); + const runner = yield* AssistedLearningRunner; + yield* runner.extractRun({ threadId, runId, runOutcome: "completed" }); + assert.deepEqual(model.calls[0]?.messages[1], { + ref: "M2", + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + threadId, + runId, + runOutcome: "completed", + text, + }); + }).pipe(Effect.provide(makeLayer(model.generate))); +}); + it.effect("marks candidates from a failed run with that outcome", () => { const model = scripted([{ candidates: [snakeCase] }]); return Effect.gen(function* () { diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts index 08742d1a02dc6..95d9f5fbc80a0 100644 --- a/evals/conversation-summaries/cases.ts +++ b/evals/conversation-summaries/cases.ts @@ -1,3 +1,67 @@ +/** One finalized exchange, as a leaf summary pass sends it. A peer carries the seat that spoke. */ +export type LeafMessage = + | { readonly role: "user" | "assistant"; readonly text: string } + | { + readonly role: "peer"; + readonly text: string; + readonly speaker: { readonly label: string; readonly model: string }; + }; + +export interface LeafCase { + readonly id: string; + readonly kind: "bad" | "control"; + readonly source: string; + readonly messages: ReadonlyArray; + /** Each regex must match some statement. */ + readonly mustMention: ReadonlyArray; + /** A statement matching `when` must also match `require`. */ + readonly attributed: ReadonlyArray<{ readonly when: string; readonly require: string }>; + /** No statement may match these. */ + readonly mustNot: ReadonlyArray; +} + +export const leafCases: ReadonlyArray = [ + { + id: "leaf-peer-proposal-is-not-a-user-decision", + kind: "bad", + source: + "Group threads (t3/peer-reply-summary-attribution): a seat model's published reply was summarized as the user's decision.", + messages: [ + { role: "user", text: "Where should sessions live? I have not decided." }, + { + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: "Drop Redis and use Postgres for sessions.", + }, + { + role: "assistant", + text: "I disagree. Keep Redis for sessions. The choice is still open.", + }, + ], + mustMention: ["Astra", "Postgres"], + attributed: [{ when: "Postgres|[Dd]rop Redis", require: "Astra" }], + mustNot: [ + "[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis)", + "[Uu]ser's decision to (drop Redis|use Postgres|keep Redis)", + ], + }, + { + id: "leaf-ordinary-exchange-has-no-peer", + kind: "control", + source: "Control for peer attribution: an ordinary user and agent exchange with no peer.", + messages: [ + { role: "user", text: "Add a README section on configuring the proxy." }, + { + role: "assistant", + text: "I added the README section with an example config. The link checker has not run yet.", + }, + ], + mustMention: ["README", "link checker|links"], + attributed: [], + mustNot: ["Astra"], + }, +]; + /** A roll-up input: four adjacent child summaries, oldest first, as the summary pass sends them. */ export interface CondensedCase { readonly id: string; diff --git a/evals/conversation-summaries/grade.ts b/evals/conversation-summaries/grade.ts index 506611fcb42f4..2fa438d578a9f 100644 --- a/evals/conversation-summaries/grade.ts +++ b/evals/conversation-summaries/grade.ts @@ -1,29 +1,60 @@ -import type { CondensedCase } from "./cases.ts"; +import type { CondensedCase, LeafCase } from "./cases.ts"; const MAX_CHARS = 1_200; -/** Every way a roll-up reply breaks the case's rules; empty when it passes. */ -export function gradeCondensed( - fixture: CondensedCase, - statements: ReadonlyArray<{ readonly text: string; readonly citations: ReadonlyArray }>, +type Statement = { readonly text: string; readonly citations: ReadonlyArray }; +type Rules = Pick; + +function gradeStatements( + refs: ReadonlySet, + statements: ReadonlyArray, + rules: Rules, + maxChars: number | undefined, ): ReadonlyArray { - const refs = new Set(fixture.summaries.map((_, index) => `M${index + 1}`)); const texts = statements.map((statement) => statement.text); const failures: Array = []; if (statements.length === 0) failures.push("no statements"); for (const statement of statements) if (!statement.citations.some((ref) => refs.has(ref.trim()))) failures.push(`cites no given source: ${statement.text}`); - const chars = texts.reduce((sum, text) => sum + text.trim().length, 0); - if (chars > MAX_CHARS) failures.push(`${chars} characters, over ${MAX_CHARS}`); - for (const pattern of fixture.mustMention) + if (maxChars !== undefined) { + const chars = texts.reduce((sum, text) => sum + text.trim().length, 0); + if (chars > maxChars) failures.push(`${chars} characters, over ${maxChars}`); + } + for (const pattern of rules.mustMention) if (!texts.some((text) => new RegExp(pattern).test(text))) failures.push(`missing ${pattern}`); - for (const rule of fixture.attributed) + for (const rule of rules.attributed) for (const text of texts) if (new RegExp(rule.when).test(text) && !new RegExp(rule.require, "i").test(text)) failures.push(`${rule.when} without ${rule.require}: ${text}`); - for (const pattern of fixture.mustNot) + for (const pattern of rules.mustNot) for (const text of texts) if (new RegExp(pattern, "i").test(text)) failures.push(`${pattern}: ${text}`); return failures; } + +/** Every way a roll-up reply breaks the case's rules; empty when it passes. */ +export function gradeCondensed( + fixture: CondensedCase, + statements: ReadonlyArray, +): ReadonlyArray { + return gradeStatements( + new Set(fixture.summaries.map((_, index) => `M${index + 1}`)), + statements, + fixture, + MAX_CHARS, + ); +} + +/** Every way a leaf reply breaks the case's rules; empty when it passes. */ +export function gradeLeaf( + fixture: LeafCase, + statements: ReadonlyArray, +): ReadonlyArray { + return gradeStatements( + new Set(fixture.messages.map((_, index) => `M${index + 1}`)), + statements, + fixture, + undefined, + ); +} diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index dc6f4a2f0c073..b6cb502240011 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -1,8 +1,9 @@ import { expect, it } from "vite-plus/test"; -import { condensedCases } from "./cases.ts"; -import { gradeCondensed } from "./grade.ts"; +import { condensedCases, leafCases } from "./cases.ts"; +import { gradeCondensed, gradeLeaf } from "./grade.ts"; const [reversal, control] = condensedCases; +const [peerLeaf, ordinaryLeaf] = leafCases; it("passes a roll-up that keeps the reversal, the attribution and the open item", () => { expect( @@ -40,6 +41,46 @@ it("fails a roll-up that drops the reversal, verifies a claim, or overruns its b ); }); +it("passes a leaf that names the peer and leaves the choice open", () => { + expect( + gradeLeaf(peerLeaf!, [ + { + text: "Astra proposed dropping Redis and using Postgres for sessions.", + citations: ["M2"], + }, + { + text: "The agent disagreed and wants to keep Redis. The user has not decided.", + citations: ["M1", "M3"], + }, + ]), + ).toEqual([]); +}); + +it("fails a leaf that records the peer proposal as the user's decision", () => { + expect( + gradeLeaf(peerLeaf!, [ + { text: "The user decided to use Postgres for sessions.", citations: ["M2"] }, + { text: "The agent wants to keep Redis.", citations: ["M3"] }, + ]), + ).toEqual([ + "missing Astra", + "Postgres|[Dd]rop Redis without Astra: The user decided to use Postgres for sessions.", + "[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis): The user decided to use Postgres for sessions.", + ]); +}); + +it("passes an ordinary leaf with no peer", () => { + expect( + gradeLeaf(ordinaryLeaf!, [ + { + text: "The user asked for a README section on the proxy, and the agent added it.", + citations: ["M1", "M2"], + }, + { text: "The link checker has not run yet.", citations: ["M2"] }, + ]), + ).toEqual([]); +}); + it("passes an ordinary roll-up in the control case", () => { expect( gradeCondensed(control!, [ diff --git a/packages/client-runtime/src/conversationSummaries/index.test.ts b/packages/client-runtime/src/conversationSummaries/index.test.ts new file mode 100644 index 0000000000000..9055cc6898ebe --- /dev/null +++ b/packages/client-runtime/src/conversationSummaries/index.test.ts @@ -0,0 +1,41 @@ +import type { + ConversationSummarySourceRef, + ConversationSummarySourceResult, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { conversationSummarySourceLabel } from "./index.ts"; + +const ref = { + kind: "message", + threadId: "thread", + messageId: "message", + digest: "a".repeat(64), +} as ConversationSummarySourceRef; + +const source = (speaker?: { + readonly label: string; + readonly model: string; +}): ConversationSummarySourceResult => + ({ + state: "available", + source: ref, + text: "Keep the store decision open.", + title: "Thread", + role: "assistant", + ...(speaker === undefined ? {} : { speaker }), + createdAt: "2026-10-22T00:00:00.000Z", + archived: false, + }) as ConversationSummarySourceResult; + +describe("conversation summary source labels", () => { + it("names a peer instead of the thread agent", () => { + expect( + conversationSummarySourceLabel(ref, source({ label: "Astra", model: "gpt-6-astra" })), + ).toBe("Astra (gpt-6-astra)"); + }); + + it("keeps an unlabeled assistant as the assistant", () => { + expect(conversationSummarySourceLabel(ref, source())).toBe("Assistant"); + }); +}); diff --git a/packages/contracts/src/conversationSummaries.ts b/packages/contracts/src/conversationSummaries.ts index 3fd05d6c43490..7ac71dcc93d1f 100644 --- a/packages/contracts/src/conversationSummaries.ts +++ b/packages/contracts/src/conversationSummaries.ts @@ -6,6 +6,7 @@ import { ProjectId, RunId, ThreadId, + TrimmedNonEmptyString, TurnItemId, } from "./baseSchemas.ts"; import { ModelSelection } from "./modelSelection.ts"; @@ -84,6 +85,10 @@ export const ConversationSummarySourceResult = Schema.Union([ title: Schema.String, /** "summary" when the source is a child summary; its text is that summary's statements. */ role: Schema.Literals(["user", "assistant", "tool", "summary"]), + /** Set when an assistant message was spoken by another model in the thread. */ + speaker: Schema.optionalKey( + Schema.Struct({ label: TrimmedNonEmptyString, model: TrimmedNonEmptyString }), + ), createdAt: IsoDateTime, archived: Schema.Boolean, /** Offset and total length within this source's recorded range. */ diff --git a/packages/provider-core/src/server/textGeneration.ts b/packages/provider-core/src/server/textGeneration.ts index 57f97ca637550..e542477fd7bc1 100644 --- a/packages/provider-core/src/server/textGeneration.ts +++ b/packages/provider-core/src/server/textGeneration.ts @@ -12,7 +12,11 @@ import type { import type * as Effect from "effect/Effect"; import type { TextGenerationPolicy } from "./textGenerationPolicy.ts"; -import type { ThreadTitleForkSource } from "./textGenerationPrompts.ts"; +import type { + ConversationSummaryPromptMessage, + KnowledgeCandidatesPromptMessage, + ThreadTitleForkSource, +} from "./textGenerationPrompts.ts"; export interface CommitMessageGenerationInput { cwd: string; @@ -111,14 +115,7 @@ export interface KnowledgeCandidatesGenerationInput { cwd: string; runOutcome: "completed" | "failed" | "interrupted"; /** Finalized new evidence from one thread family, oldest first; `ref` is what citations name. */ - messages: ReadonlyArray<{ - readonly ref: string; - readonly threadId?: string; - readonly runId?: string; - readonly runOutcome?: "completed" | "failed" | "interrupted"; - readonly role: "user" | "assistant"; - readonly text: string; - }>; + messages: ReadonlyArray; modelSelection: ModelSelection; } @@ -137,12 +134,7 @@ export interface ConversationSummaryGenerationInput { * Consecutive finalized source ranges, or consecutive summaries for a roll-up, oldest first; * `ref` is what citations name. */ - messages: ReadonlyArray<{ - readonly ref: string; - readonly role: "user" | "assistant" | "tool" | "summary"; - readonly text: string; - readonly range?: { readonly start: number; readonly end: number; readonly total: number }; - }>; + messages: ReadonlyArray; modelSelection: ModelSelection; } diff --git a/packages/provider-core/src/server/textGenerationPrompts.test.ts b/packages/provider-core/src/server/textGenerationPrompts.test.ts index cbc19e876bf75..67136b87bf55c 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.test.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { buildKnowledgeCandidatesPrompt, buildThreadTitlePrompt } from "./textGenerationPrompts.ts"; +import { + buildConversationSummaryPrompt, + buildKnowledgeCandidatesPrompt, + buildThreadTitlePrompt, +} from "./textGenerationPrompts.ts"; import { normalizeCliError } from "./textGenerationUtils.ts"; describe("normalizeCliError", () => { @@ -43,6 +47,49 @@ it("preserves each run boundary and terminal outcome in family review prompts", expect(prompt).toContain("[M2] assistant (T2/R2, completed):\nChecked compatibility."); }); +it("names a peer in a summary and forbids giving its words to the user or the agent", () => { + const { prompt } = buildConversationSummaryPrompt({ + messages: [ + { ref: "M1", role: "user", text: "Where should sessions live?" }, + { + ref: "M2", + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: "Drop Redis and use Postgres.", + }, + { ref: "M3", role: "assistant", text: "I disagree. Keep Redis." }, + ], + }); + expect(prompt).toContain("[M2] peer Astra (gpt-6-astra):\nDrop Redis and use Postgres."); + expect(prompt).toContain( + "a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", + ); + expect(prompt).not.toContain("Historical"); +}); + +it("names a peer in knowledge extraction the same way", () => { + const { prompt } = buildKnowledgeCandidatesPrompt({ + runOutcome: "completed", + messages: [ + { + ref: "M1", + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: "Drop Redis and use Postgres.", + threadId: "root", + runId: "run-a", + runOutcome: "completed", + }, + ], + }); + expect(prompt).toContain( + "[M1] peer Astra (gpt-6-astra) (T1/R1, completed):\nDrop Redis and use Postgres.", + ); + expect(prompt).toContain( + "a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", + ); +}); + describe("buildThreadTitlePrompt", () => { it("names the project to leave out of initial and regenerated titles", () => { for (const previousTitle of [undefined, "Hyperdrive Config Crash"]) { diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts index 421a76838a860..07dce74501848 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.ts @@ -504,16 +504,20 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) { return { prompt, outputSchema }; } +export type KnowledgeCandidatesPromptMessage = { + readonly ref: string; + readonly threadId?: string; + readonly runId?: string; + readonly runOutcome?: "completed" | "failed" | "interrupted"; + readonly text: string; +} & ( + | { readonly role: "user" | "assistant" } + | { readonly role: "peer"; readonly speaker: { readonly label: string; readonly model: string } } +); + export interface KnowledgeCandidatesPromptInput { runOutcome: "completed" | "failed" | "interrupted"; - messages: ReadonlyArray<{ - readonly ref: string; - readonly threadId?: string; - readonly runId?: string; - readonly runOutcome?: "completed" | "failed" | "interrupted"; - readonly role: "user" | "assistant"; - readonly text: string; - }>; + messages: ReadonlyArray; } export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptInput) { @@ -566,13 +570,17 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI /** The rolled-up statements must fit beside the verbatim tail of a small handoff. */ const CONDENSED_SUMMARY_MAX_CHARS = 1_200; +export type ConversationSummaryPromptMessage = { + readonly ref: string; + readonly text: string; + readonly range?: { readonly start: number; readonly end: number; readonly total: number }; +} & ( + | { readonly role: "user" | "assistant" | "tool" | "summary" } + | { readonly role: "peer"; readonly speaker: { readonly label: string; readonly model: string } } +); + export interface ConversationSummaryPromptInput { - messages: ReadonlyArray<{ - readonly ref: string; - readonly role: "user" | "assistant" | "tool" | "summary"; - readonly text: string; - readonly range?: { readonly start: number; readonly end: number; readonly total: number }; - }>; + messages: ReadonlyArray; } export function buildConversationSummaryPrompt(input: ConversationSummaryPromptInput) { From ae7c6e7f9eb4128d04e1028ba37b15869832d616 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:55:06 -0800 Subject: [PATCH 04/27] fix(server): name the peer who spoke in conversation summaries The summarizer was given a peer reply as the user, so a seat model's proposal could be stored as the user's decision. Summary input now carries a peer role, and the prompt attributes those words to the speaker by name. Grok 4.7 through Cursor. Co-authored-by: Cursor --- .../src/orchestration-v2/readPeerSpeakers.ts | 45 +++++++++++++ .../ConversationSummaries.ts | 67 ++++++++++--------- .../src/project/knowledge/AssistedLearning.ts | 27 +++++++- evals/README.md | 2 +- evals/conversation-summaries/README.md | 10 ++- evals/conversation-summaries/run.ts | 52 +++++++++----- .../src/conversationSummaries/index.ts | 4 +- .../provider-core/src/server/handoffBudget.ts | 2 +- .../src/server/textGenerationPrompts.ts | 32 ++++++--- 9 files changed, 175 insertions(+), 66 deletions(-) create mode 100644 apps/server/src/orchestration-v2/readPeerSpeakers.ts diff --git a/apps/server/src/orchestration-v2/readPeerSpeakers.ts b/apps/server/src/orchestration-v2/readPeerSpeakers.ts new file mode 100644 index 0000000000000..693f05e0232a5 --- /dev/null +++ b/apps/server/src/orchestration-v2/readPeerSpeakers.ts @@ -0,0 +1,45 @@ +import { MessageId, ThreadId, type OrchestrationV2MessageSpeaker } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import type * as SqlClient from "effect/sql/SqlClient"; + +const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); + +/** + * Speaker label and model for assistant items that have one. The type list and `json_valid` + * term match the message-ordinal index, so this does not decode assistant text. + */ +export const readPeerSpeakers = Effect.fn("readPeerSpeakers")(function* ( + sql: SqlClient.SqlClient, + threadId: ThreadId, + messageIds?: ReadonlyArray, +) { + const speakers = new Map(); + if (messageIds !== undefined && messageIds.length === 0) return speakers; + const rows = yield* sql<{ + readonly message_id: string; + readonly label: string | null; + readonly model: string | null; + }>` + SELECT json_extract(payload_json, '$.messageId') AS message_id, + json_extract(payload_json, '$.speaker.label') AS label, + json_extract(payload_json, '$.speaker.model') AS model + FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} + AND type IN ('user_message', 'assistant_message') + AND json_valid(payload_json) + AND json_extract(payload_json, '$.speaker.label') IS NOT NULL + AND json_extract(payload_json, '$.speaker.model') IS NOT NULL + ${ + messageIds === undefined + ? sql`` + : sql`AND json_extract(payload_json, '$.messageId') IN (SELECT value FROM json_each(${encodeIds(messageIds)}))` + } + ORDER BY ordinal ASC + `; + for (const row of rows) { + if (row.label && row.model) + speakers.set(MessageId.make(row.message_id), { label: row.label, model: row.model }); + } + return speakers; +}); diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index d419b0431073d..a85b17ec6fe9d 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -19,7 +19,6 @@ import { type KnowledgeSourceUnavailableReason, type MessageId, type OrchestrationV2ConversationMessage, - type OrchestrationV2HistoricalMessage, type OrchestrationV2RunStatus, type OrchestrationV2UserMessageInputIntent, type ProjectId, @@ -32,10 +31,6 @@ import { summaryToolText, summaryToolTypes, } from "@t3tools/provider-core/server/conversationEvidence"; -import { - historicalMessage, - renderHistoricalMessage, -} from "@t3tools/provider-core/server/handoffBudget"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline"; import * as Context from "effect/Context"; @@ -50,6 +45,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as ProjectStore from "../../orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import { readPeerSpeakers } from "../../orchestration-v2/readPeerSpeakers.ts"; import * as ServerSettings from "../../serverSettings.ts"; import * as TextGeneration from "../../textGeneration/TextGeneration.ts"; import * as ProjectKnowledge from "../knowledge/ProjectKnowledge.ts"; @@ -334,6 +330,11 @@ const make = Effect.gen(function* () { source.kind === "message", ); const messageResults = yield* knowledge.readSources({ ...input, sources: messages }); + const speakers = yield* readPeerSpeakers( + sql, + input.threadId, + messages.map((source) => source.messageId), + ); const invisible = messages.length === 0 ? new Set() @@ -342,14 +343,16 @@ const make = Effect.gen(function* () { messages.map((source) => source.messageId), ); const current = new Map(); - messages.forEach((source, index) => + messages.forEach((source, index) => { + const result = invisible.has(source.messageId) + ? { state: "unavailable" as const, reason: "missing" as const } + : messageResults[index]!; + const speaker = result.state === "available" ? speakers.get(source.messageId) : undefined; current.set( conversationSummarySourceIdentity(source), - invisible.has(source.messageId) - ? { state: "unavailable", reason: "missing" } - : messageResults[index]!, - ), - ); + speaker === undefined || result.state !== "available" ? result : { ...result, speaker }, + ); + }); const tools = unique.filter( (source): source is Extract => source.kind === "turn_item", @@ -821,7 +824,7 @@ const make = Effect.gen(function* () { const records = yield* projections .getThreadRecords(threadId, ["messages", "turnItems"], { messageRoles: ["user", "assistant"], - turnItemTypes: [...summaryToolTypes, "assistant_message"], + turnItemTypes: summaryToolTypes, turnItemStatuses: finalizedToolStatuses, }) .pipe(Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) })); @@ -927,13 +930,9 @@ const make = Effect.gen(function* () { createdAt: message.createdAt, }); } - const peerReplies = new Map(); + const speakers = yield* readPeerSpeakers(sql, threadId); for (const item of records.turnItems) { if (item.runId !== null && excluded.has(item.runId)) continue; - if (item.type === "assistant_message" && item.speaker !== undefined) { - const historical = historicalMessage(item); - if (historical !== null) peerReplies.set(item.messageId, historical); - } const text = summaryToolText(item); if (text === null) continue; all.push({ @@ -996,11 +995,18 @@ const make = Effect.gen(function* () { ); const publish = Effect.fnUntraced(function* (input: { - readonly messages: ReadonlyArray<{ - readonly role: "user" | "assistant" | "tool" | "summary"; - readonly text: string; - readonly range?: ConversationSummaryRangeRef["range"]; - }>; + readonly messages: ReadonlyArray< + { + readonly text: string; + readonly range?: ConversationSummaryRangeRef["range"]; + } & ( + | { readonly role: "user" | "assistant" | "tool" | "summary" } + | { + readonly role: "peer"; + readonly speaker: { readonly label: string; readonly model: string }; + } + ) + >; readonly sources: ReadonlyArray; readonly ranges: ReadonlyArray; readonly position: string; @@ -1013,6 +1019,7 @@ const make = Effect.gen(function* () { ref, role: message.role, text: message.text, + ...(message.role === "peer" ? { speaker: message.speaker } : {}), ...(message.range === undefined ? {} : { range: message.range }), }; }); @@ -1091,16 +1098,12 @@ const make = Effect.gen(function* () { const summarizeLeaf = (chunk: ReadonlyArray) => publish({ messages: chunk.map((source) => { - const peer = - source.ref.kind === "message" ? peerReplies.get(source.ref.messageId) : undefined; - return { - role: peer?.role ?? source.role, - text: - peer === undefined - ? source.text - : renderHistoricalMessage({ ...peer, text: source.text }), - ...(source.ref.range === undefined ? {} : { range: source.ref.range }), - }; + const speaker = + source.ref.kind === "message" ? speakers.get(source.ref.messageId) : undefined; + const range = source.ref.range === undefined ? {} : { range: source.ref.range }; + return speaker === undefined + ? { role: source.role, text: source.text, ...range } + : { role: "peer" as const, speaker, text: source.text, ...range }; }), sources: chunk.map((source) => source.ref), ranges: chunk.map((source) => source.ref), diff --git a/apps/server/src/project/knowledge/AssistedLearning.ts b/apps/server/src/project/knowledge/AssistedLearning.ts index 0a4b90b5bf2f6..a23a25d784893 100644 --- a/apps/server/src/project/knowledge/AssistedLearning.ts +++ b/apps/server/src/project/knowledge/AssistedLearning.ts @@ -24,6 +24,7 @@ import { forkParked } from "../../serverActivation.ts"; import * as ProjectStore from "../../orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import { readPeerSpeakers } from "../../orchestration-v2/readPeerSpeakers.ts"; import * as ServerSettings from "../../serverSettings.ts"; import * as TextGeneration from "../../textGeneration/TextGeneration.ts"; import { @@ -195,6 +196,20 @@ const make = Effect.gen(function* () { (left, right) => finalized.indexOf(left) - finalized.indexOf(right), ); // Citations are message ids and digests from this canonical read; the model only names refs. + const speakersByMessage = new Map< + (typeof transcript)[number]["id"], + { readonly label: string; readonly model: string } + >(); + const assistantIds = new Map>(); + for (const message of transcript) { + if (message.role !== "assistant") continue; + const ids = assistantIds.get(message.threadId) ?? []; + ids.push(message.id); + assistantIds.set(message.threadId, ids); + } + for (const [id, messageIds] of assistantIds) + for (const [messageId, speaker] of yield* readPeerSpeakers(sql, id, messageIds)) + speakersByMessage.set(messageId, speaker); const refs = new Map(); const userRefs = new Set(); const messages: Array< @@ -219,14 +234,20 @@ const make = Effect.gen(function* () { messageId: message.id, digest: yield* digest(message.text), }); - messages.push({ + const speaker = + message.role === "assistant" ? speakersByMessage.get(message.id) : undefined; + const shared = { ref, - role: message.role as "user" | "assistant", threadId: message.threadId, runId: message.runId!, runOutcome: batch.find((entry) => entry.runId === message.runId)!.runOutcome, text: message.text.slice(0, textLimits.get(message.id)), - }); + }; + messages.push( + speaker === undefined + ? { ...shared, role: message.role as "user" | "assistant" } + : { ...shared, role: "peer" as const, speaker }, + ); } const project = yield* projects.get(projectId); const cwd = Option.isSome(project) ? project.value.workspaceRoot : undefined; diff --git a/evals/README.md b/evals/README.md index 7dd4ed22cf249..815376183ae16 100644 --- a/evals/README.md +++ b/evals/README.md @@ -10,7 +10,7 @@ Write or run an eval when a change affects what a model sees or does: agent inst | [group-conversation](group-conversation/) | Whether peers engage, preserve attribution, use PASS and handles, edit with the real side chat digest, and continue through delegation. Compares parallel and serial reactions. | | [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | | [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [conversation-summaries](conversation-summaries/) | Whether a roll-up of four conversation summaries keeps reversals, attribution and open items within its budget. | +| [conversation-summaries](conversation-summaries/) | Whether a leaf summary names a peer's proposal, and a roll-up keeps reversals, attribution and open items within its budget. | | [model-evaluations](model-evaluations/) | Whether blind judges use outcome evidence, respect task scope, ignore injected scoring instructions, and abstain when evidence is missing. | | [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | | [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | diff --git a/evals/conversation-summaries/README.md b/evals/conversation-summaries/README.md index fad5d3a893340..6efb8fd3d46df 100644 --- a/evals/conversation-summaries/README.md +++ b/evals/conversation-summaries/README.md @@ -1,6 +1,8 @@ # Conversation summaries -Checks the roll-up prompt: four adjacent conversation summaries condensed into one, as the summary pass does for long threads. Each sample calls the server's real summary generator through the local Codex login, with the prompt from this checkout. +Checks the summary prompt on two inputs. A leaf is one exchange, including a reply from another model in the thread. A roll-up condenses four adjacent summaries, as the summary pass does for long threads. Each sample calls the server's real summary generator through the local Codex login, with the prompt from this checkout. + +The production summarizer is an OpenCode model. This runner only builds a Codex text-generation client, so the runs here use `gpt-6-luna`. ```sh cd evals @@ -10,12 +12,14 @@ pnpm conversation-summaries --model gpt-6-luna --out runs/summaries-after --base - `condensed-four-sources-retain-reversal-and-unverified-claim` passes when the roll-up keeps the later Postgres decision instead of the reversed Redis one, keeps the agent's test claim attributed and unverified, keeps the open rollback script, cites only the given summaries, and fits in 1,200 characters. - `condensed-four-ordinary-sources` is the control: an ordinary docs task that must keep its open item and fit the same budget. +- `leaf-peer-proposal-is-not-a-user-decision` passes when the summary names Astra as the one who proposed Postgres, and does not record that proposal as a decision the user made. +- `leaf-ordinary-exchange-has-no-peer` is the leaf control: an ordinary docs task with no peer. - `--case ` limits the run, `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result. ## Add a case -Add an entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. `run.test.ts` tests the grader. +Add a condensed entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. A leaf entry has `messages` instead of `summaries`. `run.test.ts` tests the grader. ## Cost -Each sample is one paid call through the local subscription; the full suite is six. The CLI does not report per-call cost here. +Each sample is one paid call through the local subscription. The full suite is twelve calls: six roll-up samples and six leaf samples. The CLI does not report per-call cost here. diff --git a/evals/conversation-summaries/run.ts b/evals/conversation-summaries/run.ts index a6a0cbb3f7202..319425269b0c4 100644 --- a/evals/conversation-summaries/run.ts +++ b/evals/conversation-summaries/run.ts @@ -9,8 +9,8 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; import * as ServerConfig from "../../apps/server/src/config.ts"; -import { condensedCases } from "./cases.ts"; -import { gradeCondensed } from "./grade.ts"; +import { condensedCases, leafCases } from "./cases.ts"; +import { gradeCondensed, gradeLeaf } from "./grade.ts"; const { values } = NodeUtil.parseArgs({ options: { @@ -25,12 +25,14 @@ if (!values.model || !values.out) throw new Error("Use --model --out values.case === undefined || values.case.split(",").includes(fixture.id), -); -if (selected.length === 0) +const selectedIds = values.case?.split(","); +const selected = (fixtures: ReadonlyArray) => + fixtures.filter((fixture) => selectedIds === undefined || selectedIds.includes(fixture.id)); +const selectedCondensed = selected(condensedCases); +const selectedLeaf = selected(leafCases); +if (selectedCondensed.length + selectedLeaf.length === 0) throw new Error( - `Unknown --case ${values.case}. Available cases: ${condensedCases.map((fixture) => fixture.id).join(", ")}`, + `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases].map((fixture) => fixture.id).join(", ")}`, ); const Results = Schema.Array( Schema.Struct({ @@ -57,25 +59,41 @@ await Effect.runPromise( const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-summary-eval-" }); const generation = yield* CodexTextGeneration.makeCodexTextGeneration(decodeSettings({})); const results: Array<(typeof Results.Type)[number]> = []; - for (const fixture of selected) { + const record = ( + id: string, + sample: number, + statements: (typeof Results.Type)[number]["statements"], + failures: ReadonlyArray, + ) => { + results.push({ id, sample, statements, failures, passed: failures.length === 0 }); + }; + for (const fixture of selectedCondensed) { for (let sample = 0; sample < samples; sample++) { const { statements } = yield* generation.generateConversationSummary({ cwd, modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, messages: fixture.summaries.map((text, index) => ({ ref: `M${index + 1}`, - role: "summary", + role: "summary" as const, text, })), }); - const failures = gradeCondensed(fixture, statements); - results.push({ - id: fixture.id, - sample, - statements, - failures, - passed: failures.length === 0, + record(fixture.id, sample, statements, gradeCondensed(fixture, statements)); + } + } + for (const fixture of selectedLeaf) { + for (let sample = 0; sample < samples; sample++) { + const { statements } = yield* generation.generateConversationSummary({ + cwd, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, + messages: fixture.messages.map((message, index) => { + const ref = `M${index + 1}`; + return message.role === "peer" + ? { ref, role: "peer" as const, speaker: message.speaker, text: message.text } + : { ref, role: message.role, text: message.text }; + }), }); + record(fixture.id, sample, statements, gradeLeaf(fixture, statements)); } } yield* fs.makeDirectory(outputDirectory, { recursive: true }); @@ -85,7 +103,7 @@ await Effect.runPromise( ); if (baseline !== undefined) yield* fs.writeFileString(path.join(outputDirectory, "baseline.json"), baseline); - for (const fixture of selected) { + for (const fixture of [...selectedCondensed, ...selectedLeaf]) { const rows = results.filter((row) => row.id === fixture.id); const passed = rows.filter((row) => row.passed).length; // A case fails when half or more of its samples fail. diff --git a/packages/client-runtime/src/conversationSummaries/index.ts b/packages/client-runtime/src/conversationSummaries/index.ts index 75599b3ef7587..ad9c42761427e 100644 --- a/packages/client-runtime/src/conversationSummaries/index.ts +++ b/packages/client-runtime/src/conversationSummaries/index.ts @@ -59,7 +59,9 @@ export function conversationSummarySourceLabel( case "user": return "User"; case "assistant": - return "Assistant"; + return result.speaker === undefined + ? "Assistant" + : `${result.speaker.label} (${result.speaker.model})`; case "tool": return "Tool"; case "summary": diff --git a/packages/provider-core/src/server/handoffBudget.ts b/packages/provider-core/src/server/handoffBudget.ts index 40a168e026ee3..1e8ba7473c5bc 100644 --- a/packages/provider-core/src/server/handoffBudget.ts +++ b/packages/provider-core/src/server/handoffBudget.ts @@ -304,7 +304,7 @@ export function historicalMessage( }; } -export function renderHistoricalMessage(message: OrchestrationV2HistoricalMessage): string { +function renderHistoricalMessage(message: OrchestrationV2HistoricalMessage): string { const source = message.speaker === undefined ? `${message.role}; ${message.kind}` diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts index 07dce74501848..d76684af239e5 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.ts @@ -535,6 +535,7 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI "Rules:", "- kind is one of decision, constraint, convention", "- only extract decisions the user made or accepted, constraints the project must respect, or conventions the code follows", + "- a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", "- do not summarize the work, restate the task, or record transient status, plans, or guesses", "- content is one or two plain sentences that stand alone without this conversation", "- entities lists up to 5 short names of files, modules, tools, or concepts the knowledge is about", @@ -549,10 +550,17 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI ]), "", "Messages:", - ...input.messages.map( - (message) => - `[${message.ref}] ${message.role}${message.runId === undefined ? "" : ` (${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome})`}:\n${message.text}\n`, - ), + ...input.messages.map((message) => { + const role = + message.role === "peer" + ? `peer ${message.speaker.label} (${message.speaker.model})` + : message.role; + const run = + message.runId === undefined + ? "" + : ` (${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome})`; + return `[${message.ref}] ${role}${run}:\n${message.text}\n`; + }), ].join("\n"); const outputSchema = Schema.Struct({ candidates: Schema.Array( @@ -591,6 +599,7 @@ export function buildConversationSummaryPrompt(input: ConversationSummaryPromptI "- each text is one or two plain sentences, at most 600 characters", "- keep what the user asked for, decisions made, constraints, what was done and verified, and what was left open", "- say who said what; do not present an agent's claim or plan as a verified outcome", + "- a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", "- citations lists the refs (like M1) of the sources that support the statement; never invent a ref", "- sources may be exact ranges of long messages or tool evidence; do not infer omitted ranges", "- preserve observed command results, failures and checks, distinguishing tool evidence from an agent claiming success", @@ -603,10 +612,17 @@ export function buildConversationSummaryPrompt(input: ConversationSummaryPromptI : []), "", "Sources:", - ...input.messages.map( - (message) => - `[${message.ref}] ${message.role}${message.range === undefined ? "" : ` (UTF-16 range ${message.range.start}–${message.range.end} of ${message.range.total})`}:\n${message.text}\n`, - ), + ...input.messages.map((message) => { + const role = + message.role === "peer" + ? `peer ${message.speaker.label} (${message.speaker.model})` + : message.role; + const range = + message.range === undefined + ? "" + : ` (UTF-16 range ${message.range.start}–${message.range.end} of ${message.range.total})`; + return `[${message.ref}] ${role}${range}:\n${message.text}\n`; + }), ].join("\n"); const outputSchema = Schema.Struct({ statements: Schema.Array( From 77582a0124d0c97065bf3444948198c5e407d6a4 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:21:58 -0800 Subject: [PATCH 05/27] test(evals): grade an open choice apart from a peer's Postgres proposal The leaf grader treats any Postgres mention as Astra's proposal, and it misses a user who agrees or an agent who proposes it. Co-authored-by: Cursor --- evals/conversation-summaries/run.test.ts | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index b6cb502240011..45844f19c566f 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -69,6 +69,43 @@ it("fails a leaf that records the peer proposal as the user's decision", () => { ]); }); +const userAcceptedPostgres = + "\\buser\\b(?:(?!\\bnot\\b)[^.;]){0,30}\\b(?:agre|chose|choos|accept|decid)\\w*(?:(?!\\bnot\\b)[^.;]){0,30}\\bPostgres\\b"; +const agentProposedPostgres = + "\\bagent\\b(?:(?!\\bnot\\b)[^.;]){0,40}\\b(?:propos|suggest)\\w*(?:(?!\\bnot\\b)[^.;]){0,40}\\bPostgres\\b"; + +it("does not treat an open Postgres choice as the peer's proposal", () => { + expect( + gradeLeaf(peerLeaf!, [ + { + text: "The user has not chosen between Redis and Postgres; the agent prefers Redis.", + citations: ["M1", "M3"], + }, + ]), + ).toEqual(["missing Astra"]); +}); + +it("fails a leaf where the user agrees to Postgres", () => { + const text = "Astra proposed Postgres and the user agreed to use Postgres."; + expect(gradeLeaf(peerLeaf!, [{ text, citations: ["M2"] }])).toEqual([ + `${userAcceptedPostgres}: ${text}`, + ]); +}); + +it("fails a leaf where the user chooses Postgres", () => { + const text = "The user chose Postgres for sessions, following Astra."; + expect(gradeLeaf(peerLeaf!, [{ text, citations: ["M2"] }])).toEqual([ + `${userAcceptedPostgres}: ${text}`, + ]); +}); + +it("fails a leaf that gives the peer's Postgres proposal to the agent", () => { + const text = "The agent proposed moving sessions to Postgres; Astra wants to keep Redis."; + expect(gradeLeaf(peerLeaf!, [{ text, citations: ["M2", "M3"] }])).toEqual([ + `${agentProposedPostgres}: ${text}`, + ]); +}); + it("passes an ordinary leaf with no peer", () => { expect( gradeLeaf(ordinaryLeaf!, [ From c67afa79bcec31db16e79d87331751d155b3431c Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:23:45 -0800 Subject: [PATCH 06/27] fix(evals): score Postgres proposals instead of every Postgres mention An open choice that names Postgres was graded as Astra's proposal. A user who agrees or chooses Postgres, and an agent who proposes it, now fail on their own. Co-authored-by: Cursor --- evals/conversation-summaries/cases.ts | 9 ++++++++- evals/conversation-summaries/run.test.ts | 16 ++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts index 95d9f5fbc80a0..73f76470ceb1c 100644 --- a/evals/conversation-summaries/cases.ts +++ b/evals/conversation-summaries/cases.ts @@ -39,10 +39,17 @@ export const leafCases: ReadonlyArray = [ }, ], mustMention: ["Astra", "Postgres"], - attributed: [{ when: "Postgres|[Dd]rop Redis", require: "Astra" }], + attributed: [ + { + when: "(?:[Pp]ropos|[Ss]uggest)\\w*[^.]{0,80}Postgres|Postgres[^.]{0,80}(?:[Pp]ropos|[Ss]uggest)\\w*", + require: "Astra", + }, + ], mustNot: [ "[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis)", "[Uu]ser's decision to (drop Redis|use Postgres|keep Redis)", + "\\buser\\b(?:(?!\\bnot\\b)[^.;]){0,30}\\b(?:agre|chose|choos|accept|decid)\\w*(?:(?!\\bnot\\b)[^.;]){0,30}\\bPostgres\\b", + "\\bagent\\b(?:(?!\\bnot\\b)[^.;]){0,40}\\b(?:propos|suggest)\\w*(?:(?!\\bnot\\b)[^.;]){0,40}\\bPostgres\\b", ], }, { diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index 45844f19c566f..ad5d835256808 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -4,6 +4,10 @@ import { gradeCondensed, gradeLeaf } from "./grade.ts"; const [reversal, control] = condensedCases; const [peerLeaf, ordinaryLeaf] = leafCases; +const userAcceptedPostgres = + "\\buser\\b(?:(?!\\bnot\\b)[^.;]){0,30}\\b(?:agre|chose|choos|accept|decid)\\w*(?:(?!\\bnot\\b)[^.;]){0,30}\\bPostgres\\b"; +const agentProposedPostgres = + "\\bagent\\b(?:(?!\\bnot\\b)[^.;]){0,40}\\b(?:propos|suggest)\\w*(?:(?!\\bnot\\b)[^.;]){0,40}\\bPostgres\\b"; it("passes a roll-up that keeps the reversal, the attribution and the open item", () => { expect( @@ -57,23 +61,19 @@ it("passes a leaf that names the peer and leaves the choice open", () => { }); it("fails a leaf that records the peer proposal as the user's decision", () => { + const text = "The user decided to use Postgres for sessions."; expect( gradeLeaf(peerLeaf!, [ - { text: "The user decided to use Postgres for sessions.", citations: ["M2"] }, + { text, citations: ["M2"] }, { text: "The agent wants to keep Redis.", citations: ["M3"] }, ]), ).toEqual([ "missing Astra", - "Postgres|[Dd]rop Redis without Astra: The user decided to use Postgres for sessions.", - "[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis): The user decided to use Postgres for sessions.", + `[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis): ${text}`, + `${userAcceptedPostgres}: ${text}`, ]); }); -const userAcceptedPostgres = - "\\buser\\b(?:(?!\\bnot\\b)[^.;]){0,30}\\b(?:agre|chose|choos|accept|decid)\\w*(?:(?!\\bnot\\b)[^.;]){0,30}\\bPostgres\\b"; -const agentProposedPostgres = - "\\bagent\\b(?:(?!\\bnot\\b)[^.;]){0,40}\\b(?:propos|suggest)\\w*(?:(?!\\bnot\\b)[^.;]){0,40}\\bPostgres\\b"; - it("does not treat an open Postgres choice as the peer's proposal", () => { expect( gradeLeaf(peerLeaf!, [ From 57bafc9fffa6d58808e3c6f9932dd735e4b6e609 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:25:18 -0800 Subject: [PATCH 07/27] test(provider-core): saved facts must not treat a peer proposal as the user's The knowledge prompt names the peer twice in parentheses and tells the model to put that name in a fact that has to stand alone. Co-authored-by: Cursor --- .../provider-core/src/server/textGenerationPrompts.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/provider-core/src/server/textGenerationPrompts.test.ts b/packages/provider-core/src/server/textGenerationPrompts.test.ts index 67136b87bf55c..9efc3c5cb25e2 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.test.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.test.ts @@ -67,7 +67,7 @@ it("names a peer in a summary and forbids giving its words to the user or the ag expect(prompt).not.toContain("Historical"); }); -it("names a peer in knowledge extraction the same way", () => { +it("does not record a peer proposal as the user's decision", () => { const { prompt } = buildKnowledgeCandidatesPrompt({ runOutcome: "completed", messages: [ @@ -83,9 +83,12 @@ it("names a peer in knowledge extraction the same way", () => { ], }); expect(prompt).toContain( - "[M1] peer Astra (gpt-6-astra) (T1/R1, completed):\nDrop Redis and use Postgres.", + "[M1] peer Astra (gpt-6-astra, T1/R1, completed):\nDrop Redis and use Postgres.", ); expect(prompt).toContain( + "a peer is another model in the conversation; its proposals are not the user's decisions unless the user accepted them", + ); + expect(prompt).not.toContain( "a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", ); }); From 992ef444b0ca2099aabbacfb92d4164903f6a236 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:26:37 -0800 Subject: [PATCH 08/27] fix(provider-core): keep peer names out of saved facts A saved fact has to stand alone, so the knowledge rule no longer asks for the peer's name. The source line names that peer once. Co-authored-by: Cursor --- .../src/server/textGenerationPrompts.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts index d76684af239e5..528f304cf5998 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.ts @@ -535,7 +535,7 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI "Rules:", "- kind is one of decision, constraint, convention", "- only extract decisions the user made or accepted, constraints the project must respect, or conventions the code follows", - "- a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", + "- a peer is another model in the conversation; its proposals are not the user's decisions unless the user accepted them", "- do not summarize the work, restate the task, or record transient status, plans, or guesses", "- content is one or two plain sentences that stand alone without this conversation", "- entities lists up to 5 short names of files, modules, tools, or concepts the knowledge is about", @@ -551,15 +551,15 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI "", "Messages:", ...input.messages.map((message) => { - const role = - message.role === "peer" - ? `peer ${message.speaker.label} (${message.speaker.model})` - : message.role; const run = message.runId === undefined - ? "" - : ` (${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome})`; - return `[${message.ref}] ${role}${run}:\n${message.text}\n`; + ? undefined + : `${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome}`; + const role = + message.role === "peer" + ? `peer ${message.speaker.label} (${message.speaker.model}${run === undefined ? "" : `, ${run}`})` + : `${message.role}${run === undefined ? "" : ` (${run})`}`; + return `[${message.ref}] ${role}:\n${message.text}\n`; }), ].join("\n"); const outputSchema = Schema.Struct({ From 2817d36448c0231f7d4abe363acec25d81f25976 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:29:05 -0800 Subject: [PATCH 09/27] test(server): peer speaker reads must seek an index Ordering that read by ordinal makes SQLite walk every item in the thread, even when the caller already named the messages. Co-authored-by: Cursor --- .../orchestration-v2/ProjectionStore.test.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 74dd498c3dc49..6b173cf4807f9 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -49,6 +49,7 @@ import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { readPeerSpeakers } from "./readPeerSpeakers.ts"; import { buildBoundedThreadProjection, decodeThreadHistoryCursor, @@ -2932,6 +2933,32 @@ it.effect("reads message ordinals through their index", () => messageOrdinalsReadThroughTheirIndex.pipe(Effect.provide(layerTest)), ); +it.effect("reads peer speakers through the message index when messages are named", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("thread:peer-speakers"); + const named = traceSqlStatements(); + yield* readPeerSpeakers(sql, threadId, [MessageId.make("message:peer")]).pipe( + Effect.withTracer(named.tracer), + ); + yield* assertReadsThroughMessageOrdinalIndex( + named.statements.find((statement) => statement.includes("$.speaker.label")), + ["thread_id=?", "=?"], + ); + const open = traceSqlStatements(); + yield* readPeerSpeakers(sql, threadId).pipe(Effect.withTracer(open.tracer)); + const plan = yield* queryPlan( + open.statements.find((statement) => statement.includes("$.speaker.label")), + ); + const search = plan.find((detail) => + detail.includes("orchestration_v2_projection_turn_items_thread_type_idx"), + ); + assert.isDefined(search, plan.join("\n")); + assert.include(search, "thread_id=?"); + assert.include(search, "type=?"); + }).pipe(Effect.provide(layerTest)), +); + const assertProjectScopedShells = Effect.fn("assertProjectScopedShells")(function* ( suffix: string, ) { From f2c3db23107a7bca9e9275dad0d2e49dbcf14bf6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:31:51 -0800 Subject: [PATCH 10/27] fix(server): stop sorting peer speaker reads off their index The rows land in a map keyed by message. Sorting them by ordinal made SQLite walk every item in the thread instead of the message index. Co-authored-by: Cursor --- apps/server/src/orchestration-v2/readPeerSpeakers.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/readPeerSpeakers.ts b/apps/server/src/orchestration-v2/readPeerSpeakers.ts index 693f05e0232a5..a6864800dd573 100644 --- a/apps/server/src/orchestration-v2/readPeerSpeakers.ts +++ b/apps/server/src/orchestration-v2/readPeerSpeakers.ts @@ -6,10 +6,11 @@ import type * as SqlClient from "effect/sql/SqlClient"; const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); /** - * Speaker label and model for assistant items that have one. The type list and `json_valid` - * term match the message-ordinal index, so this does not decode assistant text. + * Speaker label and model for message items that carry both. The type list and `json_valid` + * term match the message-ordinal index. Speaker fields sit outside that index, so each hit + * decodes the payload. */ -export const readPeerSpeakers = Effect.fn("readPeerSpeakers")(function* ( +export const readPeerSpeakers = Effect.fn("ReadPeerSpeakers.read")(function* ( sql: SqlClient.SqlClient, threadId: ThreadId, messageIds?: ReadonlyArray, @@ -35,7 +36,6 @@ export const readPeerSpeakers = Effect.fn("readPeerSpeakers")(function* ( ? sql`` : sql`AND json_extract(payload_json, '$.messageId') IN (SELECT value FROM json_each(${encodeIds(messageIds)}))` } - ORDER BY ordinal ASC `; for (const row of rows) { if (row.label && row.model) From 55b535d1a94631bbc966159a4b8f63351a70eccd Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 04:42:08 -0800 Subject: [PATCH 11/27] fix(server): keep a peer message a peer when it is summarized The summary request widened every row to an optional speaker, and the prompt type rejected that. Co-authored-by: Cursor --- .../conversationSummaries/ConversationSummaries.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index a85b17ec6fe9d..1f67754c39959 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -1015,13 +1015,10 @@ const make = Effect.gen(function* () { const messages = input.messages.map((message, index) => { const ref = `M${index + 1}`; refs.set(ref, conversationSummarySourceKey(input.sources[index]!)); - return { - ref, - role: message.role, - text: message.text, - ...(message.role === "peer" ? { speaker: message.speaker } : {}), - ...(message.range === undefined ? {} : { range: message.range }), - }; + const range = message.range === undefined ? {} : { range: message.range }; + return message.role === "peer" + ? { ref, role: message.role, speaker: message.speaker, text: message.text, ...range } + : { ref, role: message.role, text: message.text, ...range }; }); const reply = yield* textGeneration .generateConversationSummary({ From 70ae6599a0ec7d31c5d411dfc691d7a97a7cf6ff Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 07:22:06 -0800 Subject: [PATCH 12/27] fix(server): a decision no one but peers voiced is never saved Corroboration counted a peer's reply and the seat's own copy in its seat thread as independent evidence, so a peer proposal could be saved as a decision with no user citation. Decisions now need user support. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/AssistedLearning.test.ts | 121 +++++++++++++++--- .../src/project/knowledge/AssistedLearning.ts | 2 +- 2 files changed, 107 insertions(+), 16 deletions(-) diff --git a/apps/server/src/project/knowledge/AssistedLearning.test.ts b/apps/server/src/project/knowledge/AssistedLearning.test.ts index 955d638bfd13e..bf4a1689f544c 100644 --- a/apps/server/src/project/knowledge/AssistedLearning.test.ts +++ b/apps/server/src/project/knowledge/AssistedLearning.test.ts @@ -316,22 +316,24 @@ it.effect("saves a settled run's cited facts exactly once, recallable without re }).pipe(Effect.provide(makeLayer(model.generate))); }); -it.effect("sends a peer reply as that peer, not as the assistant", () => { - const model = scripted([{ candidates: [] }]); - const text = "Done. I converted the handlers to snake_case keys."; - return Effect.gen(function* () { - yield* seedRun; - const projections = yield* ProjectionStore.ProjectionStoreV2; - yield* projections.apply({ - id: EventId.make("peer-reply"), +/** Marks a message as a peer's reply, as a group conversation's published turn item does. */ +const speakAsPeer = (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly messageId: string; + readonly text: string; +}) => + Effect.flatMap(ProjectionStore.ProjectionStoreV2, (projections) => + projections.apply({ + id: EventId.make(`peer:${input.messageId}`), type: "turn-item.updated", - threadId, + threadId: input.threadId, providerInstanceId, occurredAt: at, payload: { - id: TurnItemId.make("learning-peer-item"), - threadId, - runId, + id: TurnItemId.make(`peer-item:${input.messageId}`), + threadId: input.threadId, + runId: input.runId, nodeId: null, providerThreadId: null, providerTurnId: null, @@ -344,12 +346,20 @@ it.effect("sends a peer reply as that peer, not as the assistant", () => { completedAt: at, updatedAt: at, type: "assistant_message", - messageId: MessageId.make("learning-reply"), - text, + messageId: MessageId.make(input.messageId), + text: input.text, streaming: false, speaker: { label: "Astra", model: "gpt-6-astra" }, }, - }); + }), + ); + +it.effect("sends a peer reply as that peer, not as the assistant", () => { + const model = scripted([{ candidates: [] }]); + const text = "Done. I converted the handlers to snake_case keys."; + return Effect.gen(function* () { + yield* seedRun; + yield* speakAsPeer({ threadId, runId, messageId: "learning-reply", text }); const runner = yield* AssistedLearningRunner; yield* runner.extractRun({ threadId, runId, runOutcome: "completed" }); assert.deepEqual(model.calls[0]?.messages[1], { @@ -364,6 +374,87 @@ it.effect("sends a peer reply as that peer, not as the assistant", () => { }).pipe(Effect.provide(makeLayer(model.generate))); }); +it.effect( + "saves no decision the user never cited, even when a seat's own thread repeats it", + () => { + const decision = { + kind: "decision" as const, + content: "Sessions move from Redis to Postgres.", + entities: ["sessions"], + citations: ["M1", "M2"], + }; + const model = scripted([{ candidates: [decision, { ...decision, kind: "convention" }] }]); + return Effect.gen(function* () { + yield* seedRun; + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.add(at, { minutes: 10 }))); + const projections = yield* ProjectionStore.ProjectionStoreV2; + const records = yield* projections.getThreadRecords(threadId, []); + const seatId = ThreadId.make("learning-seat"); + yield* projections.apply({ + id: EventId.make("create-seat"), + type: "thread.created", + threadId: seatId, + providerInstanceId, + occurredAt: at, + payload: { + ...records.thread, + id: seatId, + lineage: { + parentThreadId: threadId, + rootThreadId: threadId, + relationshipToParent: "subagent", + }, + }, + }); + const runner = yield* AssistedLearningRunner; + const replies = [ + [threadId, "peer-root", "Drop Redis and move sessions to Postgres."], + [seatId, "peer-seat", "I recommend Postgres for sessions instead of Redis."], + ] as const; + for (const [index, [replyThreadId, id, text]] of replies.entries()) { + const replyRunId = RunId.make(`${id}-run`); + yield* projections.apply({ + id: EventId.make(`message:${id}`), + type: "message.updated", + threadId: replyThreadId, + providerInstanceId, + occurredAt: DateTime.add(at, { minutes: index }), + payload: { + id: MessageId.make(id), + threadId: replyThreadId, + runId: replyRunId, + nodeId: null, + role: "assistant", + text, + attachments: [], + streaming: false, + createdAt: DateTime.add(at, { minutes: index }), + updatedAt: at, + createdBy: "agent", + creationSource: "provider", + }, + }); + if (replyThreadId === threadId) + yield* speakAsPeer({ threadId, runId: replyRunId, messageId: id, text }); + yield* runner.enqueueRun({ + threadId: replyThreadId, + runId: replyRunId, + runOutcome: "completed", + }); + } + yield* TestClock.adjust("31 minutes"); + yield* runner.drainDue; + assert.equal(model.calls.length, 1); + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const { facts } = yield* knowledge.list({ projectId, status: "saved" }); + assert.deepEqual( + facts.map((fact) => fact.kind), + ["convention"], + ); + }).pipe(Effect.provide(makeLayer(model.generate))); + }, +); + it.effect("marks candidates from a failed run with that outcome", () => { const model = scripted([{ candidates: [snakeCase] }]); return Effect.gen(function* () { diff --git a/apps/server/src/project/knowledge/AssistedLearning.ts b/apps/server/src/project/knowledge/AssistedLearning.ts index a23a25d784893..40483b1f586f8 100644 --- a/apps/server/src/project/knowledge/AssistedLearning.ts +++ b/apps/server/src/project/knowledge/AssistedLearning.ts @@ -306,7 +306,7 @@ const make = Effect.gen(function* () { candidate === null || sources.length === 0 || candidate.citations.some((ref) => !refs.has(ref.trim())) || - (!userSupported && !corroborated) + (!userSupported && (!corroborated || candidate.kind === "decision")) ) { dropped += 1; continue; From ca8aa914f4d18eb1106b72a6b07d5f439481b6a8 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:08:55 -0800 Subject: [PATCH 13/27] fix(server): a read source names the peer who spoke it t3_knowledge_read_source presented a peer reply as the thread's assistant. ProjectKnowledgeSource now carries an optional speaker, attached in knowledge.readSources, and summary expansion reuses it instead of a second lookup. The speaker query moves onto ProjectionStoreV2. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/ProjectionStore.test.ts | 11 +++-- .../src/orchestration-v2/ProjectionStore.ts | 41 +++++++++++++++++ .../ProviderTurnControlService.test.ts | 1 + .../src/orchestration-v2/readPeerSpeakers.ts | 45 ------------------- .../ConversationSummaries.test.ts | 26 +---------- .../ConversationSummaries.ts | 33 +++++--------- .../src/project/knowledge/AssistedLearning.ts | 12 +++-- .../knowledge/ProjectKnowledge.test.ts | 35 +++++++++++++++ .../src/project/knowledge/ProjectKnowledge.ts | 9 ++++ packages/contracts/src/projectKnowledge.ts | 4 ++ 10 files changed, 113 insertions(+), 104 deletions(-) delete mode 100644 apps/server/src/orchestration-v2/readPeerSpeakers.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 6b173cf4807f9..d37a894a2b42d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -49,7 +49,6 @@ import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; -import { readPeerSpeakers } from "./readPeerSpeakers.ts"; import { buildBoundedThreadProjection, decodeThreadHistoryCursor, @@ -2935,18 +2934,18 @@ it.effect("reads message ordinals through their index", () => it.effect("reads peer speakers through the message index when messages are named", () => Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; + const projections = yield* ProjectionStore.ProjectionStoreV2; const threadId = ThreadId.make("thread:peer-speakers"); const named = traceSqlStatements(); - yield* readPeerSpeakers(sql, threadId, [MessageId.make("message:peer")]).pipe( - Effect.withTracer(named.tracer), - ); + yield* projections + .getPeerSpeakers(threadId, [MessageId.make("message:peer")]) + .pipe(Effect.withTracer(named.tracer)); yield* assertReadsThroughMessageOrdinalIndex( named.statements.find((statement) => statement.includes("$.speaker.label")), ["thread_id=?", "=?"], ); const open = traceSqlStatements(); - yield* readPeerSpeakers(sql, threadId).pipe(Effect.withTracer(open.tracer)); + yield* projections.getPeerSpeakers(threadId).pipe(Effect.withTracer(open.tracer)); const plan = yield* queryPlan( open.statements.find((statement) => statement.includes("$.speaker.label")), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2303b5adf30cf..aae00f8d8ffd3 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -76,6 +76,7 @@ import { orchestrationV2RunWorkStartedAt, RunId, MessageId, + type OrchestrationV2MessageSpeaker, RuntimeRequestId, CheckpointScopeId, CheckpointId, @@ -594,6 +595,11 @@ export interface ProjectionStoreV2Shape { ReadonlyMap, ProjectionStoreV2Error >; + /** Speakers of peer replies in the thread, or of the named messages only. */ + readonly getPeerSpeakers: ( + threadId: ThreadId, + messageIds?: ReadonlyArray, + ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadRecords: ( threadId: ThreadId, fields: ReadonlyArray, @@ -6644,6 +6650,40 @@ export const layer: Layer.Layer = (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), ); + // The type list and `json_valid` term match the message-ordinal index. Speaker fields sit + // outside it, so each hit decodes the payload. + const getPeerSpeakers = Effect.fn("ProjectionStore.getPeerSpeakers")( + function* (threadId: ThreadId, messageIds?: ReadonlyArray) { + const speakers = new Map(); + if (messageIds !== undefined && messageIds.length === 0) return speakers; + const rows = yield* sql<{ + readonly message_id: string; + readonly label: string | null; + readonly model: string | null; + }>` + SELECT json_extract(payload_json, '$.messageId') AS message_id, + json_extract(payload_json, '$.speaker.label') AS label, + json_extract(payload_json, '$.speaker.model') AS model + FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} + AND type IN ('user_message', 'assistant_message') + AND json_valid(payload_json) + AND json_extract(payload_json, '$.speaker.label') IS NOT NULL + AND json_extract(payload_json, '$.speaker.model') IS NOT NULL + ${ + messageIds === undefined + ? sql`` + : sql`AND json_extract(payload_json, '$.messageId') IN (SELECT value FROM json_each(${encodeIdList([...new Set(messageIds)])}))` + } + `; + for (const row of rows) + if (row.label && row.model) + speakers.set(MessageId.make(row.message_id), { label: row.label, model: row.model }); + return speakers; + }, + (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), + ); + const getThreadRecords: ProjectionStoreV2Shape["getThreadRecords"] = ( threadId, fields, @@ -9507,6 +9547,7 @@ export const layer: Layer.Layer = getActiveGroupThreadIds: readOnReader(getActiveGroupThreadIds), getTurnItem: readOnReader(getTurnItem), getMessagesById: readOnReader(getMessagesById), + getPeerSpeakers: readOnReader(getPeerSpeakers), getThreadRecords: (threadId, fields, filter) => getThreadRecords(threadId, fields, filter).pipe(NodeSqliteClient.readOnly), getRuntimeRequest: readOnReader(getRuntimeRequest), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 034786e08a136..a03e927c251d2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -271,6 +271,7 @@ it.effect( getActiveGroupThreadIds: () => Effect.die("unused group read"), getTurnItem: () => Effect.die("unused turn item read"), getMessagesById: () => Effect.die("unused getMessagesById"), + getPeerSpeakers: () => Effect.die("unused getPeerSpeakers"), getThreadRecords: () => Effect.die("unused record read"), getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"), getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"), diff --git a/apps/server/src/orchestration-v2/readPeerSpeakers.ts b/apps/server/src/orchestration-v2/readPeerSpeakers.ts deleted file mode 100644 index a6864800dd573..0000000000000 --- a/apps/server/src/orchestration-v2/readPeerSpeakers.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { MessageId, ThreadId, type OrchestrationV2MessageSpeaker } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; -import type * as SqlClient from "effect/sql/SqlClient"; - -const encodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); - -/** - * Speaker label and model for message items that carry both. The type list and `json_valid` - * term match the message-ordinal index. Speaker fields sit outside that index, so each hit - * decodes the payload. - */ -export const readPeerSpeakers = Effect.fn("ReadPeerSpeakers.read")(function* ( - sql: SqlClient.SqlClient, - threadId: ThreadId, - messageIds?: ReadonlyArray, -) { - const speakers = new Map(); - if (messageIds !== undefined && messageIds.length === 0) return speakers; - const rows = yield* sql<{ - readonly message_id: string; - readonly label: string | null; - readonly model: string | null; - }>` - SELECT json_extract(payload_json, '$.messageId') AS message_id, - json_extract(payload_json, '$.speaker.label') AS label, - json_extract(payload_json, '$.speaker.model') AS model - FROM orchestration_v2_projection_turn_items - WHERE thread_id = ${threadId} - AND type IN ('user_message', 'assistant_message') - AND json_valid(payload_json) - AND json_extract(payload_json, '$.speaker.label') IS NOT NULL - AND json_extract(payload_json, '$.speaker.model') IS NOT NULL - ${ - messageIds === undefined - ? sql`` - : sql`AND json_extract(payload_json, '$.messageId') IN (SELECT value FROM json_each(${encodeIds(messageIds)}))` - } - `; - for (const row of rows) { - if (row.label && row.model) - speakers.set(MessageId.make(row.message_id), { label: row.label, model: row.model }); - } - return speakers; -}); diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts index 66e60955c58cd..762be92d2bcca 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.test.ts @@ -464,7 +464,7 @@ it.effect( }, ); -it.effect("attributes peer replies to their speaker in summary model input", () => { +it.effect("sends a peer reply to the summary model as that peer", () => { const model = citing(); return Effect.gen(function* () { yield* seed; @@ -491,30 +491,6 @@ it.effect("attributes peer replies to their speaker in summary model input", () role: "assistant", text: rawText(3), }); - const summary = yield* onlySummary; - const service = yield* ConversationSummaries.ConversationSummaries; - const expansion = yield* service.expand({ - ...scope, - summaryId: summary.id, - offset: 1, - limit: 1, - }); - const peerSource = expansion.sources[0]?.result; - assert.equal(peerSource?.state, "available"); - if (peerSource?.state !== "available") return yield* Effect.die("Expected the peer source"); - assert.equal(peerSource.role, "assistant"); - assert.deepEqual(peerSource.speaker, { label: "Astra", model: "gpt-6-astra" }); - assert.equal(peerSource.text, rawText(1)); - const agentPage = yield* service.expand({ - ...scope, - summaryId: summary.id, - offset: 3, - limit: 1, - }); - const agentSource = agentPage.sources[0]?.result; - if (agentSource?.state !== "available") return yield* Effect.die("Expected the agent source"); - assert.equal(agentSource.role, "assistant"); - assert.equal(agentSource.speaker, undefined); }).pipe(Effect.provide(makeLayer(model.generate, optedIn))); }); diff --git a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts index 1f67754c39959..6c3b461ea639a 100644 --- a/apps/server/src/project/conversationSummaries/ConversationSummaries.ts +++ b/apps/server/src/project/conversationSummaries/ConversationSummaries.ts @@ -2,6 +2,7 @@ import { ConversationSummary, ConversationSummaryError, ConversationSummaryPass, + ConversationSummarySourceRange, CONVERSATION_SUMMARY_MAX_EXPANSION_CHARS, CONVERSATION_SUMMARY_MAX_SOURCES, conversationSummarySourceIdentity, @@ -19,6 +20,7 @@ import { type KnowledgeSourceUnavailableReason, type MessageId, type OrchestrationV2ConversationMessage, + type OrchestrationV2MessageSpeaker, type OrchestrationV2RunStatus, type OrchestrationV2UserMessageInputIntent, type ProjectId, @@ -45,7 +47,6 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as ProjectStore from "../../orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; -import { readPeerSpeakers } from "../../orchestration-v2/readPeerSpeakers.ts"; import * as ServerSettings from "../../serverSettings.ts"; import * as TextGeneration from "../../textGeneration/TextGeneration.ts"; import * as ProjectKnowledge from "../knowledge/ProjectKnowledge.ts"; @@ -330,11 +331,6 @@ const make = Effect.gen(function* () { source.kind === "message", ); const messageResults = yield* knowledge.readSources({ ...input, sources: messages }); - const speakers = yield* readPeerSpeakers( - sql, - input.threadId, - messages.map((source) => source.messageId), - ); const invisible = messages.length === 0 ? new Set() @@ -343,16 +339,14 @@ const make = Effect.gen(function* () { messages.map((source) => source.messageId), ); const current = new Map(); - messages.forEach((source, index) => { - const result = invisible.has(source.messageId) - ? { state: "unavailable" as const, reason: "missing" as const } - : messageResults[index]!; - const speaker = result.state === "available" ? speakers.get(source.messageId) : undefined; + messages.forEach((source, index) => current.set( conversationSummarySourceIdentity(source), - speaker === undefined || result.state !== "available" ? result : { ...result, speaker }, - ); - }); + invisible.has(source.messageId) + ? { state: "unavailable", reason: "missing" } + : messageResults[index]!, + ), + ); const tools = unique.filter( (source): source is Extract => source.kind === "turn_item", @@ -930,7 +924,7 @@ const make = Effect.gen(function* () { createdAt: message.createdAt, }); } - const speakers = yield* readPeerSpeakers(sql, threadId); + const speakers = yield* projections.getPeerSpeakers(threadId); for (const item of records.turnItems) { if (item.runId !== null && excluded.has(item.runId)) continue; const text = summaryToolText(item); @@ -998,12 +992,12 @@ const make = Effect.gen(function* () { readonly messages: ReadonlyArray< { readonly text: string; - readonly range?: ConversationSummaryRangeRef["range"]; + readonly range?: (typeof ConversationSummarySourceRange)["Type"]; } & ( | { readonly role: "user" | "assistant" | "tool" | "summary" } | { readonly role: "peer"; - readonly speaker: { readonly label: string; readonly model: string }; + readonly speaker: OrchestrationV2MessageSpeaker; } ) >; @@ -1015,10 +1009,7 @@ const make = Effect.gen(function* () { const messages = input.messages.map((message, index) => { const ref = `M${index + 1}`; refs.set(ref, conversationSummarySourceKey(input.sources[index]!)); - const range = message.range === undefined ? {} : { range: message.range }; - return message.role === "peer" - ? { ref, role: message.role, speaker: message.speaker, text: message.text, ...range } - : { ref, role: message.role, text: message.text, ...range }; + return { ref, ...message }; }); const reply = yield* textGeneration .generateConversationSummary({ diff --git a/apps/server/src/project/knowledge/AssistedLearning.ts b/apps/server/src/project/knowledge/AssistedLearning.ts index 40483b1f586f8..af33e2eb524e2 100644 --- a/apps/server/src/project/knowledge/AssistedLearning.ts +++ b/apps/server/src/project/knowledge/AssistedLearning.ts @@ -4,6 +4,8 @@ import { ProjectKnowledgeMutation, type AssistedLearningRun, type KnowledgeMessageRef, + type MessageId, + type OrchestrationV2MessageSpeaker, type ProjectId, RunId, ThreadId, @@ -24,7 +26,6 @@ import { forkParked } from "../../serverActivation.ts"; import * as ProjectStore from "../../orchestration-v2/ProjectStore.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; -import { readPeerSpeakers } from "../../orchestration-v2/readPeerSpeakers.ts"; import * as ServerSettings from "../../serverSettings.ts"; import * as TextGeneration from "../../textGeneration/TextGeneration.ts"; import { @@ -196,11 +197,8 @@ const make = Effect.gen(function* () { (left, right) => finalized.indexOf(left) - finalized.indexOf(right), ); // Citations are message ids and digests from this canonical read; the model only names refs. - const speakersByMessage = new Map< - (typeof transcript)[number]["id"], - { readonly label: string; readonly model: string } - >(); - const assistantIds = new Map>(); + const speakersByMessage = new Map(); + const assistantIds = new Map>(); for (const message of transcript) { if (message.role !== "assistant") continue; const ids = assistantIds.get(message.threadId) ?? []; @@ -208,7 +206,7 @@ const make = Effect.gen(function* () { assistantIds.set(message.threadId, ids); } for (const [id, messageIds] of assistantIds) - for (const [messageId, speaker] of yield* readPeerSpeakers(sql, id, messageIds)) + for (const [messageId, speaker] of yield* projections.getPeerSpeakers(id, messageIds)) speakersByMessage.set(messageId, speaker); const refs = new Map(); const userRefs = new Set(); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index f9019e901aa83..6316b1187c729 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -358,6 +358,41 @@ it.effect("saves agent facts for immediate recall and rehydrates exact sources", }); assert.equal(source.state, "available"); if (source.state !== "available") return; + const peerId = MessageId.make("peer-message"); + yield* projections.apply(message(threadId, peerId, "assistant", "Use Postgres for sessions.")); + yield* projections.apply({ + id: EventId.make("peer-item"), + type: "turn-item.updated", + threadId, + providerInstanceId, + occurredAt: at(2), + payload: { + id: TurnItemId.make("peer-item"), + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: at(2), + completedAt: at(2), + updatedAt: at(2), + type: "assistant_message", + messageId: peerId, + text: "Use Postgres for sessions.", + streaming: false, + speaker: { label: "Astra", model: "gpt-6-astra" }, + }, + }); + const peer = yield* knowledge.readSource({ projectId, threadId, messageId: peerId }); + assert.deepEqual(peer.state === "available" && [peer.role, peer.speaker], [ + "assistant", + { label: "Astra", model: "gpt-6-astra" }, + ]); const saved = yield* knowledge.mutate( { ...createFact(projectId), sources: [source.source] }, { kind: "agent-client", sessionId: "test-agent", label: "Test agent" }, diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.ts b/apps/server/src/project/knowledge/ProjectKnowledge.ts index 766741a9fe189..5e51e929bc102 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.ts @@ -327,6 +327,14 @@ const make = Effect.gen(function* () { .filter((message) => !excluded.has(message.id)) .map((message) => [message.id, message]), ); + const speakers = yield* projections + .getPeerSpeakers( + input.threadId, + [...messages.values()] + .filter((message) => message.role === "assistant") + .map((message) => message.id), + ) + .pipe(Effect.mapError(storageError(input.projectId))); return yield* Effect.forEach( input.sources, // Per source inside the batch, which already has its span. @@ -361,6 +369,7 @@ const make = Effect.gen(function* () { text: message.text, title: projection.thread.title, role: message.role, + ...(speakers.has(message.id) ? { speaker: speakers.get(message.id)! } : {}), createdAt: DateTime.formatIso(message.createdAt), archived: projection.thread.archivedAt !== null, }; diff --git a/packages/contracts/src/projectKnowledge.ts b/packages/contracts/src/projectKnowledge.ts index 80c4ea03dd1b4..325f4e2b356e3 100644 --- a/packages/contracts/src/projectKnowledge.ts +++ b/packages/contracts/src/projectKnowledge.ts @@ -328,6 +328,10 @@ const ProjectKnowledgeSourceSchema = Schema.Union([ text: Schema.String, title: Schema.String, role: Schema.Literals(["user", "assistant"]), + /** Set when an assistant message was spoken by another model in the thread. */ + speaker: Schema.optionalKey( + Schema.Struct({ label: TrimmedNonEmptyString, model: TrimmedNonEmptyString }), + ), createdAt: IsoDateTime, archived: Schema.Boolean, }), From 209b44e79f527bfdab141e5813b4da35aaef9d42 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:10:44 -0800 Subject: [PATCH 14/27] fix: a peer named by its model is named once A seat without a label falls back to its model, so labels and prompts rendered "gpt-x (gpt-x)". Also drops the exact-wording prompt and label tests; the conversation-summaries eval covers wording. Co-Authored-By: Claude Opus 5.5 --- .../src/conversationSummaries/index.test.ts | 41 --------------- .../src/conversationSummaries/index.ts | 6 ++- .../src/server/textGenerationPrompts.test.ts | 52 +------------------ .../src/server/textGenerationPrompts.ts | 24 ++++++--- 4 files changed, 21 insertions(+), 102 deletions(-) delete mode 100644 packages/client-runtime/src/conversationSummaries/index.test.ts diff --git a/packages/client-runtime/src/conversationSummaries/index.test.ts b/packages/client-runtime/src/conversationSummaries/index.test.ts deleted file mode 100644 index 9055cc6898ebe..0000000000000 --- a/packages/client-runtime/src/conversationSummaries/index.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { - ConversationSummarySourceRef, - ConversationSummarySourceResult, -} from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { conversationSummarySourceLabel } from "./index.ts"; - -const ref = { - kind: "message", - threadId: "thread", - messageId: "message", - digest: "a".repeat(64), -} as ConversationSummarySourceRef; - -const source = (speaker?: { - readonly label: string; - readonly model: string; -}): ConversationSummarySourceResult => - ({ - state: "available", - source: ref, - text: "Keep the store decision open.", - title: "Thread", - role: "assistant", - ...(speaker === undefined ? {} : { speaker }), - createdAt: "2026-10-22T00:00:00.000Z", - archived: false, - }) as ConversationSummarySourceResult; - -describe("conversation summary source labels", () => { - it("names a peer instead of the thread agent", () => { - expect( - conversationSummarySourceLabel(ref, source({ label: "Astra", model: "gpt-6-astra" })), - ).toBe("Astra (gpt-6-astra)"); - }); - - it("keeps an unlabeled assistant as the assistant", () => { - expect(conversationSummarySourceLabel(ref, source())).toBe("Assistant"); - }); -}); diff --git a/packages/client-runtime/src/conversationSummaries/index.ts b/packages/client-runtime/src/conversationSummaries/index.ts index ad9c42761427e..4212d1179903b 100644 --- a/packages/client-runtime/src/conversationSummaries/index.ts +++ b/packages/client-runtime/src/conversationSummaries/index.ts @@ -59,8 +59,10 @@ export function conversationSummarySourceLabel( case "user": return "User"; case "assistant": - return result.speaker === undefined - ? "Assistant" + if (result.speaker === undefined) return "Assistant"; + // A seat without a label is named by its model. + return result.speaker.label === result.speaker.model + ? result.speaker.label : `${result.speaker.label} (${result.speaker.model})`; case "tool": return "Tool"; diff --git a/packages/provider-core/src/server/textGenerationPrompts.test.ts b/packages/provider-core/src/server/textGenerationPrompts.test.ts index 9efc3c5cb25e2..cbc19e876bf75 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.test.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { - buildConversationSummaryPrompt, - buildKnowledgeCandidatesPrompt, - buildThreadTitlePrompt, -} from "./textGenerationPrompts.ts"; +import { buildKnowledgeCandidatesPrompt, buildThreadTitlePrompt } from "./textGenerationPrompts.ts"; import { normalizeCliError } from "./textGenerationUtils.ts"; describe("normalizeCliError", () => { @@ -47,52 +43,6 @@ it("preserves each run boundary and terminal outcome in family review prompts", expect(prompt).toContain("[M2] assistant (T2/R2, completed):\nChecked compatibility."); }); -it("names a peer in a summary and forbids giving its words to the user or the agent", () => { - const { prompt } = buildConversationSummaryPrompt({ - messages: [ - { ref: "M1", role: "user", text: "Where should sessions live?" }, - { - ref: "M2", - role: "peer", - speaker: { label: "Astra", model: "gpt-6-astra" }, - text: "Drop Redis and use Postgres.", - }, - { ref: "M3", role: "assistant", text: "I disagree. Keep Redis." }, - ], - }); - expect(prompt).toContain("[M2] peer Astra (gpt-6-astra):\nDrop Redis and use Postgres."); - expect(prompt).toContain( - "a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", - ); - expect(prompt).not.toContain("Historical"); -}); - -it("does not record a peer proposal as the user's decision", () => { - const { prompt } = buildKnowledgeCandidatesPrompt({ - runOutcome: "completed", - messages: [ - { - ref: "M1", - role: "peer", - speaker: { label: "Astra", model: "gpt-6-astra" }, - text: "Drop Redis and use Postgres.", - threadId: "root", - runId: "run-a", - runOutcome: "completed", - }, - ], - }); - expect(prompt).toContain( - "[M1] peer Astra (gpt-6-astra, T1/R1, completed):\nDrop Redis and use Postgres.", - ); - expect(prompt).toContain( - "a peer is another model in the conversation; its proposals are not the user's decisions unless the user accepted them", - ); - expect(prompt).not.toContain( - "a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent", - ); -}); - describe("buildThreadTitlePrompt", () => { it("names the project to leave out of initial and regenerated titles", () => { for (const previousTitle of [undefined, "Hyperdrive Config Crash"]) { diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts index 528f304cf5998..bcf7fc4cbea5c 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.ts @@ -504,6 +504,15 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) { return { prompt, outputSchema }; } +type PeerSpeaker = { readonly label: string; readonly model: string }; + +/** A seat without a label is named by its model; say it once. */ +const peerDetails = (speaker: PeerSpeaker, extra?: string) => + [ + ...(speaker.label === speaker.model ? [] : [speaker.model]), + ...(extra === undefined ? [] : [extra]), + ].join(", "); + export type KnowledgeCandidatesPromptMessage = { readonly ref: string; readonly threadId?: string; @@ -512,7 +521,7 @@ export type KnowledgeCandidatesPromptMessage = { readonly text: string; } & ( | { readonly role: "user" | "assistant" } - | { readonly role: "peer"; readonly speaker: { readonly label: string; readonly model: string } } + | { readonly role: "peer"; readonly speaker: PeerSpeaker } ); export interface KnowledgeCandidatesPromptInput { @@ -555,11 +564,9 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI message.runId === undefined ? undefined : `${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome}`; - const role = - message.role === "peer" - ? `peer ${message.speaker.label} (${message.speaker.model}${run === undefined ? "" : `, ${run}`})` - : `${message.role}${run === undefined ? "" : ` (${run})`}`; - return `[${message.ref}] ${role}:\n${message.text}\n`; + const role = message.role === "peer" ? `peer ${message.speaker.label}` : message.role; + const details = message.role === "peer" ? peerDetails(message.speaker, run) : run; + return `[${message.ref}] ${role}${details ? ` (${details})` : ""}:\n${message.text}\n`; }), ].join("\n"); const outputSchema = Schema.Struct({ @@ -584,7 +591,7 @@ export type ConversationSummaryPromptMessage = { readonly range?: { readonly start: number; readonly end: number; readonly total: number }; } & ( | { readonly role: "user" | "assistant" | "tool" | "summary" } - | { readonly role: "peer"; readonly speaker: { readonly label: string; readonly model: string } } + | { readonly role: "peer"; readonly speaker: PeerSpeaker } ); export interface ConversationSummaryPromptInput { @@ -613,9 +620,10 @@ export function buildConversationSummaryPrompt(input: ConversationSummaryPromptI "", "Sources:", ...input.messages.map((message) => { + const details = message.role === "peer" ? peerDetails(message.speaker) : ""; const role = message.role === "peer" - ? `peer ${message.speaker.label} (${message.speaker.model})` + ? `peer ${message.speaker.label}${details ? ` (${details})` : ""}` : message.role; const range = message.range === undefined From 8a007b4ddb31761f59b37ec552aa6ef43b99cce8 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:16:30 -0800 Subject: [PATCH 15/27] fix(evals): grade who decided, not which words sit near Postgres The leaf grader failed open statements such as "the user has yet to decide" and passed wrong ones such as "the user went with Postgres". The patterns now need the user or agent to be the subject of an affirmative verb, and catch "per the user". Every reviewed sentence is a row. Adds a knowledge-candidates case where a peer proposes and no decision may come out, with a plain-convention control, and gives the peer case its real source. Co-Authored-By: Claude Opus 5.5 --- evals/conversation-summaries/cases.ts | 93 ++++++++++++++++++----- evals/conversation-summaries/grade.ts | 27 ++++++- evals/conversation-summaries/run.test.ts | 94 ++++++++++++++---------- 3 files changed, 154 insertions(+), 60 deletions(-) diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts index 73f76470ceb1c..a801d9e7a478e 100644 --- a/evals/conversation-summaries/cases.ts +++ b/evals/conversation-summaries/cases.ts @@ -20,24 +20,39 @@ export interface LeafCase { readonly mustNot: ReadonlyArray; } +/** Statements that hand the peer's Postgres proposal to the user or to the thread's agent. */ +const misattributed = [ + String.raw`\buser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis)`, + String.raw`\buser's decision to (drop Redis|use Postgres|keep Redis)`, + // The verb must follow the user directly, so "has yet to decide" and "never agreed" stay open. + String.raw`\buser\s+(?:(?:has|had|then|also|finally|ultimately|eventually|now)\s+)*(?:decided|chose|chosen|picked|selected|opted|went with|goes with|settled on|agreed|accepted|approved|adopted|endorsed|signed off)\b(?:(?!\b(?:not|never|against|between|whether)\b)[^.;]){0,60}\b(?:Postgres|Astra|proposal|suggestion)\b`, + String.raw`\bPostgres\b[^.;]{0,60}(?:\b(?:per|according to|as (?:decided|requested|chosen|approved) by)\s+the user\b|\bat the user's (?:request|direction)\b)`, + String.raw`\bagent\s+(?:(?:also|first|then|initially|had|has)\s+)*(?:propos(?:ed|es)|suggest(?:ed|s)|recommend(?:ed|s)|push(?:ed|es) for)\b(?:(?!\b(?:not|never|against|keep|keeping)\b)[^.;]){0,60}\bPostgres\b|\bagent's (?:proposal|suggestion|recommendation)\b[^.;]{0,40}\bPostgres\b`, +]; + +/** The group exchange both peer cases send: the user asks, Astra proposes, the agent disagrees. */ +const peerProposal: ReadonlyArray = [ + { role: "user", text: "Where should sessions live? I have not decided." }, + { + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: "Drop Redis and use Postgres for sessions.", + }, + { + role: "assistant", + text: "I disagree. Keep Redis for sessions. The choice is still open.", + }, +]; + +const peerProposalSource = + 'Group threads (t3/peer-reply-summary-attribution): a seat model\'s published reply reached the summarizer as a plain assistant message with no name, and production summaries said "The assistant answered" for words the peer spoke.'; + export const leafCases: ReadonlyArray = [ { id: "leaf-peer-proposal-is-not-a-user-decision", kind: "bad", - source: - "Group threads (t3/peer-reply-summary-attribution): a seat model's published reply was summarized as the user's decision.", - messages: [ - { role: "user", text: "Where should sessions live? I have not decided." }, - { - role: "peer", - speaker: { label: "Astra", model: "gpt-6-astra" }, - text: "Drop Redis and use Postgres for sessions.", - }, - { - role: "assistant", - text: "I disagree. Keep Redis for sessions. The choice is still open.", - }, - ], + source: peerProposalSource, + messages: peerProposal, mustMention: ["Astra", "Postgres"], attributed: [ { @@ -45,12 +60,7 @@ export const leafCases: ReadonlyArray = [ require: "Astra", }, ], - mustNot: [ - "[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis)", - "[Uu]ser's decision to (drop Redis|use Postgres|keep Redis)", - "\\buser\\b(?:(?!\\bnot\\b)[^.;]){0,30}\\b(?:agre|chose|choos|accept|decid)\\w*(?:(?!\\bnot\\b)[^.;]){0,30}\\bPostgres\\b", - "\\bagent\\b(?:(?!\\bnot\\b)[^.;]){0,40}\\b(?:propos|suggest)\\w*(?:(?!\\bnot\\b)[^.;]){0,40}\\bPostgres\\b", - ], + mustNot: misattributed, }, { id: "leaf-ordinary-exchange-has-no-peer", @@ -69,6 +79,49 @@ export const leafCases: ReadonlyArray = [ }, ]; +/** One finished exchange, as assisted learning sends it for fact candidates. */ +export interface KnowledgeCase { + readonly id: string; + readonly kind: "bad" | "control"; + readonly source: string; + readonly messages: ReadonlyArray; + /** Candidate kinds that must not come out. */ + readonly forbiddenKinds: ReadonlyArray<"decision" | "constraint" | "convention">; + /** Each regex must match some candidate. */ + readonly mustMention: ReadonlyArray; + /** No candidate may match these. */ + readonly mustNot: ReadonlyArray; +} + +export const knowledgeCases: ReadonlyArray = [ + { + id: "knowledge-peer-proposal-is-not-a-decision", + kind: "bad", + source: `${peerProposalSource} Assisted learning reads the same messages, so a peer proposal could be saved as the user's decision.`, + messages: peerProposal, + forbiddenKinds: ["decision"], + mustMention: [], + mustNot: [ + ...misattributed, + String.raw`\bsessions (?:are|will be|should be)? ?(?:stored|kept|live|living|moved?|moving) (?:in|to) Postgres\b`, + String.raw`\b(?:use|uses|using) Postgres (?:for|as the) sessions?\b`, + ], + }, + { + id: "knowledge-user-convention-is-kept", + kind: "control", + source: + "Control for the peer rule: a plain user instruction must still become a fact, so the rule cannot suppress ordinary learning.", + messages: [ + { role: "user", text: "From now on API responses use snake_case keys everywhere." }, + { role: "assistant", text: "Done. I converted the handlers to snake_case keys." }, + ], + forbiddenKinds: [], + mustMention: ["snake_case"], + mustNot: [], + }, +]; + /** A roll-up input: four adjacent child summaries, oldest first, as the summary pass sends them. */ export interface CondensedCase { readonly id: string; diff --git a/evals/conversation-summaries/grade.ts b/evals/conversation-summaries/grade.ts index 2fa438d578a9f..155d611a40bc6 100644 --- a/evals/conversation-summaries/grade.ts +++ b/evals/conversation-summaries/grade.ts @@ -1,4 +1,4 @@ -import type { CondensedCase, LeafCase } from "./cases.ts"; +import type { CondensedCase, KnowledgeCase, LeafCase } from "./cases.ts"; const MAX_CHARS = 1_200; @@ -58,3 +58,28 @@ export function gradeLeaf( undefined, ); } + +type Candidate = { + readonly kind: string; + readonly content: string; + readonly citations: ReadonlyArray; +}; + +/** Every way a fact-candidate reply breaks the case's rules; empty when it passes. */ +export function gradeKnowledge( + fixture: KnowledgeCase, + candidates: ReadonlyArray, +): ReadonlyArray { + const failures: Array = []; + for (const candidate of candidates) + if ((fixture.forbiddenKinds as ReadonlyArray).includes(candidate.kind)) + failures.push(`${candidate.kind}: ${candidate.content}`); + for (const pattern of fixture.mustMention) + if (!candidates.some((candidate) => new RegExp(pattern).test(candidate.content))) + failures.push(`missing ${pattern}`); + for (const pattern of fixture.mustNot) + for (const candidate of candidates) + if (new RegExp(pattern, "i").test(candidate.content)) + failures.push(`${pattern}: ${candidate.content}`); + return failures; +} diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index ad5d835256808..8206b1c3a7147 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -1,13 +1,15 @@ import { expect, it } from "vite-plus/test"; -import { condensedCases, leafCases } from "./cases.ts"; -import { gradeCondensed, gradeLeaf } from "./grade.ts"; +import { condensedCases, knowledgeCases, leafCases } from "./cases.ts"; +import { gradeCondensed, gradeKnowledge, gradeLeaf } from "./grade.ts"; const [reversal, control] = condensedCases; const [peerLeaf, ordinaryLeaf] = leafCases; -const userAcceptedPostgres = - "\\buser\\b(?:(?!\\bnot\\b)[^.;]){0,30}\\b(?:agre|chose|choos|accept|decid)\\w*(?:(?!\\bnot\\b)[^.;]){0,30}\\bPostgres\\b"; -const agentProposedPostgres = - "\\bagent\\b(?:(?!\\bnot\\b)[^.;]){0,40}\\b(?:propos|suggest)\\w*(?:(?!\\bnot\\b)[^.;]){0,40}\\bPostgres\\b"; +const [peerKnowledge, conventionKnowledge] = knowledgeCases; +/** The grader's misattribution failures for one statement, ignoring what it leaves out. */ +const misattributions = (text: string) => + gradeLeaf(peerLeaf!, [{ text, citations: ["M2"] }]).filter((failure) => + peerLeaf!.mustNot.some((pattern) => failure.startsWith(`${pattern}: `)), + ); it("passes a roll-up that keeps the reversal, the attribution and the open item", () => { expect( @@ -60,18 +62,30 @@ it("passes a leaf that names the peer and leaves the choice open", () => { ).toEqual([]); }); -it("fails a leaf that records the peer proposal as the user's decision", () => { - const text = "The user decided to use Postgres for sessions."; - expect( - gradeLeaf(peerLeaf!, [ - { text, citations: ["M2"] }, - { text: "The agent wants to keep Redis.", citations: ["M3"] }, - ]), - ).toEqual([ - "missing Astra", - `[Uu]ser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis): ${text}`, - `${userAcceptedPostgres}: ${text}`, - ]); +it.each([ + "Astra proposed dropping Redis and using Postgres for sessions.", + "The user has not decided.", + "The user has not chosen between Redis and Postgres; the agent prefers Redis.", + "The user has yet to decide between Redis and Postgres.", + "The user hasn't decided whether to use Postgres.", + "The user is still deciding between Redis and Postgres.", + "The user never agreed to Postgres.", + "The agent rejected the proposal to use Postgres.", +])("leaves an open choice open: %s", (text) => { + expect(misattributions(text)).toEqual([]); +}); + +it.each([ + "The user decided to use Postgres for sessions.", + "Astra proposed Postgres and the user agreed to use Postgres.", + "The user chose Postgres for sessions, following Astra.", + "The user accepted Astra's proposal, so sessions move to Postgres.", + "The user went with Postgres.", + "The user approved Postgres.", + "Sessions will move to Postgres, per the user.", + "The agent proposed moving sessions to Postgres; Astra wants to keep Redis.", +])("fails a statement that hands the proposal to the user or the agent: %s", (text) => { + expect(misattributions(text)).not.toEqual([]); }); it("does not treat an open Postgres choice as the peer's proposal", () => { @@ -85,27 +99,6 @@ it("does not treat an open Postgres choice as the peer's proposal", () => { ).toEqual(["missing Astra"]); }); -it("fails a leaf where the user agrees to Postgres", () => { - const text = "Astra proposed Postgres and the user agreed to use Postgres."; - expect(gradeLeaf(peerLeaf!, [{ text, citations: ["M2"] }])).toEqual([ - `${userAcceptedPostgres}: ${text}`, - ]); -}); - -it("fails a leaf where the user chooses Postgres", () => { - const text = "The user chose Postgres for sessions, following Astra."; - expect(gradeLeaf(peerLeaf!, [{ text, citations: ["M2"] }])).toEqual([ - `${userAcceptedPostgres}: ${text}`, - ]); -}); - -it("fails a leaf that gives the peer's Postgres proposal to the agent", () => { - const text = "The agent proposed moving sessions to Postgres; Astra wants to keep Redis."; - expect(gradeLeaf(peerLeaf!, [{ text, citations: ["M2", "M3"] }])).toEqual([ - `${agentProposedPostgres}: ${text}`, - ]); -}); - it("passes an ordinary leaf with no peer", () => { expect( gradeLeaf(ordinaryLeaf!, [ @@ -118,6 +111,29 @@ it("passes an ordinary leaf with no peer", () => { ).toEqual([]); }); +it("fails a fact candidate that saves the peer's proposal as a decision", () => { + const content = "Sessions are stored in Postgres instead of Redis."; + const failures = gradeKnowledge(peerKnowledge!, [ + { kind: "decision", content, citations: ["M2"] }, + ]); + expect(failures[0]).toBe(`decision: ${content}`); + expect(failures.length).toBeGreaterThan(1); + expect( + gradeKnowledge(peerKnowledge!, [ + { kind: "convention", content: "Session storage is undecided.", citations: ["M1"] }, + ]), + ).toEqual([]); +}); + +it("requires the control's plain user convention", () => { + expect(gradeKnowledge(conventionKnowledge!, [])).toEqual(["missing snake_case"]); + expect( + gradeKnowledge(conventionKnowledge!, [ + { kind: "convention", content: "API responses use snake_case keys.", citations: ["M1"] }, + ]), + ).toEqual([]); +}); + it("passes an ordinary roll-up in the control case", () => { expect( gradeCondensed(control!, [ From cb7e5836d9caebd6fa4a2b6c45cd62697f772815 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:36:26 -0800 Subject: [PATCH 16/27] feat(evals): compare peer-reply arms on Morph's free route --arm main, peer-as-user, no-rule and full reproduce each way a peer reply has reached the model, from one checkout. A morph-* model calls Morph directly with the production prompt builders and reply decoder, waiting out its per-minute token limit. Co-Authored-By: Claude Opus 5.5 --- evals/README.md | 2 +- evals/conversation-summaries/README.md | 27 +++-- evals/conversation-summaries/run.ts | 154 ++++++++++++++++++++++--- evals/shared/proxy.ts | 30 +++++ 4 files changed, 188 insertions(+), 25 deletions(-) diff --git a/evals/README.md b/evals/README.md index 815376183ae16..3c88d57e89cf2 100644 --- a/evals/README.md +++ b/evals/README.md @@ -10,7 +10,7 @@ Write or run an eval when a change affects what a model sees or does: agent inst | [group-conversation](group-conversation/) | Whether peers engage, preserve attribution, use PASS and handles, edit with the real side chat digest, and continue through delegation. Compares parallel and serial reactions. | | [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | | [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [conversation-summaries](conversation-summaries/) | Whether a leaf summary names a peer's proposal, and a roll-up keeps reversals, attribution and open items within its budget. | +| [conversation-summaries](conversation-summaries/) | Whether summaries and learned facts credit a peer's proposal to the peer, and a roll-up keeps reversals, attribution and open items within its budget. | | [model-evaluations](model-evaluations/) | Whether blind judges use outcome evidence, respect task scope, ignore injected scoring instructions, and abstain when evidence is missing. | | [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | | [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | diff --git a/evals/conversation-summaries/README.md b/evals/conversation-summaries/README.md index 6efb8fd3d46df..15c07b200aed1 100644 --- a/evals/conversation-summaries/README.md +++ b/evals/conversation-summaries/README.md @@ -1,25 +1,36 @@ # Conversation summaries -Checks the summary prompt on two inputs. A leaf is one exchange, including a reply from another model in the thread. A roll-up condenses four adjacent summaries, as the summary pass does for long threads. Each sample calls the server's real summary generator through the local Codex login, with the prompt from this checkout. +Checks how background text generation reads a conversation, using the prompts from this checkout. A leaf summary covers one exchange, including a reply from another model in the thread. A roll-up condenses four adjacent summaries, as the summary pass does for long threads. A knowledge case sends the same exchange to assisted learning and grades the fact candidates it returns. -The production summarizer is an OpenCode model. This runner only builds a Codex text-generation client, so the runs here use `gpt-6-luna`. +The production summarizer is an OpenCode model. A `gpt-*` model calls the server's real Codex generator through the local Codex login. A `morph-*` model calls Morph's free API directly, using the production prompt builders and reply decoder. The key comes from `MORPH_API_KEY`, or else from the `morph` provider in `~/.config/opencode/opencode.json`. ```sh cd evals -pnpm conversation-summaries --model gpt-6-luna --out runs/summaries-before -pnpm conversation-summaries --model gpt-6-luna --out runs/summaries-after --baseline runs/summaries-before/results.json +pnpm conversation-summaries --model morph-kimik31 --arm main --samples 8 --out runs/peer-main +pnpm conversation-summaries --model morph-kimik31 --arm full --samples 8 --out runs/peer-full --baseline runs/peer-main/results.json ``` +`--arm` sets how a peer reply reaches the model, so the arms compare from one checkout: + +- `main` sends it as a nameless assistant message with no peer rule, as `main` does. Its leaf case fails by construction, because the name the grader wants is not in the input. +- `peer-as-user` renders it as a historical user message with the speaker in its header and no peer rule. This was the first attempt on `t3/peer-reply-summary-attribution`. +- `no-rule` names the peer but drops the prompt's peer rule. +- `full` is this checkout. It is the default and the only arm a `gpt-*` model can run, since the other arms edit the prompt. + +Cases: + - `condensed-four-sources-retain-reversal-and-unverified-claim` passes when the roll-up keeps the later Postgres decision instead of the reversed Redis one, keeps the agent's test claim attributed and unverified, keeps the open rollback script, cites only the given summaries, and fits in 1,200 characters. - `condensed-four-ordinary-sources` is the control: an ordinary docs task that must keep its open item and fit the same budget. -- `leaf-peer-proposal-is-not-a-user-decision` passes when the summary names Astra as the one who proposed Postgres, and does not record that proposal as a decision the user made. +- `leaf-peer-proposal-is-not-a-user-decision` passes when the summary names Astra as the one who proposed Postgres, and credits that proposal to neither the user nor the agent. - `leaf-ordinary-exchange-has-no-peer` is the leaf control: an ordinary docs task with no peer. -- `--case ` limits the run, `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result. +- `knowledge-peer-proposal-is-not-a-decision` passes when no `decision` candidate comes out of the same exchange, and no candidate states Postgres as settled. +- `knowledge-user-convention-is-kept` is its control: a plain user instruction must still become a fact. +- `--case ` limits the run, and `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result. ## Add a case -Add a condensed entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. A leaf entry has `messages` instead of `summaries`. `run.test.ts` tests the grader. +Add a condensed entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. A leaf or knowledge entry has `messages` instead of `summaries`. `run.test.ts` tests the grader. ## Cost -Each sample is one paid call through the local subscription. The full suite is twelve calls: six roll-up samples and six leaf samples. The CLI does not report per-call cost here. +A `morph-*` sample is free but rate limited to about 24,000 uncached input tokens a minute; the runner waits out `Retry-After`. A `gpt-*` sample is one call on the local subscription. The CLI does not report per-call cost. diff --git a/evals/conversation-summaries/run.ts b/evals/conversation-summaries/run.ts index 319425269b0c4..527e9e4d802fb 100644 --- a/evals/conversation-summaries/run.ts +++ b/evals/conversation-summaries/run.ts @@ -1,16 +1,27 @@ #!/usr/bin/env node import * as NodeUtil from "node:util"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; +import { CodexSettings, ProviderInstanceId, RunId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; +import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; import * as ServerConfig from "../../apps/server/src/config.ts"; -import { condensedCases, leafCases } from "./cases.ts"; -import { gradeCondensed, gradeLeaf } from "./grade.ts"; +import { morphConfig } from "../shared/proxy.ts"; +import { condensedCases, knowledgeCases, leafCases, type LeafMessage } from "./cases.ts"; +import { gradeCondensed, gradeKnowledge, gradeLeaf } from "./grade.ts"; + +/** + * How a peer reply reaches the model. `main` sends it as a nameless assistant message, as main + * does. `peer-as-user` renders it as a historical user message, as b71f68c2d3 did. `no-rule` names + * the peer without the prompt's peer rule. `full` is this checkout. + */ +const arms = ["main", "peer-as-user", "no-rule", "full"] as const; const { values } = NodeUtil.parseArgs({ options: { @@ -19,20 +30,28 @@ const { values } = NodeUtil.parseArgs({ baseline: { type: "string" }, case: { type: "string" }, samples: { type: "string", default: "3" }, + arm: { type: "string", default: "full" }, }, }); if (!values.model || !values.out) throw new Error("Use --model --out ."); const model = values.model; const outputDirectory = values.out; const samples = Number(values.samples); +const arm = arms.find((candidate) => candidate === values.arm); +if (arm === undefined) throw new Error(`Unknown --arm ${values.arm}. Use ${arms.join(", ")}.`); +const morph = model.startsWith("morph-"); +const dropsPeerRule = arm === "main" || arm === "no-rule" || arm === "peer-as-user"; +if (dropsPeerRule && !morph) + throw new Error(`--arm ${arm} edits the prompt, which only a morph-* model route can do.`); const selectedIds = values.case?.split(","); const selected = (fixtures: ReadonlyArray) => fixtures.filter((fixture) => selectedIds === undefined || selectedIds.includes(fixture.id)); const selectedCondensed = selected(condensedCases); const selectedLeaf = selected(leafCases); -if (selectedCondensed.length + selectedLeaf.length === 0) +const selectedKnowledge = selected(knowledgeCases); +if (selectedCondensed.length + selectedLeaf.length + selectedKnowledge.length === 0) throw new Error( - `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases].map((fixture) => fixture.id).join(", ")}`, + `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases, ...knowledgeCases].map((fixture) => fixture.id).join(", ")}`, ); const Results = Schema.Array( Schema.Struct({ @@ -48,6 +67,89 @@ const Results = Schema.Array( const decodeSettings = Schema.decodeUnknownSync(CodexSettings); const decodeResults = Schema.decodeEffect(Schema.fromJsonString(Results)); const encodeResults = Schema.encodeEffect(Schema.fromJsonString(Results)); +const decodeMorphReply = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + output: Schema.Array( + Schema.Struct({ + type: Schema.String, + content: Schema.optional( + Schema.Array(Schema.Struct({ text: Schema.optional(Schema.String) })), + ), + }), + ), + }), + ), +); + +const MORPH_ATTEMPTS = 8; +const PEER_RULE = "- a peer is another model"; +const withoutPeerRule = (prompt: string) => { + const lines = prompt.split("\n"); + const kept = lines.filter((line) => !line.startsWith(PEER_RULE)); + if (kept.length === lines.length) throw new Error("The prompt has no peer rule to drop."); + return kept.join("\n"); +}; + +/** Morph's free Responses API, given the production prompt as OpenCode sends it: text only. */ +const morphRunner = (): TextGenerationOperations.Runner => { + const endpoint = morphConfig(); + return (request) => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const prompt = dropsPeerRule ? withoutPeerRule(request.prompt) : request.prompt; + const post = HttpClientRequest.post(`${endpoint.url}/responses`).pipe( + HttpClientRequest.setHeaders(endpoint.headers), + HttpClientRequest.bodyJson({ + model: request.modelSelection.model, + input: [{ role: "user", content: [{ type: "input_text", text: prompt }] }], + store: false, + max_output_tokens: 8_000, + }), + Effect.flatMap(client.execute), + ); + let response = yield* post; + // Morph limits input tokens per minute and says when to come back. + for (let attempt = 1; response.status === 429 || response.status >= 500; attempt++) { + if (attempt >= MORPH_ATTEMPTS) break; + const retryAfter = Number(response.headers["retry-after"]); + yield* Effect.sleep(`${retryAfter > 0 ? Math.min(retryAfter, 60) : 2 ** attempt} seconds`); + response = yield* post; + } + // The body is omitted so a credential echoed in an error never reaches the log. + if (response.status !== 200) return yield* Effect.die(`Morph HTTP ${response.status}`); + const reply = yield* decodeMorphReply(yield* response.text); + const text = reply.output + .filter((item) => item.type === "message") + .flatMap((item) => item.content ?? []) + .map((part) => part.text ?? "") + .join(""); + return yield* TextGenerationOperations.decodeJsonReply(request, "Morph", text); + }).pipe(Effect.orDie, Effect.provide(FetchHttpClient.layer)); +}; + +const asArm = (message: LeafMessage, index: number) => { + const ref = `M${index + 1}`; + if (message.role !== "peer" || arm === "full" || arm === "no-rule") return { ref, ...message }; + if (arm === "main") return { ref, role: "assistant" as const, text: message.text }; + const [, rendered] = historyResponseItems( + [ + { + role: "user", + text: message.text, + speaker: message.speaker, + threadId: ThreadId.make("thread"), + runId: RunId.make("run"), + itemId: TurnItemId.make(`item-${ref}`), + providerThreadId: null, + status: "completed", + kind: "peer_reply", + }, + ], + "", + ); + return { ref, role: "user" as const, text: rendered!.content[0]!.text }; +}; await Effect.runPromise( Effect.gen(function* () { @@ -57,7 +159,13 @@ await Effect.runPromise( ? yield* fs.readFileString(values.baseline).pipe(Effect.tap(decodeResults)) : undefined; const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-summary-eval-" }); - const generation = yield* CodexTextGeneration.makeCodexTextGeneration(decodeSettings({})); + const generation = morph + ? TextGenerationOperations.fromRunner("Morph", morphRunner()) + : yield* CodexTextGeneration.makeCodexTextGeneration(decodeSettings({})); + const modelSelection = { + instanceId: ProviderInstanceId.make(morph ? "morph" : "codex"), + model, + }; const results: Array<(typeof Results.Type)[number]> = []; const record = ( id: string, @@ -71,7 +179,7 @@ await Effect.runPromise( for (let sample = 0; sample < samples; sample++) { const { statements } = yield* generation.generateConversationSummary({ cwd, - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, + modelSelection, messages: fixture.summaries.map((text, index) => ({ ref: `M${index + 1}`, role: "summary" as const, @@ -85,17 +193,31 @@ await Effect.runPromise( for (let sample = 0; sample < samples; sample++) { const { statements } = yield* generation.generateConversationSummary({ cwd, - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, - messages: fixture.messages.map((message, index) => { - const ref = `M${index + 1}`; - return message.role === "peer" - ? { ref, role: "peer" as const, speaker: message.speaker, text: message.text } - : { ref, role: message.role, text: message.text }; - }), + modelSelection, + messages: fixture.messages.map(asArm), }); record(fixture.id, sample, statements, gradeLeaf(fixture, statements)); } } + for (const fixture of selectedKnowledge) { + for (let sample = 0; sample < samples; sample++) { + const { candidates } = yield* generation.generateKnowledgeCandidates({ + cwd, + runOutcome: "completed", + modelSelection, + messages: fixture.messages.map(asArm), + }); + record( + fixture.id, + sample, + candidates.map((candidate) => ({ + text: `${candidate.kind}: ${candidate.content}`, + citations: candidate.citations, + })), + gradeKnowledge(fixture, candidates), + ); + } + } yield* fs.makeDirectory(outputDirectory, { recursive: true }); yield* fs.writeFileString( path.join(outputDirectory, "results.json"), @@ -103,12 +225,12 @@ await Effect.runPromise( ); if (baseline !== undefined) yield* fs.writeFileString(path.join(outputDirectory, "baseline.json"), baseline); - for (const fixture of [...selectedCondensed, ...selectedLeaf]) { + for (const fixture of [...selectedCondensed, ...selectedLeaf, ...selectedKnowledge]) { const rows = results.filter((row) => row.id === fixture.id); const passed = rows.filter((row) => row.passed).length; // A case fails when half or more of its samples fail. yield* Effect.log( - `${fixture.id} (${fixture.kind}): ${passed}/${rows.length} samples passed, ${passed * 2 > rows.length ? "PASS" : "FAIL"}`, + `${arm} ${fixture.id} (${fixture.kind}): ${passed}/${rows.length} samples passed, ${passed * 2 > rows.length ? "PASS" : "FAIL"}`, ); } yield* Effect.log(`Results in ${outputDirectory}`); diff --git a/evals/shared/proxy.ts b/evals/shared/proxy.ts index ede72be8fdab2..fb4f123a2ad4e 100644 --- a/evals/shared/proxy.ts +++ b/evals/shared/proxy.ts @@ -31,3 +31,33 @@ print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h})) ), ), ); + +/** + * Morph's free OpenAI-compatible API, for evals that should not spend on paid models. The key is + * `MORPH_API_KEY`, else the `morph` provider in OpenCode's config (`$XDG_CONFIG_HOME` or `~/.config`). + */ +export const morphConfig = () => + decodeProxyConfig( + JSON.parse( + NodeChildProcess.execFileSync( + "python3", + [ + "-c", + ` +import json, os, pathlib +key = os.environ.get('MORPH_API_KEY') +url = os.environ.get('MORPH_BASE_URL', 'https://api.morphllm.com/v1') +if not key: + home = pathlib.Path(os.environ.get('XDG_CONFIG_HOME') or pathlib.Path.home() / '.config') + # OpenCode writes literal control characters inside strings, which strict parsing rejects. + settings = json.loads((home / 'opencode' / 'opencode.json').read_text(), strict=False)['providers']['morph']['settings'] + key, url = settings.get('apiKey'), settings.get('baseURL', url) +if not key: + raise SystemExit('no morph key') +print(json.dumps({'url': url.rstrip('/'), 'headers': {'Authorization': 'Bearer ' + key}})) +`, + ], + { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }, + ), + ), + ); From 7983b5e347c186e607a108c2533009f2b9d4cdd7 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 08:59:59 -0800 Subject: [PATCH 17/27] test(evals): grade every attribution row through the full leaf grade The helper kept only mustNot failures, so a row the attributed rule failed looked green, and the assistant phrasing production wrote was never tried. Co-Authored-By: Claude Opus 5.5 --- evals/conversation-summaries/run.test.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index 8206b1c3a7147..cbe88537b457e 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -5,11 +5,12 @@ import { gradeCondensed, gradeKnowledge, gradeLeaf } from "./grade.ts"; const [reversal, control] = condensedCases; const [peerLeaf, ordinaryLeaf] = leafCases; const [peerKnowledge, conventionKnowledge] = knowledgeCases; -/** The grader's misattribution failures for one statement, ignoring what it leaves out. */ -const misattributions = (text: string) => - gradeLeaf(peerLeaf!, [{ text, citations: ["M2"] }]).filter((failure) => - peerLeaf!.mustNot.some((pattern) => failure.startsWith(`${pattern}: `)), - ); +/** The full leaf grade of one statement beside a sibling that credits Astra, which passes alone. */ +const gradeBesideAstra = (text: string) => + gradeLeaf(peerLeaf!, [ + { text: "Astra proposed Postgres for sessions.", citations: ["M2"] }, + { text, citations: ["M2"] }, + ]); it("passes a roll-up that keeps the reversal, the attribution and the open item", () => { expect( @@ -71,8 +72,10 @@ it.each([ "The user is still deciding between Redis and Postgres.", "The user never agreed to Postgres.", "The agent rejected the proposal to use Postgres.", + "The user decided to wait before choosing Postgres or Redis.", + "The agent suggested keeping Redis rather than Postgres.", ])("leaves an open choice open: %s", (text) => { - expect(misattributions(text)).toEqual([]); + expect(gradeBesideAstra(text)).toEqual([]); }); it.each([ @@ -84,8 +87,15 @@ it.each([ "The user approved Postgres.", "Sessions will move to Postgres, per the user.", "The agent proposed moving sessions to Postgres; Astra wants to keep Redis.", + "The user is going with Postgres.", + "The user wants Postgres.", + "The user's choice: Postgres for sessions.", + "Per the user, sessions move to Postgres.", + "The user later agreed and sessions moved to Postgres.", + "The assistant answered that sessions should move to Postgres.", + "The assistant recommended Postgres for sessions.", ])("fails a statement that hands the proposal to the user or the agent: %s", (text) => { - expect(misattributions(text)).not.toEqual([]); + expect(gradeBesideAstra(text)).not.toEqual([]); }); it("does not treat an open Postgres choice as the peer's proposal", () => { From 3e2208a59a943c9cf282d43774f267464301e9c4 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 09:00:24 -0800 Subject: [PATCH 18/27] fix(evals): count the assistant as the agent and credit no one for a bare proposal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Production wrote "The assistant answered…" for the peer's words, and the grader only knew user and agent. A proposal noun with no subject no longer needs Astra, and words that keep a choice open stop a match. Co-Authored-By: Claude Opus 5.5 --- evals/conversation-summaries/cases.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts index a801d9e7a478e..a67df8e56905e 100644 --- a/evals/conversation-summaries/cases.ts +++ b/evals/conversation-summaries/cases.ts @@ -20,14 +20,23 @@ export interface LeafCase { readonly mustNot: ReadonlyArray; } -/** Statements that hand the peer's Postgres proposal to the user or to the thread's agent. */ +/** Words that keep a choice open or point away from Postgres before it is named. */ +const open = String.raw`(?:not|never|against|between|whether|if|or|wait|waiting|before|keep|keeping|rather than|instead of)`; +/** `target` within the clause, with no `open` word before it. */ +const toward = (target: string) => String.raw`(?:(?!\b${open}\b)[^.;]){0,60}\b${target}\b`; + +/** + * Statements that hand the peer's Postgres proposal to the user or to the thread's agent, whom the + * summarizer sees as `assistant`. Regexes, so they miss paraphrase; read the statements too. + */ const misattributed = [ - String.raw`\buser (decided|chose|wants|wanted|asked) to (drop Redis|use Postgres|keep Redis)`, - String.raw`\buser's decision to (drop Redis|use Postgres|keep Redis)`, - // The verb must follow the user directly, so "has yet to decide" and "never agreed" stay open. - String.raw`\buser\s+(?:(?:has|had|then|also|finally|ultimately|eventually|now)\s+)*(?:decided|chose|chosen|picked|selected|opted|went with|goes with|settled on|agreed|accepted|approved|adopted|endorsed|signed off)\b(?:(?!\b(?:not|never|against|between|whether)\b)[^.;]){0,60}\b(?:Postgres|Astra|proposal|suggestion)\b`, + String.raw`\buser asked to (?:drop Redis|use Postgres|keep Redis)`, + String.raw`\buser\s+(?:(?:is|has|had|then|also|later|finally|ultimately|eventually|now)\s+)*(?:decided|chose|chosen|picked|selected|opted|wants|wanted|going with|went with|goes with|settled on|agreed|accepted|approved|adopted|endorsed|signed off)\b${toward("(?:Postgres|Astra|proposal|suggestion)")}`, + String.raw`\buser's (?:decision|choice|pick|preference)\b${toward("Postgres")}`, + String.raw`\b(?:per|according to) the user\b${toward("Postgres")}`, String.raw`\bPostgres\b[^.;]{0,60}(?:\b(?:per|according to|as (?:decided|requested|chosen|approved) by)\s+the user\b|\bat the user's (?:request|direction)\b)`, - String.raw`\bagent\s+(?:(?:also|first|then|initially|had|has)\s+)*(?:propos(?:ed|es)|suggest(?:ed|s)|recommend(?:ed|s)|push(?:ed|es) for)\b(?:(?!\b(?:not|never|against|keep|keeping)\b)[^.;]){0,60}\bPostgres\b|\bagent's (?:proposal|suggestion|recommendation)\b[^.;]{0,40}\bPostgres\b`, + String.raw`\b(?:agent|assistant)\s+(?:(?:also|first|then|initially|had|has)\s+)*(?:propos(?:ed|es)|suggest(?:ed|s)|recommend(?:ed|s)|push(?:ed|es) for|answered|said|replied|argued|wants|wanted)\b${toward("Postgres")}`, + String.raw`\b(?:agent|assistant)'s (?:proposal|suggestion|recommendation)\b${toward("Postgres")}`, ]; /** The group exchange both peer cases send: the user asks, Astra proposes, the agent disagrees. */ @@ -56,7 +65,8 @@ export const leafCases: ReadonlyArray = [ mustMention: ["Astra", "Postgres"], attributed: [ { - when: "(?:[Pp]ropos|[Ss]uggest)\\w*[^.]{0,80}Postgres|Postgres[^.]{0,80}(?:[Pp]ropos|[Ss]uggest)\\w*", + // A verb, not "the proposal", so a statement that credits no one stays open. + when: `(?:propos|suggest|recommend)(?:ed|es|s)\\b${toward("Postgres")}|Postgres\\b[^.]{0,80}\\b(?:propos|suggest|recommend)ed\\b`, require: "Astra", }, ], From 55788755bd5c71dd9788dede418fe81c2d9fa19a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 09:01:38 -0800 Subject: [PATCH 19/27] fix(evals): the knowledge case tempts a decision the user never made The user asked and hedged, so every arm returned nothing. Now Astra proposes Postgres and the agent agrees and starts the migration while the user never accepts. The peer-as-user arm skips knowledge, which never rendered peers so. Co-Authored-By: Claude Opus 5.5 --- evals/conversation-summaries/README.md | 4 ++-- evals/conversation-summaries/cases.ts | 26 ++++++++++++++++-------- evals/conversation-summaries/run.test.ts | 15 ++++++++------ evals/conversation-summaries/run.ts | 19 +++++++++-------- 4 files changed, 38 insertions(+), 26 deletions(-) diff --git a/evals/conversation-summaries/README.md b/evals/conversation-summaries/README.md index 15c07b200aed1..e9158df9afd28 100644 --- a/evals/conversation-summaries/README.md +++ b/evals/conversation-summaries/README.md @@ -13,7 +13,7 @@ pnpm conversation-summaries --model morph-kimik31 --arm full --samples 8 --out r `--arm` sets how a peer reply reaches the model, so the arms compare from one checkout: - `main` sends it as a nameless assistant message with no peer rule, as `main` does. Its leaf case fails by construction, because the name the grader wants is not in the input. -- `peer-as-user` renders it as a historical user message with the speaker in its header and no peer rule. This was the first attempt on `t3/peer-reply-summary-attribution`. +- `peer-as-user` renders it as a historical user message with the speaker in its header and no peer rule, as handoff history renders a peer. It runs only the summary cases, since assisted learning never did this. - `no-rule` names the peer but drops the prompt's peer rule. - `full` is this checkout. It is the default and the only arm a `gpt-*` model can run, since the other arms edit the prompt. @@ -23,7 +23,7 @@ Cases: - `condensed-four-ordinary-sources` is the control: an ordinary docs task that must keep its open item and fit the same budget. - `leaf-peer-proposal-is-not-a-user-decision` passes when the summary names Astra as the one who proposed Postgres, and credits that proposal to neither the user nor the agent. - `leaf-ordinary-exchange-has-no-peer` is the leaf control: an ordinary docs task with no peer. -- `knowledge-peer-proposal-is-not-a-decision` passes when no `decision` candidate comes out of the same exchange, and no candidate states Postgres as settled. +- `knowledge-peer-proposal-is-not-a-decision` passes when no `decision` candidate comes out, and no candidate credits the user with Postgres, of an exchange where Astra proposes Postgres and the agent agrees and starts the migration but the user never accepts. - `knowledge-user-convention-is-kept` is its control: a plain user instruction must still become a fact. - `--case ` limits the run, and `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result. diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts index a67df8e56905e..ffe03e8523395 100644 --- a/evals/conversation-summaries/cases.ts +++ b/evals/conversation-summaries/cases.ts @@ -39,7 +39,7 @@ const misattributed = [ String.raw`\b(?:agent|assistant)'s (?:proposal|suggestion|recommendation)\b${toward("Postgres")}`, ]; -/** The group exchange both peer cases send: the user asks, Astra proposes, the agent disagrees. */ +/** The leaf exchange: the user asks, Astra proposes, the agent disagrees. */ const peerProposal: ReadonlyArray = [ { role: "user", text: "Where should sessions live? I have not decided." }, { @@ -54,7 +54,7 @@ const peerProposal: ReadonlyArray = [ ]; const peerProposalSource = - 'Group threads (t3/peer-reply-summary-attribution): a seat model\'s published reply reached the summarizer as a plain assistant message with no name, and production summaries said "The assistant answered" for words the peer spoke.'; + 'Group threads (ScriptedAlchemy/t3code#131): a seat model\'s published reply reached the summarizer as a plain assistant message with no name, and production summaries said "The assistant answered" for words the peer spoke.'; export const leafCases: ReadonlyArray = [ { @@ -107,15 +107,23 @@ export const knowledgeCases: ReadonlyArray = [ { id: "knowledge-peer-proposal-is-not-a-decision", kind: "bad", - source: `${peerProposalSource} Assisted learning reads the same messages, so a peer proposal could be saved as the user's decision.`, - messages: peerProposal, + source: `${peerProposalSource} Assisted learning reads the same messages, so a peer proposal the agent acted on could be saved as the user's decision.`, + // The user never accepts, but the agent agrees and acts, which lures a decision. + messages: [ + { role: "user", text: "Where should sessions live?" }, + { + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: "Drop Redis and use Postgres for sessions.", + }, + { + role: "assistant", + text: "Agreed, Postgres it is. I started the migration that moves sessions from Redis to Postgres.", + }, + ], forbiddenKinds: ["decision"], mustMention: [], - mustNot: [ - ...misattributed, - String.raw`\bsessions (?:are|will be|should be)? ?(?:stored|kept|live|living|moved?|moving) (?:in|to) Postgres\b`, - String.raw`\b(?:use|uses|using) Postgres (?:for|as the) sessions?\b`, - ], + mustNot: misattributed, }, { id: "knowledge-user-convention-is-kept", diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index cbe88537b457e..117a1a0fd482a 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -121,13 +121,16 @@ it("passes an ordinary leaf with no peer", () => { ).toEqual([]); }); -it("fails a fact candidate that saves the peer's proposal as a decision", () => { +it("fails a fact candidate that saves the peer's proposal as the user's decision", () => { const content = "Sessions are stored in Postgres instead of Redis."; - const failures = gradeKnowledge(peerKnowledge!, [ - { kind: "decision", content, citations: ["M2"] }, - ]); - expect(failures[0]).toBe(`decision: ${content}`); - expect(failures.length).toBeGreaterThan(1); + expect( + gradeKnowledge(peerKnowledge!, [{ kind: "decision", content, citations: ["M2"] }]), + ).toEqual([`decision: ${content}`]); + expect( + gradeKnowledge(peerKnowledge!, [ + { kind: "convention", content: "The user chose Postgres for sessions.", citations: ["M2"] }, + ]), + ).not.toEqual([]); expect( gradeKnowledge(peerKnowledge!, [ { kind: "convention", content: "Session storage is undecided.", citations: ["M1"] }, diff --git a/evals/conversation-summaries/run.ts b/evals/conversation-summaries/run.ts index 527e9e4d802fb..24454fa4f50cb 100644 --- a/evals/conversation-summaries/run.ts +++ b/evals/conversation-summaries/run.ts @@ -18,8 +18,9 @@ import { gradeCondensed, gradeKnowledge, gradeLeaf } from "./grade.ts"; /** * How a peer reply reaches the model. `main` sends it as a nameless assistant message, as main - * does. `peer-as-user` renders it as a historical user message, as b71f68c2d3 did. `no-rule` names - * the peer without the prompt's peer rule. `full` is this checkout. + * does. `peer-as-user` renders it as a historical user message with the speaker in its header, as + * handoff history does; summaries only. `no-rule` names the peer without the prompt's peer rule. + * `full` is this checkout. */ const arms = ["main", "peer-as-user", "no-rule", "full"] as const; @@ -48,7 +49,8 @@ const selected = (fixtures: ReadonlyArray) fixtures.filter((fixture) => selectedIds === undefined || selectedIds.includes(fixture.id)); const selectedCondensed = selected(condensedCases); const selectedLeaf = selected(leafCases); -const selectedKnowledge = selected(knowledgeCases); +// Assisted learning never rendered a peer as a user, so that arm has no knowledge baseline. +const selectedKnowledge = arm === "peer-as-user" ? [] : selected(knowledgeCases); if (selectedCondensed.length + selectedLeaf.length + selectedKnowledge.length === 0) throw new Error( `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases, ...knowledgeCases].map((fixture) => fixture.id).join(", ")}`, @@ -84,12 +86,11 @@ const decodeMorphReply = Schema.decodeUnknownEffect( const MORPH_ATTEMPTS = 8; const PEER_RULE = "- a peer is another model"; -const withoutPeerRule = (prompt: string) => { - const lines = prompt.split("\n"); - const kept = lines.filter((line) => !line.startsWith(PEER_RULE)); - if (kept.length === lines.length) throw new Error("The prompt has no peer rule to drop."); - return kept.join("\n"); -}; +const withoutPeerRule = (prompt: string) => + prompt + .split("\n") + .filter((line) => !line.startsWith(PEER_RULE)) + .join("\n"); /** Morph's free Responses API, given the production prompt as OpenCode sends it: text only. */ const morphRunner = (): TextGenerationOperations.Runner => { From 43fb07c24d3b11bac7062d0252a7a16f4d8591b7 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 09:04:39 -0800 Subject: [PATCH 20/27] fix(web,mobile): a knowledge source names the peer who spoke it Both views printed the raw role, so a peer source read "assistant". They now use the author label the summary views use. Co-Authored-By: Claude Opus 5.5 --- .../components/ProjectKnowledgeFactDetail.tsx | 3 ++- .../ProjectMemoryInspector.tsx | 4 +++- .../src/conversationSummaries/index.ts | 18 ++++++++++++------ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx b/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx index 76fb48a56374e..93b36e449b2b2 100644 --- a/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx +++ b/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx @@ -14,6 +14,7 @@ import type { ProjectKnowledgeStatus, ThreadId, } from "@t3tools/contracts"; +import { messageAuthorLabel } from "@t3tools/client-runtime/conversationSummaries"; import { KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL, isSupersededFact, @@ -307,7 +308,7 @@ export function ProjectKnowledgeSourceInspector(props: { {source?.state === "available" ? ( <> - {source.title} · {source.role} · {source.createdAt} + {source.title} · {messageAuthorLabel(source.role, source.speaker)} · {source.createdAt} {source.archived ? " · archived" : ""} {source.text} diff --git a/apps/web/src/components/projectKnowledge/ProjectMemoryInspector.tsx b/apps/web/src/components/projectKnowledge/ProjectMemoryInspector.tsx index 0d79b02046e39..dcbeefbef41bc 100644 --- a/apps/web/src/components/projectKnowledge/ProjectMemoryInspector.tsx +++ b/apps/web/src/components/projectKnowledge/ProjectMemoryInspector.tsx @@ -8,6 +8,7 @@ import type { ProjectKnowledgeSearchResult, ProjectKnowledgeSource, } from "@t3tools/contracts"; +import { messageAuthorLabel } from "@t3tools/client-runtime/conversationSummaries"; import { KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL, isSupersededFact, @@ -313,7 +314,8 @@ export function SourceInspector(props: { ) : data?.state === "available" ? ( <>

- {data.title} · {data.role} · {dateFormatter.format(new Date(data.createdAt))} + {data.title} · {messageAuthorLabel(data.role, data.speaker)} ·{" "} + {dateFormatter.format(new Date(data.createdAt))} {data.archived ? " · archived" : ""}

diff --git a/packages/client-runtime/src/conversationSummaries/index.ts b/packages/client-runtime/src/conversationSummaries/index.ts
index 4212d1179903b..430ed8c2a8488 100644
--- a/packages/client-runtime/src/conversationSummaries/index.ts
+++ b/packages/client-runtime/src/conversationSummaries/index.ts
@@ -49,6 +49,17 @@ export interface ConversationSummarySourceCursor {
   readonly textOffset: number;
 }
 
+/** Who wrote a message: the user, the thread's agent, or the peer seat that spoke it. */
+export function messageAuthorLabel(
+  role: "user" | "assistant",
+  speaker?: { readonly label: string; readonly model: string },
+): string {
+  if (role === "user") return "User";
+  if (speaker === undefined) return "Assistant";
+  // A seat without a label is named by its model.
+  return speaker.label === speaker.model ? speaker.label : `${speaker.label} (${speaker.model})`;
+}
+
 /** Who a source came from; a child summary is named by its id so it can be opened. */
 export function conversationSummarySourceLabel(
   ref: ConversationSummarySourceRef,
@@ -57,13 +68,8 @@ export function conversationSummarySourceLabel(
   if (result.state !== "available") return "Unavailable";
   switch (result.role) {
     case "user":
-      return "User";
     case "assistant":
-      if (result.speaker === undefined) return "Assistant";
-      // A seat without a label is named by its model.
-      return result.speaker.label === result.speaker.model
-        ? result.speaker.label
-        : `${result.speaker.label} (${result.speaker.model})`;
+      return messageAuthorLabel(result.role, result.speaker);
     case "tool":
       return "Tool";
     case "summary":

From 56c450e48aea1ea61bdc66ce741f78c4064c32c3 Mon Sep 17 00:00:00 2001
From: ScriptedAlchemy 
Date: Mon, 16 Nov 2026 09:06:47 -0800
Subject: [PATCH 21/27] test(server): a seat and the replies it published are
 one source

A seat's own thread and its published reply in the parent corroborated each
other, so the peer's words were saved as a convention.

Co-Authored-By: Claude Opus 5.5 
---
 .../knowledge/AssistedLearning.test.ts        | 40 +++++++++++++++----
 1 file changed, 33 insertions(+), 7 deletions(-)

diff --git a/apps/server/src/project/knowledge/AssistedLearning.test.ts b/apps/server/src/project/knowledge/AssistedLearning.test.ts
index bf4a1689f544c..28ca8a60bd46c 100644
--- a/apps/server/src/project/knowledge/AssistedLearning.test.ts
+++ b/apps/server/src/project/knowledge/AssistedLearning.test.ts
@@ -375,7 +375,7 @@ it.effect("sends a peer reply as that peer, not as the assistant", () => {
 });
 
 it.effect(
-  "saves no decision the user never cited, even when a seat's own thread repeats it",
+  "saves no peer words the user never cited, though the seat's own thread repeats them",
   () => {
     const decision = {
       kind: "decision" as const,
@@ -434,8 +434,38 @@ it.effect(
             creationSource: "provider",
           },
         });
-        if (replyThreadId === threadId)
+        if (replyThreadId === threadId) {
+          yield* projections.apply({
+            id: EventId.make(`run:${id}`),
+            type: "run.created",
+            threadId,
+            providerInstanceId,
+            occurredAt: at,
+            payload: {
+              id: replyRunId,
+              threadId,
+              ordinal: 2,
+              providerInstanceId,
+              modelSelection: { instanceId: providerInstanceId, model: "gpt-6-astra" },
+              providerThreadId: null,
+              userMessageId: MessageId.make(id),
+              rootNodeId: null,
+              activeAttemptId: null,
+              status: "completed",
+              requestedAt: at,
+              startedAt: at,
+              completedAt: at,
+              checkpointId: null,
+              contextHandoffId: null,
+              publication: {
+                type: "peer_reply",
+                seatThreadId: seatId,
+                seatRunId: RunId.make("peer-seat-run"),
+              },
+            },
+          });
           yield* speakAsPeer({ threadId, runId: replyRunId, messageId: id, text });
+        }
         yield* runner.enqueueRun({
           threadId: replyThreadId,
           runId: replyRunId,
@@ -444,13 +474,9 @@ it.effect(
       }
       yield* TestClock.adjust("31 minutes");
       yield* runner.drainDue;
-      assert.equal(model.calls.length, 1);
       const knowledge = yield* ProjectKnowledge.ProjectKnowledge;
       const { facts } = yield* knowledge.list({ projectId, status: "saved" });
-      assert.deepEqual(
-        facts.map((fact) => fact.kind),
-        ["convention"],
-      );
+      assert.deepEqual(facts, []);
     }).pipe(Effect.provide(makeLayer(model.generate)));
   },
 );

From 44796d11547ff50b2e56eac19aa29dd2f1502dac Mon Sep 17 00:00:00 2001
From: ScriptedAlchemy 
Date: Mon, 16 Nov 2026 09:08:09 -0800
Subject: [PATCH 22/27] fix(server): a seat and the replies it published are
 one source

Assisted learning counted a peer's published reply in the parent and the
seat's own thread as two threads, so one speaker corroborated itself. The
publication run names its seat thread; both gates now count by it.

Co-Authored-By: Claude Opus 5.5 
---
 .../src/project/knowledge/AssistedLearning.ts  | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/apps/server/src/project/knowledge/AssistedLearning.ts b/apps/server/src/project/knowledge/AssistedLearning.ts
index af33e2eb524e2..db1bbdc617686 100644
--- a/apps/server/src/project/knowledge/AssistedLearning.ts
+++ b/apps/server/src/project/knowledge/AssistedLearning.ts
@@ -134,10 +134,15 @@ const make = Effect.gen(function* () {
       if (!settings.enableAssistedLearning)
         return yield* finish("skipped", "Automatic memory is off for this project.");
       const evidence = [];
+      // A seat's reply published into its parent and the seat's own thread are one speaker.
+      const speakerThreads = new Map();
       for (const entry of batch) {
         if (yield* knowledge.hasAssistedRun(projectId, entry.runId)) continue;
         const source = yield* projections
-          .getThreadRecords(entry.threadId, ["messages"], { messageRunIds: [entry.runId] })
+          .getThreadRecords(entry.threadId, ["messages", "runs"], {
+            messageRunIds: [entry.runId],
+            runIds: [entry.runId],
+          })
           .pipe(
             Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
           );
@@ -150,6 +155,11 @@ const make = Effect.gen(function* () {
           skippedRuns.add(entry.runId);
           continue;
         }
+        const publication = source.runs[0]?.publication;
+        speakerThreads.set(
+          entry.runId,
+          publication?.type === "peer_reply" ? publication.seatThreadId : entry.threadId,
+        );
         evidence.push(
           ...source.messages.filter(
             (message) =>
@@ -175,7 +185,8 @@ const make = Effect.gen(function* () {
       if (
         !userEvidence &&
         (new Set(completedEvidence.map((message) => message.runId)).size < 2 ||
-          new Set(completedEvidence.map((message) => message.threadId)).size < 2 ||
+          new Set(completedEvidence.map((message) => speakerThreads.get(message.runId!))).size <
+            2 ||
           new Set(completedEvidence.map((message) => message.text.trim().toLowerCase())).size < 2)
       )
         return yield* finish(
@@ -295,7 +306,8 @@ const make = Effect.gen(function* () {
             const corroborated =
               citedMessages.every((message) => message.runOutcome === "completed") &&
               new Set(citedMessages.map((message) => message.runId)).size >= 2 &&
-              new Set(citedMessages.map((message) => message.threadId)).size >= 2 &&
+              new Set(citedMessages.map((message) => speakerThreads.get(message.runId))).size >=
+                2 &&
               new Set(citedMessages.map((message) => message.text.trim().toLowerCase())).size >= 2;
             const userSupported = (candidate?.citations ?? []).some((ref) =>
               userRefs.has(ref.trim()),

From fd1af49a22805d60c079bc5b94960471bb2a44f0 Mon Sep 17 00:00:00 2001
From: ScriptedAlchemy 
Date: Mon, 16 Nov 2026 09:09:26 -0800
Subject: [PATCH 23/27] test(provider-core): a prompt without a peer must not
 carry the peer rule

Co-Authored-By: Claude Opus 5.5 
---
 .../src/server/textGenerationPrompts.test.ts  | 40 ++++++++++++++++++-
 1 file changed, 39 insertions(+), 1 deletion(-)

diff --git a/packages/provider-core/src/server/textGenerationPrompts.test.ts b/packages/provider-core/src/server/textGenerationPrompts.test.ts
index cbc19e876bf75..2d6e9e27828d1 100644
--- a/packages/provider-core/src/server/textGenerationPrompts.test.ts
+++ b/packages/provider-core/src/server/textGenerationPrompts.test.ts
@@ -1,6 +1,10 @@
 import { describe, expect, it } from "vite-plus/test";
 
-import { buildKnowledgeCandidatesPrompt, buildThreadTitlePrompt } from "./textGenerationPrompts.ts";
+import {
+  buildConversationSummaryPrompt,
+  buildKnowledgeCandidatesPrompt,
+  buildThreadTitlePrompt,
+} from "./textGenerationPrompts.ts";
 import { normalizeCliError } from "./textGenerationUtils.ts";
 
 describe("normalizeCliError", () => {
@@ -43,6 +47,40 @@ it("preserves each run boundary and terminal outcome in family review prompts",
   expect(prompt).toContain("[M2] assistant (T2/R2, completed):\nChecked compatibility.");
 });
 
+const noPeer = [
+  { ref: "M1", role: "user", text: "Where should sessions live?" },
+  { ref: "M2", role: "assistant", text: "Keep Redis." },
+] as const;
+const withPeer = [
+  ...noPeer,
+  {
+    ref: "M3",
+    role: "peer",
+    speaker: { label: "Astra", model: "gpt-6-astra" },
+    text: "Use Postgres.",
+  },
+] as const;
+
+it.each([
+  [
+    "summary",
+    (messages: typeof withPeer | typeof noPeer) =>
+      buildConversationSummaryPrompt({ messages }).prompt,
+  ],
+  [
+    "knowledge",
+    (messages: typeof withPeer | typeof noPeer) =>
+      buildKnowledgeCandidatesPrompt({ runOutcome: "completed", messages }).prompt,
+  ],
+])("adds the %s peer rule only when a peer spoke", (_, build) => {
+  const rules = (prompt: string) =>
+    prompt.slice(0, prompt.search(/\n(?:Sources|Messages):/)).split("\n");
+  const withoutPeer = rules(build(noPeer));
+  const peerOnly = rules(build(withPeer)).filter((line) => !withoutPeer.includes(line));
+  expect(peerOnly).toHaveLength(1);
+  expect(rules(build(withPeer)).filter((line) => line !== peerOnly[0])).toEqual(withoutPeer);
+});
+
 describe("buildThreadTitlePrompt", () => {
   it("names the project to leave out of initial and regenerated titles", () => {
     for (const previousTitle of [undefined, "Hyperdrive Config Crash"]) {

From 22af8dd2248680738dd29bc311d3be816f82db35 Mon Sep 17 00:00:00 2001
From: ScriptedAlchemy 
Date: Mon, 16 Nov 2026 09:09:45 -0800
Subject: [PATCH 24/27] fix(provider-core): prompts without a peer match main
 byte for byte

The peer rules now appear only when a peer message is in the input.

Co-Authored-By: Claude Opus 5.5 
---
 .../src/server/textGenerationPrompts.ts              | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts
index bcf7fc4cbea5c..7c7fab092bb5e 100644
--- a/packages/provider-core/src/server/textGenerationPrompts.ts
+++ b/packages/provider-core/src/server/textGenerationPrompts.ts
@@ -544,7 +544,11 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI
     "Rules:",
     "- kind is one of decision, constraint, convention",
     "- only extract decisions the user made or accepted, constraints the project must respect, or conventions the code follows",
-    "- a peer is another model in the conversation; its proposals are not the user's decisions unless the user accepted them",
+    ...(input.messages.some((message) => message.role === "peer")
+      ? [
+          "- a peer is another model in the conversation; its proposals are not the user's decisions unless the user accepted them",
+        ]
+      : []),
     "- do not summarize the work, restate the task, or record transient status, plans, or guesses",
     "- content is one or two plain sentences that stand alone without this conversation",
     "- entities lists up to 5 short names of files, modules, tools, or concepts the knowledge is about",
@@ -606,7 +610,11 @@ export function buildConversationSummaryPrompt(input: ConversationSummaryPromptI
     "- each text is one or two plain sentences, at most 600 characters",
     "- keep what the user asked for, decisions made, constraints, what was done and verified, and what was left open",
     "- say who said what; do not present an agent's claim or plan as a verified outcome",
-    "- a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent",
+    ...(input.messages.some((message) => message.role === "peer")
+      ? [
+          "- a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent",
+        ]
+      : []),
     "- citations lists the refs (like M1) of the sources that support the statement; never invent a ref",
     "- sources may be exact ranges of long messages or tool evidence; do not infer omitted ranges",
     "- preserve observed command results, failures and checks, distinguishing tool evidence from an agent claiming success",

From dba8c78192fb42112952c5707657c650808d1192 Mon Sep 17 00:00:00 2001
From: ScriptedAlchemy 
Date: Mon, 16 Nov 2026 09:27:11 -0800
Subject: [PATCH 25/27] fix(provider-core): drop the peer prompt rules the eval
 did not support

On morph-kimik31, naming the peer was enough: the leaf peer case passed 8/8
without the summary rule, and the knowledge case passed 8/8 on main and
without the knowledge rule. With no rule left, prompts without a peer match
main and the conditional and its test go too.

Co-Authored-By: Claude Opus 5.5 
---
 .../src/server/textGenerationPrompts.test.ts  | 40 +------------------
 .../src/server/textGenerationPrompts.ts       | 10 -----
 2 files changed, 1 insertion(+), 49 deletions(-)

diff --git a/packages/provider-core/src/server/textGenerationPrompts.test.ts b/packages/provider-core/src/server/textGenerationPrompts.test.ts
index 2d6e9e27828d1..cbc19e876bf75 100644
--- a/packages/provider-core/src/server/textGenerationPrompts.test.ts
+++ b/packages/provider-core/src/server/textGenerationPrompts.test.ts
@@ -1,10 +1,6 @@
 import { describe, expect, it } from "vite-plus/test";
 
-import {
-  buildConversationSummaryPrompt,
-  buildKnowledgeCandidatesPrompt,
-  buildThreadTitlePrompt,
-} from "./textGenerationPrompts.ts";
+import { buildKnowledgeCandidatesPrompt, buildThreadTitlePrompt } from "./textGenerationPrompts.ts";
 import { normalizeCliError } from "./textGenerationUtils.ts";
 
 describe("normalizeCliError", () => {
@@ -47,40 +43,6 @@ it("preserves each run boundary and terminal outcome in family review prompts",
   expect(prompt).toContain("[M2] assistant (T2/R2, completed):\nChecked compatibility.");
 });
 
-const noPeer = [
-  { ref: "M1", role: "user", text: "Where should sessions live?" },
-  { ref: "M2", role: "assistant", text: "Keep Redis." },
-] as const;
-const withPeer = [
-  ...noPeer,
-  {
-    ref: "M3",
-    role: "peer",
-    speaker: { label: "Astra", model: "gpt-6-astra" },
-    text: "Use Postgres.",
-  },
-] as const;
-
-it.each([
-  [
-    "summary",
-    (messages: typeof withPeer | typeof noPeer) =>
-      buildConversationSummaryPrompt({ messages }).prompt,
-  ],
-  [
-    "knowledge",
-    (messages: typeof withPeer | typeof noPeer) =>
-      buildKnowledgeCandidatesPrompt({ runOutcome: "completed", messages }).prompt,
-  ],
-])("adds the %s peer rule only when a peer spoke", (_, build) => {
-  const rules = (prompt: string) =>
-    prompt.slice(0, prompt.search(/\n(?:Sources|Messages):/)).split("\n");
-  const withoutPeer = rules(build(noPeer));
-  const peerOnly = rules(build(withPeer)).filter((line) => !withoutPeer.includes(line));
-  expect(peerOnly).toHaveLength(1);
-  expect(rules(build(withPeer)).filter((line) => line !== peerOnly[0])).toEqual(withoutPeer);
-});
-
 describe("buildThreadTitlePrompt", () => {
   it("names the project to leave out of initial and regenerated titles", () => {
     for (const previousTitle of [undefined, "Hyperdrive Config Crash"]) {
diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts
index 7c7fab092bb5e..fea15f7858dff 100644
--- a/packages/provider-core/src/server/textGenerationPrompts.ts
+++ b/packages/provider-core/src/server/textGenerationPrompts.ts
@@ -544,11 +544,6 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI
     "Rules:",
     "- kind is one of decision, constraint, convention",
     "- only extract decisions the user made or accepted, constraints the project must respect, or conventions the code follows",
-    ...(input.messages.some((message) => message.role === "peer")
-      ? [
-          "- a peer is another model in the conversation; its proposals are not the user's decisions unless the user accepted them",
-        ]
-      : []),
     "- do not summarize the work, restate the task, or record transient status, plans, or guesses",
     "- content is one or two plain sentences that stand alone without this conversation",
     "- entities lists up to 5 short names of files, modules, tools, or concepts the knowledge is about",
@@ -610,11 +605,6 @@ export function buildConversationSummaryPrompt(input: ConversationSummaryPromptI
     "- each text is one or two plain sentences, at most 600 characters",
     "- keep what the user asked for, decisions made, constraints, what was done and verified, and what was left open",
     "- say who said what; do not present an agent's claim or plan as a verified outcome",
-    ...(input.messages.some((message) => message.role === "peer")
-      ? [
-          "- a peer is another model in the conversation, so attribute its words to it by name, never to the user or the agent",
-        ]
-      : []),
     "- citations lists the refs (like M1) of the sources that support the statement; never invent a ref",
     "- sources may be exact ranges of long messages or tool evidence; do not infer omitted ranges",
     "- preserve observed command results, failures and checks, distinguishing tool evidence from an agent claiming success",

From bac95e82d41c8adb75fcf751a771c250a86ab26e Mon Sep 17 00:00:00 2001
From: ScriptedAlchemy 
Date: Mon, 16 Nov 2026 09:27:40 -0800
Subject: [PATCH 26/27] fix(evals): cut the knowledge cases and the no-rule arm

With the prompt rules gone, no-rule equals full, and a knowledge prompt
without a peer is main's, so neither knowledge case guards this change.

Co-Authored-By: Claude Opus 5.5 
---
 evals/README.md                          |  2 +-
 evals/conversation-summaries/README.md   | 13 +++---
 evals/conversation-summaries/cases.ts    | 51 ------------------------
 evals/conversation-summaries/grade.ts    | 27 +------------
 evals/conversation-summaries/run.test.ts | 31 +-------------
 evals/conversation-summaries/run.ts      | 50 +++++------------------
 6 files changed, 18 insertions(+), 156 deletions(-)

diff --git a/evals/README.md b/evals/README.md
index 3c88d57e89cf2..226e0c5a41af8 100644
--- a/evals/README.md
+++ b/evals/README.md
@@ -10,7 +10,7 @@ Write or run an eval when a change affects what a model sees or does: agent inst
 | [group-conversation](group-conversation/)         | Whether peers engage, preserve attribution, use PASS and handles, edit with the real side chat digest, and continue through delegation. Compares parallel and serial reactions. |
 | [thread-titles](thread-titles/)                   | Whether generated thread titles name the right subject.                                                                                                                         |
 | [pr-content](pr-content/)                         | Whether PR generation describes the diff when project instructions try to redirect it.                                                                                          |
-| [conversation-summaries](conversation-summaries/) | Whether summaries and learned facts credit a peer's proposal to the peer, and a roll-up keeps reversals, attribution and open items within its budget.                          |
+| [conversation-summaries](conversation-summaries/) | Whether summaries credit a peer's proposal to the peer, and a roll-up keeps reversals, attribution and open items within its budget.                                            |
 | [model-evaluations](model-evaluations/)           | Whether blind judges use outcome evidence, respect task scope, ignore injected scoring instructions, and abstain when evidence is missing.                                      |
 | [voice-cleanup](voice-cleanup/)                   | Whether optional dictation cleanup edits only the spoken text and preserves its meaning.                                                                                        |
 | [test-signal](test-signal/)                       | Whether a cheap model running the test-signal check flags low-signal tests.                                                                                                     |
diff --git a/evals/conversation-summaries/README.md b/evals/conversation-summaries/README.md
index e9158df9afd28..881401363d2f8 100644
--- a/evals/conversation-summaries/README.md
+++ b/evals/conversation-summaries/README.md
@@ -1,6 +1,6 @@
 # Conversation summaries
 
-Checks how background text generation reads a conversation, using the prompts from this checkout. A leaf summary covers one exchange, including a reply from another model in the thread. A roll-up condenses four adjacent summaries, as the summary pass does for long threads. A knowledge case sends the same exchange to assisted learning and grades the fact candidates it returns.
+Checks how background text generation reads a conversation, using the prompts from this checkout. A leaf summary covers one exchange, including a reply from another model in the thread. A roll-up condenses four adjacent summaries, as the summary pass does for long threads.
 
 The production summarizer is an OpenCode model. A `gpt-*` model calls the server's real Codex generator through the local Codex login. A `morph-*` model calls Morph's free API directly, using the production prompt builders and reply decoder. The key comes from `MORPH_API_KEY`, or else from the `morph` provider in `~/.config/opencode/opencode.json`.
 
@@ -12,10 +12,9 @@ pnpm conversation-summaries --model morph-kimik31 --arm full --samples 8 --out r
 
 `--arm` sets how a peer reply reaches the model, so the arms compare from one checkout:
 
-- `main` sends it as a nameless assistant message with no peer rule, as `main` does. Its leaf case fails by construction, because the name the grader wants is not in the input.
-- `peer-as-user` renders it as a historical user message with the speaker in its header and no peer rule, as handoff history renders a peer. It runs only the summary cases, since assisted learning never did this.
-- `no-rule` names the peer but drops the prompt's peer rule.
-- `full` is this checkout. It is the default and the only arm a `gpt-*` model can run, since the other arms edit the prompt.
+- `main` sends it as a nameless assistant message, as `main` does. Its leaf case fails by construction, because the name the grader wants is not in the input.
+- `peer-as-user` renders it as a historical user message with the speaker in its header, as handoff history renders a peer.
+- `full` is this checkout, where it carries the peer's name. It is the default.
 
 Cases:
 
@@ -23,13 +22,11 @@ Cases:
 - `condensed-four-ordinary-sources` is the control: an ordinary docs task that must keep its open item and fit the same budget.
 - `leaf-peer-proposal-is-not-a-user-decision` passes when the summary names Astra as the one who proposed Postgres, and credits that proposal to neither the user nor the agent.
 - `leaf-ordinary-exchange-has-no-peer` is the leaf control: an ordinary docs task with no peer.
-- `knowledge-peer-proposal-is-not-a-decision` passes when no `decision` candidate comes out, and no candidate credits the user with Postgres, of an exchange where Astra proposes Postgres and the agent agrees and starts the migration but the user never accepts.
-- `knowledge-user-convention-is-kept` is its control: a plain user instruction must still become a fact.
 - `--case ` limits the run, and `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result.
 
 ## Add a case
 
-Add a condensed entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. A leaf or knowledge entry has `messages` instead of `summaries`. `run.test.ts` tests the grader.
+Add a condensed entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. A leaf entry has `messages` instead of `summaries`. `run.test.ts` tests the grader.
 
 ## Cost
 
diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts
index ffe03e8523395..886bacc738b71 100644
--- a/evals/conversation-summaries/cases.ts
+++ b/evals/conversation-summaries/cases.ts
@@ -89,57 +89,6 @@ export const leafCases: ReadonlyArray = [
   },
 ];
 
-/** One finished exchange, as assisted learning sends it for fact candidates. */
-export interface KnowledgeCase {
-  readonly id: string;
-  readonly kind: "bad" | "control";
-  readonly source: string;
-  readonly messages: ReadonlyArray;
-  /** Candidate kinds that must not come out. */
-  readonly forbiddenKinds: ReadonlyArray<"decision" | "constraint" | "convention">;
-  /** Each regex must match some candidate. */
-  readonly mustMention: ReadonlyArray;
-  /** No candidate may match these. */
-  readonly mustNot: ReadonlyArray;
-}
-
-export const knowledgeCases: ReadonlyArray = [
-  {
-    id: "knowledge-peer-proposal-is-not-a-decision",
-    kind: "bad",
-    source: `${peerProposalSource} Assisted learning reads the same messages, so a peer proposal the agent acted on could be saved as the user's decision.`,
-    // The user never accepts, but the agent agrees and acts, which lures a decision.
-    messages: [
-      { role: "user", text: "Where should sessions live?" },
-      {
-        role: "peer",
-        speaker: { label: "Astra", model: "gpt-6-astra" },
-        text: "Drop Redis and use Postgres for sessions.",
-      },
-      {
-        role: "assistant",
-        text: "Agreed, Postgres it is. I started the migration that moves sessions from Redis to Postgres.",
-      },
-    ],
-    forbiddenKinds: ["decision"],
-    mustMention: [],
-    mustNot: misattributed,
-  },
-  {
-    id: "knowledge-user-convention-is-kept",
-    kind: "control",
-    source:
-      "Control for the peer rule: a plain user instruction must still become a fact, so the rule cannot suppress ordinary learning.",
-    messages: [
-      { role: "user", text: "From now on API responses use snake_case keys everywhere." },
-      { role: "assistant", text: "Done. I converted the handlers to snake_case keys." },
-    ],
-    forbiddenKinds: [],
-    mustMention: ["snake_case"],
-    mustNot: [],
-  },
-];
-
 /** A roll-up input: four adjacent child summaries, oldest first, as the summary pass sends them. */
 export interface CondensedCase {
   readonly id: string;
diff --git a/evals/conversation-summaries/grade.ts b/evals/conversation-summaries/grade.ts
index 155d611a40bc6..2fa438d578a9f 100644
--- a/evals/conversation-summaries/grade.ts
+++ b/evals/conversation-summaries/grade.ts
@@ -1,4 +1,4 @@
-import type { CondensedCase, KnowledgeCase, LeafCase } from "./cases.ts";
+import type { CondensedCase, LeafCase } from "./cases.ts";
 
 const MAX_CHARS = 1_200;
 
@@ -58,28 +58,3 @@ export function gradeLeaf(
     undefined,
   );
 }
-
-type Candidate = {
-  readonly kind: string;
-  readonly content: string;
-  readonly citations: ReadonlyArray;
-};
-
-/** Every way a fact-candidate reply breaks the case's rules; empty when it passes. */
-export function gradeKnowledge(
-  fixture: KnowledgeCase,
-  candidates: ReadonlyArray,
-): ReadonlyArray {
-  const failures: Array = [];
-  for (const candidate of candidates)
-    if ((fixture.forbiddenKinds as ReadonlyArray).includes(candidate.kind))
-      failures.push(`${candidate.kind}: ${candidate.content}`);
-  for (const pattern of fixture.mustMention)
-    if (!candidates.some((candidate) => new RegExp(pattern).test(candidate.content)))
-      failures.push(`missing ${pattern}`);
-  for (const pattern of fixture.mustNot)
-    for (const candidate of candidates)
-      if (new RegExp(pattern, "i").test(candidate.content))
-        failures.push(`${pattern}: ${candidate.content}`);
-  return failures;
-}
diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts
index 117a1a0fd482a..42f5de22734a5 100644
--- a/evals/conversation-summaries/run.test.ts
+++ b/evals/conversation-summaries/run.test.ts
@@ -1,10 +1,9 @@
 import { expect, it } from "vite-plus/test";
-import { condensedCases, knowledgeCases, leafCases } from "./cases.ts";
-import { gradeCondensed, gradeKnowledge, gradeLeaf } from "./grade.ts";
+import { condensedCases, leafCases } from "./cases.ts";
+import { gradeCondensed, gradeLeaf } from "./grade.ts";
 
 const [reversal, control] = condensedCases;
 const [peerLeaf, ordinaryLeaf] = leafCases;
-const [peerKnowledge, conventionKnowledge] = knowledgeCases;
 /** The full leaf grade of one statement beside a sibling that credits Astra, which passes alone. */
 const gradeBesideAstra = (text: string) =>
   gradeLeaf(peerLeaf!, [
@@ -121,32 +120,6 @@ it("passes an ordinary leaf with no peer", () => {
   ).toEqual([]);
 });
 
-it("fails a fact candidate that saves the peer's proposal as the user's decision", () => {
-  const content = "Sessions are stored in Postgres instead of Redis.";
-  expect(
-    gradeKnowledge(peerKnowledge!, [{ kind: "decision", content, citations: ["M2"] }]),
-  ).toEqual([`decision: ${content}`]);
-  expect(
-    gradeKnowledge(peerKnowledge!, [
-      { kind: "convention", content: "The user chose Postgres for sessions.", citations: ["M2"] },
-    ]),
-  ).not.toEqual([]);
-  expect(
-    gradeKnowledge(peerKnowledge!, [
-      { kind: "convention", content: "Session storage is undecided.", citations: ["M1"] },
-    ]),
-  ).toEqual([]);
-});
-
-it("requires the control's plain user convention", () => {
-  expect(gradeKnowledge(conventionKnowledge!, [])).toEqual(["missing snake_case"]);
-  expect(
-    gradeKnowledge(conventionKnowledge!, [
-      { kind: "convention", content: "API responses use snake_case keys.", citations: ["M1"] },
-    ]),
-  ).toEqual([]);
-});
-
 it("passes an ordinary roll-up in the control case", () => {
   expect(
     gradeCondensed(control!, [
diff --git a/evals/conversation-summaries/run.ts b/evals/conversation-summaries/run.ts
index 24454fa4f50cb..222a5e988c4be 100644
--- a/evals/conversation-summaries/run.ts
+++ b/evals/conversation-summaries/run.ts
@@ -13,16 +13,15 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
 import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts";
 import * as ServerConfig from "../../apps/server/src/config.ts";
 import { morphConfig } from "../shared/proxy.ts";
-import { condensedCases, knowledgeCases, leafCases, type LeafMessage } from "./cases.ts";
-import { gradeCondensed, gradeKnowledge, gradeLeaf } from "./grade.ts";
+import { condensedCases, leafCases, type LeafMessage } from "./cases.ts";
+import { gradeCondensed, gradeLeaf } from "./grade.ts";
 
 /**
  * How a peer reply reaches the model. `main` sends it as a nameless assistant message, as main
  * does. `peer-as-user` renders it as a historical user message with the speaker in its header, as
- * handoff history does; summaries only. `no-rule` names the peer without the prompt's peer rule.
- * `full` is this checkout.
+ * handoff history does. `full` is this checkout.
  */
-const arms = ["main", "peer-as-user", "no-rule", "full"] as const;
+const arms = ["main", "peer-as-user", "full"] as const;
 
 const { values } = NodeUtil.parseArgs({
   options: {
@@ -41,19 +40,14 @@ const samples = Number(values.samples);
 const arm = arms.find((candidate) => candidate === values.arm);
 if (arm === undefined) throw new Error(`Unknown --arm ${values.arm}. Use ${arms.join(", ")}.`);
 const morph = model.startsWith("morph-");
-const dropsPeerRule = arm === "main" || arm === "no-rule" || arm === "peer-as-user";
-if (dropsPeerRule && !morph)
-  throw new Error(`--arm ${arm} edits the prompt, which only a morph-* model route can do.`);
 const selectedIds = values.case?.split(",");
 const selected = (fixtures: ReadonlyArray) =>
   fixtures.filter((fixture) => selectedIds === undefined || selectedIds.includes(fixture.id));
 const selectedCondensed = selected(condensedCases);
 const selectedLeaf = selected(leafCases);
-// Assisted learning never rendered a peer as a user, so that arm has no knowledge baseline.
-const selectedKnowledge = arm === "peer-as-user" ? [] : selected(knowledgeCases);
-if (selectedCondensed.length + selectedLeaf.length + selectedKnowledge.length === 0)
+if (selectedCondensed.length + selectedLeaf.length === 0)
   throw new Error(
-    `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases, ...knowledgeCases].map((fixture) => fixture.id).join(", ")}`,
+    `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases].map((fixture) => fixture.id).join(", ")}`,
   );
 const Results = Schema.Array(
   Schema.Struct({
@@ -85,12 +79,6 @@ const decodeMorphReply = Schema.decodeUnknownEffect(
 );
 
 const MORPH_ATTEMPTS = 8;
-const PEER_RULE = "- a peer is another model";
-const withoutPeerRule = (prompt: string) =>
-  prompt
-    .split("\n")
-    .filter((line) => !line.startsWith(PEER_RULE))
-    .join("\n");
 
 /** Morph's free Responses API, given the production prompt as OpenCode sends it: text only. */
 const morphRunner = (): TextGenerationOperations.Runner => {
@@ -98,12 +86,11 @@ const morphRunner = (): TextGenerationOperations.Runner => {
   return (request) =>
     Effect.gen(function* () {
       const client = yield* HttpClient.HttpClient;
-      const prompt = dropsPeerRule ? withoutPeerRule(request.prompt) : request.prompt;
       const post = HttpClientRequest.post(`${endpoint.url}/responses`).pipe(
         HttpClientRequest.setHeaders(endpoint.headers),
         HttpClientRequest.bodyJson({
           model: request.modelSelection.model,
-          input: [{ role: "user", content: [{ type: "input_text", text: prompt }] }],
+          input: [{ role: "user", content: [{ type: "input_text", text: request.prompt }] }],
           store: false,
           max_output_tokens: 8_000,
         }),
@@ -131,7 +118,7 @@ const morphRunner = (): TextGenerationOperations.Runner => {
 
 const asArm = (message: LeafMessage, index: number) => {
   const ref = `M${index + 1}`;
-  if (message.role !== "peer" || arm === "full" || arm === "no-rule") return { ref, ...message };
+  if (message.role !== "peer" || arm === "full") return { ref, ...message };
   if (arm === "main") return { ref, role: "assistant" as const, text: message.text };
   const [, rendered] = historyResponseItems(
     [
@@ -200,25 +187,6 @@ await Effect.runPromise(
         record(fixture.id, sample, statements, gradeLeaf(fixture, statements));
       }
     }
-    for (const fixture of selectedKnowledge) {
-      for (let sample = 0; sample < samples; sample++) {
-        const { candidates } = yield* generation.generateKnowledgeCandidates({
-          cwd,
-          runOutcome: "completed",
-          modelSelection,
-          messages: fixture.messages.map(asArm),
-        });
-        record(
-          fixture.id,
-          sample,
-          candidates.map((candidate) => ({
-            text: `${candidate.kind}: ${candidate.content}`,
-            citations: candidate.citations,
-          })),
-          gradeKnowledge(fixture, candidates),
-        );
-      }
-    }
     yield* fs.makeDirectory(outputDirectory, { recursive: true });
     yield* fs.writeFileString(
       path.join(outputDirectory, "results.json"),
@@ -226,7 +194,7 @@ await Effect.runPromise(
     );
     if (baseline !== undefined)
       yield* fs.writeFileString(path.join(outputDirectory, "baseline.json"), baseline);
-    for (const fixture of [...selectedCondensed, ...selectedLeaf, ...selectedKnowledge]) {
+    for (const fixture of [...selectedCondensed, ...selectedLeaf]) {
       const rows = results.filter((row) => row.id === fixture.id);
       const passed = rows.filter((row) => row.passed).length;
       // A case fails when half or more of its samples fail.

From 521c296dc3f5eaf2e2150ea7a8690e45d2185ea3 Mon Sep 17 00:00:00 2001
From: Zack Jackson <25274700+ScriptedAlchemy@users.noreply.github.com>
Date: Mon, 16 Nov 2026 11:48:23 -0800
Subject: [PATCH 27/27] fix(evals): bound Morph summary evaluation requests

---
 evals/conversation-summaries/morph.test.ts | 49 ++++++++++++++++++
 evals/conversation-summaries/morph.ts      | 59 ++++++++++++++++++++++
 evals/conversation-summaries/run.ts        | 56 +-------------------
 3 files changed, 109 insertions(+), 55 deletions(-)
 create mode 100644 evals/conversation-summaries/morph.test.ts
 create mode 100644 evals/conversation-summaries/morph.ts

diff --git a/evals/conversation-summaries/morph.test.ts b/evals/conversation-summaries/morph.test.ts
new file mode 100644
index 0000000000000..676844882820d
--- /dev/null
+++ b/evals/conversation-summaries/morph.test.ts
@@ -0,0 +1,49 @@
+import { expect, it } from "@effect/vitest";
+import { ProviderInstanceId } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
+import * as Schema from "effect/Schema";
+import * as TestClock from "effect/testing/TestClock";
+import { vi } from "vite-plus/test";
+
+import { morphRunner } from "./morph.ts";
+
+it.effect("times out when Morph response headers arrive but the body stalls", () =>
+  Effect.gen(function* () {
+    vi.stubEnv("MORPH_API_KEY", "eval-test-key");
+    const reading = Promise.withResolvers();
+    const body = Promise.withResolvers();
+    const response = new Response(null, { status: 200 });
+    using _body = vi.spyOn(response, "arrayBuffer").mockImplementation(() => {
+      reading.resolve();
+      return body.promise;
+    });
+    using _fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(response);
+    const completed = new TextEncoder().encode(
+      JSON.stringify({
+        output: [{ type: "message", content: [{ text: '{"statements":[]}' }] }],
+      }),
+    ).buffer;
+    try {
+      const result = yield* morphRunner()({
+        operation: "generateConversationSummary",
+        cwd: "/project",
+        modelSelection: { instanceId: ProviderInstanceId.make("morph"), model: "morph-test" },
+        prompt: "Summarize the conversation.",
+        outputSchema: Schema.Struct({ statements: Schema.Array(Schema.Unknown) }),
+      }).pipe(Effect.exit, Effect.forkChild);
+      yield* Effect.promise(() => reading.promise);
+      yield* TestClock.adjust("121 seconds");
+      body.resolve(completed);
+      const exit = yield* Fiber.join(result);
+      expect(Exit.isFailure(exit) ? Cause.squash(exit.cause) : exit).toMatchObject({
+        _tag: "TimeoutError",
+      });
+    } finally {
+      body.resolve(completed);
+      vi.unstubAllEnvs();
+    }
+  }),
+);
diff --git a/evals/conversation-summaries/morph.ts b/evals/conversation-summaries/morph.ts
new file mode 100644
index 0000000000000..335b09b8c9dcd
--- /dev/null
+++ b/evals/conversation-summaries/morph.ts
@@ -0,0 +1,59 @@
+import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
+
+import { morphConfig } from "../shared/proxy.ts";
+
+const decodeMorphReply = Schema.decodeUnknownEffect(
+  Schema.fromJsonString(
+    Schema.Struct({
+      output: Schema.Array(
+        Schema.Struct({
+          type: Schema.String,
+          content: Schema.optional(
+            Schema.Array(Schema.Struct({ text: Schema.optional(Schema.String) })),
+          ),
+        }),
+      ),
+    }),
+  ),
+);
+
+const MORPH_ATTEMPTS = 8;
+
+/** Morph's free Responses API, given the production prompt as OpenCode sends it: text only. */
+export const morphRunner = (): TextGenerationOperations.Runner => {
+  const endpoint = morphConfig();
+  return (request) =>
+    Effect.gen(function* () {
+      const client = yield* HttpClient.HttpClient;
+      const post = HttpClientRequest.post(`${endpoint.url}/responses`).pipe(
+        HttpClientRequest.setHeaders(endpoint.headers),
+        HttpClientRequest.bodyJson({
+          model: request.modelSelection.model,
+          input: [{ role: "user", content: [{ type: "input_text", text: request.prompt }] }],
+          store: false,
+          max_output_tokens: 8_000,
+        }),
+        Effect.flatMap(client.execute),
+      );
+      let response = yield* post;
+      // Morph limits input tokens per minute and says when to come back.
+      for (let attempt = 1; response.status === 429 || response.status >= 500; attempt++) {
+        if (attempt >= MORPH_ATTEMPTS) break;
+        const retryAfter = Number(response.headers["retry-after"]);
+        yield* Effect.sleep(`${retryAfter > 0 ? Math.min(retryAfter, 60) : 2 ** attempt} seconds`);
+        response = yield* post;
+      }
+      // The body is omitted so a credential echoed in an error never reaches the log.
+      if (response.status !== 200) return yield* Effect.die(`Morph HTTP ${response.status}`);
+      const reply = yield* decodeMorphReply(yield* response.text);
+      const text = reply.output
+        .filter((item) => item.type === "message")
+        .flatMap((item) => item.content ?? [])
+        .map((part) => part.text ?? "")
+        .join("");
+      return yield* TextGenerationOperations.decodeJsonReply(request, "Morph", text);
+    }).pipe(Effect.timeout("120 seconds"), Effect.orDie, Effect.provide(FetchHttpClient.layer));
+};
diff --git a/evals/conversation-summaries/run.ts b/evals/conversation-summaries/run.ts
index 222a5e988c4be..ef8d8679f7baa 100644
--- a/evals/conversation-summaries/run.ts
+++ b/evals/conversation-summaries/run.ts
@@ -9,12 +9,11 @@ import * as FileSystem from "effect/FileSystem";
 import * as Layer from "effect/Layer";
 import * as Path from "effect/Path";
 import * as Schema from "effect/Schema";
-import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
 import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts";
 import * as ServerConfig from "../../apps/server/src/config.ts";
-import { morphConfig } from "../shared/proxy.ts";
 import { condensedCases, leafCases, type LeafMessage } from "./cases.ts";
 import { gradeCondensed, gradeLeaf } from "./grade.ts";
+import { morphRunner } from "./morph.ts";
 
 /**
  * How a peer reply reaches the model. `main` sends it as a nameless assistant message, as main
@@ -63,59 +62,6 @@ const Results = Schema.Array(
 const decodeSettings = Schema.decodeUnknownSync(CodexSettings);
 const decodeResults = Schema.decodeEffect(Schema.fromJsonString(Results));
 const encodeResults = Schema.encodeEffect(Schema.fromJsonString(Results));
-const decodeMorphReply = Schema.decodeUnknownEffect(
-  Schema.fromJsonString(
-    Schema.Struct({
-      output: Schema.Array(
-        Schema.Struct({
-          type: Schema.String,
-          content: Schema.optional(
-            Schema.Array(Schema.Struct({ text: Schema.optional(Schema.String) })),
-          ),
-        }),
-      ),
-    }),
-  ),
-);
-
-const MORPH_ATTEMPTS = 8;
-
-/** Morph's free Responses API, given the production prompt as OpenCode sends it: text only. */
-const morphRunner = (): TextGenerationOperations.Runner => {
-  const endpoint = morphConfig();
-  return (request) =>
-    Effect.gen(function* () {
-      const client = yield* HttpClient.HttpClient;
-      const post = HttpClientRequest.post(`${endpoint.url}/responses`).pipe(
-        HttpClientRequest.setHeaders(endpoint.headers),
-        HttpClientRequest.bodyJson({
-          model: request.modelSelection.model,
-          input: [{ role: "user", content: [{ type: "input_text", text: request.prompt }] }],
-          store: false,
-          max_output_tokens: 8_000,
-        }),
-        Effect.flatMap(client.execute),
-      );
-      let response = yield* post;
-      // Morph limits input tokens per minute and says when to come back.
-      for (let attempt = 1; response.status === 429 || response.status >= 500; attempt++) {
-        if (attempt >= MORPH_ATTEMPTS) break;
-        const retryAfter = Number(response.headers["retry-after"]);
-        yield* Effect.sleep(`${retryAfter > 0 ? Math.min(retryAfter, 60) : 2 ** attempt} seconds`);
-        response = yield* post;
-      }
-      // The body is omitted so a credential echoed in an error never reaches the log.
-      if (response.status !== 200) return yield* Effect.die(`Morph HTTP ${response.status}`);
-      const reply = yield* decodeMorphReply(yield* response.text);
-      const text = reply.output
-        .filter((item) => item.type === "message")
-        .flatMap((item) => item.content ?? [])
-        .map((part) => part.text ?? "")
-        .join("");
-      return yield* TextGenerationOperations.decodeJsonReply(request, "Morph", text);
-    }).pipe(Effect.orDie, Effect.provide(FetchHttpClient.layer));
-};
-
 const asArm = (message: LeafMessage, index: number) => {
   const ref = `M${index + 1}`;
   if (message.role !== "peer" || arm === "full") return { ref, ...message };