From 5877b1f771ab443aa7ad79977933dc83ecbd0d0e Mon Sep 17 00:00:00 2001 From: d-robotics Date: Sun, 22 Nov 2026 22:28:38 +0800 Subject: [PATCH 01/16] feat(sdk): stream retractable versioned answer drafts --- scripts/verify/versioned-context.mjs | 90 +++++++++++++++++++++++ src/cli/print.ts | 3 + src/core/agent/moss-agent-loop-adapter.ts | 11 +++ src/core/agent/moss-agent-types.ts | 4 + src/core/agent/moss-agent.ts | 2 +- src/core/loop/agent-loop-response.ts | 2 + src/core/loop/agent-loop-types.ts | 1 + src/core/loop/agent-loop.ts | 39 ++++++++-- src/core/loop/versioned-text-draft.ts | 65 ++++++++++++++++ src/core/subagent/agent-events.ts | 2 + 10 files changed, 211 insertions(+), 8 deletions(-) create mode 100644 src/core/loop/versioned-text-draft.ts diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index fce7e9a7..ef072822 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -1353,6 +1353,95 @@ if (process.argv[2] === '--commit-and-exit') { process.exit(0); } +async function testVersionedDrafts(workspace) { + for (const steer of [false, true]) { + const store = new VersionedSessionStore( + path.join(workspace, steer ? 'steer.sqlite' : 'accept.sqlite') + ); + const session = 'draft-test'; + const seen = latch(); + const withdrawn = latch(); + const release = latch(); + const events = []; + const first = '这里是实时输出的待校验正文。'; + const tail = '这段文字由第二个模型增量产生。'; + const corrected = '更正已生效,以下仅以最新输入为准。'; + let requests = 0; + const agent = new MossAgent({ + sessionStore: store, + workspaceDir: workspace, + contextTokens: 32_000, + maxTokens: 1024, + taskIntent: true, + enableFollowUpGuard: false, + llmProvider: { + id: 'draft-fixture', + displayName: 'Draft fixture', + async complete(request) { + return summarize(summaryInput(request)); + }, + async stream(request, emit) { + const step = ++requests; + if (step === 1) return response(...decide(request, 'execute')); + if (step === 2) { + emit({ type: 'content_block_delta', text: first }); + await release.promise; + emit({ type: 'content_block_delta', text: tail }); + return response(text(first + tail)); + } + assert.equal(step, 3); + return response(...decide(request, 'answer', { answer: corrected })); + }, + }, + }); + const run = (async () => { + for await (const event of agent.streamChat(session, 'Check the workspace before answering.', { + userInput: { id: 'initial' }, + streamVersionedDrafts: true, + })) { + events.push(event); + if (event.type === 'text_draft_delta') seen.resolve(); + if (event.type === 'text_draft_end' && !event.accepted) withdrawn.resolve(); + } + })(); + try { + await observeRace(run, seen, 'the first draft before provider completion'); + assert.equal( + events.some((event) => event.type === 'text_delta'), + false + ); + assert(!JSON.stringify(await store.sourceMessages(session)).includes(first)); + if (steer) { + assert(agent.steer(session, '更正,先停止旧任务,只回答本次更正。', { id: 'correction' })); + await observeRace(run, withdrawn, 'draft withdrawal while the provider is blocked'); + } + release.resolve(); + await waitFor(run, 'canonical output'); + const draft = events + .filter((event) => event.type === 'text_draft_delta') + .map((event) => event.delta) + .join(''); + const canonical = events + .filter((event) => event.type === 'text_delta') + .map((event) => event.delta) + .join(''); + assert.equal(draft, steer ? first : first + tail); + assert.equal(canonical, steer ? corrected : first + tail); + assert.deepEqual( + events.filter((event) => event.type === 'text_draft_end').map((event) => event.accepted), + [!steer] + ); + } finally { + release.resolve(); + await run.catch(() => {}); + store.close(); + } + } + console.log( + 'PASS versioned drafts stream before provider completion and disappear when a new input supersedes them' + ); +} + const workspace = await fs.realpath( await fs.mkdtemp(path.join(os.tmpdir(), 'moss-versioned-context-')) ); @@ -1369,6 +1458,7 @@ try { ['claims', testClaimDependencies], ['acceptance', testLateAcceptance], ['restart', testProcessRestart], + ['streaming-drafts', testVersionedDrafts], ['unsettled-mutation', testUnknownMutationRecovery], ['cli', testCliCorrections], ]) { diff --git a/src/cli/print.ts b/src/cli/print.ts index e6e10d6f..5e438be7 100644 --- a/src/cli/print.ts +++ b/src/cli/print.ts @@ -532,6 +532,9 @@ export function formatHeadlessStreamEvent( event: MossAgentEvent ): HeadlessStreamEvent[] { switch (event.type) { + case 'text_draft_delta': + case 'text_draft_end': + return []; case 'text_delta': state.finalText += event.delta; state.pendingAssistantText += streamRedactorFor(state).push(event.delta); diff --git a/src/core/agent/moss-agent-loop-adapter.ts b/src/core/agent/moss-agent-loop-adapter.ts index ee60ae70..22c3d588 100644 --- a/src/core/agent/moss-agent-loop-adapter.ts +++ b/src/core/agent/moss-agent-loop-adapter.ts @@ -82,6 +82,9 @@ export function createMossAgentLoopEventAdapter( const textRedactor = createAssistantTextRedactor({ normalizeLeadingWhitespace: options?.normalizeLeadingWhitespace !== false, }); + const draftRedactor = createAssistantTextRedactor({ + normalizeLeadingWhitespace: options?.normalizeLeadingWhitespace !== false, + }); let continuingOutput = false; const thinkingRedactor = createAssistantTextRedactor(); const thinking: string[] = []; @@ -144,6 +147,14 @@ export function createMossAgentLoopEventAdapter( return { onMiniEvent(event) { switch (event.type) { + case 'message_draft_delta': { + if (options?.isAborted?.()) return []; + const delta = draftRedactor.push(event.delta); + return delta ? [{ type: 'text_draft_delta', delta }] : []; + } + case 'message_draft_end': + draftRedactor.reset(); + return [{ type: 'text_draft_end', accepted: event.accepted }]; case 'message_delta': { response += event.delta; // Public prose starts after the reasoning block has settled. Emit diff --git a/src/core/agent/moss-agent-types.ts b/src/core/agent/moss-agent-types.ts index 475524fd..7dd7b2cf 100644 --- a/src/core/agent/moss-agent-types.ts +++ b/src/core/agent/moss-agent-types.ts @@ -321,6 +321,8 @@ export interface MossAgentConfig } export interface ChatOptions { + /** Opt in to provisional text events that a host can retract. Canonical text is still guarded. */ + streamVersionedDrafts?: boolean; /** Trusted raw user input; false marks autonomous engine prompts. */ userInput?: { id: string; text?: string; taskId?: string } | false; /** Host-owned native Task Runtime binding, including autonomous turns. */ @@ -432,6 +434,8 @@ export interface ChatResult { export type MossAgentEvent = | { type: 'text_delta'; delta: string } + | { type: 'text_draft_delta'; delta: string } + | { type: 'text_draft_end'; accepted: boolean } | { type: 'thinking_delta'; delta: string } | { type: 'tool_start'; toolName: string; toolCallId: string; input: Record } | { diff --git a/src/core/agent/moss-agent.ts b/src/core/agent/moss-agent.ts index 90adb7d3..b192f991 100644 --- a/src/core/agent/moss-agent.ts +++ b/src/core/agent/moss-agent.ts @@ -2638,6 +2638,7 @@ ${result.stderr ?? ''}`.trim(); }); }, ...(intentTurn ? { taskIntentTurn: intentTurn } : {}), + streamVersionedDrafts: options?.streamVersionedDrafts === true, getFollowUpMessages: this.config.enableFollowUpGuard !== false ? async () => { @@ -2671,7 +2672,6 @@ ${result.stderr ?? ''}`.trim(); : undefined, // Buffer only when a host completionGate may rewrite or discard the answer. shouldBufferAssistantOutput: () => - Boolean(intentTurn) || this.config.bufferAssistantUntilComplete === true || runtimeJudge?.shouldBufferCompletion() === true, completionGate, diff --git a/src/core/loop/agent-loop-response.ts b/src/core/loop/agent-loop-response.ts index e75508af..5d14a604 100644 --- a/src/core/loop/agent-loop-response.ts +++ b/src/core/loop/agent-loop-response.ts @@ -128,6 +128,7 @@ export interface ProcessLlmResponseParams { >; completionGate?: AgentLoopExtensions['completionGate']; delayedVisibleDeltas?: boolean; + settleTextDraft?: (accepted: boolean) => void; toolAbortSignalFor?: (toolCallId: string) => AbortSignal | undefined; enrichToolContext?: (baseCtx: ToolContext, sessionKey: string) => ToolContext; evaluateSteering: () => Message[]; @@ -477,6 +478,7 @@ export async function processLlmResponse( return { control: 'continue' }; } } + params.settleTextDraft?.(!outputLimited && !hasThinkingOnly); if (delayedVisibleDeltas && !hasThinkingOnly) { pushGuardedMessageDeltas(push, visibleAssistantText); } diff --git a/src/core/loop/agent-loop-types.ts b/src/core/loop/agent-loop-types.ts index afd9275f..2ad58063 100644 --- a/src/core/loop/agent-loop-types.ts +++ b/src/core/loop/agent-loop-types.ts @@ -124,6 +124,7 @@ export interface AgentLoopPolicy { } export interface AgentLoopExtensions { + streamVersionedDrafts?: boolean; prepareContextProjection?: (input: { window: number; output: number; diff --git a/src/core/loop/agent-loop.ts b/src/core/loop/agent-loop.ts index fbf08057..fa6b5931 100644 --- a/src/core/loop/agent-loop.ts +++ b/src/core/loop/agent-loop.ts @@ -44,6 +44,7 @@ import { shouldIncludeThinkingInBudget, } from './agent-loop-context-prep.js'; import { executeLlmTurn } from './agent-loop-llm-call.js'; +import { createVersionedTextDraft } from './versioned-text-draft.js'; import { processLlmResponse } from './agent-loop-response.js'; import { buildBackgroundCompletionSystemText, @@ -533,6 +534,7 @@ export function runAgentLoop( const effectiveContextTokens = getEffectiveContextWindowTokens(contextTokens, maxOut); let turnToolCalls: { id: string; name: string; input: Record }[] = []; + let textDraft: ReturnType | undefined; try { refreshActiveSystemPrompt(); const wire = params.prepareContextProjection @@ -612,6 +614,31 @@ export function runAgentLoop( } } const projectedContext = projection && wire ? wire(projection.messages) : undefined; + const bufferOutput = Boolean( + params.guardAssistantOutput || params.shouldBufferAssistantOutput?.() + ); + const intent = params.taskIntentTurn; + const delayedVisibleDeltas = + projection !== undefined || bufferOutput || Boolean(intent); + if ( + params.streamVersionedDrafts && + projectionRevision !== undefined && + params.assertContextRevision && + !bufferOutput && + !state.carriedAssistantText && + (!intent || + (!intent.needsDecision && intent.bindingSnapshot()?.disposition === 'execute')) + ) { + const assertIntent = intent?.executionGuard(); + textDraft = createVersionedTextDraft( + (event) => stream.push(event), + () => { + params.assertContextRevision!(projectionRevision); + assertIntent?.(); + }, + abortSignal + ); + } const llmResult = await executeLlmTurn({ reasoningBudget: params.reasoningBudget, modelTiers: params.modelTiers, @@ -632,7 +659,7 @@ export function runAgentLoop( sessionKey, runId, runStartMs, - push: (e) => stream.push(e), + push: textDraft?.push ?? ((e) => stream.push(e)), currentMessages, prepareCompaction, replaceMessages: params.replaceMessages, @@ -642,9 +669,7 @@ export function runAgentLoop( // host says this turn needs buffering. A always-installed // completionGate alone must NOT suppress streaming — that made // every coding turn non-streamed. - suppressVisibleDeltas: Boolean( - projection || params.guardAssistantOutput || params.shouldBufferAssistantOutput?.() - ), + suppressVisibleDeltas: delayedVisibleDeltas && !textDraft, }); if (llmResult.control === 'retry') { @@ -708,9 +733,8 @@ export function runAgentLoop( runtimeJudge: params.runtimeJudge, guardAssistantOutput: params.guardAssistantOutput, completionGate: params.completionGate, - delayedVisibleDeltas: Boolean( - projection || params.guardAssistantOutput || params.shouldBufferAssistantOutput?.() - ), + delayedVisibleDeltas, + settleTextDraft: textDraft?.settle, toolAbortSignalFor: params.toolAbortSignalFor, enrichToolContext: params.enrichToolContext, evaluateSteering, @@ -854,6 +878,7 @@ export function runAgentLoop( state.pendingMessages = correctionMessages; continue; } finally { + textDraft?.dispose(); try { await flushAssistantBuffer(turnAssistantBuffer); } catch (flushErr) { diff --git a/src/core/loop/versioned-text-draft.ts b/src/core/loop/versioned-text-draft.ts new file mode 100644 index 00000000..c4a1a799 --- /dev/null +++ b/src/core/loop/versioned-text-draft.ts @@ -0,0 +1,65 @@ +import type { MiniAgentEvent } from '../subagent/agent-events.js'; + +/** A provisional view of one model attempt. Never used by the canonical response or store. */ +export function createVersionedTextDraft( + publish: (event: MiniAgentEvent) => void, + assertCurrent: () => void, + signal: AbortSignal +) { + let closed = false; + let active = false; + let watcher: ReturnType | undefined; + + const end = (accepted: boolean) => { + if (!active) return; + active = false; + if (watcher) clearInterval(watcher); + watcher = undefined; + publish({ type: 'message_draft_end', accepted }); + }; + + const current = () => { + if (closed || signal.aborted) return false; + try { + assertCurrent(); + return true; + } catch { + return false; + } + }; + + const dispose = () => { + closed = true; + signal.removeEventListener('abort', dispose); + end(false); + }; + signal.addEventListener('abort', dispose, { once: true }); + + return { + push(event: MiniAgentEvent) { + if (event.type !== 'message_delta') { + if (event.type === 'retry') end(false); + publish(event); + return; + } + if (!current()) { + dispose(); + return; + } + if (!active) { + active = true; + // An external store correction can occur while the provider is silent. + watcher = setInterval(() => { + if (!current()) dispose(); + }, 75); + watcher.unref(); + } + publish({ type: 'message_draft_delta', delta: event.delta }); + }, + settle(accepted: boolean) { + end(accepted && current()); + dispose(); + }, + dispose, + }; +} diff --git a/src/core/subagent/agent-events.ts b/src/core/subagent/agent-events.ts index e36f2f9d..2a76a2c2 100644 --- a/src/core/subagent/agent-events.ts +++ b/src/core/subagent/agent-events.ts @@ -30,6 +30,8 @@ type MiniAgentEventPayload = | { type: 'turn_end'; turn: number; stopReason?: string; totalToolCalls?: number } | { type: 'message_start'; message: Message } | { type: 'message_delta'; delta: string } + | { type: 'message_draft_delta'; delta: string } + | { type: 'message_draft_end'; accepted: boolean } | { type: 'message_end'; message: Message; text: string; stopReason?: string } | { type: 'thinking_delta'; delta: string } | { type: 'tool_execution_start'; toolCallId: string; toolName: string; args: unknown } From e5e74566039f0b7ed1ccb9c033b484afc9964ccd Mon Sep 17 00:00:00 2001 From: d-robotics Date: Sun, 22 Nov 2026 22:30:51 +0800 Subject: [PATCH 02/16] fix(cli): ignore provisional SDK text events --- src/cli/output.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cli/output.ts b/src/cli/output.ts index dfdf3821..ac307def 100644 --- a/src/cli/output.ts +++ b/src/cli/output.ts @@ -600,6 +600,9 @@ export function createCliRunRenderer(options: CliRunRendererOptions = {}) { state.thinkingNoted = true; } break; + case 'text_draft_delta': + case 'text_draft_end': + break; case 'text_delta': spinner?.stop(); if (state.thinkingOpen) { From 1634ee13c0d4a3b83772d88186c6c95847bfa26c Mon Sep 17 00:00:00 2001 From: d-robotics Date: Sun, 22 Nov 2026 22:40:42 +0800 Subject: [PATCH 03/16] fix(sdk): stream quoted prose and markdown tables --- scripts/verify/assistant-live-text.mjs | 21 +++++++++++++++++++++ src/safety/redact-stream.ts | 9 +++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/scripts/verify/assistant-live-text.mjs b/scripts/verify/assistant-live-text.mjs index dd115ef9..c3a21d76 100644 --- a/scripts/verify/assistant-live-text.mjs +++ b/scripts/verify/assistant-live-text.mjs @@ -34,6 +34,9 @@ const cases = [ '- RDK-X5 状态正常。\n- 第二个条目正常。', '```text\nname=stream-check\nstatus=ready\n```\n代码说明继续输出。', '普通路径 https://example.test/docs 之后继续写作。', + '可行,而且板子上已经有路径。要看你想要哪种「YOLO」。\n\n|项|状态|\n|---|:---:|\n|BPU|正常|', + '|项|状态|\n|---|---|\n|password="full credential sample"|已掩码|', + '先看「板端状态」。\n- -----BEGIN PRIVATE KEY-----\nABCdef12345\n-----END PRIVATE KEY-----', '普通输出路径为 /tmp/stream-check/result.txt。针对 RDK-X5 继续说明。', '\n\n 原始前导空白用于校验纯脱敏函数的原文一致性。', 'name=stream-check status=ready password="full credential sample"', @@ -224,6 +227,24 @@ assert.equal( ); assert.equal(formatted.flush(), ''); +const table = createAssistantTextRedactor(); +const tableChunks = [ + '结论:可行。要看你想要哪种', + '「YOLO」。\n\n', + '|项|状态|\n', + '|---|:---:|\n', + '|BPU|正常|\n', + '下一步可用静态图。', +]; +let liveTable = ''; +for (const chunk of tableChunks) { + const delta = table.push(chunk); + assert.ok(delta, `the stream stalled on ${JSON.stringify(chunk)}`); + liveTable += delta; +} +assert.equal(liveTable, tableChunks.join('')); +assert.equal(table.flush(), ''); + const normalized = createMossAgentLoopEventAdapter(); normalized.onMiniEvent({ type: 'turn_start', turn: 1 }); assert.deepEqual(normalized.onMiniEvent({ type: 'message_delta', delta: '\n\n ' }), []); diff --git a/src/safety/redact-stream.ts b/src/safety/redact-stream.ts index 33ded4eb..b4070125 100644 --- a/src/safety/redact-stream.ts +++ b/src/safety/redact-stream.ts @@ -112,8 +112,8 @@ const CREDENTIAL_WORD = new RegExp( 'i' ); const PROSE_SYMBOL = - /[\p{L}\p{M}\p{N}\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}\u200D.,!?;'"()[\]{}#*`,。!?、;:“”‘’()《》…—–]/uy; -const PROSE_BREAK = /^[ \t\r\n.,!?;'"()[\]{}#*`]|^[^\x00-\x7f]/u; + /[\p{L}\p{M}\p{N}\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}\u200D.,!?;'"()[\]{}#*`|,。!?、;:“”‘’()《》「」『』【】…—–]/uy; +const PROSE_BREAK = /^[ \t\r\n.,!?;'"()[\]{}#*`|]|^[^\x00-\x7f]/u; const ATOM_BREAK = /^[\s'"`()\[\]{};,!]/u; /** @@ -175,7 +175,8 @@ export function createAssistantTextRedactor( const words = value.match(/[A-Za-z0-9_]+/g) ?? []; const contextual = CREDENTIAL_WORD.test(value) || words.some((word) => CREDENTIAL_WORD.test(word)); - const flag = value.startsWith('-') && !/^-\d/.test(value); + // A Markdown divider is ordinary punctuation once its boundary is known. + const flag = value.startsWith('-') && !/^(?:-\d|---+:?$)/.test(value); const url = value.includes('://'); // A URL password can include non-ASCII text and punctuation. Only // actual URL/argv terminators make such an atom complete. @@ -191,7 +192,7 @@ export function createAssistantTextRedactor( if (scanned + 1 === raw.length && /[\uD800-\uDBFF]/.test(char)) return; symbol.lastIndex = scanned; if (!symbol.test(raw)) return; - structured ||= char === '`' || char === '{' || char === '}'; + structured ||= char === '`' || char === '{' || char === '}' || char === '|'; scanned = symbol.lastIndex; } proseEnd = scanned; From 2c75a876098b4b6d564ad7861367a2e19d3ccc62 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 16:08:38 +0800 Subject: [PATCH 04/16] fix(context): retain recent tool evidence under active-turn pressure --- scripts/verify/versioned-context.mjs | 57 +++++++++++++++++++++++++++ src/core/session/versioned-context.ts | 42 +++++++++++++++++--- 2 files changed, 93 insertions(+), 6 deletions(-) diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index ef072822..21ef6b1c 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -492,6 +492,62 @@ async function testPressureContinuation(workspace) { ); } +async function testActiveToolPressure(workspace) { + const session = 'active-tool-pressure'; + const user = 'Inspect the selected board and report the exact detection count.'; + const original = + 'Board model is RDK X5.\n' + + 'log line\n'.repeat(1600) + + 'RAW_ARCHIVE_ONLY\n' + + 'log line\n'.repeat(1600) + + 'End of board diagnostics.'; + const latest = 'Inference exited with status 0.\n' + 'trace\n'.repeat(250) + 'Detection count: 4'; + await usingAgent(workspace, async ({ store }) => { + await add(store, session, 'user', user); + for (const [id, name, content] of [ + ['diagnostics', 'device_diagnose', original], + ['inference', 'device_exec', latest], + ]) { + await add(store, session, 'assistant', [toolCall(name, id)]); + await add( + store, + session, + 'user', + [{ type: 'tool_result', tool_use_id: id, name, content }], + 'tool' + ); + } + const pipeline = new VersionedContextPipeline(store); + const input = { + sessionKey: session, + window: 10_000, + output: 2048, + minOutput: 1024, + policyKey: 'active-tool-pressure-probe', + measure: (messages) => 3400 + Math.ceil(Buffer.byteLength(JSON.stringify(messages)) / 4), + summarize: async () => { + throw new Error('The active turn cannot be summarized'); + }, + signal: AbortSignal.timeout(8_000), + }; + const sources = await store.sourceMessages(session); + const archived = sources.find((row) => row.message.content[0]?.tool_use_id === 'diagnostics'); + assert.ok(archived); + const full = await pipeline.prepare({ ...input, window: 40_000 }); + assert(full.messages.some((message) => message.content[0]?.content === original)); + const projected = await pipeline.prepare(input); + assert(projected.stages.includes('S2')); + assert(projected.messages.some((message) => message.content === user)); + assert(projected.messages.some((message) => message.content[0]?.content === latest)); + assert.match(JSON.stringify(projected.messages), /Board model is RDK X5/); + assert(JSON.stringify(projected.messages).includes(archived.id)); + assert(projected.sourceIds.includes(archived.id)); + assert.doesNotMatch(JSON.stringify(projected.messages), /RAW_ARCHIVE_ONLY/); + assert.deepEqual(await store.sourceMessages(session), sources); + }); + console.log('PASS active tool pressure preserves the latest receipt and the full source archive'); +} + async function testConcurrentSummary(workspace) { const summaryStarted = latch(); const releaseSummary = latch(); @@ -1449,6 +1505,7 @@ try { for (const [directory, test] of [ ['progressive', testProgressiveStages], ['pressure-continuation', testPressureContinuation], + ['active-tool-pressure', testActiveToolPressure], ['checkpoint', testConcurrentSummary], ['source-validation', testSummarySourceValidation], ['approval', testApproval], diff --git a/src/core/session/versioned-context.ts b/src/core/session/versioned-context.ts index 364a92bb..821487c7 100644 --- a/src/core/session/versioned-context.ts +++ b/src/core/session/versioned-context.ts @@ -204,7 +204,7 @@ function summaryMessage( ); } -/** Keep exact tool output available to the turn that requested it. */ +/** Keep exact authored input as the boundary for ordinary tool-output editing. */ function activeTurnStart(sources: ContextSourceMessage[]): number { for (let index = sources.length - 1; index >= 0; index--) { if (trustedUser(sources[index]!)) return index; @@ -226,10 +226,11 @@ function limitToolOutput(text: string, id: string, head: number, tail: number): return `${text.slice(0, head)}\n[Output shortened. Original source: ${id}]\n${text.slice(-tail)}`; } -function editableView(sources: ContextSourceMessage[], currentTurnOrdinal: number): Message[] { +function editableView(sources: ContextSourceMessage[], preserveToolResultsFrom: number): Message[] { const messages = sources.map((source) => { const message = asMessage(source); - if (source.ordinal >= currentTurnOrdinal || !Array.isArray(message.content)) return message; + if (source.ordinal >= preserveToolResultsFrom || !Array.isArray(message.content)) + return message; return { ...message, content: message.content.map((block) => @@ -427,10 +428,13 @@ export class VersionedContextPipeline { hashContextSources( snapshot.messages.filter((row) => row.ordinal <= candidate.throughOrdinal) ); - const projected = (checkpoint: ContextCheckpoint) => { + const projected = ( + checkpoint: ContextCheckpoint, + preserveToolResultsFrom = currentTurnOrdinal + ) => { const tail = editableView( sources.filter((row) => row.ordinal > checkpoint.throughOrdinal || trustedUser(row)), - currentTurnOrdinal + preserveToolResultsFrom ); const evidence = lastEvidence && lastEvidence.ordinal <= checkpoint.throughOrdinal @@ -470,6 +474,8 @@ export class VersionedContextPipeline { return { ...minimal, evidence: undefined, historical: [] }; return best; }; + let pressureCheckpoint = isCompatible ? { checkpoint: candidate, stage: 'S4' } : undefined; + let summaryFailure: { error: unknown } | undefined; if (isCompatible) { const projection = projected(candidate); if (projection.legal && projection.tokens < selected.tokens) { @@ -481,6 +487,7 @@ export class VersionedContextPipeline { if (boundary && (!selected.legal || (input.force && !stages.includes('S4')))) { try { const checkpoint = await this.prepareSummary(input, snapshot, sources, boundary, policy); + pressureCheckpoint = { checkpoint, stage: 'S5' }; const projection = projected(checkpoint); if (projection.legal && projection.tokens < selected.tokens) { selected = projection; @@ -489,7 +496,8 @@ export class VersionedContextPipeline { } } catch (error) { input.signal.throwIfAborted(); - if (!selected.legal || input.force) throw error; + if (input.force) throw error; + if (!selected.legal) summaryFailure = { error }; } } else if (boundary && (retired || raw.tokens >= capacity * 0.5)) { // The current source view already excludes superseded conclusions. A @@ -513,6 +521,27 @@ export class VersionedContextPipeline { stages.push('S3'); } } + if (!selected.legal && lastEvidence && lastEvidence.ordinal > currentTurnOrdinal) { + // A multi-tool turn can exhaust the window even with a historical + // checkpoint. Shorten earlier receipts in the request only, preserving + // their source IDs and keeping the latest result batch exact. + const edited = fit(complete(editableView(sources, lastEvidence.ordinal))); + if (edited.legal) { + selected = edited; + } else if ( + pressureCheckpoint && + pressureCheckpoint.checkpoint.throughOrdinal < lastEvidence.ordinal + ) { + const { checkpoint, stage } = pressureCheckpoint; + const projection = projected(checkpoint, lastEvidence.ordinal); + if (projection.legal) { + selected = projection; + submittedSources = retainedIds(checkpoint, projection.evidence, projection.historical); + stages.push(stage); + } + } + if (selected.legal && !stages.includes('S2')) stages.unshift('S2'); + } input.signal.throwIfAborted(); if (this.store.revision(input.sessionKey) !== snapshot.revision) { throw new MossError({ @@ -522,6 +551,7 @@ export class VersionedContextPipeline { }); } if (!selected.legal) { + if (summaryFailure) throw summaryFailure.error; throw new MossError({ code: ErrorCode.PROVIDER_CONTEXT_OVERFLOW, message: 'Protected context cannot fit the model window with the current output budget', From 214bef18a80cfdab7d4c8f8d08dc7b40f41fd9e1 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 16:21:53 +0800 Subject: [PATCH 05/16] feat(sdk): prepare tool batches under the committed task decision --- docs/sdk-task-intent-revisions.md | 8 ++++ scripts/verify/task-intent-revisions.mjs | 45 ++++++++++++++++++++++ src/core/agent/agent-hooks.ts | 10 +++++ src/core/agent/index.ts | 1 + src/core/agent/moss-agent.ts | 19 +++++++++- src/core/index.ts | 1 + src/core/loop/agent-loop-response.ts | 48 +++++++++++++++++++++--- src/core/loop/agent-loop-types.ts | 2 + src/core/loop/agent-loop.ts | 1 + 9 files changed, 127 insertions(+), 8 deletions(-) diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index 61df6497..d43b3c57 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -26,6 +26,14 @@ For native tasks, `applyTaskRevision` commits a revision with an idempotent `rev Host callbacks outside normal tool execution must freeze the binding at callback creation and use `withTaskExecutionGuard(() => agent.assertTaskIntentCurrent(sessionKey, capturedIntent), action)`. Do not reread a new binding when an old callback wakes. Host evidence must also preserve its producing plan identity: stamping an old observation with the current revision does not make it current evidence. +Hosts that provision an isolated workspace can register `hooks.prepareToolBatch`. +The hook receives currently available, schema-checked business calls after the +runtime commits the pending decision. Use `assertCurrent()` before provisioning +and after each asynchronous step. The hook can update the host tool registry and +return a dispatch context with the new workspace. The SDK rechecks the decision, +resolves the updated tools and applies its usual approval and execution guards. +An answer or decision with no business calls skips the hook. + The SDK defaults to the existing path when this option is absent. Studio enables it for ordinary runs, while fixed JSON execution profiles retain their own protocol. Verification: `npm run verify` includes the `task-intent` stage, which exercises a scripted provider, durable recovery and native task revision/acceptance. These offline probes do not measure model interpretation accuracy or real-device behavior. diff --git a/scripts/verify/task-intent-revisions.mjs b/scripts/verify/task-intent-revisions.mjs index e3150a4e..db46bbcd 100644 --- a/scripts/verify/task-intent-revisions.mjs +++ b/scripts/verify/task-intent-revisions.mjs @@ -106,6 +106,51 @@ function register(agent, name, execute) { } try { + const workspaceSteps = []; + const admittedWorkspace = path.join(workspace, 'admitted'); + const admitted = createAgent( + (request, count) => { + if (count > 1) return response(text('Workspace verified.')); + return response(declaration(frame(request)), toolCall('workspace_probe')); + }, + { + hooks: { + prepareToolBatch: async ({ calls, context, assertCurrent }) => { + assertCurrent(); + assert.deepEqual( + calls.map((call) => call.name), + ['workspace_probe'] + ); + assert.equal(admitted.agent.getTaskIntent('workspace-admission').disposition, 'execute'); + assert.equal( + admitted.agent.getTaskIntentReceipt('workspace-admission', 'workspace-input').status, + 'committed' + ); + workspaceSteps.push('admit'); + admitted.agent.tools.remove('workspace_probe'); + register(admitted.agent, 'workspace_probe', async (_input, ctx) => { + assert.equal(ctx.workspaceDir, admittedWorkspace); + workspaceSteps.push('execute'); + return 'Verified the admitted workspace.'; + }); + return { ...context, workspaceDir: admittedWorkspace }; + }, + }, + } + ); + register(admitted.agent, 'workspace_probe', async () => { + workspaceSteps.push('stale tool'); + return 'This tool was replaced before dispatch.'; + }); + await admitted.agent.chat('workspace-admission', 'Verify the project', { + userInput: { id: 'workspace-input' }, + taskFlow: false, + }); + assert.deepEqual(workspaceSteps, ['admit', 'execute']); + console.log( + 'PASS tool batch preparation observes committed intent and replaces dispatch context' + ); + const starts = []; const { agent, provider } = createAgent((request, count) => { const f = frame(request); diff --git a/src/core/agent/agent-hooks.ts b/src/core/agent/agent-hooks.ts index b9bf9f71..6f64d957 100644 --- a/src/core/agent/agent-hooks.ts +++ b/src/core/agent/agent-hooks.ts @@ -12,6 +12,13 @@ export interface ToolApprovalRequest { abortSignal: AbortSignal; } +export interface ToolBatchPreparation { + calls: ReadonlyArray & { readonly tool: Tool }>; + context: Readonly; + abortSignal: AbortSignal; + assertCurrent(): void; +} + export type ToolApprovalDecision = | { approved: true; updatedInput?: Record } | { @@ -50,6 +57,9 @@ export interface AgentHooks { onOutputGuardrail?(request: OutputGuardrailRequest): Promise; + /** Prepare host resources after task intent commits, before resolving final tools and approvals. */ + prepareToolBatch?(request: ToolBatchPreparation): Promise; + onBeforeToolExec?(request: ToolApprovalRequest): Promise; onToolResult?(call: ToolCall, result: ToolResult): void; diff --git a/src/core/agent/index.ts b/src/core/agent/index.ts index 0390fff7..07e2074e 100644 --- a/src/core/agent/index.ts +++ b/src/core/agent/index.ts @@ -6,6 +6,7 @@ export type { OutputGuardrailRequest, OutputGuardrailDecision, ToolApprovalRequest, + ToolBatchPreparation, ToolApprovalDecision, } from './agent-hooks.js'; export { CommandQueueRegistry } from './command-queue.js'; diff --git a/src/core/agent/moss-agent.ts b/src/core/agent/moss-agent.ts index b192f991..ce66285a 100644 --- a/src/core/agent/moss-agent.ts +++ b/src/core/agent/moss-agent.ts @@ -1814,6 +1814,7 @@ ${result.stderr ?? ''}`.trim(); this.deferredTools.reveal('task'); } const hostDescribeMissingTool = this.config.describeMissingTool; + let toolWorkspaceDir = workspaceDir; const enrichedRun = enrichRunToolContext(hooks?.enrichToolContext, { workspaceDir, runId, @@ -1828,7 +1829,11 @@ ${result.stderr ?? ''}`.trim(); ...(this.config.fileWriteRoots ? { fileWriteRoots: this.config.fileWriteRoots } : {}), ...(this.config.osSandbox ? { osSandbox: true } : {}), mergeWorkspacePatch: async (leaseId, patchId) => { - const result = await mergeLeasePatch({ parentWorkspace: workspaceDir, leaseId, patchId }); + const result = await mergeLeasePatch({ + parentWorkspace: toolWorkspaceDir, + leaseId, + patchId, + }); return { status: result.status, conflictingPaths: result.status === 'merge_conflict' ? result.conflictingPaths : [], @@ -2084,7 +2089,9 @@ ${result.stderr ?? ''}`.trim(); reasoning: runReasoning, toolHooks: this.toolHooks, spawnRegistry: this.spawnRegistry, - workspaceDir, + get workspaceDir() { + return toolWorkspaceDir; + }, ...(toolCtx.protectedConfigPaths ? { protectedConfigPaths: toolCtx.protectedConfigPaths } : {}), @@ -2595,6 +2602,14 @@ ${result.stderr ?? ''}`.trim(); }; }, checkToolApproval: buildToolApprovalCheck(sessionKey, runId), + prepareToolBatch: + hooks?.prepareToolBatch && + (async (request) => { + const prepared = await hooks.prepareToolBatch!(request); + request.assertCurrent(); + if (prepared) toolWorkspaceDir = prepared.workspaceDir; + return prepared; + }), toolAbortSignalFor: options?.toolAbortSignalFor, enrichToolContext: (baseContext) => this.userQuestionAsker diff --git a/src/core/index.ts b/src/core/index.ts index 25c5bbcb..2575aeeb 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -12,6 +12,7 @@ export type { OutputGuardrailRequest, OutputGuardrailDecision, ToolApprovalRequest, + ToolBatchPreparation, ToolApprovalDecision, } from './agent/index.js'; export { CommandQueueRegistry } from './agent/index.js'; diff --git a/src/core/loop/agent-loop-response.ts b/src/core/loop/agent-loop-response.ts index 5d14a604..bbdd586c 100644 --- a/src/core/loop/agent-loop-response.ts +++ b/src/core/loop/agent-loop-response.ts @@ -30,6 +30,7 @@ import { import { executeAgentLoopToolCalls } from './agent-loop-tool-execution.js'; import type { PendingToolAbortStore } from './pending-tool-aborts.js'; import type { TaskIntentTurn } from '../session/task-intent-turn.js'; +import { validateToolInputObject } from '../tools/tool-pipeline.js'; import { isTaskExecutionSupersededError } from '../task/task-execution-guard.js'; export const EMPTY_MODEL_RESPONSE = @@ -106,6 +107,7 @@ export interface ProcessLlmResponseParams { maxToolCalls?: number; toolStartGuard?: AgentLoopExtensions['toolStartGuard']; runtimeJudge?: AgentLoopExtensions['runtimeJudge']; + prepareToolBatch?: import('./agent-loop-types.js').AgentLoopToolInput['prepareToolBatch']; checkToolApproval?: (call: { id: string; name: string; @@ -674,6 +676,43 @@ export async function processLlmResponse( assistantBuffer.shift(); } const intentGuard = params.taskIntentTurn?.executionGuard(); + let supersededPreparation: unknown; + const assertExecutionCurrent = () => { + if (supersededPreparation) throw supersededPreparation; + params.assertContextCurrent?.(); + intentGuard?.(); + }; + let dispatchContext = toolCtx; + if (params.prepareToolBatch && toolCalls.length > 0) { + const availableTools = new Map(resolveToolsForRun().map((tool) => [tool.name, tool])); + const calls = toolCalls.flatMap((call) => { + const tool = availableTools.get(call.name); + if (!tool) return []; + const input = validateToolInputObject(tool, call.input); + return input.ok ? [{ ...call, input: input.value, tool }] : []; + }); + if (calls.length > 0) { + const assertCurrent = () => { + abortSignal.throwIfAborted(); + assertExecutionCurrent(); + }; + try { + assertCurrent(); + const prepared = await params.prepareToolBatch({ + calls, + context: toolCtx, + abortSignal, + assertCurrent, + }); + assertCurrent(); + if (prepared) dispatchContext = prepared; + } catch (error) { + // The ordinary per-call guard records suppressed results for the stale batch. + if (!isTaskExecutionSupersededError(error)) throw error; + supersededPreparation = error; + } + } + } const toolExecution = await executeAgentLoopToolCalls({ initialToolResults: intentResponse?.results, registerToolInvocation: params.registerToolInvocation @@ -681,11 +720,8 @@ export async function processLlmResponse( params.registerToolInvocation!(id, name, mutates, intentGuard ?? (() => {})) : undefined, assertExecutionCurrent: - params.assertContextCurrent || intentGuard - ? () => { - params.assertContextCurrent?.(); - intentGuard?.(); - } + params.assertContextCurrent || intentGuard || supersededPreparation + ? assertExecutionCurrent : undefined, state, runId, @@ -695,7 +731,7 @@ export async function processLlmResponse( assistantContent, toolCalls, resolveToolsForRun, - toolCtx, + toolCtx: dispatchContext, toolHooks, abortSignal, toolTimeoutMs, diff --git a/src/core/loop/agent-loop-types.ts b/src/core/loop/agent-loop-types.ts index 2ad58063..4940452c 100644 --- a/src/core/loop/agent-loop-types.ts +++ b/src/core/loop/agent-loop-types.ts @@ -1,3 +1,4 @@ +import type { AgentHooks } from '../agent/agent-hooks.js'; import type { RuntimeJudgeRun } from '../agent/runtime-judge.js'; import type { Model, StreamFunction, ThinkingLevel } from '../../provider/pi-ai-types.js'; import type { ContextPruningSettings } from '../../context/pruning.js'; @@ -71,6 +72,7 @@ export interface AgentLoopToolInput { toolsForRun: Tool[]; getToolsForRun?: () => Tool[]; toolCtx: ToolContext; + prepareToolBatch?: AgentHooks['prepareToolBatch']; checkToolApproval?: (call: { id: string; name: string; diff --git a/src/core/loop/agent-loop.ts b/src/core/loop/agent-loop.ts index fa6b5931..88ca4892 100644 --- a/src/core/loop/agent-loop.ts +++ b/src/core/loop/agent-loop.ts @@ -729,6 +729,7 @@ export function runAgentLoop( toolLoopGuard, maxToolCalls, checkToolApproval: params.checkToolApproval, + prepareToolBatch: params.prepareToolBatch, toolStartGuard: params.toolStartGuard, runtimeJudge: params.runtimeJudge, guardAssistantOutput: params.guardAssistantOutput, From ae3a9cb0dd578169becbf6c98aa4a6367ed4dd70 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 16:46:42 +0800 Subject: [PATCH 06/16] feat(sdk): persist active constraint citations and one-shot claims --- docs/sdk-task-intent-revisions.md | 2 + scripts/verify/task-intent-store.mjs | 43 +++++++++++++++++++++ src/contracts/task-intent.ts | 2 + src/core/session/task-intent-state.ts | 24 ++++++++++-- src/core/session/versioned-session-store.ts | 19 +++++++++ 5 files changed, 86 insertions(+), 4 deletions(-) diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index d43b3c57..d5c7d6a9 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -34,6 +34,8 @@ return a dispatch context with the new workspace. The SDK rechecks the decision, resolves the updated tools and applies its usual approval and execution guards. An answer or decision with no business calls skips the hook. +Each active constraint may have an exact author citation in `state.constraintSources`. A host can use that citation to bind an execution allowance to its originating input. `VersionedSessionStore.claimExecutionReceipt(scope, id)` atomically reserves a host action in a durable namespace. Call it when a validated operation is about to cross its dispatch boundary. A reservation only records admission and survives an uncertain or failed dispatch. Confirm the outcome from the transport or tool receipt. + The SDK defaults to the existing path when this option is absent. Studio enables it for ordinary runs, while fixed JSON execution profiles retain their own protocol. Verification: `npm run verify` includes the `task-intent` stage, which exercises a scripted provider, durable recovery and native task revision/acceptance. These offline probes do not measure model interpretation accuracy or real-device behavior. diff --git a/scripts/verify/task-intent-store.mjs b/scripts/verify/task-intent-store.mjs index defaf658..726a378e 100644 --- a/scripts/verify/task-intent-store.mjs +++ b/scripts/verify/task-intent-store.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; +import { VersionedSessionStore } from '../../dist/core/session/versioned-session-store.js'; import { TaskIntentCoordinator } from '../../dist/core/session/task-intent-coordinator.js'; import { loadSessionInbox, @@ -68,6 +69,48 @@ try { } console.log('PASS correction during acceptance environment setup prevents process startup'); } + { + const authorizationInbox = path.join(workspace, 'authorization.json'); + const authorization = new TaskIntentCoordinator(port(authorizationInbox), workspace); + authorization.admit({ id: 'action-1', text: 'Run exactly uname -a once' }); + const authorizationBatch = await authorization.capture(); + const change = { + field: 'constraints', + operation: 'add', + value: 'example:uname -a', + messageId: 'action-1', + quote: 'uname -a', + }; + await authorization.commit( + authorizationBatch, + proposal(authorizationBatch, 'execute', [change]) + ); + const recovered = new TaskIntentCoordinator(port(authorizationInbox), workspace); + assert.deepEqual((await recovered.capture()).snapshot.state.constraintSources?.[change.value], { + messageId: 'action-1', + quote: 'uname -a', + }); + recovered.admit({ id: 'action-remove', text: 'Remove the uname -a permission' }); + const removal = await recovered.capture(); + await recovered.commit( + removal, + proposal(removal, 'answer', [{ ...change, operation: 'remove', messageId: 'action-remove' }]) + ); + assert.equal( + (await recovered.capture()).snapshot.state.constraintSources?.[change.value], + undefined + ); + const db = path.join(workspace, 'execution.sqlite'); + const firstStore = new VersionedSessionStore(db); + assert.equal(firstStore.claimExecutionReceipt('session', 'action-1'), true); + firstStore.close(); + const restartedStore = new VersionedSessionStore(db); + assert.equal(restartedStore.claimExecutionReceipt('session', 'action-1'), false); + assert.equal(restartedStore.claimExecutionReceipt('other-session', 'action-1'), true); + assert.deepEqual((await restartedStore.loadDeliverySnapshot('session')).deliveryIds, []); + restartedStore.close(); + console.log('PASS active constraint provenance and durable once-only action admission'); + } const file = path.join(workspace, 'receipt.json'); const a = new TaskIntentCoordinator(port(file), workspace); const b = new TaskIntentCoordinator(port(file), workspace); diff --git a/src/contracts/task-intent.ts b/src/contracts/task-intent.ts index 273508fc..792fa12a 100644 --- a/src/contracts/task-intent.ts +++ b/src/contracts/task-intent.ts @@ -11,6 +11,8 @@ export interface TaskIntentState { target: string; executionSurface: string; constraints: string[]; + /** Latest exact author quote for each active constraint value. */ + constraintSources?: Record; responseRequirements: string[]; sources: Record; } diff --git a/src/core/session/task-intent-state.ts b/src/core/session/task-intent-state.ts index 79bfa12e..8e6a0709 100644 --- a/src/core/session/task-intent-state.ts +++ b/src/core/session/task-intent-state.ts @@ -47,6 +47,19 @@ export function validatePersistedTaskIntent(input: unknown): void { strings(snapshot.planDependsOn, 'persisted plan dependencies', 32); strings(state.constraints, 'persisted constraints', Number.MAX_SAFE_INTEGER); strings(state.responseRequirements, 'persisted response requirements', Number.MAX_SAFE_INTEGER); + if (state.constraintSources !== undefined) { + for (const [constraint, source] of Object.entries(record(state.constraintSources))) { + const citation = record(source); + if ( + !(state.constraints as string[]).includes(constraint) || + typeof citation.messageId !== 'string' || + !citation.messageId || + typeof citation.quote !== 'string' || + !citation.quote + ) + throw new Error('Invalid persisted task constraint source'); + } + } for (const sources of Object.values(record(state.sources))) { if ( !Array.isArray(sources) || @@ -209,6 +222,12 @@ export function applyIntentChanges( if (!source || !source.prompt.includes(change.quote)) { throw new Error('Task changes must cite an exact quote from a pending user input'); } + const citation = { messageId: change.messageId, quote: change.quote }; + if (change.field === 'constraints') { + if (change.operation === 'add') + state.constraintSources = { ...state.constraintSources, [change.value]: citation }; + else if (state.constraintSources) delete state.constraintSources[change.value]; + } if (change.field === 'constraints' || change.field === 'responseRequirements') { const values = state[change.field]; if (change.operation === 'add') { @@ -219,10 +238,7 @@ export function applyIntentChanges( } else { state[change.field] = change.value; } - (state.sources[change.field] ??= []).push({ - messageId: change.messageId, - quote: change.quote, - }); + (state.sources[change.field] ??= []).push(citation); } return state; } diff --git a/src/core/session/versioned-session-store.ts b/src/core/session/versioned-session-store.ts index e628697c..8c0a5e7b 100644 --- a/src/core/session/versioned-session-store.ts +++ b/src/core/session/versioned-session-store.ts @@ -23,6 +23,8 @@ import { validatePersistedTaskIntent } from './task-intent-state.js'; const loadBuiltin = createRequire(import.meta.url); +import { assertTaskExecutionCurrent } from '../task/task-execution-guard.js'; + const SCHEMA = ` CREATE TABLE IF NOT EXISTS sessions ( key TEXT PRIMARY KEY, revision INTEGER NOT NULL DEFAULT 0, @@ -70,6 +72,11 @@ const SCHEMA = ` id TEXT NOT NULL, revision INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY(session, id) ); + CREATE TABLE IF NOT EXISTS execution_receipts ( + scope TEXT NOT NULL, + id TEXT NOT NULL, + PRIMARY KEY(scope, id) + ); CREATE TABLE IF NOT EXISTS invocations ( session TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE, id TEXT NOT NULL, revision INTEGER NOT NULL, started INTEGER NOT NULL, settled INTEGER, @@ -321,6 +328,18 @@ export class VersionedSessionStore implements SessionStore { }); } + /** Claim a host-owned action before dispatch. A receipt makes no claim about its outcome. */ + claimExecutionReceipt(scope: string, id: string): boolean { + if (!scope || !id) throw new Error('Execution receipt requires a host scope and identity'); + assertTaskExecutionCurrent(); + return this.transaction(() => + Boolean( + this.db.prepare('INSERT OR IGNORE INTO execution_receipts VALUES(?,?)').run(scope, id) + .changes + ) + ); + } + async seedIfEmpty(key: string, messages: LLMMessage[]): Promise { await this.adopt(key); return this.transaction(() => { From da2137de4a1d9af89e057533b9facdbac4e23800 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 17:13:23 +0800 Subject: [PATCH 07/16] Project oversized active tool evidence with source references --- docs/sdk-task-intent-revisions.md | 5 ++- scripts/verify/versioned-context.mjs | 41 +++++++++++++++++++- src/core/session/versioned-context.ts | 54 +++++++++++++++------------ 3 files changed, 75 insertions(+), 25 deletions(-) diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index d5c7d6a9..719923df 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -59,7 +59,10 @@ identity. Close the agent before closing a store owned by the host. The request pipeline progressively adjusts the output reservation, shortens old tool results, prepares checkpoints in the background, reuses compatible -checkpoints, or performs bounded synchronous summarization. Provider-independent +checkpoints, or performs bounded synchronous summarization. It keeps the latest +tool result batch intact when it fits. If that batch still prevents a request, +the projection sends source-linked excerpts with the same tool call IDs. The +original results remain available in the archive. Provider-independent admission uses a conservative serialized-size estimate. Provider-reported overflow triggers a bounded retry with a smaller budget. Structured summaries are historical data, and do not authorize work or commit acceptance. diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index 21ef6b1c..40c098e4 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -544,8 +544,47 @@ async function testActiveToolPressure(workspace) { assert(projected.sourceIds.includes(archived.id)); assert.doesNotMatch(JSON.stringify(projected.messages), /RAW_ARCHIVE_ONLY/); assert.deepEqual(await store.sourceMessages(session), sources); + + const oversized = + 'Full log for the newest board operation.\n' + + 'diagnostic payload\n'.repeat(1150) + + 'MIDDLE_ARCHIVE_ONLY\n' + + 'diagnostic payload\n'.repeat(1150) + + 'Final detection count: 7'; + await add(store, session, 'assistant', [toolCall('device_file_read', 'oversized')]); + await add( + store, + session, + 'user', + [ + { + type: 'tool_result', + tool_use_id: 'oversized', + name: 'device_file_read', + content: oversized, + structuredContent: [{ type: 'text', text: oversized }], + }, + ], + 'tool' + ); + const latestSources = await store.sourceMessages(session); + const source = latestSources.at(-1); + const bounded = await pipeline.prepare(input); + assert(bounded.stages.includes('S2')); + assert(bounded.messages.some((message) => message.content === user)); + const excerpt = bounded.messages + .flatMap((message) => message.content) + .find((part) => part.tool_use_id === 'oversized'); + assert(excerpt, 'An oversized active tool result must keep its call/result identity'); + assert(excerpt.content.includes(source.id)); + assert.match(excerpt.content, /Final detection count: 7/); + assert.doesNotMatch(JSON.stringify(bounded.messages), /MIDDLE_ARCHIVE_ONLY/); + assert(bounded.sourceIds.includes(source.id)); + assert.deepEqual(await store.sourceMessages(session), latestSources); }); - console.log('PASS active tool pressure preserves the latest receipt and the full source archive'); + console.log( + 'PASS active tool pressure keeps recent receipts when possible and cites oversized archived results' + ); } async function testConcurrentSummary(workspace) { diff --git a/src/core/session/versioned-context.ts b/src/core/session/versioned-context.ts index 821487c7..fae0b787 100644 --- a/src/core/session/versioned-context.ts +++ b/src/core/session/versioned-context.ts @@ -231,6 +231,8 @@ function editableView(sources: ContextSourceMessage[], preserveToolResultsFrom: const message = asMessage(source); if (source.ordinal >= preserveToolResultsFrom || !Array.isArray(message.content)) return message; + const excerpt = (text: string) => + limitToolOutput(text, source.id, HISTORICAL_TOOL_HEAD_CHARS, HISTORICAL_TOOL_TAIL_CHARS); return { ...message, content: message.content.map((block) => @@ -238,12 +240,14 @@ function editableView(sources: ContextSourceMessage[], preserveToolResultsFrom: ? block : { ...block, - content: limitToolOutput( - block.content, - source.id, - HISTORICAL_TOOL_HEAD_CHARS, - HISTORICAL_TOOL_TAIL_CHARS - ), + content: excerpt(block.content), + ...(block.structuredContent + ? { + structuredContent: block.structuredContent.map((part) => + part.type === 'text' ? { ...part, text: excerpt(part.text) } : part + ), + } + : {}), } ), }; @@ -522,25 +526,29 @@ export class VersionedContextPipeline { } } if (!selected.legal && lastEvidence && lastEvidence.ordinal > currentTurnOrdinal) { - // A multi-tool turn can exhaust the window even with a historical - // checkpoint. Shorten earlier receipts in the request only, preserving - // their source IDs and keeping the latest result batch exact. - const edited = fit(complete(editableView(sources, lastEvidence.ordinal))); - if (edited.legal) { - selected = edited; - } else if ( - pressureCheckpoint && - pressureCheckpoint.checkpoint.throughOrdinal < lastEvidence.ordinal - ) { - const { checkpoint, stage } = pressureCheckpoint; - const projection = projected(checkpoint, lastEvidence.ordinal); - if (projection.legal) { - selected = projection; - submittedSources = retainedIds(checkpoint, projection.evidence, projection.historical); - stages.push(stage); + // Prefer exact recent evidence. If the latest batch itself exceeds the + // model window, project cited excerpts while keeping the archive intact. + for (const preserveFrom of [lastEvidence.ordinal, lastEvidence.ordinal + 1]) { + const edited = fit(complete(editableView(sources, preserveFrom))); + if (edited.legal) { + selected = edited; + } else if ( + pressureCheckpoint && + pressureCheckpoint.checkpoint.throughOrdinal < lastEvidence.ordinal + ) { + const { checkpoint, stage } = pressureCheckpoint; + const projection = projected(checkpoint, preserveFrom); + if (projection.legal) { + selected = projection; + submittedSources = retainedIds(checkpoint, projection.evidence, projection.historical); + stages.push(stage); + } + } + if (selected.legal) { + if (!stages.includes('S2')) stages.unshift('S2'); + break; } } - if (selected.legal && !stages.includes('S2')) stages.unshift('S2'); } input.signal.throwIfAborted(); if (this.store.revision(input.sessionKey) !== snapshot.revision) { From 32832ae57c9d4dd10fc3a7f3de9258abc492295a Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 17:45:54 +0800 Subject: [PATCH 08/16] Allow hosts to validate task decisions before commit SDK adds the optional synchronous MossAgentConfig.validateTaskIntentDecision callback. A rejection uses the native decision repair loop before any durable intent or business dispatch. --- docs/sdk-task-intent-revisions.md | 9 +++ scripts/verify/task-intent-revisions.mjs | 87 ++++++++++++++++++++++++ src/core/agent/moss-agent-types.ts | 7 ++ src/core/agent/moss-agent.ts | 3 +- src/core/session/task-intent-turn.ts | 12 +++- 5 files changed, 115 insertions(+), 3 deletions(-) diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index 719923df..1cb068a5 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -16,6 +16,15 @@ agent.steer(sessionKey, correction, { id: stableCorrectionId, taskId }); The model proposes field-level changes and a plan through `turn_decision` in its normal response. Runtime checks input identity, exact source quotations, schema and the captured revision before committing. Unmentioned fields survive. This validates protocol and provenance, not the semantic correctness of an interpretation. Ambiguous input should produce `clarify`, and capability questions should produce `answer`, with no business calls. +Hosts can set `MossAgentConfig.validateTaskIntentDecision` when a proposed +decision must follow host-specific rules. The synchronous callback receives a +copy of the parsed `TurnDecision` with any runtime-bound fields filled in. Return +without a value to continue to the SDK's commit checks. Throw an error with +model-facing repair guidance to reject the decision and every business call in +the response. The input stays pending, and the existing bounded decision retry +gives the model a chance to submit a corrected declaration. Use a short error +message suitable for the model with sensitive details omitted. + `getTaskIntent` returns the committed state plus the current pending-input barrier. `getTaskIntentReceipt` distinguishes semantic commit from canonical message delivery. Input IDs are session-scoped and must never be reused for different text. After the inbox payload limit, processed inputs retain compact hash/receipt tombstones so retries remain idempotent; these small identity records grow with the session. With `sessionInboxDir`, input, receipt and the retryable task projection share the existing locked, fsynced inbox journal. A projecting entry blocks actions until recovery completes. Deterministically rejected projections remain failed/pending and may be superseded by a valid new input, including a fresh task binding. Storage errors fail closed. diff --git a/scripts/verify/task-intent-revisions.mjs b/scripts/verify/task-intent-revisions.mjs index db46bbcd..47782824 100644 --- a/scripts/verify/task-intent-revisions.mjs +++ b/scripts/verify/task-intent-revisions.mjs @@ -11,8 +11,12 @@ const { MossAgent } = await import(pathToFileURL(path.join(dist, 'core/agent/mos const { InMemorySessionStore } = await import( pathToFileURL(path.join(dist, 'core/session/session.js')).href ); +const { VersionedSessionStore } = await import( + pathToFileURL(path.join(dist, 'core/session/versioned-session-store.js')).href +); const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'moss-intent-')); const agents = []; +const validationStore = new VersionedSessionStore(path.join(workspace, 'validation.sqlite')); function frame(options) { const lines = options.systemPrompt.split('\n'); @@ -151,6 +155,88 @@ try { 'PASS tool batch preparation observes committed intent and replaces dispatch context' ); + const session = 'host-validation'; + const hostInputId = 'host-source-input'; + const literal = 'uname -m'; + const hostInput = `Run this exact command once: ${literal}`; + const repair = 'Quote only the exact command literal'; + const validConstraint = `device_command_once:${literal}`; + const proposedQuotes = []; + const dispatched = []; + const validated = createAgent( + (request, count) => { + if (count === 3) return response(text('Checked the requested architecture.')); + if (count === 2) { + assert.match(JSON.stringify(request.messages), new RegExp(repair)); + const pending = validated.agent.getTaskIntent(session); + assert.equal(pending.pending, true); + assert.equal(pending.processedSeq, 0); + assert.deepEqual(pending.state.constraints, []); + assert.deepEqual(dispatched, []); + assert.equal(validated.agent.getTaskIntentReceipt(session, hostInputId).status, 'pending'); + } + const quote = count === 1 ? hostInput : literal; + return response( + { + type: 'tool_use', + id: `validated-decision-${count}`, + name: 'turn_decision', + input: { + disposition: 'execute', + plan: ['Check architecture'], + changes: [ + { + field: 'constraints', + operation: 'add', + value: validConstraint, + messageId: hostInputId, + quote, + }, + ], + }, + }, + toolCall('validate_action', `validated-action-${count}`) + ); + }, + { + sessionStore: validationStore, + validateTaskIntentDecision(decision) { + assert.equal(decision.baseRevision, 0); + assert.equal(decision.inputSeq, 1); + assert.deepEqual(decision.messageIds, [hostInputId]); + const change = decision.changes[0]; + proposedQuotes.push(change.quote); + if (change.quote !== literal) throw new Error(repair); + change.value = 'ignored-by-the-runtime'; + }, + } + ); + register(validated.agent, 'validate_action', async (_input, context) => { + const committed = validated.agent.getTaskIntent(session); + assert.equal(committed.pending, false); + assert.equal(committed.processedSeq, 1); + assert.equal(validated.agent.getTaskIntentReceipt(session, hostInputId).status, 'committed'); + assert.deepEqual(committed.state.constraints, [validConstraint]); + assert.deepEqual(committed.state.constraintSources[validConstraint], { + messageId: hostInputId, + quote: literal, + }); + dispatched.push(context.toolCallId); + return 'Architecture confirmed by the probe.'; + }); + const validatedResult = await validated.agent.chat(session, hostInput, { + userInput: { id: hostInputId }, + taskFlow: false, + maxTurns: 5, + }); + assert.deepEqual(proposedQuotes, [hostInput, literal]); + assert.deepEqual(dispatched, ['validated-action-2']); + assert.equal(validated.provider.calls, 3); + assert.equal(validatedResult.response, 'Checked the requested architecture.'); + console.log( + 'PASS host validation rejects the entire batch before commit and repairs the same pending input' + ); + const starts = []; const { agent, provider } = createAgent((request, count) => { const f = frame(request); @@ -392,5 +478,6 @@ try { console.log('PASS restart persistence, receipt dedupe, pending-input barrier'); } finally { await Promise.allSettled(agents.map((agent) => agent.close())); + validationStore.close(); await fs.rm(workspace, { recursive: true, force: true }); } diff --git a/src/core/agent/moss-agent-types.ts b/src/core/agent/moss-agent-types.ts index 7dd7b2cf..643b1e0a 100644 --- a/src/core/agent/moss-agent-types.ts +++ b/src/core/agent/moss-agent-types.ts @@ -7,6 +7,7 @@ import type { LLMStreamEvent, } from '../llm/llm-provider.js'; import type { PromptLayersPort } from '../../contracts/prompt-layer.js'; +import type { TurnDecision } from '../../contracts/task-intent.js'; import type { Message, ContentBlock } from '../session/session-jsonl.js'; import type { SessionStore } from '../session/session.js'; import type { @@ -184,6 +185,12 @@ export interface MossAgentConfig /** Require same-response task updates before acting on genuine user inputs. */ taskIntent?: boolean; + /** + * Synchronously check a parsed decision before it commits. Throw a + * model-facing repair message to reject the decision and its tool batch. + */ + validateTaskIntentDecision?: (decision: Readonly) => void; + /** Host provider id (`deepseek`, `openai-compatible`, …). Updated by `switchModel`. */ provider?: string; diff --git a/src/core/agent/moss-agent.ts b/src/core/agent/moss-agent.ts index ce66285a..17320427 100644 --- a/src/core/agent/moss-agent.ts +++ b/src/core/agent/moss-agent.ts @@ -1629,7 +1629,8 @@ ${result.stderr ?? ''}`.trim(); pendingTexts, correctionsOnly ) - : undefined + : undefined, + this.config.validateTaskIntentDecision ) : undefined; await intentTurn?.prepare(); diff --git a/src/core/session/task-intent-turn.ts b/src/core/session/task-intent-turn.ts index 83620b9d..b59af34d 100644 --- a/src/core/session/task-intent-turn.ts +++ b/src/core/session/task-intent-turn.ts @@ -3,7 +3,7 @@ import { CONTEXT_CLAIMS_TOOL, parseClaimDrafts, } from './context-claim-declaration.js'; -import type { TaskIntentSnapshot } from '../../contracts/task-intent.js'; +import type { TaskIntentSnapshot, TurnDecision } from '../../contracts/task-intent.js'; import type { Tool } from '../tools/tool-types.js'; import { isTaskExecutionSupersededError } from '../task/task-execution-guard.js'; import type { ContentBlock } from './session-jsonl.js'; @@ -44,7 +44,8 @@ export class TaskIntentTurn { private readonly correctionTargets?: ( pendingTexts: readonly string[], correctionsOnly?: boolean - ) => Array<{ id: string; origin: string; text: string }> + ) => Array<{ id: string; origin: string; text: string }>, + private readonly validateDecision?: (decision: Readonly) => void ) {} async prepare(): Promise { @@ -319,6 +320,13 @@ export class TaskIntentTurn { ) { throw new Error('answer/clarify/cancel cannot include business tool calls'); } + const validation: unknown = this.validateDecision?.(structuredClone(decision)); + if (validation !== undefined) { + void Promise.resolve(validation).catch(() => {}); + throw new Error( + 'Host task intent validation must finish synchronously without a return value' + ); + } this.binding = await this.coordinator.commit(this.batch!, decision); this.assertCurrent(decision.disposition !== 'execute'); this.batch = { ...this.batch!, snapshot: this.binding, inputs: [] }; From eacaa614900066c024f09bfda0d2c1a4dbe0331a Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 20:16:58 +0800 Subject: [PATCH 09/16] Project corrected history for scoped context handoffs --- scripts/verify/versioned-context.mjs | 62 ++++++++++++++++++++- src/core/index.ts | 1 + src/core/session/versioned-context.ts | 18 ++++++ src/core/session/versioned-session-store.ts | 41 ++++++++++++++ 4 files changed, 121 insertions(+), 1 deletion(-) diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index 40c098e4..d7a260a8 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -17,7 +17,7 @@ const [ artifacts, { resumeTask }, { createAgentTurnRunner }, - { VersionedContextPipeline }, + { VersionedContextPipeline, projectContextHandoff }, { decodeSummaryEntries, relevantHistoricalExcerpts }, ] = await Promise.all([ load('core/agent/moss-agent.js'), @@ -146,6 +146,65 @@ async function add(store, session, role, content, origin = role) { await store.appendMessage(session, { role, content }, origin); } +async function testContextHandoff(workspace) { + const database = path.join(workspace, 'handoff.sqlite'); + const store = new VersionedSessionStore(database); + const sourceKey = 'original-device'; + const targetKey = 'new-device'; + const request = { sourceKey, targetKey, deliveryId: 'handoff-one' }; + try { + await add(store, sourceKey, 'user', 'Keep model M.'); + await add(store, sourceKey, 'assistant', 'Model M is ready to inspect.'); + await add(store, sourceKey, 'assistant', oldClaim); + const targetId = (await store.sourceMessages(sourceKey)).at(-1).id; + await store.correct(sourceKey, { id: 'correct-original', targetId, text: correctionText }); + const snapshot = store.snapshot(sourceKey); + const projected = projectContextHandoff(snapshot); + assert.deepEqual( + projected.map(({ text }) => text), + ['Keep model M.', 'Model M is ready to inspect.'] + ); + const content = projected.map(({ text }) => text).join('\n') + '\n' + correctionText; + const input = { + ...request, + sourceRevision: snapshot.revision, + message: { role: 'assistant', content }, + }; + assert.equal( + await store.appendContextHandoffOnce({ ...input, sourceRevision: 0 }), + 'source-changed' + ); + assert.deepEqual(await store.loadMessages(targetKey), []); + assert.equal(await store.appendContextHandoffOnce(input), 'imported'); + assert.equal(await store.appendContextHandoffOnce(input), 'duplicate'); + assert.deepEqual( + store.snapshot(targetKey).messages.map(({ origin }) => origin), + ['assistant'] + ); + store.updateInbox(sourceKey, (inbox) => inbox.admit({ prompt: 'A correction may follow.' })); + assert.equal( + await store.appendContextHandoffOnce({ ...input, deliveryId: 'handoff-two' }), + 'source-changed' + ); + } finally { + store.close(); + } + const reopened = new VersionedSessionStore(database); + try { + const transferred = await reopened.sourceMessages(targetKey); + assert.equal(transferred.length, 1); + assert.doesNotMatch(JSON.stringify(transferred), new RegExp(oldClaim)); + await reopened.correct(targetKey, { + id: 'correct-import', + targetId: transferred[0].id, + text: 'Model M still needs testing.', + }); + assert.deepEqual(projectContextHandoff(reopened.snapshot(targetKey)), []); + } finally { + reopened.close(); + } +} + async function seed(store, session) { for (let index = 0; index < 8; index++) { await add(store, session, 'assistant', `Earlier note ${index}. `.repeat(215)); @@ -1542,6 +1601,7 @@ const workspace = await fs.realpath( ); try { for (const [directory, test] of [ + ['context-handoff', testContextHandoff], ['progressive', testProgressiveStages], ['pressure-continuation', testPressureContinuation], ['active-tool-pressure', testActiveToolPressure], diff --git a/src/core/index.ts b/src/core/index.ts index 2575aeeb..c38a0340 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,4 +1,5 @@ export { VersionedSessionStore } from './session/versioned-session-store.js'; +export { projectContextHandoff } from './session/versioned-context.js'; export type { ContextCorrection, ContextSourceMessage, diff --git a/src/core/session/versioned-context.ts b/src/core/session/versioned-context.ts index fae0b787..61b2a1f5 100644 --- a/src/core/session/versioned-context.ts +++ b/src/core/session/versioned-context.ts @@ -28,6 +28,7 @@ import { dedupeUnchangedReadToolResults, invalidateStaleReadToolResults, } from '../../context/stale-read-invalidate.js'; +import { isInternalAssistantText, resumeUserText } from './internal-transcript.js'; const SUMMARY_PROMPT = [ 'Summarize the supplied historical data. Use corrections to filter obsolete interpretations. Do not produce entries for corrections themselves, which are already retained in the context.', @@ -139,6 +140,23 @@ export function contextSourceView(snapshot: VersionedContextSnapshot): ContextSo }); } +/** Visible historical text after correction, with original source identities. */ +export function projectContextHandoff(snapshot: VersionedContextSnapshot) { + return contextSourceView(snapshot).flatMap((source) => { + const { role, content } = source.message; + const user = role === 'user' && trustedUser(source); + const assistant = + role === 'assistant' && (source.origin === 'assistant' || source.origin === 'legacy'); + if (!user && !assistant) return []; + const raw = + typeof content === 'string' + ? content + : content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('\n'); + const text = user ? resumeUserText(raw) : stripThinkingTagsKeepVisible(raw).trim(); + return text && (user || !isInternalAssistantText(text)) ? [{ id: source.id, role, text }] : []; + }); +} + function correctionMessage(snapshot: VersionedContextSnapshot): Message[] { const claims = snapshot.claims.filter((claim) => claim.status === 'active').slice(-32); if (!snapshot.corrections.length && !claims.length) return []; diff --git a/src/core/session/versioned-session-store.ts b/src/core/session/versioned-session-store.ts index 8c0a5e7b..d1923de8 100644 --- a/src/core/session/versioned-session-store.ts +++ b/src/core/session/versioned-session-store.ts @@ -328,6 +328,47 @@ export class VersionedSessionStore implements SessionStore { }); } + /** Import quoted historical context without admitting it as a new user input. */ + async appendContextHandoffOnce(input: { + sourceKey: string; + sourceRevision: number; + targetKey: string; + deliveryId: string; + message: LLMMessage; + }): Promise<'imported' | 'duplicate' | 'source-changed'> { + const { sourceKey, sourceRevision, targetKey, deliveryId, message } = input; + if ( + !sourceKey || + !targetKey || + sourceKey === targetKey || + !deliveryId || + message.role !== 'assistant' + ) { + throw new Error( + 'A context handoff requires distinct sessions, a delivery ID, and historical assistant text' + ); + } + await this.adopt(targetKey); + return this.transaction(() => { + if ( + this.db + .prepare('SELECT 1 FROM receipts WHERE session=? AND id=?') + .get(targetKey, deliveryId) + ) + return 'duplicate'; + if ( + !this.has(sourceKey) || + this.revision(sourceKey) !== sourceRevision || + this.readInbox(sourceKey).pending().length + ) + return 'source-changed'; + this.create(targetKey); + this.db.prepare('INSERT INTO receipts VALUES(?,?)').run(targetKey, deliveryId); + this.append(targetKey, message, 'assistant', undefined, this.revision(targetKey)); + return 'imported'; + }); + } + /** Claim a host-owned action before dispatch. A receipt makes no claim about its outcome. */ claimExecutionReceipt(scope: string, id: string): boolean { if (!scope || !id) throw new Error('Execution receipt requires a host scope and identity'); From dc945d210ca750d999d4f3af5c7d2af19efc1d43 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 21:12:08 +0800 Subject: [PATCH 10/16] Keep corrected answer rebuilds on the read-only surface --- scripts/verify/versioned-context.mjs | 19 ++++++++-- src/core/agent/moss-agent.ts | 4 +++ src/core/session/task-intent-turn.ts | 52 ++++++++++++++++++--------- src/core/session/versioned-context.ts | 4 ++- 4 files changed, 58 insertions(+), 21 deletions(-) diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index d7a260a8..6bf8e32b 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -933,6 +933,15 @@ async function testCapturedCorrection(workspace) { workspace, async ({ agent, store, modelRequests }) => { const session = 'captured-correction'; + agent.tools.register({ + name: 'test_correction_pending_action', + description: 'Represents an otherwise available host tool', + metadata: { sideEffectClass: 'local_write' }, + inputSchema: { type: 'object', properties: {} }, + async execute() { + throw new Error('A committed answer must not start any business tool'); + }, + }); await add(store, session, 'assistant', oldClaim); for (let index = 0; index < 18; index++) { await add(store, session, 'assistant', `Independent historical note ${index}. `.repeat(60)); @@ -971,7 +980,8 @@ async function testCapturedCorrection(workspace) { { onMain(request, count) { if (count === 2) { - assert(!request.tools?.some(({ name }) => name === 'context_claims')); + assert.equal(request.tools?.length ?? 0, 0, 'Rebuilding a corrected answer has no tools'); + assert.doesNotMatch(request.systemPrompt, /"contextSources":/); return response(text(answer)); } const previous = request.systemPrompt @@ -980,12 +990,15 @@ async function testCapturedCorrection(workspace) { assert(previous); const { contextSources } = JSON.parse(previous); assert(!contextSources.some(({ text }) => text === correctionText) || count === 3); - if (count === 1) assert(contextSources.some(({ id }) => id === targetId)); + const target = contextSources.find(({ id }) => id === targetId); + if (count === 1) assert.match(target.correctionId, /^s\d+$/); return response( toolCall('turn_decision', `capture-${count}`, { disposition: 'answer', answer, - contextCorrections: [{ targetId, quote: correctionText }], + contextCorrections: [ + { targetId: target?.correctionId ?? targetId, quote: correctionText }, + ], }), toolCall('context_claims', `invalid-claim-${count}`, { claims: [{ text: 'Unsupported', sourceIds: ['unknown'], dependsOn: [] }], diff --git a/src/core/agent/moss-agent.ts b/src/core/agent/moss-agent.ts index 17320427..fa7aaeeb 100644 --- a/src/core/agent/moss-agent.ts +++ b/src/core/agent/moss-agent.ts @@ -1884,6 +1884,10 @@ ${result.stderr ?? ''}`.trim(); }; }; const resolveRunTools = (): ReturnType => { + if (intentTurn?.isAnswerOnly) { + readOnlyIntentSurface = true; + return []; + } const tools = filterToolsForRun( [...this.tools.getAll(), ...(options?.ephemeralTools ?? [])], visibleForRun diff --git a/src/core/session/task-intent-turn.ts b/src/core/session/task-intent-turn.ts index b59af34d..27d90ee1 100644 --- a/src/core/session/task-intent-turn.ts +++ b/src/core/session/task-intent-turn.ts @@ -44,7 +44,7 @@ export class TaskIntentTurn { private readonly correctionTargets?: ( pendingTexts: readonly string[], correctionsOnly?: boolean - ) => Array<{ id: string; origin: string; text: string }>, + ) => Array<{ id: string; origin: string; role: string; text: string }>, private readonly validateDecision?: (decision: Readonly) => void ) {} @@ -67,6 +67,21 @@ export class TaskIntentTurn { return (this.batch?.inputs.length ?? 0) > 0; } + get isAnswerOnly(): boolean { + return Boolean( + this.correctionTargets && + this.binding && + !this.needsDecision && + this.binding.disposition !== 'execute' + ); + } + + private registerCorrectionAlias(id: string, ordinal: number): string { + const alias = `s${ordinal}`; + this.correctionAliases.set(alias, id); + return alias; + } + private readOnlyPrompt(batch: TaskIntentBatch, renderedInputId?: string): string { const frame = { revision: batch.snapshot.revision, @@ -98,11 +113,10 @@ export class TaskIntentTurn { const targets = this.correctionTargets!( batch.inputs.map(({ prompt }) => prompt), true - ).map((source, index) => { - const alias = `s${index + 1}`; - this.correctionAliases.set(alias, source.id); - return { ...source, id: alias }; - }); + ).map(({ role: _role, ...source }, index) => ({ + ...source, + id: this.registerCorrectionAlias(source.id, index + 1), + })); if (targets.length) header.push(JSON.stringify({ contextSources: targets })); return [ ...header, @@ -120,13 +134,19 @@ export class TaskIntentTurn { prompt(readOnly = false, renderedInputId?: string): string { const batch = this.batch; if (!batch) return ''; - if ( - this.correctionTargets && - !this.hasBoundTask && - (readOnly || (!this.needsDecision && batch.snapshot.disposition !== 'execute')) - ) { + if (this.correctionTargets && (this.isAnswerOnly || (readOnly && !this.hasBoundTask))) { return this.readOnlyPrompt(batch, renderedInputId); } + let correctionOrdinal = 0; + const sources = this.correctionTargets?.(batch.inputs.map(({ prompt }) => prompt)).map( + ({ role, ...source }) => + role === 'assistant' && this.needsDecision + ? { + ...source, + correctionId: this.registerCorrectionAlias(source.id, ++correctionOrdinal), + } + : source + ); return [ '[Runtime-owned current task intent]', JSON.stringify({ @@ -136,16 +156,14 @@ export class TaskIntentTurn { plan: batch.snapshot.pending ? [] : batch.snapshot.plan, pendingInputs: batch.inputs.map((entry) => ({ id: entry.id, text: entry.prompt })), }), - ...(this.correctionTargets + ...(sources ? [ - 'Use context_claims only for new facts a future action will depend on. Skip it for a read-only answer or for repeating a user correction. Use original source IDs and explicit claim dependencies. A claim grants no permissions.', - JSON.stringify({ - contextSources: this.correctionTargets(batch.inputs.map((entry) => entry.prompt)), - }), + 'Use context_claims only for new facts a future action will depend on. Skip it for a read-only answer or for repeating a user correction. Cite the id field and explicit claim dependencies. A claim grants no permissions.', + JSON.stringify({ contextSources: sources }), ...(this.needsDecision ? [ CORRECTION_SCOPE_GUIDANCE, - 'When a pending user input explicitly corrects or supplies facts that contradict an older assistant conclusion, include contextCorrections with the old assistant/claim ID as targetId and copy an exact quote from the pending input. The runtime matches a unique quote to its input ID. Never resubmit a recorded correction during a follow-up. Clarify when you cannot identify the old conclusion.', + 'When a pending user input contradicts an older conclusion, set contextCorrections.targetId to the correctionId shown on the exact assistant source containing the old conclusion. Copy an exact quote from the pending input. Never select an unrelated source or resubmit a recorded correction. Clarify when you cannot identify the old conclusion.', 'For a read-only answer or historical correction, call turn_decision with disposition: "answer", the answer, and any contextCorrections. Omit changes and plan unless updating a real task. Do not copy runtime metadata or add a task change for the requested answer format.', ] : []), diff --git a/src/core/session/versioned-context.ts b/src/core/session/versioned-context.ts index 61b2a1f5..d3910b7d 100644 --- a/src/core/session/versioned-context.ts +++ b/src/core/session/versioned-context.ts @@ -346,6 +346,7 @@ export class VersionedContextPipeline { .map(({ id, origin, message }) => ({ id, origin, + role: message.role, text: typeof message.content === 'string' ? message.content @@ -356,9 +357,10 @@ export class VersionedContextPipeline { .join(' '), })) .filter(({ text }) => text.trim() && !pendingTexts.includes(text)) - .map(({ id, origin, text }) => ({ + .map(({ id, origin, role, text }) => ({ id, origin, + role, text: correctionsOnly && text.length > 360 ? `${text.slice(0, 180)}\n[…]\n${text.slice(-180)}` From b32b304919ca678b9ac6fc93719a7eb77d0adf70 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 21:40:08 +0800 Subject: [PATCH 11/16] Expose bounded original tool evidence for the active context --- docs/sdk-task-intent-revisions.md | 6 +++ scripts/verify/versioned-context.mjs | 64 +++++++++++++++++++++++- src/core/index.ts | 7 ++- src/core/session/versioned-context.ts | 70 +++++++++++++++++++++++++++ 4 files changed, 145 insertions(+), 2 deletions(-) diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index 1cb068a5..88179b01 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -65,6 +65,12 @@ identity. Close the agent before closing a store owned by the host. - `/compact` prepares or selects a source-checked checkpoint. It preserves original source rows. `MossAgent.listContextSources` can inspect them after a restart. Imported sessions can only retain messages still present on disk. +- Hosts can call `readContextToolEvidence(store.snapshot(sessionKey), query)` to + retrieve a bounded excerpt from an original tool receipt. Resolve the session + and its owner on the host. The query accepts a source ID, a result block + index, an offset and an optional literal match. The result carries the + context revision and original tool call ID. A receipt from an earlier + execution remains historical evidence for that execution. The request pipeline progressively adjusts the output reservation, shortens old tool results, prepares checkpoints in the background, reuses compatible diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index 6bf8e32b..d45d7925 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -17,7 +17,12 @@ const [ artifacts, { resumeTask }, { createAgentTurnRunner }, - { VersionedContextPipeline, projectContextHandoff }, + { + CONTEXT_TOOL_EVIDENCE_TOOL, + VersionedContextPipeline, + projectContextHandoff, + readContextToolEvidence, + }, { decodeSummaryEntries, relevantHistoricalExcerpts }, ] = await Promise.all([ load('core/agent/moss-agent.js'), @@ -146,6 +151,62 @@ async function add(store, session, role, content, origin = role) { await store.appendMessage(session, { role, content }, origin); } +async function testSameSessionToolEvidence(workspace) { + const filename = path.join(workspace, 'tool-evidence.sqlite'); + const key = 'authorized-session'; + const store = new VersionedSessionStore(filename); + let sourceId; + try { + const raw = 'a'.repeat(3_000) + '\nORIGINAL_MIDDLE_RECEIPT\n' + 'z'.repeat(3_000); + await add(store, key, 'assistant', [toolCall('device_file_read', 'actual-call')]); + await add( + store, + key, + 'user', + [{ type: 'tool_result', tool_use_id: 'actual-call', content: raw, name: 'device_file_read' }], + 'tool' + ); + await add(store, key, 'assistant', oldClaim); + const before = store.snapshot(key); + sourceId = before.messages[1].id; + const excerpt = readContextToolEvidence(before, { sourceId, match: 'ORIGINAL_MIDDLE_RECEIPT' }); + assert.match(excerpt.text, /ORIGINAL_MIDDLE_RECEIPT/); + assert.equal(excerpt.toolUseId, 'actual-call'); + assert.equal(excerpt.text.length, 2_000); + assert(excerpt.nextOffset > excerpt.offset); + assert.equal(readContextToolEvidence(before, { sourceId, match: 'missing' }).offset, null); + assert.equal(readContextToolEvidence(store.snapshot('another-session'), { sourceId }), null); + const old = before.messages[2].id; + await store.correct(key, { id: 'revised-evidence', targetId: old, text: correctionText }); + assert.equal(readContextToolEvidence(store.snapshot(key), { sourceId: old }), null); + + await add(store, key, 'assistant', [toolCall(CONTEXT_TOOL_EVIDENCE_TOOL, 'derived-call')]); + await add( + store, + key, + 'user', + [{ type: 'tool_result', tool_use_id: 'derived-call', content: 'Derived copy' }], + 'tool' + ); + const current = store.snapshot(key); + assert.equal(readContextToolEvidence(current, { sourceId: current.messages.at(-1).id }), null); + assert.equal(readContextToolEvidence(current, { sourceId, offset: -1 }), null); + } finally { + store.close(); + } + const reopened = new VersionedSessionStore(filename); + try { + assert.equal(readContextToolEvidence(reopened.snapshot(key), { sourceId }).revision, 1); + await reopened.rewind(key, 1); + assert.equal(readContextToolEvidence(reopened.snapshot(key), { sourceId }), null); + } finally { + reopened.close(); + } + console.log( + 'PASS original tool receipts can be read by source without recovering stale or foreign messages' + ); +} + async function testContextHandoff(workspace) { const database = path.join(workspace, 'handoff.sqlite'); const store = new VersionedSessionStore(database); @@ -1615,6 +1676,7 @@ const workspace = await fs.realpath( try { for (const [directory, test] of [ ['context-handoff', testContextHandoff], + ['same-session-tool-evidence', testSameSessionToolEvidence], ['progressive', testProgressiveStages], ['pressure-continuation', testPressureContinuation], ['active-tool-pressure', testActiveToolPressure], diff --git a/src/core/index.ts b/src/core/index.ts index c38a0340..68c9cde4 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,5 +1,10 @@ export { VersionedSessionStore } from './session/versioned-session-store.js'; -export { projectContextHandoff } from './session/versioned-context.js'; +export { + CONTEXT_TOOL_EVIDENCE_TOOL, + projectContextHandoff, + readContextToolEvidence, +} from './session/versioned-context.js'; +export type { ContextToolEvidenceQuery } from './session/versioned-context.js'; export type { ContextCorrection, ContextSourceMessage, diff --git a/src/core/session/versioned-context.ts b/src/core/session/versioned-context.ts index d3910b7d..0d669315 100644 --- a/src/core/session/versioned-context.ts +++ b/src/core/session/versioned-context.ts @@ -45,6 +45,8 @@ const MAX_SUMMARY_MS = 25_000; const RECENT_GROUP_MESSAGES = 8; const HISTORICAL_TOOL_HEAD_CHARS = 800; const HISTORICAL_TOOL_TAIL_CHARS = 300; +export const CONTEXT_TOOL_EVIDENCE_TOOL = 'context_source_read'; +const CONTEXT_TOOL_EVIDENCE_CHARS = 2_000; const SUMMARY_POLICY = createHash('sha256').update(SUMMARY_PROMPT).digest('hex'); function asMessage(source: ContextSourceMessage): Message { @@ -157,6 +159,74 @@ export function projectContextHandoff(snapshot: VersionedContextSnapshot) { }); } +export interface ContextToolEvidenceQuery { + sourceId: string; + block?: number; + offset?: number; + match?: string; +} + +/** Read an original tool receipt from an active, already owner-scoped session snapshot. */ +export function readContextToolEvidence( + snapshot: VersionedContextSnapshot, + { sourceId, block = 0, offset = 0, match }: ContextToolEvidenceQuery +) { + if ( + !sourceId || + sourceId.length > 200 || + !Number.isSafeInteger(block) || + block < 0 || + !Number.isSafeInteger(offset) || + offset < 0 || + (match !== undefined && (!match || match.length > 200)) + ) + return null; + const view = contextSourceView(snapshot); + const source = view.find((candidate) => candidate.id === sourceId); + if (!source || !['tool', 'legacy'].includes(source.origin)) return null; + const content = source.message.content; + if (!Array.isArray(content)) return null; + const results = content.filter((part) => part.type === 'tool_result'); + const result = results[block]; + if ( + !result || + result.name === CONTEXT_TOOL_EVIDENCE_TOOL || + view.some( + ({ message }) => + Array.isArray(message.content) && + message.content.some( + (part) => + part.type === 'tool_use' && + part.id === result.tool_use_id && + part.name === CONTEXT_TOOL_EVIDENCE_TOOL + ) + ) + ) + return null; + const text = + result.content || + result.structuredContent + ?.flatMap((part) => (part.type === 'text' ? [part.text] : [])) + .join('\n') || + ''; + const found = match === undefined ? offset : text.indexOf(match, offset); + const start = found === -1 ? null : match === undefined ? offset : Math.max(offset, found - 240); + const end = start === null ? null : Math.min(text.length, start + CONTEXT_TOOL_EVIDENCE_CHARS); + return { + sourceId, + revision: snapshot.revision, + block, + blockCount: results.length, + toolUseId: result.tool_use_id, + ...(result.name ? { tool: result.name } : {}), + ...(result.is_error ? { isError: true } : {}), + length: text.length, + offset: start, + nextOffset: end !== null && end < text.length ? end : null, + text: start !== null && end !== null ? text.slice(start, end) : '', + }; +} + function correctionMessage(snapshot: VersionedContextSnapshot): Message[] { const claims = snapshot.claims.filter((claim) => claim.status === 'active').slice(-32); if (!snapshot.corrections.length && !claims.length) return []; From 2d2fa2ee7f99ce7335c5af989d436693ad2e9165 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 21:51:28 +0800 Subject: [PATCH 12/16] Restrict task decision repair to the decision declaration --- scripts/verify/task-intent-revisions.mjs | 45 +++++++++++++++++++++++- src/core/agent/moss-agent.ts | 8 ++++- src/core/session/task-intent-turn.ts | 4 +++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/scripts/verify/task-intent-revisions.mjs b/scripts/verify/task-intent-revisions.mjs index 47782824..75874476 100644 --- a/scripts/verify/task-intent-revisions.mjs +++ b/scripts/verify/task-intent-revisions.mjs @@ -384,7 +384,16 @@ try { console.log('PASS input during receipt persistence prevents stale answer publication'); let illegalStarts = 0; - const invalid = createAgent(() => response(toolCall('illegal'))); + const invalid = createAgent((request, count) => { + if (count === 2) { + assert.deepEqual( + request.tools.map(({ name }) => name), + ['turn_decision'] + ); + assert.equal(request.toolChoice, 'required'); + } + return response(toolCall('illegal')); + }); register(invalid.agent, 'illegal', async () => { illegalStarts++; return 'should not execute'; @@ -399,6 +408,40 @@ try { assert.equal(held.stopReason, 'task_intent_hold'); console.log('PASS missing declaration blocks all actions with bounded repair'); + let recoveredStarts = 0; + const recovered = createAgent((request, count) => { + if (count === 1) return response(toolCall('recovered_action')); + if (count === 2) { + assert.deepEqual( + request.tools.map(({ name }) => name), + ['turn_decision'] + ); + return response(declaration(frame(request), 'execute')); + } + if (count === 3) { + assert(request.tools.some(({ name }) => name === 'recovered_action')); + return response(toolCall('recovered_action')); + } + return response(text('Verified after the decision repair.')); + }); + register(recovered.agent, 'recovered_action', async () => { + recoveredStarts++; + return 'verified'; + }); + await recovered.agent.chat('decision-repair', 'Recover the pending task', { + userInput: { id: 'decision-repair-1' }, + taskFlow: false, + maxTurns: 5, + }); + assert.equal(recoveredStarts, 1); + assert.equal( + recovered.agent.getTaskIntentReceipt('decision-repair', 'decision-repair-1').status, + 'committed' + ); + console.log( + 'PASS a failed declaration can repair and execute without replaying its original tool call' + ); + const raceStarts = []; let race; race = createAgent((request, count) => { diff --git a/src/core/agent/moss-agent.ts b/src/core/agent/moss-agent.ts index fa7aaeeb..f15b0f7d 100644 --- a/src/core/agent/moss-agent.ts +++ b/src/core/agent/moss-agent.ts @@ -1904,6 +1904,10 @@ ${result.stderr ?? ''}`.trim(); hostFiltersTools && (!claimTool || !hostFiltersTools(claimTool)) ); + if (intentTurn?.isRepairingDecision) { + const decisionTool = intentTurn.tool(readOnlyIntentSurface); + if (decisionTool) return [decisionTool]; + } const declarations = [ intentTurn?.tool(readOnlyIntentSurface), readOnlyIntentSurface ? undefined : claimTool, @@ -1966,7 +1970,9 @@ ${result.stderr ?? ''}`.trim(); const streamFn = createStreamFunctionFromLlmProvider({ provider, getToolChoice: (tools) => - readOnlyIntentSurface && intentTurn?.needsDecision && tools?.length === 1 + (readOnlyIntentSurface || intentTurn?.isRepairingDecision) && + intentTurn?.needsDecision && + tools?.length === 1 ? 'required' : undefined, preferStructuredOutput: () => Boolean(preparedProjection?.revision), diff --git a/src/core/session/task-intent-turn.ts b/src/core/session/task-intent-turn.ts index 27d90ee1..4a17bf73 100644 --- a/src/core/session/task-intent-turn.ts +++ b/src/core/session/task-intent-turn.ts @@ -67,6 +67,10 @@ export class TaskIntentTurn { return (this.batch?.inputs.length ?? 0) > 0; } + get isRepairingDecision(): boolean { + return this.needsDecision && this.attempts > 0; + } + get isAnswerOnly(): boolean { return Boolean( this.correctionTargets && From 67a5d45ab31b24447f210a8eb75f1584ffc5662d Mon Sep 17 00:00:00 2001 From: d-robotics Date: Mon, 23 Nov 2026 22:00:08 +0800 Subject: [PATCH 13/16] Bind task amendments to exact pending user citations --- scripts/verify/versioned-context.mjs | 69 +++++++++++++++++++++++++++ src/core/loop/agent-loop-response.ts | 1 - src/core/session/task-intent-state.ts | 16 +++++++ src/core/session/task-intent-turn.ts | 20 +++++++- 4 files changed, 104 insertions(+), 2 deletions(-) diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index d45d7925..905db803 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -987,6 +987,74 @@ async function testModelDeclaredCorrection(workspace) { ); } +async function testCurrentQuoteAmendsTaskScope(workspace) { + const session = 'task-scope-amendment'; + const prior = 'Inspect the fixture without changes.'; + const next = 'Now update the first value.'; + let writes = 0; + const change = (operation, quote, messageId) => ({ + field: 'constraints', + operation, + value: 'read_only', + quote, + ...(messageId ? { messageId } : {}), + }); + await usingAgent( + workspace, + async ({ agent }) => { + agent.tools.register({ + name: 'test_scope_amendment', + description: 'Execute the newly authorized fixture write', + inputSchema: { type: 'object', properties: {} }, + metadata: { sideEffectClass: 'local_write' }, + async execute() { + writes++; + return 'Fixture updated'; + }, + }); + await agent.chat(session, prior, { userInput: { id: 'prior-inspection' }, taskFlow: false }); + await agent.chat(session, next, { userInput: { id: 'current-amendment' }, taskFlow: false }); + assert.equal(agent.getTaskIntentReceipt(session, 'current-amendment').status, 'committed'); + assert.equal(writes, 1); + }, + { + onMain(request, count) { + if (count === 1) + return response( + toolCall('turn_decision', 'inspection', { + disposition: 'answer', + changes: [change('add', prior)], + answer: 'Inspection noted.', + }) + ); + if (count === 2 || count === 3) { + if (count === 3) + assert.deepEqual( + request.tools.map(({ name }) => name), + ['turn_decision'] + ); + return response( + toolCall('turn_decision', `amend-${count}`, { + disposition: 'execute', + plan: ['Update the fixture.'], + changes: [ + count === 2 ? change('remove', prior, 'prior-inspection') : change('remove', next), + ], + }) + ); + } + assert.equal(writes, count === 4 ? 0 : 1); + return count === 4 + ? response(toolCall('test_scope_amendment')) + : response(text('Fixture updated.')); + }, + } + ); + console.log( + 'PASS scope amendments bind to current exact author quotes without reusing stale citations' + ); +} + async function testCapturedCorrection(workspace) { let targetId; const answer = 'Full acceptance is pending.'; @@ -1684,6 +1752,7 @@ try { ['source-validation', testSummarySourceValidation], ['approval', testApproval], ['declaration', testModelDeclaredCorrection], + ['scope-amendment-quote', testCurrentQuoteAmendsTaskScope], ['captured-correction', testCapturedCorrection], ['read-only-intent', testReadOnlyIntentPrompt], ['claims', testClaimDependencies], diff --git a/src/core/loop/agent-loop-response.ts b/src/core/loop/agent-loop-response.ts index bbdd586c..0a1fb8e1 100644 --- a/src/core/loop/agent-loop-response.ts +++ b/src/core/loop/agent-loop-response.ts @@ -224,7 +224,6 @@ export async function processLlmResponse( if (intentResponse.halt) { state.taskIntentHalted = true; state.finalText = intentResponse.halt; - pushGuardedMessageDeltas(push, intentResponse.halt); } pushTurnEnd(); if (intentResponse.halt) { diff --git a/src/core/session/task-intent-state.ts b/src/core/session/task-intent-state.ts index 8e6a0709..1e5e0680 100644 --- a/src/core/session/task-intent-state.ts +++ b/src/core/session/task-intent-state.ts @@ -319,6 +319,22 @@ export const versionedTurnDecisionSchema = { ...turnDecisionSchema.properties.changes, description: 'Omit for a read-only answer or historical correction. Only include actual task amendments.', + items: { + ...turnDecisionSchema.properties.changes.items, + properties: { + ...turnDecisionSchema.properties.changes.items.properties, + messageId: { + type: 'string', + description: 'Omit when the quote uniquely matches one pending user input.', + }, + quote: { + type: 'string', + description: + 'Exact words of the pending input authorizing this amendment. For a removal, quote the new instruction, never the older restriction.', + }, + }, + required: ['field', 'operation', 'value', 'quote'], + }, }, plan: { ...turnDecisionSchema.properties.plan, diff --git a/src/core/session/task-intent-turn.ts b/src/core/session/task-intent-turn.ts index 4a17bf73..8989cde6 100644 --- a/src/core/session/task-intent-turn.ts +++ b/src/core/session/task-intent-turn.ts @@ -181,6 +181,10 @@ export class TaskIntentTurn { ? 'The runtime binds this declaration to the captured user inputs.' : 'Copy revision/inputSeq and all pending messageIds in order.', 'Propose task changes only with exact quotes from pending inputs. Use set for scalars and add/remove for lists. Use answer for a read-only response, clarify for uncertainty and cancel to stop. Execute requires a concrete plan and existing authorization. Never use an internal engine prompt to replace the user goal.', + 'When removing a previous constraint, quote the current words that authorize the change. The old restriction is not authorization.', + this.correctionTargets + ? 'If a quote matches just one pending input, omit the messageId and the runtime will bind it.' + : '', ].join(' ') : 'No new user input needs interpretation. Continue the effective task using its committed plan. Do not emit turn_decision again.', ].join('\n'); @@ -226,6 +230,20 @@ export class TaskIntentTurn { private parseDecision(input: Record, batch: TaskIntentBatch) { if (!this.correctionTargets) return parseTurnDecision(input); + const changes: unknown = Array.isArray(input.changes) + ? (input.changes as unknown[]).map((item) => { + if (!item || typeof item !== 'object') return item; + const change = item as Record; + const { quote, messageId } = change; + if (messageId !== undefined || typeof quote !== 'string' || !quote.trim()) return change; + const matches = batch.inputs.filter((entry) => entry.prompt.includes(quote)); + if (matches.length !== 1) + throw new Error( + 'Every task change must quote one pending user input. For a removal, quote the new instruction.' + ); + return { ...change, messageId: matches[0]!.id }; + }) + : input.changes; const corrections: unknown = Array.isArray(input.contextCorrections) ? (input.contextCorrections as unknown[]).flatMap((item) => { if (!item || typeof item !== 'object') return [item]; @@ -261,7 +279,7 @@ export class TaskIntentTurn { baseRevision: input.baseRevision ?? batch.snapshot.revision, inputSeq: input.inputSeq ?? batch.snapshot.inputSeq, messageIds: input.messageIds ?? batch.inputs.map(({ id }) => id), - changes: input.changes ?? [], + changes: changes ?? [], plan: input.plan ?? [], contextCorrections: corrections, }); From 41dcfc4c2ee989a16b4e145ac62368ad71f06edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E5=90=8C=E6=98=A5?= <1195898813@qq.com> Date: Tue, 24 Nov 2026 16:40:23 +0800 Subject: [PATCH 14/16] Preserve versioned history across Studio project scope changes --- docs/sdk-task-intent-revisions.md | 8 + scripts/verify/versioned-context.mjs | 116 ++++++++++++++- src/core/session/versioned-session-store.ts | 157 +++++++++++++++++--- 3 files changed, 256 insertions(+), 25 deletions(-) diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index 88179b01..4bf45cc0 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -71,6 +71,14 @@ identity. Close the agent before closing a store owned by the host. index, an offset and an optional literal match. The result carries the context revision and original tool call ID. A receipt from an earlier execution remains historical evidence for that execution. +- Hosts that switch the active workspace within a session can call + `store.enterContextScope(sessionKey, scopeId)` with an identity selected by the + host. Switching starts a new revision and hides the previous workspace's + sources, corrections, claims and checkpoints from the next model request. + The original rows remain in `sourceMessages`. The store rejects scope changes + while an input is still pending. `activeContextScope` returns a scope identity + and revision that a host can include in a context handoff's `scopeCheck` to + reject a transfer captured before either session changed scope. The request pipeline progressively adjusts the output reservation, shortens old tool results, prepares checkpoints in the background, reuses compatible diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index 905db803..a84acd45 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -12,7 +12,7 @@ const dist = process.env.MOSS_VERIFY_DIST_ROOT ?? path.join(root, 'dist'); const load = (file) => import(pathToFileURL(path.join(dist, file)).href); const [ { MossAgent }, - { VersionedSessionStore }, + { VersionedSessionStore, hashContextSources }, tasks, artifacts, { resumeTask }, @@ -207,6 +207,119 @@ async function testSameSessionToolEvidence(workspace) { ); } +async function testContextScope(workspace) { + const database = path.join(workspace, 'context.sqlite'); + const key = 'same-conversation'; + const first = new VersionedSessionStore(database); + const original = createAgent(workspace, first); + let originalIds; + try { + assert.equal(await first.enterContextScope(key, 'first-project'), true); + await original.agent.chat(key, 'Old workspace goal and target', { + userInput: { id: 'old-goal' }, + }); + assert.equal( + original.agent.getTaskIntent(key).state.goal, + 'Old workspace goal and target' + ); + await add(first, key, 'assistant', [toolCall('read_file', 'old-read')]); + await add( + first, + key, + 'user', + [{ type: 'tool_result', tool_use_id: 'old-read', content: 'OLD_WORKSPACE_RECEIPT' }], + 'tool' + ); + await add(first, key, 'assistant', 'OLD_WORKSPACE_CONCLUSION'); + const old = first.snapshot(key); + originalIds = old.messages.map(({ id }) => id); + const sourceId = old.messages.at(-2).id; + const targetId = old.messages.at(-1).id; + const correction = { id: 'old-correction', targetId, text: 'OLD_WORKSPACE_CORRECTION' }; + await first.correct(key, correction); + const corrected = first.snapshot(key); + const priorCheckpoint = { + revision: corrected.revision, + policy: 'summary:project-test', + throughOrdinal: corrected.messages.at(-1).ordinal, + sourceHash: hashContextSources(corrected.messages), + entries: [{ kind: 'observation', text: 'OLD_WORKSPACE_SUMMARY', sourceIds: [sourceId] }], + }; + assert(first.commitCheckpoint(key, priorCheckpoint)); + await first.replaceMessages(key, [{ role: 'assistant', content: 'OLD_WORKSPACE_OVERLAY' }]); + const scopeCheck = { target: first.activeContextScope(key) }; + await first.enterContextScope('same-project-other-device', 'first-project'); + await add(first, 'same-project-other-device', 'assistant', 'OLD_DEVICE_HISTORY'); + scopeCheck.source = first.activeContextScope('same-project-other-device'); + + first.updateInbox(key, (inbox) => + inbox.admit({ id: 'pending', prompt: 'Complete old pending request' }) + ); + await assert.rejects(first.enterContextScope(key, 'next-project'), /Resolve pending input/); + assert.deepEqual(first.activeContextScope(key), scopeCheck.target); + first.updateInbox(key, (inbox) => inbox.promote('pending')); + + assert.equal( + await first.enterContextScope(key, 'next-project', { + boundaryMessage: 'Use only the active project.', + }), + true + ); + const switched = first.snapshot(key); + assert.equal(switched.revision, corrected.revision + 1); + assert.deepEqual(switched.corrections, []); + assert.equal(readContextToolEvidence(switched, { sourceId }), null); + assert.equal( + first.earlierCheckpointBoundary(key, switched.revision, 'project-test'), + undefined + ); + assert.equal(first.commitCheckpoint(key, priorCheckpoint), false); + await assert.rejects(first.correct(key, correction), /Correction ID was reused/); + await assert.rejects( + first.correct(key, { ...correction, id: 'retry-stale' }), + /active assistant message/ + ); + assert.equal(original.agent.getTaskIntent(key).state.goal, ''); + assert.equal(original.agent.getTaskIntent(key).planId, ''); + assert.equal(await first.enterContextScope(key, 'next-project'), false); + assert.equal( + await first.appendContextHandoffOnce({ + sourceKey: 'same-project-other-device', + sourceRevision: first.revision('same-project-other-device'), + targetKey: key, + deliveryId: 'delayed-import', + scopeCheck, + message: { role: 'assistant', content: 'OLD_DEVICE_HISTORY' }, + }), + 'source-changed' + ); + } finally { + await original.agent.close(); + first.close(); + } + + const reopened = new VersionedSessionStore(database); + const updated = createAgent(workspace, reopened); + try { + assert.equal(reopened.activeContextScope(key)?.id, 'next-project'); + assert.deepEqual( + (await reopened.sourceMessages(key)).slice(0, originalIds.length).map(({ id }) => id), + originalIds + ); + await updated.agent.chat(key, 'Inspect the new project.', { userInput: { id: 'next-goal' } }); + const request = JSON.stringify(updated.modelRequests[0]); + assert.match(request, /Use only the active project/); + assert.doesNotMatch(request, /OLD_WORKSPACE_|OLD_DEVICE_HISTORY|Old workspace goal/); + assert.equal(updated.agent.getTaskIntent(key).state.goal, 'Inspect the new project.'); + } finally { + await updated.agent.close(); + reopened.close(); + } + console.log( + 'PASS project scope retains old raw history, retires old decisions, and survives restart' + ); +} + async function testContextHandoff(workspace) { const database = path.join(workspace, 'handoff.sqlite'); const store = new VersionedSessionStore(database); @@ -1744,6 +1857,7 @@ const workspace = await fs.realpath( try { for (const [directory, test] of [ ['context-handoff', testContextHandoff], + ['context-scope', testContextScope], ['same-session-tool-evidence', testSameSessionToolEvidence], ['progressive', testProgressiveStages], ['pressure-continuation', testPressureContinuation], diff --git a/src/core/session/versioned-session-store.ts b/src/core/session/versioned-session-store.ts index d1923de8..489d91c7 100644 --- a/src/core/session/versioned-session-store.ts +++ b/src/core/session/versioned-session-store.ts @@ -19,7 +19,11 @@ import type { LLMMessage } from '../llm/llm-provider.js'; import { redactJsonLine } from './redact-json-line.js'; import type { SessionMeta, SessionStore } from './session.js'; import { SessionInbox, type SessionInboxEntry } from './session-inbox.js'; -import { validatePersistedTaskIntent } from './task-intent-state.js'; +import { + emptyTaskIntent, + readTaskIntent, + validatePersistedTaskIntent, +} from './task-intent-state.js'; const loadBuiltin = createRequire(import.meta.url); @@ -30,6 +34,10 @@ const SCHEMA = ` key TEXT PRIMARY KEY, revision INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL, updated INTEGER NOT NULL, imported INTEGER NOT NULL DEFAULT 0 ); + CREATE TABLE IF NOT EXISTS context_scopes ( + session TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE, + scope TEXT NOT NULL, first_ordinal INTEGER NOT NULL, first_revision INTEGER NOT NULL + ); CREATE TABLE IF NOT EXISTS messages ( session TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE, ordinal INTEGER NOT NULL, id TEXT NOT NULL, origin TEXT NOT NULL, body TEXT NOT NULL, @@ -210,13 +218,33 @@ export class VersionedSessionStore implements SessionStore { }); } + private contextScope( + key: string + ): { scope: string; firstOrdinal: number; firstRevision: number } | undefined { + const row = this.db + .prepare('SELECT scope,first_ordinal,first_revision FROM context_scopes WHERE session=?') + .get(key); + return row + ? { + scope: String(row.scope), + firstOrdinal: Number(row.first_ordinal), + firstRevision: Number(row.first_revision), + } + : undefined; + } + + activeContextScope(key: string): { id: string; revision: number } | undefined { + const current = this.contextScope(key); + return current ? { id: current.scope, revision: current.firstRevision } : undefined; + } + private sourceRows(key: string, includeInactive = false): ContextSourceMessage[] { return this.db .prepare( `SELECT id,ordinal,origin,body,generation FROM messages WHERE session=? - ${includeInactive ? '' : 'AND active=1'} ORDER BY ordinal` + ${includeInactive ? '' : 'AND active=1 AND ordinal>=?'} ORDER BY ordinal` ) - .all(key) + .all(...(includeInactive ? [key] : [key, this.contextScope(key)?.firstOrdinal ?? 0])) .map((row) => ({ id: String(row.id), ordinal: Number(row.ordinal), @@ -226,6 +254,77 @@ export class VersionedSessionStore implements SessionStore { })); } + private activeCorrections(key: string): CommittedContextCorrection[] { + const firstRevision = this.contextScope(key)?.firstRevision ?? 0; + return this.db + .prepare('SELECT body FROM corrections WHERE session=? AND revision>=? ORDER BY revision') + .all(key, firstRevision) + .map((row) => parse(row.body)); + } + + /** A trusted host can move the active context to a new scope without changing the source archive. */ + async enterContextScope( + key: string, + scope: string, + options: { adoptCurrent?: boolean; boundaryMessage?: string } = {} + ): Promise { + if (!scope.trim() || scope.length > 240) + throw new MossError({ code: ErrorCode.USER_INPUT_INVALID, message: 'Invalid context scope' }); + await this.adopt(key); + return this.transaction(() => { + const previous = this.contextScope(key); + if (previous?.scope === scope) return false; + const lastOrdinal = this.lastOrdinal(key); + const startFresh = + (lastOrdinal > 0 || Boolean(previous)) && !(options.adoptCurrent && !previous); + this.create(key); + if (startFresh) this.retireContextIntent(key); + const revision = this.revision(key) + 1; + this.db + .prepare('INSERT OR REPLACE INTO context_scopes VALUES(?,?,?,?)') + .run(key, scope, startFresh ? lastOrdinal + 1 : 0, startFresh ? revision : 0); + if (startFresh) { + this.db.prepare('UPDATE claims SET active=0 WHERE session=?').run(key); + this.db.prepare('DELETE FROM overlays WHERE session=?').run(key); + this.db + .prepare('UPDATE sessions SET revision=?,updated=? WHERE key=?') + .run(revision, Date.now(), key); + if (options.boundaryMessage?.trim()) { + this.append(key, { role: 'user', content: options.boundaryMessage }, 'runtime'); + } + } + return true; + }); + } + + private retireContextIntent(key: string): void { + const inbox = this.readInbox(key); + const current = readTaskIntent(inbox.toEntries()); + if (current.pending || inbox.pending().length) { + throw new MossError({ + code: ErrorCode.EXECUTION_STATE_INVALID, + message: 'Resolve pending input in the current context before switching scopes', + }); + } + if (!current.inputSeq) return; + const entry = inbox.admit({ + id: `context-scope:${randomUUID()}`, + prompt: '', + metadata: { intentOnly: true }, + }); + inbox.promote(entry.id); + inbox.setIntent(entry.id, { + status: 'committed', + snapshot: { + ...emptyTaskIntent(), + revision: current.revision + 1, + inputSeq: entry.admittedSeq, + processedSeq: entry.admittedSeq, + }, + }); + this.saveInbox(key, inbox); + } + readInbox(key: string, legacy?: () => SessionInbox): SessionInbox { const row = this.db.prepare('SELECT body FROM inboxes WHERE session=?').get(key); if (!row) return legacy?.() ?? new SessionInbox(); @@ -266,10 +365,7 @@ export class VersionedSessionStore implements SessionStore { () => ({ revision: this.revision(key), messages: this.sourceRows(key), - corrections: this.db - .prepare('SELECT body FROM corrections WHERE session=? ORDER BY revision') - .all(key) - .map((row) => parse(row.body)), + corrections: this.activeCorrections(key), claims: this.claimRows(key), }), false @@ -335,6 +431,10 @@ export class VersionedSessionStore implements SessionStore { targetKey: string; deliveryId: string; message: LLMMessage; + scopeCheck?: { + source?: ReturnType; + target?: ReturnType; + }; }): Promise<'imported' | 'duplicate' | 'source-changed'> { const { sourceKey, sourceRevision, targetKey, deliveryId, message } = input; if ( @@ -356,10 +456,20 @@ export class VersionedSessionStore implements SessionStore { .get(targetKey, deliveryId) ) return 'duplicate'; + const scopeMatches = ( + key: string, + expected: ReturnType + ) => { + const current = this.activeContextScope(key); + return current?.id === expected?.id && current?.revision === expected?.revision; + }; if ( !this.has(sourceKey) || this.revision(sourceKey) !== sourceRevision || - this.readInbox(sourceKey).pending().length + this.readInbox(sourceKey).pending().length || + (input.scopeCheck && + (!scopeMatches(sourceKey, input.scopeCheck.source) || + !scopeMatches(targetKey, input.scopeCheck.target))) ) return 'source-changed'; this.create(targetKey); @@ -466,7 +576,11 @@ export class VersionedSessionStore implements SessionStore { .get(key, input.id); if (previous) { const value = parse(previous.body); - if (value.targetId !== clean.targetId || value.text !== clean.text) { + if ( + value.targetId !== clean.targetId || + value.text !== clean.text || + value.revision < (this.contextScope(key)?.firstRevision ?? 0) + ) { throw new MossError({ code: ErrorCode.EXECUTION_REVISION_CONFLICT, message: 'Correction ID was reused for different content', @@ -475,8 +589,10 @@ export class VersionedSessionStore implements SessionStore { return value; } const target = this.db - .prepare('SELECT ordinal,body FROM messages WHERE session=? AND id=? AND active=1') - .get(key, clean.targetId); + .prepare( + 'SELECT ordinal,body FROM messages WHERE session=? AND id=? AND active=1 AND ordinal>=?' + ) + .get(key, clean.targetId, this.contextScope(key)?.firstOrdinal ?? 0); const claim = this.claimRows(key).find( (item) => item.id === clean.targetId && item.status === 'active' ); @@ -540,10 +656,7 @@ export class VersionedSessionStore implements SessionStore { /** Joins the transaction that is recording the model's validated declaration. */ registerClaimsInTransaction(key: string, drafts: ContextClaimDraft[]): ContextClaim[] { const sources = new Map(this.sourceRows(key).map((row) => [row.id, row])); - const corrections = this.db - .prepare('SELECT body FROM corrections WHERE session=?') - .all(key) - .map((row) => parse(row.body)); + const corrections = this.activeCorrections(key); const active = new Set( this.claimRows(key) .filter((claim) => claim.status === 'active') @@ -710,9 +823,9 @@ export class VersionedSessionStore implements SessionStore { earlierCheckpointBoundary(key: string, revision: number, policyKey: string): number | undefined { const row = this.db .prepare( - `SELECT covered FROM checkpoints WHERE session=? AND revision=? AND substr(policy,instr(policy,':')+1)=? ORDER BY revision DESC, covered DESC LIMIT 1` ) - .get(key, revision, policyKey); + .get(key, revision, this.contextScope(key)?.firstOrdinal ?? 0, policyKey); return row ? Number(row.covered) : undefined; } @@ -720,13 +833,9 @@ export class VersionedSessionStore implements SessionStore { const clean = parse>( redactJsonLine({ targetId, text }) ); - return this.db - .prepare('SELECT body FROM corrections WHERE session=?') - .all(key) - .some((row) => { - const correction = parse(row.body); - return correction.targetId === clean.targetId && correction.text === clean.text; - }); + return this.activeCorrections(key).some( + (correction) => correction.targetId === clean.targetId && correction.text === clean.text + ); } checkpoint(key: string, revision: number, policy: string): ContextCheckpoint | undefined { From 4d8b58401b74752bb036a886cf68b019475f49b1 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Tue, 24 Nov 2026 17:46:33 +0800 Subject: [PATCH 15/16] fix(context): fence late project output and legacy pending input --- scripts/verify/versioned-context.mjs | 35 ++++++++++++++++++--- src/core/rsi/engine.ts | 4 ++- src/core/session/versioned-session-store.ts | 24 +++++++++----- 3 files changed, 50 insertions(+), 13 deletions(-) diff --git a/scripts/verify/versioned-context.mjs b/scripts/verify/versioned-context.mjs index a84acd45..0060d05e 100644 --- a/scripts/verify/versioned-context.mjs +++ b/scripts/verify/versioned-context.mjs @@ -218,10 +218,7 @@ async function testContextScope(workspace) { await original.agent.chat(key, 'Old workspace goal and target', { userInput: { id: 'old-goal' }, }); - assert.equal( - original.agent.getTaskIntent(key).state.goal, - 'Old workspace goal and target' - ); + assert.equal(original.agent.getTaskIntent(key).state.goal, 'Old workspace goal and target'); await add(first, key, 'assistant', [toolCall('read_file', 'old-read')]); await add( first, @@ -267,6 +264,14 @@ async function testContextScope(workspace) { ); const switched = first.snapshot(key); assert.equal(switched.revision, corrected.revision + 1); + await first.appendMessage( + key, + { role: 'assistant', content: 'OLD_WORKSPACE_LATE_ANSWER' }, + 'assistant', + corrected.revision + ); + assert.doesNotMatch(JSON.stringify(first.snapshot(key)), /OLD_WORKSPACE_LATE_ANSWER/); + assert.match(JSON.stringify(await first.sourceMessages(key)), /OLD_WORKSPACE_LATE_ANSWER/); assert.deepEqual(switched.corrections, []); assert.equal(readContextToolEvidence(switched, { sourceId }), null); assert.equal( @@ -318,6 +323,28 @@ async function testContextScope(workspace) { console.log( 'PASS project scope retains old raw history, retires old decisions, and survives restart' ); + + const legacyInboxPath = path.join(workspace, 'legacy-inbox.json'); + const { updateSessionInbox } = await load('core/session/session-inbox-store.js'); + const migrated = new VersionedSessionStore(path.join(workspace, 'legacy-scope.sqlite')); + try { + updateSessionInbox(legacyInboxPath, (inbox) => { + const entry = inbox.admit({ id: 'legacy-steer', prompt: 'Finish the previous project' }); + inbox.defer(entry.id); + }); + await assert.rejects( + migrated.enterContextScope(key, 'new-project', { legacyInboxPath }), + /Resolve pending input/ + ); + updateSessionInbox(legacyInboxPath, (inbox) => inbox.promote('legacy-steer')); + assert.equal(await migrated.enterContextScope(key, 'new-project', { legacyInboxPath }), true); + assert.deepEqual( + migrated.readInbox(key, () => assert.fail('legacy fallback was reused')).pending(), + [] + ); + } finally { + migrated.close(); + } } async function testContextHandoff(workspace) { diff --git a/src/core/rsi/engine.ts b/src/core/rsi/engine.ts index 3d33c59b..7fd40c17 100644 --- a/src/core/rsi/engine.ts +++ b/src/core/rsi/engine.ts @@ -1221,7 +1221,9 @@ export class RsiEngine { } catch { if (!run.coverage.gaps.includes('persistence_gap')) { run.coverage.gaps.push('persistence_gap'); - getRootLogger().child('rsi').warn('RSI run record could not be persisted', { runId: run.runId }); + getRootLogger() + .child('rsi') + .warn('RSI run record could not be persisted', { runId: run.runId }); } } }; diff --git a/src/core/session/versioned-session-store.ts b/src/core/session/versioned-session-store.ts index 489d91c7..4427e590 100644 --- a/src/core/session/versioned-session-store.ts +++ b/src/core/session/versioned-session-store.ts @@ -19,6 +19,7 @@ import type { LLMMessage } from '../llm/llm-provider.js'; import { redactJsonLine } from './redact-json-line.js'; import type { SessionMeta, SessionStore } from './session.js'; import { SessionInbox, type SessionInboxEntry } from './session-inbox.js'; +import { loadSessionInbox } from './session-inbox-store.js'; import { emptyTaskIntent, readTaskIntent, @@ -239,12 +240,16 @@ export class VersionedSessionStore implements SessionStore { } private sourceRows(key: string, includeInactive = false): ContextSourceMessage[] { + const scope = includeInactive ? undefined : this.contextScope(key); return this.db .prepare( `SELECT id,ordinal,origin,body,generation FROM messages WHERE session=? - ${includeInactive ? '' : 'AND active=1 AND ordinal>=?'} ORDER BY ordinal` + ${includeInactive ? '' : 'AND active=1 AND ordinal>=? AND (generation IS NULL OR generation>=?)'} + ORDER BY ordinal` + ) + .all( + ...(includeInactive ? [key] : [key, scope?.firstOrdinal ?? 0, scope?.firstRevision ?? 0]) ) - .all(...(includeInactive ? [key] : [key, this.contextScope(key)?.firstOrdinal ?? 0])) .map((row) => ({ id: String(row.id), ordinal: Number(row.ordinal), @@ -266,7 +271,7 @@ export class VersionedSessionStore implements SessionStore { async enterContextScope( key: string, scope: string, - options: { adoptCurrent?: boolean; boundaryMessage?: string } = {} + options: { adoptCurrent?: boolean; boundaryMessage?: string; legacyInboxPath?: string } = {} ): Promise { if (!scope.trim() || scope.length > 240) throw new MossError({ code: ErrorCode.USER_INPUT_INVALID, message: 'Invalid context scope' }); @@ -275,10 +280,15 @@ export class VersionedSessionStore implements SessionStore { const previous = this.contextScope(key); if (previous?.scope === scope) return false; const lastOrdinal = this.lastOrdinal(key); + const inbox = this.readInbox(key, () => + options.legacyInboxPath ? loadSessionInbox(options.legacyInboxPath) : new SessionInbox() + ); const startFresh = - (lastOrdinal > 0 || Boolean(previous)) && !(options.adoptCurrent && !previous); + (lastOrdinal > 0 || Boolean(previous) || inbox.toEntries().length > 0) && + !(options.adoptCurrent && !previous); this.create(key); - if (startFresh) this.retireContextIntent(key); + if (startFresh) this.retireContextIntent(inbox); + this.saveInbox(key, inbox); const revision = this.revision(key) + 1; this.db .prepare('INSERT OR REPLACE INTO context_scopes VALUES(?,?,?,?)') @@ -297,8 +307,7 @@ export class VersionedSessionStore implements SessionStore { }); } - private retireContextIntent(key: string): void { - const inbox = this.readInbox(key); + private retireContextIntent(inbox: SessionInbox): void { const current = readTaskIntent(inbox.toEntries()); if (current.pending || inbox.pending().length) { throw new MossError({ @@ -322,7 +331,6 @@ export class VersionedSessionStore implements SessionStore { processedSeq: entry.admittedSeq, }, }); - this.saveInbox(key, inbox); } readInbox(key: string, legacy?: () => SessionInbox): SessionInbox { From 7693243217c15aef10805d4d3447c9e502f79b7f Mon Sep 17 00:00:00 2001 From: d-robotics Date: Tue, 24 Nov 2026 17:53:32 +0800 Subject: [PATCH 16/16] test(cli): wait for the initial turn before probing /todos --- scripts/verify/todos-view.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/scripts/verify/todos-view.py b/scripts/verify/todos-view.py index d84ed08e..57d1aa39 100644 --- a/scripts/verify/todos-view.py +++ b/scripts/verify/todos-view.py @@ -119,15 +119,14 @@ def do_POST(self): self._send(body.encode('utf-8'), 'text/event-stream') -def read_until_prompt(master, timeout, quiet=1.0): - chunks = [] +def read_until_prompt(master, timeout, quiet=1.0, completion=None): text = '' deadline = time.time() + timeout last_output = time.time() while time.time() < deadline: ready, _, _ = select.select([master], [], [], 0.05) if not ready: - if chunks and time.time() - last_output > quiet: + if completion is None and text and time.time() - last_output > quiet: break continue try: @@ -136,12 +135,12 @@ def read_until_prompt(master, timeout, quiet=1.0): break if not chunk: break - chunks.append(chunk) text += chunk.decode('utf-8', 'replace') last_output = time.time() plain = ANSI_RE.sub('', text).replace('\r', '\n') lines = [line for line in plain.split('\n') if line.strip()] - if lines and lines[-1].rstrip().endswith(PROMPT): + completed = completion is None or completion in plain + if completed and lines and lines[-1].rstrip().endswith(PROMPT): break return text @@ -197,7 +196,13 @@ def main(): print(json.dumps({'error': 'REPL prompt not detected', 'boot': boot[-1200:]})) return 1 os.write(master, b'plan the refactor\n') - read_until_prompt(master, 30.0) + # The REPL also paints prompts and may go quiet while a turn is running. + # Only send a new slash command once the stub's response and prompt arrive. + turn = read_until_prompt(master, 30.0, completion='checklist written') + plain_turn = ANSI_RE.sub('', turn) + if 'checklist written' not in plain_turn or not plain_turn.rstrip().endswith(PROMPT): + print(json.dumps({'error': 'Initial turn did not finish', 'output': plain_turn[-900:]})) + return 1 os.write(master, b'/todos\n') output = read_until_prompt(master, 20.0) finally: