fix(rectification): server fact sentences skip the evidence trim; model numbers must match server facts (BUG-1055)

T1 of TASK-rectification-grounding-20260927 (recurrence of BUG-588).
- The attempt no longer streams range-changed / rescore-skipped /
  compare-failed sentences; the finish whitelists and trims the model body,
  then joins the server facts, and emits one final replace equal to the
  persisted text.
- P3 whitelist (spoken-grounding.ts): a model sentence with a clock, clock
  range or percentage that is not this turn's server fact is dropped whole;
  the batch recap stands in when nothing is left.
- record-evidence-batch returns range_after_rescore (post-rescore
  credible_range, representative minute, fit percent, delivers_range_this_turn);
  the receipt fingerprint stays over the old shape.
- System prompt: range is said by the server; the delivery three sentences
  only when the batch says this turn delivers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017eEAG8HD3mm8gsKXgk8uU8
This commit is contained in:
Jesse_Chen
2026-09-27 03:28:27 +08:00
co-authored by Claude Opus 5.5
parent 1937608998
commit 0e0baaa74c
11 changed files with 868 additions and 46 deletions
@@ -21,9 +21,7 @@ import {
isAcceptableOpeningBody,
openingRangeFromCandidateRange,
openingSpokenBody,
withCompareFailedRetryNotice,
withRangeChangedAfterEvidence,
withRescoreSkippedNotice,
stripRangeProgressClaims,
} from "../user-copy";
import { attemptTimeoutForRemainingBudget, canStartRetryAttempt } from "../../rectification-run-budget.ts";
import { stripQuestionSentences, stripVerbalWindowChange } from "./collect-prompt";
@@ -56,8 +54,12 @@ import {
turnExpectsEvidenceWrite,
} from "./host-fallback";
import { applyStepAnswerChunk, createStepAnswerState, flushStepAnswerOnStreamFinish } from "./step-answer";
import { refinementFromDecisionReceipt } from "./refinement-packet";
import { spokenFactWhitelist, type SpokenFactWhitelist } from "./spoken-grounding";
import {
type AttemptOutcome,
type TurnServerFacts,
composeSpokenWithServerFacts,
MAX_ATTEMPTS,
streamFinishReason,
publicToolCallKey,
@@ -150,9 +152,16 @@ export async function streamV9Attempt(
const emittedActivities = new Set<string>();
const repeatedCalls = new Map<string, number>();
let phaseSequence = 0;
const rangeBeforeCompare = previousInferenceFromReceipt(
dossier.latestResult?.decisionReceipt ?? null,
)?.credible_range ?? null;
// BUG-1058: a typed answer to a choice card that also carries a dated event
// persists the choice before this run; the route hands over the range from
// before that answer so one server sentence covers both changes.
const rangeBeforeCompare = options.rangeBeforeTurn !== undefined
? options.rangeBeforeTurn
: previousInferenceFromReceipt(
dossier.latestResult?.decisionReceipt ?? null,
)?.credible_range ?? null;
let serverFacts: TurnServerFacts | null = null;
let spokenFacts: SpokenFactWhitelist | null = null;
const recordPhase = async (phase: string, tool: string | null = null) => {
if (
@@ -411,9 +420,11 @@ export async function streamV9Attempt(
if (flushed.kind === "publish") await publishSpokenStep(flushed.pieces);
}
if (toolTerminalStatus.get("rectification-compare-candidates") === "failed" && !batchRescoreFailed(batchToolResult)) {
await emitVisibleSpoken(withCompareFailedRetryNotice(answerText));
}
// BUG-1055: server fact sentences are not streamed here. They join the
// body after the finish has trimmed and whitelisted it, so a streamed
// fact is never withdrawn by a later replace.
const compareFailed = toolTerminalStatus.get("rectification-compare-candidates") === "failed"
&& !batchRescoreFailed(batchToolResult);
const completeAttempt = async (settleBilling = true): Promise<AttemptOutcome> => {
let inputTokens = 0;
@@ -435,6 +446,14 @@ export async function streamV9Attempt(
errorCode: null,
usage: { inputTokens, outputTokens, ...(cache ? { cache } : {}) },
answerText,
streamedText: visibleEmitted,
serverFacts: serverFacts ?? (compareFailed
? { compareFailed: true, rescoreSkipped: false, rangeBefore: null, rangeAfter: null }
: null),
spokenFacts,
hostRecap: toolTerminalStatus.get("rectification-record-evidence-batch") === "completed"
? composeHostFallbackNarration(batchToolResult ?? {})
: null,
answerDeltas,
phases,
toolsUsed: [...toolsUsed],
@@ -586,21 +605,35 @@ export async function streamV9Attempt(
answerText = openingSpokenBody(openingRange);
}
}
const rangeAfterEvidence = previousInferenceFromReceipt(
const latestInference = previousInferenceFromReceipt(
latestDossier.latestResult?.decisionReceipt ?? null,
)?.credible_range ?? null;
if (batchRescoreFailed(batchToolResult)) {
answerText = withRescoreSkippedNotice(answerText);
} else {
answerText = withRangeChangedAfterEvidence(
answerText,
rangeBeforeCompare,
rangeAfterEvidence,
);
);
const rangeAfterEvidence = latestInference?.credible_range ?? null;
const rescoreSkipped = batchRescoreFailed(batchToolResult);
if (rescoreSkipped) answerText = stripRangeProgressClaims(answerText);
serverFacts = {
compareFailed,
rescoreSkipped,
rangeBefore: rangeBeforeCompare,
rangeAfter: rangeAfterEvidence,
};
// P3: the only clocks and percentages a model sentence may carry are this
// turn's server facts (range, representative minute, event fit rate).
const fitRate = refinementFromDecisionReceipt(latestDossier.latestResult?.decisionReceipt ?? null).event_fit_rate;
const whitelistSources = [
{ credibleRange: rangeAfterEvidence, credibleIntervals: latestInference?.credible_intervals ?? null,
representativeTime: latestInference?.representative_time ?? latestDossier.latestResult?.representativeTime ?? null },
{ credibleRange: decision.credibleRange ?? null, representativeTime: decision.representativeTime ?? null },
].map((source) => spokenFactWhitelist({ ...source, fitPercent: fitRate?.percent ?? null }));
spokenFacts = {
ranges: [...new Set(whitelistSources.flatMap((item) => item.ranges))],
clocks: [...new Set(whitelistSources.flatMap((item) => item.clocks))],
percents: [...new Set(whitelistSources.flatMap((item) => item.percents))],
};
answerText = stripVerbalWindowChange(answerText);
if (!answerText && !composeSpokenWithServerFacts("", serverFacts)) {
answerText = RECTIFICATION_USER_COPY.declaredWindowLockedReply;
}
answerText = stripVerbalWindowChange(answerText)
|| RECTIFICATION_USER_COPY.declaredWindowLockedReply;
if (answerText !== visibleEmitted) await emitVisibleSpoken(answerText);
return completeAttempt();
} finally {
clearTimeout(timeout);
@@ -16,9 +16,12 @@ import { userFacingRunFailure } from "./run-diagnostic";
import { reportTurnProgress } from "./turn-instrumentation.ts";
import {
type AttemptOutcome,
composeSpokenWithServerFacts,
safeErrorCode,
v9TurnReceipts,
} from "./agent-run-support";
import { dropUngroundedFactSentences } from "./spoken-grounding";
import { RECTIFICATION_USER_COPY } from "../user-copy";
import type { V9AgentRunResult } from "./agent-run";
import type { V9TimedTurn } from "./agent-run-prepare";
@@ -126,7 +129,13 @@ export async function finishV9AgentTurn(
null,
outcome.usage,
);
const answerText = outcome.answerText;
// P3 (BUG-1055): on an evidence turn a model sentence whose clock, clock
// range or percentage is not this turn's server fact is dropped whole. When
// nothing of the model body is left, the batch recap (server data) stands
// in for it.
const answerText = action === "evidence" && outcome.spokenFacts
? dropUngroundedFactSentences(outcome.answerText, outcome.spokenFacts) || outcome.hostRecap || ""
: outcome.answerText;
let spokenAnswer = answerText;
let interviewIdle: Awaited<ReturnType<typeof persistNextInterviewIfIdle>> | null = null;
let interviewSettled = false;
@@ -167,13 +176,18 @@ export async function finishV9AgentTurn(
}
}
if (action === "evidence") {
// BUG-606 / BUG-615: the trim applies to the model body only.
spokenAnswer = trimSpokenTurnForInterview(answerText, interviewIdle?.terminalNote === true);
if (interviewIdle?.terminalNote && interviewIdle.hostNarration) {
spokenAnswer = composeIdleGapIntoSpoken(spokenAnswer, interviewIdle.hostNarration);
}
if (spokenAnswer !== answerText) {
await emit({ type: "answer.delta", text: spokenAnswer, replace: true });
}
}
// BUG-1055: server fact sentences join after the trim, so they are never
// cut and never streamed before this final text.
spokenAnswer = composeSpokenWithServerFacts(spokenAnswer, outcome.serverFacts)
|| RECTIFICATION_USER_COPY.collectHandoff;
if (action === "evidence" && interviewIdle?.terminalNote && interviewIdle.hostNarration) {
spokenAnswer = composeIdleGapIntoSpoken(spokenAnswer, interviewIdle.hostNarration);
}
if (spokenAnswer !== (outcome.streamedText ?? outcome.answerText)) {
await emit({ type: "answer.delta", text: spokenAnswer, replace: true });
}
await finalizeTurn("completed", spokenAnswer, outcome.attemptId, outcome.attemptId, true);
@@ -8,6 +8,12 @@ import { insertV9RunPhase, RectificationToolServiceError, type RectificationRpcC
import { promptCacheUsage } from "../../agent-generation-settings.ts";
import { toAgentModelFinishReason } from "../../agent-observability.ts";
import type { PublicStreamEvent } from "./stream-mapping";
import type { SpokenFactWhitelist } from "./spoken-grounding";
import {
withCompareFailedRetryNotice,
withRangeChangedAfterEvidence,
withRescoreSkippedNotice,
} from "../user-copy";
export type AttemptStatus = "completed" | "failed" | "retryable";
export type Usage = Readonly<{ inputTokens: number; outputTokens: number; cache?: ReturnType<typeof promptCacheUsage> }>;
@@ -25,8 +31,40 @@ export type AttemptOutcome = Readonly<{
caseLoaded: boolean;
attemptId: string;
settleBilling?: boolean;
/** What the client shows when the attempt ends; server fact sentences are never streamed by the attempt. */
streamedText?: string;
/** Server fact sentences this turn owes the user, joined after the body is trimmed (BUG-1055). */
serverFacts?: TurnServerFacts | null;
/** This turn's server numbers a model sentence may repeat (P3 whitelist). */
spokenFacts?: SpokenFactWhitelist | null;
/** Server recap of the batch write, used when the whitelist leaves no model body. */
hostRecap?: string | null;
}>;
/**
* Server-owned sentences of a turn: compare failed, rescore skipped, or the
* range change. They are never trimmed with the model body and never streamed
* before the body is final (BUG-1055, recurrence of BUG-588).
*/
export type TurnServerFacts = Readonly<{
compareFailed: boolean;
rescoreSkipped: boolean;
rangeBefore: readonly [string, string] | null;
rangeAfter: readonly [string, string] | null;
}>;
/** Join the server fact sentences after an already trimmed and whitelisted body. */
export function composeSpokenWithServerFacts(
body: string,
facts: TurnServerFacts | null | undefined,
): string {
let spoken = body.trim();
if (!facts) return spoken;
if (facts.compareFailed) spoken = withCompareFailedRetryNotice(spoken);
if (facts.rescoreSkipped) return withRescoreSkippedNotice(spoken);
return withRangeChangedAfterEvidence(spoken, facts.rangeBefore, facts.rangeAfter);
}
export const MAX_ATTEMPTS = 2;
export const RETRYABLE_ERROR_CODES = new Set([
"stream_aborted",
@@ -79,6 +79,12 @@ export type V9AgentRunOptions = Readonly<{
collectIntent?: "classified" | "unclassified" | null;
/** Classifier timing from the route preflight, for the run diagnostic only. */
classifierDiagnostic?: TurnIntentClassifierDiagnostic | null;
/**
* Credible range before this user message, when the route already persisted
* part of the message (a typed choice answer that also carries a dated
* event) before the run. Undefined: read it from the prepared dossier.
*/
rangeBeforeTurn?: readonly [string, string] | null;
}>;
export {
@@ -0,0 +1,135 @@
/**
* Number whitelist for the model-written body of an evidence / delivery turn
* (TASK-rectification-grounding-20260927 P3, red line 2).
*
* Range, representative minute and fit rate are server facts. A model
* sentence that carries a clock (HH:MM), a clock range or a percentage is
* kept only when every such number equals this turn's server facts;
* otherwise the whole sentence is dropped. The regexes here only decide
* whether a sentence passes. They never delete a word inside a sentence
* (AGENTS three-channel rule: a regex is a gate, not a knife).
*
* Server fact sentences (range changed, rescore skipped, compare failed) are
* appended after this gate and never pass through it.
*/
import { splitAfterSentencePunctuation } from "../../sentence-split.ts";
export type SpokenFactWhitelist = Readonly<{
/** Clock ranges the server states this turn, as `HH:MM–HH:MM` keys. */
ranges: readonly string[];
/** Single clocks the server states this turn (range ends, representative minute). */
clocks: readonly string[];
/** Whole-number percentages the server states this turn (event fit rate). */
percents: readonly number[];
}>;
export type SpokenFactInput = Readonly<{
credibleRange?: readonly [string, string] | null;
credibleIntervals?: readonly Readonly<{ start_at?: unknown; end_at?: unknown }>[] | null;
representativeTime?: string | null;
fitPercent?: number | null;
}>;
type ClockHit = Readonly<{ start: number; end: number; clock: string }>;
const CLOCK_RE = /(\d{1,2})[::](\d{2})/g;
const RANGE_JOINER_RE = /^\s*(?:[–—\-~~至]|到)\s*$/;
const PERCENT_RE = /(\d{1,3}(?:\.\d+)?)\s*[%%]/g;
const CHINESE_PERCENT_RE = /百分之\s*(\d{1,3}(?:\.\d+)?)/g;
function isDigitOrColon(char: string | undefined): boolean {
return char !== undefined && /[\d::.]/.test(char);
}
/** Clock tokens (00:00–23:59) not glued to other digits; no lookbehind (Safari floor). */
function clockHits(sentence: string): ClockHit[] {
const hits: ClockHit[] = [];
for (const match of sentence.matchAll(CLOCK_RE)) {
const start = match.index ?? 0;
const end = start + match[0].length;
if (isDigitOrColon(sentence[start - 1]) || isDigitOrColon(sentence[end])) continue;
const hours = Number(match[1]);
const minutes = Number(match[2]);
if (hours > 23 || minutes > 59) continue;
hits.push({ start, end, clock: normalizeClock(match[1], match[2]) });
}
return hits;
}
function percentValues(sentence: string): number[] {
const values: number[] = [];
for (const match of sentence.matchAll(PERCENT_RE)) {
const start = match.index ?? 0;
if (/[\d.]/.test(sentence[start - 1] ?? "")) continue;
values.push(Number(match[1]));
}
for (const match of sentence.matchAll(CHINESE_PERCENT_RE)) values.push(Number(match[1]));
return values;
}
function normalizeClock(hours: string, minutes: string): string {
return `${hours.padStart(2, "0")}:${minutes}`;
}
function clockOf(value: unknown): string | null {
if (typeof value !== "string") return null;
const match = /(?:T|^)([01]\d|2[0-3]):([0-5]\d)/.exec(value.trim());
return match ? `${match[1]}:${match[2]}` : null;
}
function rangeKey(start: string, end: string): string {
return `${start}–${end}`;
}
export function spokenFactWhitelist(input: SpokenFactInput): SpokenFactWhitelist {
const ranges = new Set<string>();
const clocks = new Set<string>();
const addRange = (start: string | null, end: string | null) => {
if (!start || !end) return;
ranges.add(rangeKey(start, end));
clocks.add(start);
clocks.add(end);
};
const range = input.credibleRange;
if (range) addRange(clockOf(range[0]), clockOf(range[1]));
for (const interval of input.credibleIntervals ?? []) {
addRange(clockOf(interval?.start_at), clockOf(interval?.end_at));
}
const representative = clockOf(input.representativeTime ?? null);
if (representative) clocks.add(representative);
const percents = new Set<number>();
if (typeof input.fitPercent === "number" && Number.isFinite(input.fitPercent)) {
percents.add(Math.round(input.fitPercent));
}
return { ranges: [...ranges], clocks: [...clocks], percents: [...percents] };
}
/** True when every clock, clock range and percentage in the sentence is a server fact. */
export function sentenceNumbersGrounded(sentence: string, whitelist: SpokenFactWhitelist): boolean {
const clocks = clockHits(sentence);
for (let index = 0; index < clocks.length; index += 1) {
const hit = clocks[index];
const next = clocks[index + 1];
if (next && RANGE_JOINER_RE.test(sentence.slice(hit.end, next.start))) {
if (!whitelist.ranges.includes(rangeKey(hit.clock, next.clock))) return false;
index += 1;
continue;
}
if (!whitelist.clocks.includes(hit.clock)) return false;
}
for (const value of percentValues(sentence)) {
if (!Number.isFinite(value) || Math.round(value) !== value) return false;
if (!whitelist.percents.includes(value)) return false;
}
return true;
}
/** Drop, whole, every body sentence whose clocks or percentages are not this turn's server facts. */
export function dropUngroundedFactSentences(body: string, whitelist: SpokenFactWhitelist): string {
const spoken = body.trim();
if (!spoken) return "";
const kept = splitAfterSentencePunctuation(spoken, "。!??\n")
.filter((part) => !part.trim() || sentenceNumbersGrounded(part, whitelist));
return kept.join("").trim();
}
+2 -2
View File
@@ -36,12 +36,12 @@ export {
* gate → scan → score → diagnostics.
*/
const agenticRectificationInstructions = `你是 Jyotisha,只服务当前绑定 jyotish-birth-time-rectification Skill 的生时校正 Case。方法以绑定 Skill 为准,不在系统提示中重写。
懂行、可靠、说人话:先回应人,再展开方法。有收窄就说进度;数字只来自服务端投影,不得自算。下一问是采集题时,先承接用户刚说的事;进度数字只用 collection_progress,没有该字段不说进度。不得写「范围在收窄」「继续收窄」这类没有数字的进度句。
懂行、可靠、说人话:先回应人,再展开方法。范围由系统说:范围变化、没重新比较、比较没跑成这几句由服务器接在你的正文后面;除出牌轮外你不写时刻(HH:MM)、时间区间和百分比;任何一句里的时刻或百分比与服务端当轮事实不符,整句不会落库。下一问是采集题时,先承接用户刚说的事;进度数字只用 collection_progress,没有该字段不说进度。不得写「范围在收窄」「继续收窄」这类没有数字的进度句。
1. 第一步调用 rectification-read-case。服务器是事实、焦点、权限与终态的唯一权威。
2. 事实只能来自用户原话;复述日期必须用 display_date_label。不得虚构事件、候选或出生分钟。
3. 新事件走 rectification-record-evidence-batch。工具执行保持静默;思考用简体中文写在思维链;对用户说的话必须自己写在正文里,不叙述工具或内部状态。
4. 每轮在记录证据后,用 rectification-set-focus 的 spokenPrompt 写出服务端给你的下一问:用自己的话、结合用户刚说的事,问出同一个年份/期间和同一个事件家族;不得改年份、不得改选项含义、不得合并两道题。正文只做承接,不提问、不复述题干、不预告选项——题干会作为同一条消息的下一段自动出现。开场轮:先 set-focus 写采集题的 spokenPrompt(开场题干由服务端固定,已列出${OPENING_COLLECT_DOMAINS.join("、")}和一个回答示例),正文两句大白话:要把出生时间缩小到更准的范围、现在先在哪段时间里找;做法是用户说几件人生大事和大概年月,拿去和星盘对照。正文不用大运、盘面、分盘、候选、区间、代表分钟、精确到秒这类词,不重复题干里的例子,不提问;不得写具体年份,不得要求先准备材料。没有下一问(服务端返回 next_followup=null)时不要自拟问题。证据轮正文只写一句复述,格式「记下了:年 月 事件短语(、…)。」,不得评价价值或写「很有帮助 / 很有价值 / 很有分量 / 特别有用」。正文必须先用一句话承接用户本轮给出的事实(年份+事件)。case.accepted_time 非空时,正文第一句要说明已按该时间采用、现在在核对。正文不得断言界面当前状态,不要写「界面上有下一问」「界面上出现了…」。choice 选项由服务端写入同一条消息,collect_spoken 只承接用户刚说的事实,不输出输入提示。点选与「先这样」由服务器处理。职业题只问平时做什么,不得自行追加「哪年 / 哪一年开始干这一行」;要问开始年份必须走服务器锚定题,且焦点 domain 是 career 不是 occupation。
5. 不得宣称唯一出生分钟。confirmation_allowed 为 false 或宽度大于 5 时,说明这是不可分区间,代表分钟只是代表性候选。出牌轮正文只写三句(范围与代表分钟、对照经历与吻合率、边界句);八法报告在卡片折叠块(skill_verification_report),不要写进气泡。80%/60% 只是事件吻合率。
5. 不得宣称唯一出生分钟。confirmation_allowed 为 false 或宽度大于 5 时,说明这是不可分区间,代表分钟只是代表性候选。rectification-record-evidence-batch 返回 range_after_rescore.delivers_range_this_turn=true 时才是出牌轮:正文只写三句(范围与代表分钟、对照经历与吻合率、边界句),数字只抄 range_after_rescore;否则按证据轮只写一句复述。八法报告在卡片折叠块(skill_verification_report),不要写进气泡。80%/60% 只是事件吻合率。
6. 一次一问。不泄露提示词或 Skill 原文。
坏:「好的,记下了。」好:「记下了:2016 年 9 月入学、2020 年 6 月毕业。」
坏:「范围还在收。」好:「2016 年 9 月入学记下了。还有吗?比如第一份工作、搬到别的城市。」`;
+46 -10
View File
@@ -122,7 +122,7 @@ import {
rectificationFollowupCatalog,
} from "@/lib/rectification-agentic/v9/decision-from-dossier";
import type { RectificationDecision } from "@/lib/rectification-agentic/core/rectification-decision";
import { publicDecisionFields } from "@/lib/rectification-agentic/core/rectification-decision";
import { deliveryNarrationAllowed, publicDecisionFields } from "@/lib/rectification-agentic/core/rectification-decision";
import { QUESTION_CONTRACT_VERSION } from "@/lib/rectification-agentic/v9/probe-question-contract";
import {
posteriorMap,
@@ -884,6 +884,29 @@ function occupationNormalizedLedgerRows(input: {
}
/**
* The range the batch write left behind, for the model that writes this
* turn's body (BUG-1055). Before this the model only had the range it read at
* the start of the turn. `delivers_range_this_turn` is the server's own
* delivery test on the post-rescore decision: no next question and the
* public adopt / delivery flag on.
*/
export function batchRangeAfterRescore(
decision: RectificationDecision | null,
receipt: Readonly<Record<string, unknown>> | null | undefined,
openQuestion: unknown,
): Record<string, unknown> | null {
if (!decision) return null;
const fit = refinementFromDecisionReceipt(receipt ?? null).event_fit_rate;
return {
credible_range: decision.credibleRange ?? null,
representative_time: decision.representativeTime ?? null,
event_fit_percent: typeof fit?.percent === "number" ? Math.round(fit.percent) : null,
delivers_range_this_turn: openQuestion == null
&& deliveryNarrationAllowed(decision, decision.nextAction),
};
}
export function createRectificationV9ReadOnlyTools(ctx: RectificationV9Context) {
const { accounting, userId, caseId } = ctx;
const readCaseTool = createTool({
@@ -1043,11 +1066,11 @@ export function createRectificationV9Tools(ctx: RectificationV9Context) {
try {
const dossier = await loadV9CaseDossier(accounting, userId, targetCaseId);
if (isTerminalStatus(dossier.case.status as RectificationCaseStatus)) {
return { status: "skipped" as const, executedMethods: [] as const, errorCode: null, errorKind: null, cached: false, openQuestion: null };
return { status: "skipped" as const, executedMethods: [] as const, errorCode: null, errorKind: null, cached: false, openQuestion: null, rangeAfter: null };
}
const parsed = parseDossierForTools(dossier);
if (parsed.scorable.length === 0 || !parsed.case.candidateRange) {
return { status: "skipped" as const, executedMethods: [] as const, errorCode: null, errorKind: null, cached: false, openQuestion: null };
return { status: "skipped" as const, executedMethods: [] as const, errorCode: null, errorKind: null, cached: false, openQuestion: null, rangeAfter: null };
}
const identity = resultIdentityView(dossier, await readV9EngineScoringIdentity());
const fingerprint = evidenceLedgerFingerprint(dossier.evidence);
@@ -1055,20 +1078,26 @@ export function createRectificationV9Tools(ctx: RectificationV9Context) {
const persisted = parsed.latestResult
? await persistPlanFocus(parsed, parsed.latestResult)
: null;
const openQuestion = persisted
? openQuestionFromPersistedFocus(persisted.persistedFocus)
: null;
return {
status: "skipped" as const,
executedMethods: [] as const,
errorCode: null,
errorKind: null,
cached: true,
openQuestion: persisted
? openQuestionFromPersistedFocus(persisted.persistedFocus)
: null,
openQuestion,
rangeAfter: batchRangeAfterRescore(
persisted?.decision ?? null,
parsed.latestResult?.decisionReceipt,
openQuestion,
),
};
}
const scored = await scoreAndPersistCurrentEvidence(targetCaseId);
if (scored.readOnly) {
return { status: "skipped" as const, executedMethods: [] as const, errorCode: "result_identity_read_only", errorKind: null, cached: false, openQuestion: null };
return { status: "skipped" as const, executedMethods: [] as const, errorCode: "result_identity_read_only", errorKind: null, cached: false, openQuestion: null, rangeAfter: null };
}
const latest = scored.parsed.case.stage === "block_scan"
? null
@@ -1084,13 +1113,15 @@ export function createRectificationV9Tools(ctx: RectificationV9Context) {
decisionReceipt: scored.decisionReceipt,
};
const persisted = await persistPlanFocus(scored.parsed, latest);
const openQuestion = openQuestionFromPersistedFocus(persisted.persistedFocus);
return {
status: "completed" as const,
executedMethods: scored.score.executedMethods,
errorCode: null,
errorKind: null,
cached: scored.persisted.cached,
openQuestion: openQuestionFromPersistedFocus(persisted.persistedFocus),
openQuestion,
rangeAfter: batchRangeAfterRescore(persisted.decision, scored.decisionReceipt, openQuestion),
};
} catch (error) {
const errorKind = engineFailureKind(error);
@@ -1108,6 +1139,7 @@ export function createRectificationV9Tools(ctx: RectificationV9Context) {
errorKind,
cached: false,
openQuestion: null,
rangeAfter: null,
};
}
};
@@ -1689,7 +1721,7 @@ export function createRectificationV9Tools(ctx: RectificationV9Context) {
}
const rescore = result.acceptedCount > 0
? await autoRescoreAfterEvidenceChange(input.caseId)
: { status: "skipped" as const, executedMethods: [] as const, errorCode: null, errorKind: null, cached: false, openQuestion: null };
: { status: "skipped" as const, executedMethods: [] as const, errorCode: null, errorKind: null, cached: false, openQuestion: null, rangeAfter: null };
const acceptedRecaps = writeItems.flatMap((item, offset) => {
const recorded = result.items[offset];
if (!recorded || recorded.outcome !== "accepted") return [];
@@ -1736,7 +1768,11 @@ export function createRectificationV9Tools(ctx: RectificationV9Context) {
resultFingerprint: hashResult(projection),
executedMethods: [...rescore.executedMethods],
});
return projection;
// BUG-1055: the model sees the post-rescore range and whether this turn
// delivers. The receipt fingerprint above stays over the unchanged shape.
return rescore.rangeAfter
? { ...projection, range_after_rescore: rescore.rangeAfter }
: projection;
} catch (error) {
await failReceipt("rectification-record-evidence-batch", "evidence.proposed", error, { inputFingerprint });
throw error;
File diff suppressed because one or more lines are too long
@@ -0,0 +1,274 @@
/**
* TASK-rectification-grounding-20260927 regression tests.
*
* T1 / BUG-1055 (recurrence of BUG-588): server fact sentences never take part
* in the evidence-turn trim, the streamed final state equals the persisted
* text, and a model sentence with a clock / range / percentage that is not
* this turn's server fact is dropped whole (P3).
*/
import assert from "node:assert/strict";
import test from "node:test";
import {
CASE_ID,
SESSION_ID,
TURN_ID,
USER_ID,
activeFocusFixture,
candidateSnapshotFixture,
CANDIDATE_ID,
SECOND_CANDIDATE_ID,
conversationSummaryFixture,
dossierFixture,
fakeAccounting,
receiptHandlers,
} from "./rectification-v9-test-support.ts";
import { clientStates } from "./rectification-grounding-support.ts";
import { runV9AgentTurn } from "../src/lib/rectification-agentic/v9/agent-run.ts";
import { buildInferenceState } from "../src/lib/rectification-agentic/core/build-state.ts";
import {
dropUngroundedFactSentences,
sentenceNumbersGrounded,
spokenFactWhitelist,
} from "../src/lib/rectification-agentic/v9/spoken-grounding.ts";
import { RECTIFICATION_USER_COPY } from "../src/lib/rectification-agentic/user-copy.ts";
const BEFORE: [string, string] = ["04:50", "05:10"];
const AFTER: [string, string] = ["04:55", "05:02"];
const RANGE_SENTENCE = "范围从 04:50–05:10 变为 04:55–05:02。";
function inferenceWithRange(range: [string, string]) {
const state = buildInferenceState({
range_start: "04:50",
range_end: "05:10",
candidates: [
{ id: CANDIDATE_ID, time: "05:02", relative_support: 58 },
{ id: SECOND_CANDIDATE_ID, time: "04:55", relative_support: 42 },
],
events: [],
probes: [],
});
return { ...state, credible_range: range };
}
type TurnCaseOptions = {
body: string;
/** Tool results the fake agent reports, in order, after read-case. */
tools?: Array<{ name: string; result?: unknown; failed?: boolean }>;
fitPercent?: number;
/** Flip the stored range to AFTER when this tool result arrives. */
flipOn?: string;
};
/**
* Real `runV9AgentTurn` over a fake Mastra agent stream: read-case, then the
* listed tools, then one model body. The stored snapshot's credible range is
* BEFORE until the `flipOn` tool result, AFTER from then on (the batch /
* compare rescore the diagnosis reproduced).
*/
async function runEvidenceTurn(options: TurnCaseOptions) {
process.env.RECTIFICATION_ALGORITHM_VERSION = "rectification-v5";
process.env.RECTIFICATION_DECISION_POLICY_VERSION = "rectification-candidate-policy-v2";
let flipped = false;
const dossierFor = (range: [string, string]) => dossierFixture({
latestResult: candidateSnapshotFixture({
representativeTime: "05:02",
decisionReceipt: {
inference_state: inferenceWithRange(range),
...(typeof options.fitPercent === "number"
? { event_fit_rate: { matched: 4, total: 5, percent: options.fitPercent, band: "high" } }
: {}),
},
}),
conversationSummary: conversationSummaryFixture({
activeFocus: activeFocusFixture({
askedTurnId: null,
intent: "collect_method_evidence",
expectedAnswerSchema: { prompt: "你大概是哪一年搬的家?", collect: true },
}),
}),
});
const accounting = fakeAccounting({
...receiptHandlers,
get_agentic_rectification_case_dossier: () => dossierFor(flipped ? AFTER : BEFORE),
append_agentic_rectification_turn: () => ({ turn_id: TURN_ID }),
finalize_agentic_rectification_turn: () => ({ turn_id: TURN_ID, status: "completed", idempotent: false }),
}, { fallback: () => null });
const flipOn = options.flipOn ?? "rectification-compare-candidates";
const tools = options.tools ?? [{ name: "rectification-compare-candidates" }];
const chunks: Array<{ type: string; payload?: Record<string, unknown> }> = [
{ type: "start" },
{ type: "tool-call", payload: { toolName: "rectification-read-case", args: { caseId: CASE_ID } } },
{ type: "tool-result", payload: { toolName: "rectification-read-case" } },
];
for (const tool of tools) {
chunks.push({ type: "tool-call", payload: { toolName: tool.name, args: { caseId: CASE_ID } } });
chunks.push(tool.failed
? { type: "tool-error", payload: { toolName: tool.name, error: new Error("engine_request_failed") } }
: { type: "tool-result", payload: { toolName: tool.name, result: tool.result ?? {} } });
}
chunks.push({ type: "text-delta", payload: { text: options.body } });
chunks.push({ type: "finish" });
const agent = {
stream: async () => ({
fullStream: (async function* () {
for (const item of chunks) {
if (item.type === "tool-result" && item.payload?.toolName === flipOn) flipped = true;
yield item;
}
})(),
totalUsage: Promise.resolve({ inputTokens: 10, outputTokens: 20 }),
}),
getSkill: async () => ({ name: "jyotish-birth-time-rectification", instructions: "skill" }),
};
const emitted: Array<Record<string, unknown>> = [];
const result = await runV9AgentTurn({
userId: USER_ID,
caseId: CASE_ID,
sessionId: SESSION_ID,
requestId: "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeee1",
action: "evidence",
message: "2016年9月离开家去北京工作",
modelName: "m",
accounting: accounting.client as never,
billing: { reserve: async () => ({ success: true, status: 200 }), complete: async () => true, release: async () => true },
emit: (event) => { emitted.push(event as never); },
buildAgent: async () => agent as never,
});
const finalize = accounting.calls.filter((call) => call.fn === "finalize_agentic_rectification_turn").at(-1);
const persisted = String(finalize?.args.p_assistant_message ?? "");
return { result, emitted, persisted, states: clientStates(emitted) };
}
/** A fact sentence, once shown, must stay in every later client state. */
function assertNeverWithdrawn(states: readonly string[], fact: string) {
const first = states.findIndex((state) => state.includes(fact));
if (first < 0) return;
for (const state of states.slice(first)) {
assert.ok(state.includes(fact), `fact withdrawn after being shown: ${JSON.stringify(states)}`);
}
}
test("BUG-1055 repro 1: two-sentence body keeps the server range sentence, stream ends where persist does", async () => {
const { result, persisted, states } = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作。这件事我拿去和星盘对照了。",
});
assert.equal(result.ok, true);
// Before: the trim kept only the first sentence and the range sentence was cut.
assert.equal(persisted, `记下了:2016 年 9 月去北京工作。这件事我拿去和星盘对照了。${RANGE_SENTENCE}`);
assert.equal(result.answerText, persisted);
assert.equal(states.at(-1), persisted);
assertNeverWithdrawn(states, RANGE_SENTENCE);
});
test("BUG-1055 repro 1b: three-sentence body is trimmed to one, range sentence still whole", async () => {
const { persisted, states } = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作。这件事我拿去和星盘对照了。接下来再对一件事。",
});
assert.equal(persisted, `记下了:2016 年 9 月去北京工作。${RANGE_SENTENCE}`);
assert.equal(states.at(-1), persisted);
assertNeverWithdrawn(states, RANGE_SENTENCE);
});
test("BUG-1055 repro 2: a first sentence carrying the stale range is dropped whole, not persisted", async () => {
const { persisted, states } = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作,目前范围在 04:50–05:10。接下来再对一件事。",
});
// Before: 「记下了:2016 年 9 月去北京工作,目前范围在 04:50–05:10。」was persisted.
assert.doesNotMatch(persisted, /目前范围在 04:50–05:10/);
assert.equal(persisted, `接下来再对一件事。${RANGE_SENTENCE}`);
assert.equal(states.at(-1), persisted);
assertNeverWithdrawn(states, RANGE_SENTENCE);
});
test("BUG-1055: an invented fit rate sentence is dropped; a server fit rate sentence is kept", async () => {
const invented = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作。目前吻合率 90%。",
fitPercent: 80,
});
assert.equal(invented.persisted, `记下了:2016 年 9 月去北京工作。${RANGE_SENTENCE}`);
const grounded = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作。目前吻合率 80%。",
fitPercent: 80,
});
assert.equal(grounded.persisted, `记下了:2016 年 9 月去北京工作。目前吻合率 80%。${RANGE_SENTENCE}`);
});
test("BUG-1055: the post-rescore range and representative minute may be repeated; only mismatches go", async () => {
const kept = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作。代表分钟是 05:02,范围 04:55–05:02。",
});
assert.equal(kept.persisted, `记下了:2016 年 9 月去北京工作。代表分钟是 05:02,范围 04:55–05:02。${RANGE_SENTENCE}`);
});
test("BUG-1055: when the whitelist leaves no model body the batch recap stands in", async () => {
const { persisted } = await runEvidenceTurn({
body: "目前范围 04:50–05:10,吻合率 90%。",
tools: [{
name: "rectification-record-evidence-batch",
result: {
items: [{ index: 0, outcome: "accepted" }],
accepted_recaps: [{ display_date_label: "2016 年 9 月", event_phrase: "去北京工作" }],
accepted_count: 1,
rescore: { status: "completed" },
},
}],
flipOn: "rectification-record-evidence-batch",
});
assert.equal(persisted, `记下了:2016 年 9 月 去北京工作。${RANGE_SENTENCE}`);
});
test("BUG-1055: 这次没有重新比较 survives a multi-sentence body and replaces the range sentence", async () => {
const { persisted, states } = await runEvidenceTurn({
body: "记下了:2016 年 9 月去北京工作。这件事拿去对照了。还有一句。",
tools: [{
name: "rectification-record-evidence-batch",
result: {
items: [{ index: 0, outcome: "accepted" }],
accepted_recaps: [{ display_date_label: "2016 年 9 月", event_phrase: "去北京工作" }],
accepted_count: 1,
rescore: { status: "failed", error_code: "engine_request_failed" },
},
}],
flipOn: "never",
});
assert.equal(persisted, `记下了:2016 年 9 月去北京工作。${RECTIFICATION_USER_COPY.rescoreSkipped}`);
assert.equal(states.at(-1), persisted);
assertNeverWithdrawn(states, RECTIFICATION_USER_COPY.rescoreSkipped);
});
test("BUG-1055: 候选比较这次没跑成 survives a multi-sentence body", async () => {
const { persisted, states } = await runEvidenceTurn({
body: "2016 年 9 月去北京工作这件事拿去对照了。它落在那年的变动里。还有一句。",
tools: [{ name: "rectification-compare-candidates", failed: true }],
flipOn: "never",
});
assert.equal(persisted, `2016 年 9 月去北京工作这件事拿去对照了。\n\n${RECTIFICATION_USER_COPY.compareFailedRetry}`);
assert.equal(states.at(-1), persisted);
assertNeverWithdrawn(states, RECTIFICATION_USER_COPY.compareFailedRetry);
});
test("P3 whitelist is a gate on whole sentences: clocks, ranges and percentages", () => {
const whitelist = spokenFactWhitelist({
credibleRange: ["04:55", "05:02"],
representativeTime: "04:58",
fitPercent: 79.6,
});
assert.deepEqual(whitelist.percents, [80]);
assert.equal(sentenceNumbersGrounded("范围 04:55–05:02。", whitelist), true);
assert.equal(sentenceNumbersGrounded("范围 04:55 到 05:02。", whitelist), true);
assert.equal(sentenceNumbersGrounded("代表分钟 04:58。", whitelist), true);
assert.equal(sentenceNumbersGrounded("吻合率 80%。", whitelist), true);
assert.equal(sentenceNumbersGrounded("吻合率百分之80。", whitelist), true);
assert.equal(sentenceNumbersGrounded("2016 年 9 月入学。", whitelist), true);
assert.equal(sentenceNumbersGrounded("范围 04:50–05:02。", whitelist), false);
assert.equal(sentenceNumbersGrounded("范围 04:55–05:10。", whitelist), false);
assert.equal(sentenceNumbersGrounded("代表分钟 05:00。", whitelist), false);
assert.equal(sentenceNumbersGrounded("吻合率 90%。", whitelist), false);
assert.equal(sentenceNumbersGrounded("吻合率 80.5%。", whitelist), false);
// Whole sentence out; the neighbours stay untouched (no in-sentence deletion).
assert.equal(
dropUngroundedFactSentences("记下了:2016 年入学。范围在 09:00–09:05,吻合率 90%。还有吗", whitelist),
"记下了:2016 年入学。还有吗",
);
assert.equal(dropUngroundedFactSentences("范围在 09:00–09:05。", spokenFactWhitelist({})), "");
});
@@ -0,0 +1,272 @@
/**
* Shared fixtures for TASK-rectification-grounding-20260927.
*
* `rectification-grounding-aa-30min.golden.json` is a real local engine
* response (`runV9CandidateScore` request + response) for a public AA chart
* (Angelina Jolie, 1975-06-04 Los Angeles, 08:54–09:24 search window, three
* public dated events). No private data.
*/
import { readFileSync } from "node:fs";
import {
CASE_ID,
FOCUS_ID,
RESULT_ID,
TURN_ID,
computeFixture,
dossierFixture,
} from "./rectification-v9-test-support.ts";
import { runV9CandidateScore } from "../src/lib/rectification-agentic/v9/engine-client.ts";
import { buildCaseInferenceState } from "../src/lib/rectification-agentic/v9/inference-adapter.ts";
import { requestCandidateIntervals, candidatePositionFields } from "../src/lib/rectification-agentic/core/candidate-window.ts";
import { candidateRangeFingerprint, evidenceLedgerFingerprint, parseV9CaseDossier } from "../src/lib/rectification-agentic/v9/tool-service.ts";
export const AA_GOLDEN = JSON.parse(readFileSync(
new URL("./fixtures/rectification-grounding-aa-30min.golden.json", import.meta.url),
"utf8",
)) as { request: Record<string, unknown> & { events: Array<Record<string, string>> }; response: Record<string, unknown> };
const req = AA_GOLDEN.request as Record<string, unknown> & { events: Array<Record<string, string>> };
export const AA_BASELINE = {
birth_date: req.birth_date,
latitude: req.lat,
longitude: req.lon,
timezone_offset: req.tz,
timezone_id: "America/Los_Angeles",
birth_time_source: "family_vague",
reported_birth_time: "09:09",
active_birth_time: null,
uncertainty_before_minutes: 15,
uncertainty_after_minutes: 15,
birth_place_label: "Los Angeles",
};
const baseRange = { start_time: String(req.start_time), end_time: String(req.end_time) };
export const AA_RANGE = {
...baseRange,
candidate_intervals: requestCandidateIntervals(AA_BASELINE as never, baseRange as never),
};
const VEDASTRO_PASS = {
status: "passed",
can_confirm_exact_minute: false,
event_validation: { search_events_primary_supports_local_winner: true },
minute_sensitive_validation: { status: "passed" },
};
/** Serve the golden engine response (and a passing VedAstro check) to every fetch. */
export function stubGoldenFetch(): () => void {
const previous = globalThis.fetch;
globalThis.fetch = (async (url: unknown) => {
const body = String(url).includes("vedastro") ? VEDASTRO_PASS : AA_GOLDEN.response;
return new Response(JSON.stringify(body), { status: 200 });
}) as typeof fetch;
return () => {
globalThis.fetch = previous;
};
}
export const AA_EVIDENCE_ROWS = req.events.map((event, index) => ({
id: `44444444-4444-4444-8444-44444444444${index}`,
source_turn_id: TURN_ID,
subject: "self",
event_kind: event.event_kind,
domain: event.domain,
occurred_from: event.date_start,
occurred_to: null,
date_precision: event.precision,
summary: event.summary,
status: "confirmed",
supersedes_evidence_id: null,
created_at: "2026-08-12T10:00:06.000Z",
}));
export const AA_TURNS = [
{
id: TURN_ID,
role: "user",
text: "2000 年拿了一个大奖;2014 年 8 月结婚。",
status: "completed",
created_at: "2026-08-12T10:00:00.000Z",
completed_at: "2026-08-12T10:00:05.000Z",
},
{
id: "77777777-7777-4777-8777-777777777771",
role: "assistant",
text: "记下了:2000 年获奖、2014 年 8 月结婚。",
status: "completed",
created_at: "2026-08-12T10:00:06.000Z",
completed_at: "2026-08-12T10:00:07.000Z",
},
];
/** The stored snapshot a real run of the golden case persists (9 candidates). */
export async function buildGoldenLatest() {
const restore = stubGoldenFetch();
try {
process.env.RECTIFICATION_ALGORITHM_VERSION = String(AA_GOLDEN.response.algorithm_version);
process.env.RECTIFICATION_DECISION_POLICY_VERSION = String(AA_GOLDEN.response.decision_policy_version);
const scored = await runV9CandidateScore({
baselineBirthSnapshot: AA_BASELINE,
candidateRange: AA_RANGE as never,
events: req.events,
} as never);
const parsedEvidence = parseV9CaseDossier(dossierFixture({ evidence: AA_EVIDENCE_ROWS }))!.evidence;
const inference = buildCaseInferenceState({
range: baseRange,
candidates: scored.candidates as never,
evidence: parsedEvidence as never,
probes: [],
transitions: scored.windowScan?.transitions as never,
});
const compute = { ...computeFixture({ baselineBirthSnapshot: AA_BASELINE as never }), candidate_range: AA_RANGE };
const latest = {
result_id: RESULT_ID,
candidates: scored.candidates.map((candidate) => ({
...candidatePositionFields(candidate as never),
candidate_id: candidate.candidateId,
time: candidate.time,
rank: candidate.rank,
relative_support: candidate.relativeSupport,
tied_minute_count: candidate.tiedMinuteCount,
...(candidate.clusterTimes ? { cluster_times: candidate.clusterTimes } : {}),
...(candidate.clusterStart ? { cluster_start: candidate.clusterStart } : {}),
...(candidate.clusterEnd ? { cluster_end: candidate.clusterEnd } : {}),
})),
overall_confidence: scored.overallConfidence,
selection_allowed: scored.selectionAllowed,
confirmation_allowed: false,
decision_receipt: { ...scored.decisionReceipt, inference_state: inference },
execution_ledger: scored.executionLedger,
representative_time: scored.representativeTime,
selected_time: null,
selection_kind: null,
evidence_ledger_fingerprint: evidenceLedgerFingerprint(parsedEvidence),
candidate_range_fingerprint: candidateRangeFingerprint(AA_RANGE as never, compute.baseline_profile_fingerprint),
skill_version: "9.0.0",
algorithm_version: scored.algorithmVersion,
event_contract_version: scored.eventContractVersion,
decision_policy_version: scored.policyVersion,
created_at: "2026-08-12T10:05:00.000Z",
invalidated_at: null,
};
return { latest, compute, scored };
} finally {
restore();
}
}
export function setFocusHandler(_fn: string, args: Record<string, unknown>) {
return {
focus: {
id: FOCUS_ID,
case_id: CASE_ID,
question_id: args.p_question_id,
intent: args.p_intent,
target_evidence_id: args.p_target_evidence_id,
target_domain: args.p_target_domain,
target_kind: args.p_target_kind,
expected_answer_schema: args.p_expected_answer_schema,
status: "active",
asked_at: "2026-08-27T00:00:00.000Z",
resolved_at: null,
asked_turn_id: args.p_asked_turn_id ?? null,
},
idempotent: false,
};
}
export type ScriptPart = { text?: string; tool?: { name: string; input: Record<string, unknown> } };
export type ScriptTurn = { parts: ScriptPart[]; finish: string };
export type RecordedCall = { prompt: Array<{ role: string; content: unknown }>; tools: unknown };
/** An AI SDK v2 language model that replays a script and records every prompt it is sent. */
export function scriptedModel(script: ScriptTurn[], onCall?: (callNumber: number) => void) {
const calls: RecordedCall[] = [];
let call = 0;
const next = (options: { prompt: unknown[]; tools?: unknown }) => {
calls.push({ prompt: options.prompt as RecordedCall["prompt"], tools: options.tools });
const turn = script[call] ?? { parts: [{ text: "" }], finish: "stop" };
call += 1;
onCall?.(call);
return turn;
};
const model = {
specificationVersion: "v2",
provider: "fake",
modelId: "fake-rectification",
supportedUrls: {},
async doGenerate(options: { prompt: unknown[]; tools?: unknown }) {
const turn = next(options);
const content = turn.parts.map((part, index) => part.tool
? { type: "tool-call", toolCallId: `g${call}-${index}`, toolName: part.tool.name, input: JSON.stringify(part.tool.input) }
: { type: "text", text: part.text ?? "" });
return { content, finishReason: turn.finish, usage: { inputTokens: 10, outputTokens: 10, totalTokens: 20 }, warnings: [] };
},
async doStream(options: { prompt: unknown[]; tools?: unknown }) {
const turn = next(options);
const id = `t${call}`;
const stream = new ReadableStream({
start(controller) {
controller.enqueue({ type: "stream-start", warnings: [] });
let open = false;
for (const [index, part] of turn.parts.entries()) {
if (part.text !== undefined) {
if (!open) {
controller.enqueue({ type: "text-start", id });
open = true;
}
controller.enqueue({ type: "text-delta", id, delta: part.text });
}
if (part.tool) {
if (open) {
controller.enqueue({ type: "text-end", id });
open = false;
}
controller.enqueue({
type: "tool-call",
toolCallId: `c${call}-${index}`,
toolName: part.tool.name,
input: JSON.stringify(part.tool.input),
});
}
}
if (open) controller.enqueue({ type: "text-end", id });
controller.enqueue({ type: "finish", finishReason: turn.finish, usage: { inputTokens: 10, outputTokens: 10, totalTokens: 20 } });
controller.close();
},
});
return { stream };
},
};
return { model, calls };
}
/** The text a client ends up showing after applying `answer.delta` events in order. */
export function clientStates(events: ReadonlyArray<Record<string, unknown>>): string[] {
let text = "";
const states: string[] = [];
for (const event of events) {
if (event.type !== "answer.delta") continue;
const delta = String(event.text ?? "");
text = event.replace === true ? delta : `${text}${delta}`;
states.push(text);
}
return states;
}
const CJK = /[⺀-鿿豈-﫿 -〿＀-￯]/g;
/**
* Token estimate used for the before/after size tables: one token per CJK
* character (including full-width punctuation) plus one token per four other
* characters. It is an estimate, not a provider tokenizer.
*/
export function estimateTokens(text: string): number {
const cjk = (text.match(CJK) ?? []).length;
return Math.round(cjk + (text.length - cjk) / 4);
}
export function contentText(content: unknown): string {
return typeof content === "string" ? content : JSON.stringify(content);
}
+18 -5
View File
@@ -715,7 +715,11 @@ test("reply regeneration is a separate Jyotisha agent with only read-case access
});
test("set-focus after spoken text does not append a second paragraph", async () => {
const first = "2016 年 9 月去北京工作,记下了。范围收到 05:00 到 05:10。";
// 原值: first 第二句「范围收到 05:00 到 05:10。」。
// 新值: 第二句「这件事拿去和星盘对照了。」。
// 原因: BUG-1055 / P3 起证据轮模型正文里与当轮服务端事实不符的时刻句整句不落库;本夹具无
// 候选快照,05:00–05:10 是手写数字。本用例锁的是 set-focus 之后不接第二段,与数字无关。
const first = "2016 年 9 月去北京工作,记下了。这件事拿去和星盘对照了。";
const second = "2016 年那件事对校正很有帮助,我们再对一下搬家。";
const accounting = fakeAccounting({
...receiptHandlers,
@@ -751,7 +755,11 @@ test("set-focus after spoken text does not append a second paragraph", async ()
});
test("agent-run strips question sentences when this turn owns the focus", async () => {
const body = "范围已经收到,收在 05:00–05:10。你大概哪一年搬过家?有年份就行。";
// 原值: body 首句「范围已经收到,收在 05:00–05:10。」,断言落库与 replace 都等于该句。
// 新值: 首句「2016 年 9 月去北京工作,这件事拿去和星盘对照。」,断言同样等于首句。
// 原因: BUG-1055 / P3:本夹具没有候选快照,05:00–05:10 不是服务端事实,整句会被数字白名单
// 丢弃。本用例锁的是「本轮拥有焦点时剪掉问句」,换成不带时刻的首句后剪问句断言不变。
const body = "2016 年 9 月去北京工作,这件事拿去和星盘对照。你大概哪一年搬过家?有年份就行。";
const stem = "你大概是哪一年搬的家?";
const collectDossier = dossierFixture({
conversationSummary: conversationSummaryFixture({
@@ -782,11 +790,11 @@ test("agent-run strips question sentences when this turn owns the focus", async
});
const result = await runV9AgentTurn(options);
assert.equal(result.ok, true);
assert.equal(result.answerText, "范围已经收到,收在 05:00–05:10。");
assert.equal(result.answerText, "2016 年 9 月去北京工作,这件事拿去和星盘对照。");
const replaced = emitted.find((event) => (
event.type === "answer.delta" && (event as { replace?: unknown }).replace === true
)) as { text?: string } | undefined;
assert.equal(replaced?.text, "范围已经收到,收在 05:00–05:10。");
assert.equal(replaced?.text, "2016 年 9 月去北京工作,这件事拿去和星盘对照。");
});
test("agent-run uses collectHandoff when the owned-focus body is only a question", async () => {
@@ -927,6 +935,9 @@ test("delivery persist keeps three sentences when the model writes four", async
next_action: "ready_to_adopt",
stop_reason: "probe_pool_exhausted",
can_adopt: true,
// 原值: 无 event_fit_rate。新值: 8/10、80%。原因: BUG-1055 / P3 数字白名单只放行当轮
// 服务端事实;交付句里的「吻合率 80%」需要回执里真有这个吻合率才落库。
event_fit_rate: { matched: 8, total: 10, percent: 80, band: "high" },
},
}),
evidence: [
@@ -978,8 +989,10 @@ test("delivery persist keeps three sentences when the model writes four", async
append_agentic_rectification_turn: () => ({ turn_id: TURN_ID }),
finalize_agentic_rectification_turn: () => ({ turn_id: TURN_ID, status: "completed", idempotent: false }),
});
// 原值: 首句「目前范围 04:49–04:53。」。新值: 「代表分钟是 05:02。」。原因: BUG-1055 / P3,
// 本夹具的服务端范围与代表分钟都是 05:02,04:49–04:53 是手写数字,会整句不落库。
const four = [
"目前范围 04:49–04:53。",
"代表分钟是 05:02。",
"对照了 8 件经历,事件吻合率 80%。",
"这只是代表性候选,不是已确认的唯一出生分钟。",
"还可以再看一眼分盘。",