diff --git a/docs/design/2026-12-04-context-claim-recovery.md b/docs/design/2026-12-04-context-claim-recovery.md new file mode 100644 index 00000000..803e7007 --- /dev/null +++ b/docs/design/2026-12-04-context-claim-recovery.md @@ -0,0 +1,22 @@ +# Agent 上下文证据引用纠错 + +适用于执行态的上下文声明。证据不存在、已失效,或依赖声明已失效时,运行时拒绝本批声明,可以在同一次任务里重新确认依据。 + +## 行为 + +- 首次拒绝后,整次运行最多再请求模型两轮。普通工具调用、空声明和无进展的回答都会占用这两轮,成功登记修正后的声明也不会返还已用额度。调用者配置不限轮数时,此额度仍然生效。 +- 取消、新输入和实际并发或存储故障走既有处理路径。常规任务预算先耗尽时保留原有停止原因。纠错不能使用为普通工具回执预留的追加轮次。 +- 引用被拒绝就撤回当轮草稿,清掉待拼接正文,保留已经确认的证据和已经执行的工具结果。同批被拦下的工具只产生内部回执。 +- 后续模型请求携带配对的工具调用与拒绝回执,工具入参使用空声明,错误回执包含原因和最多三个相关编号。纠错消息只在当前运行有待修正时存在。 +- 改正后恢复正常完成校验。额度用尽时由运行时结束,用户只看到「没能确认完成任务所需的依据」,没有未经校验的回答。只读路径沿用原有处理方式。 + +## 验收 + +| 场景 | 预期 | +| -------------------------------- | ------------------------------------------------------ | +| 首次登记或修正成功 | 已执行工具只跑一次,最终回复仍经过完成校验 | +| 连续三次提交无效引用 | 第三次失败后停止,失败正文和被拦操作的回执没有公开输出 | +| 穿插工具结果、空声明或无进展回复 | 已完成结果保留,两轮额度继续累计 | +| 上下文窗口接近上限 | 回执保持配对,省去原声明,下一轮可准备 | +| 常规任务预算提前触顶 | 保留原停止原因,结果给出通用说明 | +| 取消、新请求、真实存储或并发错误 | 优先沿用原有处理路径 | diff --git a/packages/core/src/agent/moss-agent.ts b/packages/core/src/agent/moss-agent.ts index c06f7bdb..d3f37fc8 100644 --- a/packages/core/src/agent/moss-agent.ts +++ b/packages/core/src/agent/moss-agent.ts @@ -2649,9 +2649,12 @@ ${result.stderr ?? ''}`.trim(); { sessionKey, runId: `${runId}:compact` }, (usage) => versionedStore.recordSummaryUsage(sessionKey, runId, usage) ), - ...(extraContext - ? { ephemeral: [{ role: 'user', timestamp: Date.now(), content: extraContext }] } - : {}), + ephemeral: [ + ...(input.ephemeral ?? []), + ...(extraContext + ? [{ role: 'user' as const, timestamp: Date.now(), content: extraContext }] + : []), + ], }); input.repairSignal?.throwIfAborted(); contextGeneration = projection.revision; diff --git a/packages/core/src/loop/agent-loop-compaction.ts b/packages/core/src/loop/agent-loop-compaction.ts index 9eb7e1bc..d9d0a538 100644 --- a/packages/core/src/loop/agent-loop-compaction.ts +++ b/packages/core/src/loop/agent-loop-compaction.ts @@ -10,7 +10,7 @@ import { runWithCompactionPrepareTimeout, } from './compaction-timeout.js'; import { notifyReadContextDropped } from '@rdk-moss/context/read-context-events.js'; -import type { AgentLoopLlmUsage } from './agent-loop-types.js'; +import type { AgentLoopDeps } from './agent-loop-types.js'; /** Distinct tool names across tool_use blocks (summary quality signal). */ function countDistinctToolNames(messages: Message[]): number { @@ -32,25 +32,7 @@ function countDistinctToolNames(messages: Message[]): number { return names.size; } -export interface AgentLoopPrepareCompaction { - (params: { - messages: Message[]; - sessionKey: string; - runId: string; - forceCompaction?: boolean; - includeThinking?: boolean; - /** Retry path only: skip the LLM summarizer and use the local deterministic one. */ - skipLlmCompaction?: boolean; - abortSignal?: AbortSignal; - }): Promise<{ - summary?: string; - summaryMessage?: Message; - messages?: Message[]; - droppedMessages?: number; - checkpointOutline?: string[]; - usage?: AgentLoopLlmUsage[]; - }>; -} +export type AgentLoopPrepareCompaction = AgentLoopDeps['prepareCompaction']; export interface AgentLoopCompactionOutcome { attempted: boolean; @@ -61,7 +43,7 @@ export interface AgentLoopCompactionOutcome { degraded?: boolean; } -interface CompactionCoreParams { +interface CompactionInput { sessionKey: string; runId: string; currentMessages: Message[]; @@ -71,11 +53,12 @@ interface CompactionCoreParams { push: (event: MiniAgentEvent) => void; onWarn?: (message: string, meta: Record) => void; abortSignal?: AbortSignal; + includeThinking?: boolean; +} +interface CompactionCoreParams extends CompactionInput { forceCompaction?: boolean; - includeThinking?: boolean; - hookReason: 'proactive' | 'overflow'; computeStats: (prep: { summary: string; summaryMessage: Message; droppedMessages?: number }) => { @@ -125,9 +108,8 @@ async function runCompactionCore( // as degraded so the transcript says the summary is not the LLM's. let degraded = false; const prepareStartedAt = Date.now(); - let prep: Awaited>; - try { - prep = await runWithCompactionPrepareTimeout( + const prepare = (skipLlmCompaction?: true) => + runWithCompactionPrepareTimeout( (prepareAbortSignal) => prepareCompaction({ messages: currentMessages, @@ -135,10 +117,14 @@ async function runCompactionCore( runId, forceCompaction, includeThinking, + ...(skipLlmCompaction ? { skipLlmCompaction } : {}), abortSignal: prepareAbortSignal, }), - { abortSignal, label: errorLabel } + { abortSignal, label: skipLlmCompaction ? `${errorLabel}-deterministic` : errorLabel } ); + let prep: Awaited>; + try { + prep = await prepare(); } catch (error) { if (!isCompactionPrepareTimeout(error) || abortSignal?.aborted) throw error; const timeoutMs = resolveCompactionPrepareTimeoutMs(); @@ -151,19 +137,7 @@ async function runCompactionCore( sessionKey, }); degraded = true; - prep = await runWithCompactionPrepareTimeout( - (prepareAbortSignal) => - prepareCompaction({ - messages: currentMessages, - sessionKey, - runId, - forceCompaction, - includeThinking, - skipLlmCompaction: true, - abortSignal: prepareAbortSignal, - }), - { abortSignal, label: `${errorLabel}-deterministic` } - ); + prep = await prepare(true); } const checkpointOutline = @@ -278,20 +252,12 @@ async function runCompactionCore( } } -export async function runProactiveWindowCompaction(params: { - sessionKey: string; - runId: string; - currentMessages: Message[]; - rawTotalChars: number; - promptUnitsForWindow: number; - prepareCompaction: AgentLoopPrepareCompaction; - compactHooks?: CompactHookRegistry; - persistCurrentMessages: (messages?: Message[]) => Promise; - push: (event: MiniAgentEvent) => void; - onWarn?: (message: string, meta: Record) => void; - abortSignal?: AbortSignal; - includeThinking?: boolean; -}): Promise { +export async function runProactiveWindowCompaction( + params: CompactionInput & { + rawTotalChars: number; + promptUnitsForWindow: number; + } +): Promise { const { rawTotalChars, promptUnitsForWindow } = params; return runCompactionCore({ ...params, @@ -313,19 +279,11 @@ export async function runProactiveWindowCompaction(params: { }); } -export async function runPromptPruneCompaction(params: { - sessionKey: string; - runId: string; - currentMessages: Message[]; - droppedMessagesForStats: Message[]; - prepareCompaction: AgentLoopPrepareCompaction; - compactHooks?: CompactHookRegistry; - persistCurrentMessages: (messages?: Message[]) => Promise; - push: (event: MiniAgentEvent) => void; - onWarn?: (message: string, meta: Record) => void; - abortSignal?: AbortSignal; - includeThinking?: boolean; -}): Promise { +export async function runPromptPruneCompaction( + params: CompactionInput & { + droppedMessagesForStats: Message[]; + } +): Promise { const { droppedMessagesForStats } = params; return runCompactionCore({ ...params, diff --git a/packages/core/src/loop/agent-loop-context-prep.ts b/packages/core/src/loop/agent-loop-context-prep.ts index 9652e37e..f1ac63b1 100644 --- a/packages/core/src/loop/agent-loop-context-prep.ts +++ b/packages/core/src/loop/agent-loop-context-prep.ts @@ -7,7 +7,7 @@ import type { CompactHookRegistry } from './compact-hooks.js'; import type { ContextPruningSettings, PruneResult } from '@rdk-moss/context/pruning.js'; import type { AgentLoopMutableState } from './agent-loop-state.js'; import type { AgentLoopCompactionOutcome } from './agent-loop-compaction.js'; -import type { AgentLoopLlmUsage } from './agent-loop-types.js'; +import type { AgentLoopDeps } from './agent-loop-types.js'; import { estimateMessageChars, estimateMessageTokens, @@ -214,22 +214,7 @@ export interface PrepareTurnContextParams { getToolsForRun: () => Tool[]; sessionKey: string; runId: string; - prepareCompaction: (params: { - messages: Message[]; - sessionKey: string; - runId: string; - forceCompaction?: boolean; - includeThinking?: boolean; - skipLlmCompaction?: boolean; - abortSignal?: AbortSignal; - }) => Promise<{ - summary?: string; - summaryMessage?: Message; - messages?: Message[]; - droppedMessages?: number; - checkpointOutline?: string[]; - usage?: AgentLoopLlmUsage[]; - }>; + prepareCompaction: AgentLoopDeps['prepareCompaction']; compactHooks?: CompactHookRegistry; persistCurrentMessages: (messages?: Message[]) => Promise; push: (event: MiniAgentEvent) => void; @@ -299,7 +284,7 @@ export async function prepareTurnContext( toolOrderChecks: 0, toolOrderChanges: 0, }; - const pendingToolResultFollowUp = lastMessageEndsWithToolResult(currentMessages); + const pendingToolResultFollowUp = lastMessageNeedsToolFollowUpLlm(currentMessages); const includeThinkingInBudget = shouldIncludeThinkingInBudget(currentMessages, modelDef); let estPromptTokens = estimatePromptUnitsForContextWindow({ @@ -564,7 +549,7 @@ export async function prepareTurnContext( }; } -function lastMessageEndsWithToolResult(messages: Message[]): boolean { +export function lastMessageNeedsToolFollowUpLlm(messages: Message[]): boolean { const last = messages[messages.length - 1]; if (!last || last.role !== 'user') return false; const c = last.content; diff --git a/packages/core/src/loop/agent-loop-llm-call.ts b/packages/core/src/loop/agent-loop-llm-call.ts index 215aba0a..5c3ee92b 100644 --- a/packages/core/src/loop/agent-loop-llm-call.ts +++ b/packages/core/src/loop/agent-loop-llm-call.ts @@ -17,7 +17,7 @@ import { totalPromptTokens } from '@rdk-moss/ai/llm/usage.js'; import { runAgentLoopLlmTurn } from './agent-loop-stream-helpers.js'; import { runOverflowRecovery } from './overflow-recovery.js'; import type { LoopControlSignal } from './agent-loop-context-prep.js'; -import type { AgentLoopLlmUsage } from './agent-loop-types.js'; +import type { AgentLoopDeps } from './agent-loop-types.js'; export interface ExecuteLlmTurnParams { state: AgentLoopMutableState; @@ -39,22 +39,7 @@ export interface ExecuteLlmTurnParams { runStartMs: number; push: (event: MiniAgentEvent) => void; currentMessages: Message[]; - prepareCompaction: (params: { - messages: Message[]; - sessionKey: string; - runId: string; - forceCompaction?: boolean; - includeThinking?: boolean; - skipLlmCompaction?: boolean; - abortSignal?: AbortSignal; - }) => Promise<{ - summary?: string; - summaryMessage?: Message; - messages?: Message[]; - droppedMessages?: number; - checkpointOutline?: string[]; - usage?: AgentLoopLlmUsage[]; - }>; + prepareCompaction: AgentLoopDeps['prepareCompaction']; replaceMessages?: (sessionKey: string, messages: Message[]) => Promise; compactHooks?: CompactHookRegistry; lastMessageNeedsToolFollowUpLlm: (messages: Message[]) => boolean; diff --git a/packages/core/src/loop/agent-loop-response.ts b/packages/core/src/loop/agent-loop-response.ts index 6644376a..be217988 100644 --- a/packages/core/src/loop/agent-loop-response.ts +++ b/packages/core/src/loop/agent-loop-response.ts @@ -1,12 +1,9 @@ import type { StopReason } from '@rdk-moss/ai/provider/pi-ai-types.js'; import type { MiniAgentEvent } from './agent-events.js'; import type { ContentBlock, Message } from '@rdk-moss/contracts/messages.js'; -import type { Tool, ToolContext } from '../tools/tool-types.js'; -import type { ToolHookRegistry } from '../tools/tool-hooks.js'; -import type { AgentLoopMutableState } from './agent-loop-state.js'; -import type { ToolLoopGuardState } from '../tools/tool-loop-guard.js'; +import { MAX_CLAIM_RECOVERY_TURNS } from './agent-loop-state.js'; import type { LoopControlSignal } from './agent-loop-context-prep.js'; -import type { AgentLoopExtensions } from './agent-loop-types.js'; +import type { AgentLoopExtensions, AgentLoopToolInput } from './agent-loop-types.js'; import { normalizeAssistantToolCalls, isThinkingOnlyAssistantTurn, @@ -24,8 +21,10 @@ import { isOutputLimitStopReason, stitchTruncatedOutput, } from './output-limit.js'; -import { executeAgentLoopToolCalls } from './agent-loop-tool-execution.js'; -import type { PendingToolAbortStore } from './pending-tool-aborts.js'; +import { + executeAgentLoopToolCalls, + type ExecuteAgentLoopToolCallsParams, +} from './agent-loop-tool-execution.js'; import type { TaskIntentTurn } from '../session/task-intent-turn.js'; import { validateToolInputObject } from '../tools/tool-pipeline.js'; @@ -48,7 +47,14 @@ function replaceAssistantVisibleText(content: ContentBlock[], text: string): voi content.splice(0, content.length, ...next); } -export interface ProcessLlmResponseParams { +export interface ProcessLlmResponseParams extends Omit< + ExecuteAgentLoopToolCallsParams, + | 'initialToolResults' + | 'assertExecutionCurrent' + | 'registerToolInvocation' + | 'turnIndex' + | 'metrics' +> { taskIntentTurn?: TaskIntentTurn; assertContextCurrent?: () => void; registerToolInvocation?( @@ -57,11 +63,7 @@ export interface ProcessLlmResponseParams { mutates: boolean, assertIntent: () => void ): () => void; - state: AgentLoopMutableState; - runId: string; - assistantContent: ContentBlock[]; messageThinkingChunks: string[]; - toolCalls: { id: string; name: string; input: Record }[]; turnTextParts: string[]; streamStopReason: StopReason | undefined; /** Gateway-reported model for this turn, recorded on the assistant message. */ @@ -71,53 +73,13 @@ export interface ProcessLlmResponseParams { modelId?: string; maxTurns: number | null; maxOutputContinuations: number; - abortSignal: AbortSignal; - sessionKey: string; - currentMessages: Message[]; - assistantBuffer: Message[]; - resolveToolsForRun: () => Tool[]; - toolCtx: ToolContext; - toolHooks?: ToolHookRegistry; - toolTimeoutMs: number; - toolHeartbeatIntervalMs: number; - skipHeartbeatToolNames: Set; - parallelSafeTools: Set; - loadToolsMetaName?: string; - toolLoopGuard: ToolLoopGuardState; - maxToolCalls?: number; - toolStartGuard?: AgentLoopExtensions['toolStartGuard']; - runtimeJudge?: AgentLoopExtensions['runtimeJudge']; - prepareToolBatch?: import('./agent-loop-types.js').AgentLoopToolInput['prepareToolBatch']; - checkToolApproval?: (call: { - id: string; - name: string; - input: unknown; - abortSignal: AbortSignal; - tool?: Tool; - }) => Promise<{ - approved: boolean; - decision: string; - updatedInput?: Record; - } | null>; - guardAssistantOutput?: (request: { - sessionKey: string; - runId: string; - turn: number; - response: string; - stopReason?: string; - }) => Promise< - { approved: true; response?: string } | { approved: false; reason: string; response?: string } - >; + prepareToolBatch?: AgentLoopToolInput['prepareToolBatch']; + guardAssistantOutput?: AgentLoopExtensions['guardAssistantOutput']; completionGate?: AgentLoopExtensions['completionGate']; delayedVisibleDeltas?: boolean; settleTextDraft?: (accepted: boolean) => void; - toolAbortSignalFor?: (toolCallId: string) => AbortSignal | undefined; - enrichToolContext?: (baseCtx: ToolContext, sessionKey: string) => ToolContext; - appendMessage: (sessionKey: string, msg: Message) => Promise; - push: (event: MiniAgentEvent) => void; buildCorrectionMessage: (systemText: string) => Message; - pendingToolAborts: PendingToolAbortStore; } export interface ProcessLlmResponseResult { @@ -185,6 +147,7 @@ export async function processLlmResponse( state.lastTurnEndMs = Date.now(); }; const retrySuperseded = (instruction: string): ProcessLlmResponseResult => { + state.claimRecovery = undefined; state.finalText = ''; state.hasMoreToolCalls = true; state.pendingMessages = [buildCorrectionMessage(instruction)]; @@ -210,6 +173,7 @@ export async function processLlmResponse( ) ); if (intentResponse?.retry || intentResponse?.superseded) { + if (intentResponse.superseded) state.claimRecovery = undefined; const repair = params.taskIntentTurn?.repair; const exhausted = Boolean(repair?.exhausted); state.hasMoreToolCalls = !exhausted; @@ -225,6 +189,45 @@ export async function processLlmResponse( return { control: 'continue' }; } + const claim = intentResponse?.claim; + if (claim === 'recorded' || intentResponse?.hold) { + state.claimRecovery = undefined; + } else if (claim) { + const { id, name, message } = claim; + const timestamp = Date.now(); + state.claimRecovery = [ + { + role: 'assistant', + timestamp, + content: [{ type: 'tool_use', id, name, input: { claims: [] } }], + }, + { + role: 'user', + timestamp, + content: [{ type: 'tool_result', tool_use_id: id, is_error: true, content: message }], + }, + ]; + } + const results = intentResponse?.results ?? []; + const recoveringClaim = Boolean(state.claimRecovery); + if (recoveringClaim) { + state.finalText = ''; + state.carriedAssistantText = ''; + turnTextParts.length = 0; + replaceAssistantVisibleText(assistantContent, ''); + if (state.claimRecoveryTurns >= MAX_CLAIM_RECOVERY_TURNS) { + for (const { id } of toolCalls.splice(0)) { + results.push({ + type: 'tool_result', + tool_use_id: id, + is_error: true, + outcome: 'suppressed', + content: 'Not executed: context claim recovery did not complete.', + }); + } + } + } + const plainReply = intentResponse?.plainReply; const truncatedToolCall = outputLimited && toolCalls.length > 0; if (plainReply || truncatedToolCall) { @@ -268,7 +271,7 @@ export async function processLlmResponse( ...(outputLimited ? { outputLimit: 'truncated' as const } : {}), }; - if (!hasThinkingOnly) { + if (!hasThinkingOnly && (!recoveringClaim || assistantContent.length)) { assistantBuffer.push(assistantMsg); } @@ -284,7 +287,7 @@ export async function processLlmResponse( if (!delayedVisibleDeltas && !state.carriedAssistantText) { visibleAssistantText = visibleAssistantText.trimStart(); } - if (guardAssistantOutput && !hasThinkingOnly) { + if (guardAssistantOutput && !hasThinkingOnly && !recoveringClaim) { let decision: | { approved: true; response?: string } | { approved: false; reason: string; response?: string }; @@ -317,7 +320,16 @@ export async function processLlmResponse( visibleAssistantText ); state.hasMoreToolCalls = toolCalls.length > 0; - const canComplete = plainReply !== 'pending' && !state.hasMoreToolCalls && !outputLimited; + const continueAfterIntentResults = Boolean( + intentResponse?.results.length && !intentResponse.hold && !state.hasMoreToolCalls + ); + // These receipts still need a model turn, even when rejected calls left visible text. + const canComplete = + plainReply !== 'pending' && + !state.hasMoreToolCalls && + !outputLimited && + !continueAfterIntentResults && + !recoveringClaim; if (!state.hasMoreToolCalls && stitchedAssistantText.trim()) { state.finalText = stitchedAssistantText; } @@ -391,11 +403,11 @@ export async function processLlmResponse( if (!state.ports.taskGuard.isSuperseded(error)) throw error; if (plainReply && assistantBuffer.at(-1) === assistantMsg) assistantBuffer.pop(); await flushBuffered(); - const results: Message = { + const supersededResults: Message = { role: 'user', timestamp: Date.now(), content: [ - ...(intentResponse?.results ?? []), + ...results, ...toolCalls.map( (call): ContentBlock => ({ type: 'tool_result', @@ -408,14 +420,15 @@ export async function processLlmResponse( ), ], }; - if (Array.isArray(results.content) && results.content.length) await persistMessage(results); + if (Array.isArray(supersededResults.content) && supersededResults.content.length) + await persistMessage(supersededResults); return retrySuperseded( '[Runtime] A newer user input superseded the response. Process the latest pending input before continuing.' ); } - if (toolCalls.length === 0 && intentResponse?.results.length) { + if (toolCalls.length === 0 && results.length) { await flushBuffered(); - await persistMessage({ role: 'user', content: intentResponse.results, timestamp: Date.now() }); + await persistMessage({ role: 'user', content: results, timestamp: Date.now() }); try { params.taskIntentTurn?.assertCurrent(true); } catch (error) { @@ -425,7 +438,7 @@ export async function processLlmResponse( ); } } - params.settleTextDraft?.(!outputLimited && !hasThinkingOnly); + params.settleTextDraft?.(!outputLimited && !hasThinkingOnly && !recoveringClaim); if (delayedVisibleDeltas && !hasThinkingOnly) { pushGuardedMessageDeltas(push, visibleAssistantText); } @@ -436,7 +449,13 @@ export async function processLlmResponse( ...(streamStopReason ? { stopReason: streamStopReason } : {}), }); - if (intentResponse?.results.length && !intentResponse.hold && toolCalls.length === 0) { + if (recoveringClaim && !toolCalls.length) { + state.hasMoreToolCalls = true; + pushTurnEnd(); + return { control: 'continue' }; + } + + if (continueAfterIntentResults) { state.finalText = ''; state.hasMoreToolCalls = true; state.pendingMessages = [ diff --git a/packages/core/src/loop/agent-loop-state.ts b/packages/core/src/loop/agent-loop-state.ts index 78a0f9b0..b6d18242 100644 --- a/packages/core/src/loop/agent-loop-state.ts +++ b/packages/core/src/loop/agent-loop-state.ts @@ -4,10 +4,14 @@ import type { OverflowRecoveryState } from './overflow-recovery.js'; import { createOverflowRecoveryState } from './overflow-recovery.js'; import type { AgentLoopToolExecutionMetrics } from './agent-loop-tool-execution.js'; +export const MAX_CLAIM_RECOVERY_TURNS = 2; + export interface AgentLoopMutableState { /** Product services the engine calls; fixed for the run. */ readonly ports: LoopPorts; taskIntentHalted?: boolean; + claimRecovery?: Message[]; + claimRecoveryTurns: number; suspendedTool?: import('../tools/tool-suspension.js').SuspendedToolCall; taskWaitTimeout?: import('../tools/task-observation.js').ToolWaitTimeout; turns: number; @@ -65,6 +69,7 @@ export function createInitialLoopState(ports: LoopPorts): AgentLoopMutableState return { ports, turns: 0, + claimRecoveryTurns: 0, compactionRetries: 0, outputContinuationCount: 0, carriedAssistantText: '', diff --git a/packages/core/src/loop/agent-loop-tool-execution.ts b/packages/core/src/loop/agent-loop-tool-execution.ts index c8902309..9eedb86b 100644 --- a/packages/core/src/loop/agent-loop-tool-execution.ts +++ b/packages/core/src/loop/agent-loop-tool-execution.ts @@ -7,7 +7,7 @@ import type { ExecuteToolCallDeps } from '../tools/execute-tool-call.js'; import { maybeSuppressRedundantWebFetchAfterOpenUrl } from '../tools/open-url-web-fetch-guard.js'; import type { PendingToolAbortStore } from './pending-tool-aborts.js'; import type { AgentLoopMutableState } from './agent-loop-state.js'; -import type { LoopPorts } from './agent-loop-types.js'; +import type { AgentLoopToolInput, LoopPorts } from './agent-loop-types.js'; import type { Message, ContentBlock } from '@rdk-moss/contracts/messages.js'; import type { Tool, ToolContext, ToolResultOutcome } from '../tools/tool-types.js'; import type { ToolHookRegistry } from '../tools/tool-hooks.js'; @@ -71,18 +71,7 @@ export interface ExecuteAgentLoopToolCallsParams { toolTimeoutMs: number; toolHeartbeatIntervalMs: number; skipHeartbeatToolNames: Set; - checkToolApproval?: (call: { - id: string; - name: string; - input: unknown; - abortSignal: AbortSignal; - tool?: Tool; - }) => Promise<{ - approved: boolean; - decision: string; - reason?: string; - updatedInput?: Record; - } | null>; + checkToolApproval?: AgentLoopToolInput['checkToolApproval']; toolStartGuard?: ExecuteToolCallDeps['toolStartGuard']; runtimeJudge?: RuntimeJudgeRun; buildCorrectionMessage?: (text: string) => Message; diff --git a/packages/core/src/loop/agent-loop-types.ts b/packages/core/src/loop/agent-loop-types.ts index 0b25304b..efffaa39 100644 --- a/packages/core/src/loop/agent-loop-types.ts +++ b/packages/core/src/loop/agent-loop-types.ts @@ -135,6 +135,7 @@ export interface AgentLoopExtensions { window: number; output: number; measure(messages: Message[], output: number): number; + ephemeral?: Message[]; force?: boolean; repairSignal?: AbortSignal; }) => Promise; diff --git a/packages/core/src/loop/agent-loop.ts b/packages/core/src/loop/agent-loop.ts index 3649bfc4..9b6a95a1 100644 --- a/packages/core/src/loop/agent-loop.ts +++ b/packages/core/src/loop/agent-loop.ts @@ -36,8 +36,13 @@ import { } from '@rdk-moss/ai/llm/prompt-prefix-cache.js'; import { createToolLoopGuardState } from '../tools/tool-loop-guard.js'; import type { AgentLoopHardCaps, TurnEngineParams } from './agent-loop-types.js'; -import { createInitialLoopState, resetIterationState } from './agent-loop-state.js'; import { + createInitialLoopState, + MAX_CLAIM_RECOVERY_TURNS, + resetIterationState, +} from './agent-loop-state.js'; +import { + lastMessageNeedsToolFollowUpLlm, prepareProjectionWire, prepareTurnContext, shouldIncludeThinkingInBudget, @@ -96,15 +101,7 @@ export function resolveEffectiveCaps(hardCaps?: AgentLoopHardCaps) { }; } -export function lastMessageNeedsToolFollowUpLlm(messages: Message[]): boolean { - const last = messages[messages.length - 1]; - if (!last || last.role !== 'user') return false; - const c = last.content; - if (!Array.isArray(c)) return false; - return c.some( - (b) => b && typeof b === 'object' && (b as { type?: string }).type === 'tool_result' - ); -} +export { lastMessageNeedsToolFollowUpLlm }; /** * B240: every harness correction buys another model turn. Without a rule, that @@ -302,8 +299,15 @@ export function runTurnEngine( ? state.outputTokenBudget : (maxOutputTokensParam ?? modelDef.maxTokens ?? 8192); - const publishTurnStop = (reason: string) => + const publishTurnStop = (reason: string) => { + if (state.claimRecovery && reason !== 'aborted_by_user') { + state.finalText = uiText( + 'I could not verify the evidence needed to finish.', + '没能确认完成任务所需的依据。' + ); + } stream.push({ type: 'turn_transition', turn: state.turns, reason }); + }; try { // Grok TaskCompletionReminder parity: ensure lifecycle events queue @@ -385,10 +389,14 @@ export function runTurnEngine( } if (getSteeringMessages && !repair) { const steeringMessages = await getSteeringMessages(); - if (steeringMessages.length > 0) state.pendingMessages.push(...steeringMessages); + if (steeringMessages.length > 0) { + state.claimRecovery = undefined; + state.pendingMessages.push(...steeringMessages); + } } if (maxTurns !== null && state.turns >= maxTurns) { - const needsToolFollow = !repair && lastMessageNeedsToolFollowUpLlm(currentMessages); + const needsToolFollow = + !repair && !state.claimRecovery && lastMessageNeedsToolFollowUpLlm(currentMessages); if (needsToolFollow && state.postLimitToolFollowUpsUsed < toolFollowupBypassCap) { state.postLimitToolFollowUpsUsed += 1; } else { @@ -415,6 +423,10 @@ export function runTurnEngine( publishTurnStop(budgetBreach); break outerLoop; } + if (state.claimRecovery && state.claimRecoveryTurns >= MAX_CLAIM_RECOVERY_TURNS) { + publishTurnStop('budget_context_claim_recovery_reached'); + break outerLoop; + } // After steering, bind tools and the prompt to the same snapshot. repair?.assertCurrent(); @@ -469,6 +481,7 @@ export function runTurnEngine( output: maxOut, force: projectionOverflowRetries > 0, repairSignal, + ephemeral: state.claimRecovery, measure: (messages) => { const context = wire(messages); return estimatePromptUnitsForContextWindow({ @@ -551,6 +564,7 @@ export function runTurnEngine( projectionRevision !== undefined && params.assertContextRevision && !bufferOutput && + !state.claimRecovery && !state.carriedAssistantText && (!intent || (!intent.needsDecision && intent.bindingSnapshot()?.disposition === 'execute')) @@ -565,6 +579,7 @@ export function runTurnEngine( abortSignal ); } + if (state.claimRecovery) state.claimRecoveryTurns++; const llmResult = await executeLlmTurn({ reasoningBudget: params.reasoningBudget, modelTiers: params.modelTiers, @@ -704,7 +719,10 @@ export function runTurnEngine( if (getSteeringMessages && !params.taskIntentTurn?.repair) { const steeringMessages = await getSteeringMessages(); - if (steeringMessages.length > 0) state.pendingMessages.push(...steeringMessages); + if (steeringMessages.length > 0) { + state.claimRecovery = undefined; + state.pendingMessages.push(...steeringMessages); + } } if (responseResult.control === 'continue') { diff --git a/packages/core/src/loop/overflow-recovery.ts b/packages/core/src/loop/overflow-recovery.ts index 509442ce..16c11235 100644 --- a/packages/core/src/loop/overflow-recovery.ts +++ b/packages/core/src/loop/overflow-recovery.ts @@ -11,7 +11,7 @@ import { estimateMessagesChars, estimateMessagesTokens } from '@rdk-moss/context import { describeError } from '@rdk-moss/ai/provider/errors.js'; import { getRootLogger } from '@rdk-moss/foundation/logger.js'; import { runWithCompactionPrepareTimeout } from './compaction-timeout.js'; -import type { AgentLoopLlmUsage } from './agent-loop-types.js'; +import type { AgentLoopDeps } from './agent-loop-types.js'; const log = getRootLogger().child('agent:overflow'); @@ -189,21 +189,7 @@ export interface OverflowRecoveryParams { currentMessages: Message[]; sessionKey: string; runId: string; - prepareCompaction: (params: { - messages: Message[]; - sessionKey: string; - runId: string; - forceCompaction?: boolean; - skipLlmCompaction?: boolean; - abortSignal?: AbortSignal; - }) => Promise<{ - summary?: string; - summaryMessage?: Message; - messages?: Message[]; - droppedMessages?: number; - checkpointOutline?: string[]; - usage?: AgentLoopLlmUsage[]; - }>; + prepareCompaction: AgentLoopDeps['prepareCompaction']; replaceMessages?: (sessionKey: string, messages: Message[]) => Promise; compactHooks?: CompactHookRegistry; push: (event: MiniAgentEvent) => void; diff --git a/packages/core/src/session/context-claim-declaration.ts b/packages/core/src/session/context-claim-declaration.ts index 0c9c94c4..b9487b9f 100644 --- a/packages/core/src/session/context-claim-declaration.ts +++ b/packages/core/src/session/context-claim-declaration.ts @@ -1,4 +1,21 @@ import type { ContextClaimDraft } from '@rdk-moss/contracts/versioned-context.js'; +import { ErrorCode, MossError } from '@rdk-moss/foundation/errors.js'; + +/** A rejected model citation, distinct from a concurrent context change or storage failure. */ +export class ContextClaimRejection extends MossError { + constructor( + readonly reason: 'missing_source' | 'invalidated_source' | 'inactive_dependency', + readonly ids: string[] + ) { + super({ + code: ErrorCode.EXECUTION_REVISION_CONFLICT, + message: 'Claim refers to a missing or invalidated source', + source: 'runtime', + recoverable: true, + }); + this.name = 'ContextClaimRejection'; + } +} export const CONTEXT_CLAIMS_TOOL = 'context_claims'; diff --git a/packages/core/src/session/task-intent-turn.ts b/packages/core/src/session/task-intent-turn.ts index 98638770..1ba947f4 100644 --- a/packages/core/src/session/task-intent-turn.ts +++ b/packages/core/src/session/task-intent-turn.ts @@ -2,6 +2,7 @@ import { TURN_DECISION_TOOL } from '@rdk-moss/contracts/task-intent.js'; import { claimDraftSchema, CONTEXT_CLAIMS_TOOL, + ContextClaimRejection, parseClaimDrafts, } from './context-claim-declaration.js'; import type { TaskIntentSnapshot, TurnDecision } from '@rdk-moss/contracts/task-intent.js'; @@ -33,6 +34,7 @@ export interface TaskIntentResponse { hold?: boolean; answer?: string; plainReply?: 'answered' | 'pending'; + claim?: 'recorded' | { id: string; name: string; message: string }; } /** One instance per run. Captured bindings must never be refreshed by old callbacks. */ @@ -353,16 +355,35 @@ export class TaskIntentTurn { calls: Call[], interrupted: boolean, options: { readOnly?: boolean; corrected?: boolean } = {} - ): ContentBlock[] { + ): Pick { const claimCalls = calls.filter((call) => call.name === CONTEXT_CLAIMS_TOOL); - if (!claimCalls.length) return []; - const reject = (message: string): ContentBlock[] => - claimCalls.map((call) => ({ + const first = claimCalls[0]; + if (!first) return { results: [] }; + let claim: TaskIntentResponse['claim']; + const reject = (message: string): ContentBlock[] => { + if (!options.readOnly) claim = { id: first.id, name: first.name, message }; + const results: ContentBlock[] = claimCalls.map((call) => ({ type: 'tool_result', tool_use_id: call.id, is_error: true, content: message, })); + // Other calls may rely on any rejected claim, including one rejected after a correction. + // Keep the committed decision receipt; the next model turn chooses actions again. + for (const call of calls.filter( + (call) => call.name !== CONTEXT_CLAIMS_TOOL && call.name !== TURN_DECISION_TOOL + )) { + results.push({ + type: 'tool_result', + tool_use_id: call.id, + is_error: true, + outcome: 'suppressed', + content: 'Not executed: a context claim in this response was rejected.', + }); + calls.splice(calls.indexOf(call), 1); + } + return results; + }; let results: ContentBlock[]; try { @@ -373,22 +394,32 @@ export class TaskIntentTurn { } else { if (interrupted || claimCalls.length !== 1 || !this.correctionTargets) throw new Error('A single complete context_claims declaration is required'); - const call = claimCalls[0]!; const claims = this.coordinator.publishClaims( this.binding, - parseClaimDrafts(call.input.claims) + parseClaimDrafts(first.input.claims) ); + if (claims.length) claim = 'recorded'; results = [ - { type: 'tool_result', tool_use_id: call.id, content: JSON.stringify({ claims }) }, + { type: 'tool_result', tool_use_id: first.id, content: JSON.stringify({ claims }) }, ]; } } catch (error) { - if (!options.readOnly || isTaskExecutionSupersededError(error)) throw error; - // A claim is optional in a read-only answer. Its rejection does not roll back the receipt. - results = reject(error instanceof Error ? error.message : 'Invalid context claim'); + if (error instanceof ContextClaimRejection) { + results = reject( + JSON.stringify({ + error: 'context_claim_rejected', + reason: error.reason, + ids: error.ids.slice(0, 3), + }) + ); + } else { + if (!options.readOnly || isTaskExecutionSupersededError(error)) throw error; + // A claim is optional in a read-only answer. Its rejection does not roll back the receipt. + results = reject(error instanceof Error ? error.message : 'Invalid context claim'); + } } for (const call of claimCalls) calls.splice(calls.indexOf(call), 1); - return results; + return { results, claim }; } assertCurrent(allowHold = false): void { @@ -425,7 +456,7 @@ export class TaskIntentTurn { if (declarations.length > 0) throw new Error('No pending input requires turn_decision'); this.assertCurrent(calls.every((call) => call.name === CONTEXT_CLAIMS_TOOL)); const hold = Boolean(this.correctionTargets && this.binding?.disposition !== 'execute'); - return { results: this.takeClaims(calls, interrupted, { readOnly: hold }), hold }; + return { ...this.takeClaims(calls, interrupted, { readOnly: hold }), hold }; } abortSignal?.throwIfAborted(); this.repair?.assertCurrent(); @@ -473,27 +504,26 @@ export class TaskIntentTurn { this.assertCurrent(decision.disposition !== 'execute'); this.batch = { ...this.batch!, snapshot: this.binding, inputs: [] }; const hold = decision.disposition !== 'execute'; - const results: ContentBlock[] = [ - ...this.takeClaims(calls, interrupted, { - readOnly: hold, - corrected: Boolean(decision.contextCorrections?.length), + const { results, claim } = this.takeClaims(calls, interrupted, { + readOnly: hold, + corrected: Boolean(decision.contextCorrections?.length), + }); + results.push({ + type: 'tool_result', + tool_use_id: declarations[0]!.id, + content: JSON.stringify({ + committed: true, + revision: this.binding.revision, + planId: this.binding.planId, }), - { - type: 'tool_result', - tool_use_id: declarations[0]!.id, - content: JSON.stringify({ - committed: true, - revision: this.binding.revision, - planId: this.binding.planId, - }), - }, - ]; + }); for (let index = calls.length - 1; index >= 0; index--) { if (calls[index]!.name === TURN_DECISION_TOOL) calls.splice(index, 1); } const answer = input.answer; return { results, + claim, hold, ...(this.correctionTargets && hold && diff --git a/packages/core/src/session/versioned-session-store.ts b/packages/core/src/session/versioned-session-store.ts index 20bc03f8..8c4b1501 100644 --- a/packages/core/src/session/versioned-session-store.ts +++ b/packages/core/src/session/versioned-session-store.ts @@ -17,6 +17,7 @@ import type { import { ErrorCode, MossError } from '@rdk-moss/foundation/errors.js'; import type { LLMMessage } from '@rdk-moss/ai/llm/llm-provider.js'; import { redactJsonLine } from './redact-json-line.js'; +import { ContextClaimRejection } from './context-claim-declaration.js'; import type { SessionDeliverySnapshot, SessionMeta, @@ -774,28 +775,24 @@ export class VersionedSessionStore implements SessionStore { ); const insert = this.db.prepare('INSERT INTO claims(session,id,ordinal,body) VALUES(?,?,?,?)'); return drafts.map((draft) => { - if ( - draft.dependsOn.some((id) => !active.has(id)) || - draft.sourceIds.some((id) => { - const source = sources.get(id); - return ( - !source || - (source.origin !== 'user' && - source.origin !== 'tool' && - corrections.some( - (correction) => - source.ordinal >= correction.fromOrdinal && - (source.ordinal <= correction.throughOrdinal || - (source.generatedRevision !== undefined && - source.generatedRevision < correction.revision)) - )) - ); - }) - ) - throw new MossError({ - code: ErrorCode.EXECUTION_REVISION_CONFLICT, - message: 'Claim refers to a missing or invalidated source', - }); + const inactive = draft.dependsOn.filter((id) => !active.has(id)); + if (inactive.length) throw new ContextClaimRejection('inactive_dependency', inactive); + for (const id of draft.sourceIds) { + const source = sources.get(id); + if (!source) throw new ContextClaimRejection('missing_source', [id]); + if ( + source.origin !== 'user' && + source.origin !== 'tool' && + corrections.some( + (correction) => + source.ordinal >= correction.fromOrdinal && + (source.ordinal <= correction.throughOrdinal || + (source.generatedRevision !== undefined && + source.generatedRevision < correction.revision)) + ) + ) + throw new ContextClaimRejection('invalidated_source', [id]); + } const ordinal = this.lastOrdinal(key) + 1; const claim: ContextClaim = { ...draft, id: randomUUID(), ordinal, status: 'active' }; insert.run(key, claim.id, ordinal, redactJsonLine(claim)); diff --git a/scripts/verify/context-claim-recovery.mjs b/scripts/verify/context-claim-recovery.mjs new file mode 100644 index 00000000..7ea60ab4 --- /dev/null +++ b/scripts/verify/context-claim-recovery.mjs @@ -0,0 +1,593 @@ +#!/usr/bin/env node +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { distResolve } from './lib/dist-resolve.mjs'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const repoRoot = process.env.MOSS_VERIFY_DIST_ROOT + ? path.resolve(process.env.MOSS_VERIFY_DIST_ROOT, '..') + : root; +const load = (file) => import(pathToFileURL(distResolve(repoRoot, file)).href); +const [ + { VersionedSessionStore }, + { TaskIntentCoordinator }, + { TaskIntentTurn }, + { MossAgent }, + { VersionedContextPipeline }, + { estimatePromptUnitsForContextWindow }, +] = await Promise.all([ + load('core/session/versioned-session-store.js'), + load('core/session/task-intent-coordinator.js'), + load('core/session/task-intent-turn.js'), + load('core/agent/moss-agent.js'), + load('core/session/versioned-context.js'), + load('context/tokens.js'), +]); +const call = (name, id, input = {}) => ({ name, id, input }); +const claim = (sourceIds, dependsOn = [], text = 'Observed fixture fact') => ({ + text, + sourceIds, + dependsOn, +}); +const claimCall = (drafts, id = 'claims') => call('context_claims', id, { claims: drafts }); +const toolCall = (name, id, input = {}) => ({ type: 'tool_use', ...call(name, id, input) }); +const response = (...content) => ({ + content, + stopReason: content.some((block) => block.type === 'tool_use') ? 'tool_use' : 'end_turn', +}); + +async function fixture(workspace, key, disposition = 'execute', registerClaims) { + const store = new VersionedSessionStore(path.join(workspace, `${key}.sqlite`)); + await store.appendMessage(key, { role: 'user', content: 'Inspect and report the fixture.' }); + await store.appendMessage(key, { role: 'assistant', content: 'An earlier fixture conclusion.' }); + const [user, assistant] = store.snapshot(key).messages; + const coordinator = new TaskIntentCoordinator( + { + read: () => store.readInbox(key), + mutate: (operation) => store.updateInbox(key, operation).result, + }, + workspace, + { + correct: (correction) => store.correctInTransaction(key, correction), + hasRecordedCorrection: (id, text) => store.hasRecordedCorrection(key, id, text), + registerClaims: + registerClaims ?? ((drafts) => store.registerClaimsInTransaction(key, drafts)), + claimsActive: (ids) => store.assertClaimsActive(key, ids), + } + ); + coordinator.admit({ id: 'input', text: 'Inspect and report the fixture.' }); + const turn = new TaskIntentTurn(coordinator, undefined, () => []); + await turn.prepare(); + const decided = await turn.process( + [ + call('turn_decision', 'decision', { + disposition, + changes: [], + plan: disposition === 'execute' ? ['Inspect the fixture'] : [], + }), + ], + false + ); + assert.equal(decided.retry, undefined); + return { store, coordinator, turn, user, assistant, key }; +} + +async function rejectedReferences(workspace) { + for (const scenario of [ + 'missing-source', + 'corrected-source', + 'unknown-dependency', + 'invalidated-dependency', + ]) { + const f = await fixture(workspace, scenario); + try { + let sourceIds = [f.user.id]; + let dependsOn = []; + if (scenario === 'missing-source') sourceIds = ['missing-source-id']; + if (scenario === 'unknown-dependency') dependsOn = ['missing-claim-id']; + if (scenario === 'invalidated-dependency') { + const existing = f.store.updateInbox(f.key, () => + f.store.registerClaimsInTransaction(f.key, [claim([f.assistant.id])]) + ).result; + dependsOn = [existing[0].id]; + } + if (scenario === 'corrected-source' || scenario === 'invalidated-dependency') { + await f.store.correct(f.key, { + id: 'correction', + targetId: f.assistant.id, + text: 'The old conclusion is obsolete.', + }); + if (scenario === 'corrected-source') sourceIds = [f.assistant.id]; + } + const before = f.store.snapshot(f.key).claims; + // The first valid draft must also roll back when the second one is rejected. + const calls = [ + claimCall([claim([f.user.id], [], 'Must roll back'), claim(sourceIds, dependsOn)]), + call('write_fixture', 'blocked-action'), + ]; + const result = await f.turn.process(calls, false); + assert.equal(result.hold, false); + assert.deepEqual(calls, [], 'a rejected declaration must suppress all accompanying actions'); + assert.deepEqual(f.store.snapshot(f.key).claims, before, 'claims are atomic'); + const rejected = result.results.find((item) => item.tool_use_id === 'claims'); + assert.equal(rejected.is_error, true); + const diagnostic = JSON.parse(rejected.content); + assert.equal(diagnostic.error, 'context_claim_rejected'); + assert.equal( + diagnostic.reason, + scenario === 'missing-source' + ? 'missing_source' + : scenario === 'corrected-source' + ? 'invalidated_source' + : 'inactive_dependency' + ); + assert.deepEqual(diagnostic.ids, dependsOn.length ? dependsOn : sourceIds); + const suppressed = result.results.find((item) => item.tool_use_id === 'blocked-action'); + assert.equal(suppressed.is_error, true); + assert.equal(suppressed.outcome, 'suppressed'); + assert.equal(result.results.length, 2, 'every suppressed call gets exactly one receipt'); + const repaired = await f.turn.process([claimCall([claim([f.user.id])], 'repaired')], false); + assert.equal(repaired.results[0].is_error, undefined); + assert.equal( + f.store.snapshot(f.key).claims.filter((item) => item.status === 'active').length, + 1 + ); + console.log(`PASS ${scenario}: reject atomically, suppress the business batch, then repair`); + } finally { + f.store.close(); + } + } +} + +async function correctedBatch(workspace) { + const f = await fixture(workspace, 'corrected-batch'); + try { + const correction = 'The old conclusion is obsolete.'; + f.coordinator.admit({ id: 'correction-input', text: correction + ' Inspect the fixture.' }); + await f.turn.prepare(); + const calls = [ + call('turn_decision', 'correct-and-execute', { + disposition: 'execute', + plan: ['Inspect the corrected fixture'], + contextCorrections: [{ targetId: f.assistant.id, quote: correction }], + }), + claimCall([claim([f.user.id])]), + call('write_fixture', 'blocked-after-correction'), + ]; + const result = await f.turn.process(calls, false); + assert.equal(result.hold, false); + assert.deepEqual(calls, [], 'a correction rejection must also suppress same-batch actions'); + assert.equal(result.results.length, 3); + assert.equal(result.results.find((item) => item.tool_use_id === 'claims').is_error, true); + const suppressed = result.results.find( + (item) => item.tool_use_id === 'blocked-after-correction' + ); + assert.equal(suppressed.is_error, true); + assert.equal(suppressed.outcome, 'suppressed'); + const committed = result.results.find((item) => item.tool_use_id === 'correct-and-execute'); + assert.equal(committed.is_error, undefined); + assert.equal(JSON.parse(committed.content).committed, true); + assert.equal(f.turn.needsDecision, false, 'the committed intent must not be replayed'); + assert.equal(f.store.snapshot(f.key).corrections.length, 1); + assert.equal(f.store.snapshot(f.key).claims.length, 0); + const repaired = await f.turn.process([claimCall([claim([f.user.id])], 'repaired')], false); + assert.equal(repaired.results[0].is_error, undefined); + assert.equal(f.store.snapshot(f.key).claims.length, 1); + console.log( + 'PASS same-batch correction preserves its decision and suppresses actions until claims recover' + ); + } finally { + f.store.close(); + } +} + +async function guardBoundaries(workspace) { + const readonly = await fixture(workspace, 'readonly', 'answer'); + try { + const result = await readonly.turn.process([claimCall([claim(['missing'])])], false); + assert.equal(result.hold, true); + assert.equal(result.results[0].is_error, true); + } finally { + readonly.store.close(); + } + const failure = new Error('fixture database write failure'); + const broken = await fixture(workspace, 'store-failure', 'execute', () => { + throw failure; + }); + try { + await assert.rejects( + broken.turn.process([claimCall([claim([broken.user.id])])], false), + (error) => error === failure + ); + } finally { + broken.store.close(); + } + const superseded = await fixture(workspace, 'superseded'); + try { + superseded.coordinator.admit({ id: 'new-input', text: 'Stop the old action.' }); + const calls = [claimCall([claim(['missing'])]), call('write_fixture', 'old-action')]; + const result = await superseded.turn.process(calls, false); + assert.equal(result.superseded, true); + assert.equal(calls.length, 0); + assert.equal(superseded.store.snapshot(superseded.key).claims.length, 0); + } finally { + superseded.store.close(); + } + console.log( + 'PASS read-only claims stay optional; store failures and superseding inputs retain their semantics' + ); +} + +async function loopRecovery(workspace, mode = 'repaired') { + const capped = [ + 'bounded', + 'unlimited', + 'interleaved', + 'no-progress', + 'run-budget', + 'run-shared', + ].includes(mode); + const interrupted = ['interleaved', 'no-progress', 'run-shared'].includes(mode); + const repairedOnLastTry = mode === 'last-try-repaired'; + const cancelled = mode === 'cancelled'; + const cancelledRecovery = mode === 'cancelled-recovery'; + const visibleClaim = capped || mode === 'visible-claim'; + const claimOnly = mode === 'claim-only'; + const completionChecks = []; + const controller = new AbortController(); + const key = mode; + const store = new VersionedSessionStore(path.join(workspace, `${key}.sqlite`)); + let requests = 0; + let reads = 0; + let writes = 0; + let sourceId; + const maxTurns = mode === 'bounded' ? 3 : capped ? 'unlimited' : 7; + const events = []; + const agent = new MossAgent({ + llmProvider: { + id: 'claim-recovery-fixture', + displayName: 'Claim recovery fixture', + capabilities: { streaming: false }, + async complete(request) { + requests++; + assert.ok( + requests <= (repairedOnLastTry ? 7 : 6), + 'the fixture must never enter an unbounded recovery loop' + ); + if (requests === 1) + return response( + toolCall('turn_decision', 'decide', { + disposition: 'execute', + plan: ['Read fixture, record evidence, then act'], + }) + ); + if (requests === 2) return response(toolCall('read_fixture', 'read-once')); + if ( + requests === 3 || + (capped && !interrupted) || + (mode === 'run-shared' && requests >= 5) + ) { + if (cancelled) controller.abort(); + return response( + ...(visibleClaim ? [{ type: 'text', text: 'claim fixture narration' }] : []), + toolCall('context_claims', `invalid-${requests}`, { + claims: [claim(['not-a-source'])], + }), + ...(!claimOnly ? [toolCall('write_fixture', `blocked-${requests}`)] : []) + ); + } + if (requests === 4) { + assert.equal(reads, 1); + assert.equal(writes, 0, 'invalid evidence must prevent same-batch execution'); + const results = request.messages + .flatMap((message) => (Array.isArray(message.content) ? message.content : [])) + .filter((block) => block.type === 'tool_result'); + assert.ok( + results.some((block) => block.tool_use_id === 'invalid-3'), + 'the next model request must receive the rejected claim receipt' + ); + assert.equal(results.find((block) => block.tool_use_id === 'invalid-3').is_error, true); + assert.deepEqual( + request.messages + .flatMap((message) => (Array.isArray(message.content) ? message.content : [])) + .find((block) => block.type === 'tool_use' && block.id === 'invalid-3').input, + { claims: [] }, + 'the provider sees pairing data, not the rejected declaration' + ); + if (cancelledRecovery) { + controller.abort(); + return response(toolCall('write_fixture', 'cancelled-action')); + } + if (mode === 'steered') { + assert.ok(agent.steer(key, 'Answer this new request only.', { id: 'replacement' })); + return response(toolCall('write_fixture', 'stale-action')); + } + if (mode === 'no-progress') + return response( + { type: 'text', text: 'claim fixture narration' }, + toolCall('context_claims', 'empty-repair', { claims: [] }) + ); + if (mode === 'interleaved' || repairedOnLastTry) + return response(toolCall('read_more', 'interleaved-read')); + if (!claimOnly) + assert.equal(results.find((block) => block.tool_use_id === 'blocked-3').is_error, true); + sourceId = store + .snapshot(key) + .messages.find( + (item) => + item.origin === 'tool' && + JSON.stringify(item.message).includes('fixture-observation') + ).id; + return response( + toolCall('context_claims', 'valid-claim', { claims: [claim([sourceId])] }) + ); + } + if (requests === 5) { + if (mode === 'steered') { + assert.doesNotMatch(JSON.stringify(request.messages), /context_claim_rejected/); + return response( + toolCall('turn_decision', 'replaced', { + disposition: 'answer', + answer: 'Answered the new request.', + }) + ); + } + if (repairedOnLastTry) { + assert.match(JSON.stringify(request.messages), /interleaved-read/); + sourceId = store + .snapshot(key) + .messages.find( + (item) => + item.origin === 'tool' && + JSON.stringify(item.message).includes('interleaved-read') + ).id; + return response( + toolCall('context_claims', 'valid-claim', { claims: [claim([sourceId])] }) + ); + } + if (mode === 'interleaved') { + assert.match(JSON.stringify(request.messages), /interleaved-read/); + assert.match(JSON.stringify(request.messages), /context_claim_rejected/); + return response( + { type: 'text', text: 'claim fixture narration' }, + toolCall('write_fixture', 'blocked-at-limit') + ); + } + if (mode === 'no-progress') + return response({ type: 'text', text: 'claim fixture narration' }); + assert.doesNotMatch( + JSON.stringify(request.messages), + /context_claim_rejected/, + 'resolved claim errors must leave the provider context' + ); + assert.equal(store.snapshot(key).claims.length, 1); + return response(toolCall('write_fixture', 'authorized-action')); + } + if (repairedOnLastTry && requests === 6) + return response(toolCall('write_fixture', 'authorized-action')); + assert.equal(requests, repairedOnLastTry ? 7 : 6); + return response({ + type: 'text', + text: 'Recorded the evidence and completed the fixture action.', + }); + }, + }, + sessionStore: store, + workspaceDir: workspace, + sessionInboxDir: path.join(workspace, 'inbox'), + baseSystemPrompt: 'Use the available evidence and tools.', + domainPrompt: false, + taskIntent: true, + contextTokens: 131_072, + maxLLMRetries: 0, + ...(mode === 'run-budget' ? { budget: { maxTurns: 3 } } : {}), + ...(visibleClaim + ? { + completionGate: async ({ response: answer }) => { + completionChecks.push(answer); + return answer.includes('claim fixture narration') + ? { ok: false, reason: 'fixture strict gate', retryLimit: 0 } + : { ok: true }; + }, + } + : {}), + }); + for (const name of ['read_fixture', 'read_more', 'write_fixture']) + agent.tools.register({ + name, + description: name, + inputSchema: { type: 'object', properties: {} }, + metadata: { + sideEffectClass: name === 'write_fixture' ? 'local_write' : 'readonly', + requiresApproval: false, + }, + async execute() { + if (name !== 'write_fixture') { + reads++; + return 'fixture-observation'; + } + writes++; + return 'fixture action completed'; + }, + }); + try { + for await (const event of agent.streamChat( + key, + 'Read the fixture and act on current evidence.', + { + taskFlow: false, + userInput: { id: key }, + maxTurns, + abortSignal: controller.signal, + streamVersionedDrafts: capped, + } + )) + events.push(event); + if (cancelled || cancelledRecovery) { + const failure = events.findLast((event) => event.type === 'error'); + assert.equal(failure?.errorDetails?.message, controller.signal.reason.message); + assert.equal(requests, cancelledRecovery ? 4 : 3, 'no model calls may follow cancellation'); + assert.equal(reads, 1); + assert.equal(writes, 0); + assert.equal(store.snapshot(key).claims.length, 0); + console.log('PASS cancellation propagates before declaration or tool execution'); + return; + } + assert.equal( + events.some((event) => event.type === 'error'), + false, + JSON.stringify(events.filter((event) => event.type === 'error')) + ); + const result = events.findLast((event) => event.type === 'done')?.result; + assert.ok(result, 'the original run must settle'); + assert.equal( + reads, + mode === 'interleaved' || repairedOnLastTry ? 2 : 1, + 'completed tools must not replay' + ); + if (mode === 'steered') { + assert.equal(requests, 5); + assert.equal(writes, 0); + assert.equal(result.response, 'Answered the new request.'); + console.log('PASS new input supersedes pending claim recovery'); + return; + } + assert.equal(writes, capped ? 0 : 1); + if (capped) { + const budgetStop = mode === 'bounded' || mode === 'run-budget'; + assert.equal(requests, budgetStop ? 3 : mode === 'run-shared' ? 6 : 5); + assert.equal( + result.stopReason, + mode === 'bounded' + ? 'max_turns_reached' + : mode === 'run-budget' + ? 'budget_turns_reached' + : 'budget_context_claim_recovery_reached' + ); + assert.match(result.response, /could not verify the evidence|没能确认完成任务所需的依据/); + assert.doesNotMatch( + JSON.stringify(result), + /claim fixture narration|context_claim_rejected|blocked-at-limit/ + ); + assert.doesNotMatch( + JSON.stringify(events.filter((event) => event.type !== 'text_draft_delta')), + /claim fixture narration|context_claim_rejected/ + ); + assert.ok(!events.some((event) => event.type === 'text_draft_end' && event.accepted)); + assert.deepEqual(completionChecks, []); + assert.equal(store.snapshot(key).claims.length, mode === 'run-shared' ? 1 : 0); + assert.doesNotMatch(JSON.stringify(store.snapshot(key).messages), /claim fixture narration/); + if (mode === 'interleaved') + assert.match(JSON.stringify(store.snapshot(key).messages), /blocked-at-limit/); + } else { + assert.equal(result.response, 'Recorded the evidence and completed the fixture action.'); + assert.equal(result.stopReason, 'end_turn'); + assert.deepEqual(store.snapshot(key).claims[0].sourceIds, [sourceId]); + if (visibleClaim) { + assert.ok( + completionChecks.length > 0, + 'the final answer must still pass completion validation' + ); + assert.ok( + completionChecks.every((answer) => !answer.includes('claim fixture narration')), + 'rejected declaration narration is not a completion candidate' + ); + assert.ok(completionChecks.includes(result.response)); + } + } + console.log( + capped + ? `PASS ${mode}: recovery stops with a verified empty draft and a runtime failure message` + : `PASS ${mode}: same run repairs evidence, preserves tool receipts and executes once` + ); + } finally { + await agent.close(); + store.close(); + } +} + +async function nearFullWindow(workspace) { + const store = new VersionedSessionStore(path.join(workspace, 'near-full.sqlite')); + try { + const key = 'near-full'; + const pipeline = new VersionedContextPipeline(store); + await store.appendMessage(key, { role: 'user', content: 'Check test record. '.repeat(300) }); + await store.appendMessage(key, { + role: 'assistant', + content: [ + toolCall('context_claims', 'large-claim', { + claims: Array.from({ length: 4 }, (_, i) => + claim(['missing'], [], `Fixture record ${i} `.repeat(80)) + ), + }), + ], + }); + const receipt = { + type: 'tool_result', + tool_use_id: 'large-claim', + content: '{"error":"context_claim_rejected","reason":"missing_source","ids":["missing"]}', + is_error: true, + }; + await store.appendMessage(key, { role: 'user', content: [receipt] }); + const ephemeral = [ + { + role: 'assistant', + timestamp: 0, + content: [toolCall('context_claims', 'large-claim', { claims: [] })], + }, + { role: 'user', timestamp: 0, content: [receipt] }, + ]; + const projection = await pipeline.prepare({ + sessionKey: key, + window: 4096, + output: 2048, + minOutput: 2048, + force: true, + signal: new AbortController().signal, + policyKey: 'claim-recovery-fixture', + summarize: async () => '[]', + ephemeral, + measure: (messages) => + estimatePromptUnitsForContextWindow({ + messages, + systemPrompt: 'Use available evidence.', + charsPerTokenUnit: 4, + }), + }); + assert.equal(projection.output, 2048); + assert.deepEqual(projection.messages.slice(-2), ephemeral); + assert.doesNotMatch(JSON.stringify(projection.messages), /Fixture record/); + console.log('PASS near-full 4K window retains the compact error pair and 2K output'); + } finally { + store.close(); + } +} + +const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'moss-claim-recovery-')); +try { + await rejectedReferences(workspace); + await correctedBatch(workspace); + await guardBoundaries(workspace); + await loopRecovery(workspace); + await loopRecovery(workspace, 'visible-claim'); + await loopRecovery(workspace, 'claim-only'); + for (const mode of [ + 'bounded', + 'unlimited', + 'interleaved', + 'last-try-repaired', + 'no-progress', + 'run-shared', + 'run-budget', + 'cancelled', + 'cancelled-recovery', + 'steered', + ]) + await loopRecovery(workspace, mode); + await nearFullWindow(workspace); +} finally { + await fs.rm(workspace, { recursive: true, force: true }); +} diff --git a/scripts/verify/stages/versioned-context.mjs b/scripts/verify/stages/versioned-context.mjs index f28c19d5..d24fcaf9 100644 --- a/scripts/verify/stages/versioned-context.mjs +++ b/scripts/verify/stages/versioned-context.mjs @@ -15,6 +15,14 @@ export const stage = { if (probe.timedOut || probe.status !== 0) return { ok: false, detail: `${probe.stdout}${probe.stderr}` }; console.log(probe.stdout.trim()); + const claims = await captureProcess( + process.execPath, + [path.join(context.root, 'scripts/verify/context-claim-recovery.mjs')], + { cwd: context.root, env: { ...process.env, MOSS_NO_RDK_DOCS: '1' }, timeoutMs: 20_000 } + ); + if (claims.timedOut || claims.status !== 0) + return { ok: false, detail: `${claims.stdout}${claims.stderr}` }; + console.log(claims.stdout.trim()); const result = await captureProcess( process.execPath, [path.join(context.root, 'scripts/verify/versioned-context.mjs')],