The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge upstream main into PR 81234
poisdahl7ca19874593b
diff --cc apps/desktop/src/app/chat/session-tile-actions.tsindex 1e96c891758,274be26c6f5..8eaf52cf8e4--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@@ -43,10 -42,8 +42,9 @@@ importplanReload,planRestore,rebindSurvivorRowIds,++ durableRowIdsForRebind,runRewindSubmit,- survivorRowIdsFrom,- type SurvivorUserRowIds,- truncateSubmitParams+ type SurvivorUserRowIds} from '../session/hooks/use-prompt-actions/rewind'import { useSubmitPrompt } from '../session/hooks/use-prompt-actions/submit'import {@@@ -394,7 -391,8 +392,9 @@@ export function useSessionTileActions(truncateOrdinal: number | undefined,interruptFirst: boolean,truncateMessageId?: string,- truncateRowId?: number+ truncateRowId?: number,- sourceText?: string++ sourceText?: string,++ rebindRowIds?: readonly number[]) =>runRewindSubmit(requestGateway,@@@ -409,7 -407,8 +409,9 @@@runtimeIdRef.current = recoveredId}},- truncateRowId+ truncateRowId,- sourceText++ sourceText,++ rebindRowIds),[requestGateway])@@@ -447,17 -446,16 +449,17 @@@update(current => applyReloadOptimistic(current, plan))try {- const result = await requestGateway<{ survivor_user_row_ids?: unknown }>(- 'prompt.submit',- {- session_id: runtimeIdRef.current,- text: plan.text,- ...truncateSubmitParams(plan.truncateOrdinal, plan.truncateMessageId, plan.truncateRowId)- },- PROMPT_SUBMIT_REQUEST_TIMEOUT_MS+ applySurvivorRowIds(+ await submitRewind(+ plan.text,+ plan.truncateOrdinal,+ false,+ plan.truncateMessageId,+ plan.truncateRowId,- plan.sourceText++ plan.sourceText,++ durableRowIdsForRebind(state.messages)+ ))-- applySurvivorRowIds(survivorRowIdsFrom(result))} catch (err) {update(current => ({ ...current, busy: false, awaitingResponse: false }))notifyError(err, copy.regenerateFailed)@@@ -490,7 -488,8 +492,9 @@@plan.truncateOrdinal,interruptFirst,plan.truncateMessageId,- plan.truncateRowId+ plan.truncateRowId,- plan.sourceText++ plan.sourceText,++ durableRowIdsForRebind(messages)))} catch (err) {@@@ -530,7 -529,8 +534,9 @@@plan.truncateOrdinal,interruptFirst,plan.truncateMessageId,- plan.truncateRowId+ plan.truncateRowId,- plan.sourceText++ plan.sourceText,++ durableRowIdsForRebind(messages)))} catch (err) {diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex 333bca63e33,e41d1a9f01f..5dca8468236--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@@ -59,10 -60,8 +60,9 @@@ importplanReload,planRestore,rebindSurvivorRowIds,++ durableRowIdsForRebind,runRewindSubmit,- survivorRowIdsFrom,- type SurvivorUserRowIds,- truncateSubmitParams+ type SurvivorUserRowIds} from './rewind'import { useSlashCommand } from './slash'import { useSubmitPrompt } from './submit'@@@ -826,6 -825,36 +826,38 @@@ export function usePromptActions([updateSessionState])+ const submitRewindPrompt = useCallback(+ (+ sessionId: string,+ text: string,+ truncateOrdinal: number | undefined,+ truncateMessageId: string | undefined,+ interruptFirst: boolean,+ truncateRowId?: number,- sourceText?: string++ sourceText?: string,++ rebindRowIds?: readonly number[]+ ) =>+ runRewindSubmit(+ requestGateway,+ sessionId,+ text,+ truncateOrdinal,+ truncateMessageId,+ interruptFirst,+ {+ storedSessionId: selectedStoredSessionIdRef.current,+ onSessionRecovered: recoveredId => {+ activeSessionIdRef.current = recoveredId+ setActiveSessionId(recoveredId)+ }+ },+ truncateRowId,- sourceText++ sourceText,++ rebindRowIds+ ),+ [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]+ )+const reloadFromMessage = useCallback(async (parentId: string | null) => {// Ref, not the closure-captured prop — a truncating resubmit aimed at a@@@ -836,7 -865,7 +868,8 @@@return}-- const plan = planReload($messages.get(), parentId)++ const messages = $messages.get()++ const plan = planReload(messages, parentId)if (!plan) {return@@@ -846,17 -875,17 +879,18 @@@updateSessionState(sessionId, state => applyReloadOptimistic(state, plan))try {- const result = await requestGateway<{ survivor_user_row_ids?: unknown }>(- 'prompt.submit',- {- session_id: sessionId,- text: plan.text,- ...truncateSubmitParams(plan.truncateOrdinal, plan.truncateMessageId, plan.truncateRowId)- },- PROMPT_SUBMIT_REQUEST_TIMEOUT_MS+ const survivorRowIds = await submitRewindPrompt(+ sessionId,+ plan.text,+ plan.truncateOrdinal,+ plan.truncateMessageId,+ false,+ plan.truncateRowId,- plan.sourceText++ plan.sourceText,++ durableRowIdsForRebind(messages))- applySurvivorRowIds(sessionId, survivorRowIdsFrom(result))+ applySurvivorRowIds(sessionId, survivorRowIds)} catch (err) {updateSessionState(sessionId, state => ({...state,@@@ -946,7 -947,8 +952,9 @@@plan.truncateOrdinal,plan.truncateMessageId,interruptFirst,- plan.truncateRowId+ plan.truncateRowId,- plan.sourceText++ plan.sourceText,++ durableRowIdsForRebind(messages))applySurvivorRowIds(sessionId, survivorRowIds)@@@ -1009,11 -1030,55 +1036,57 @@@plan.truncateOrdinal,plan.truncateMessageId,interruptFirst,- plan.truncateRowId+ plan.truncateRowId,- plan.sourceText++ plan.sourceText,++ durableRowIdsForRebind(messages))applySurvivorRowIds(sessionId, survivorRowIds)} catch (err) {+ let surfaced: unknown = err+ let unavailable = isCompressedAwayError(err)++ // Stale target after compression/resume drift (the cached rowId and+ // ordinal address the pre-compression segment): reload server history,+ // recompute the full edit plan against the refreshed transcript, and+ // retry the real edit once. Do NOT plain-resubmit without a truncation+ // address — that drops rewind semantics and silently appends the edit+ // as a new turn (#82462).+ if (!plan.isFailedTurn && !unavailable && isStaleTargetError(err)) {+ try {+ const storedId = selectedStoredSessionIdRef.current++ if (storedId) {+ await resumeStoredSession(storedId)+ }++ const refreshed = $messages.get()+ const retryPlan = planEdit(refreshed, edited)++ if (retryPlan && !retryPlan.isFailedTurn) {+ const survivorRowIds = await submitRewindPrompt(+ sessionId,+ retryPlan.text,+ retryPlan.truncateOrdinal,+ retryPlan.truncateMessageId,+ false,+ retryPlan.truncateRowId,- retryPlan.sourceText++ retryPlan.sourceText,++ durableRowIdsForRebind(refreshed)+ )++ applySurvivorRowIds(sessionId, survivorRowIds)++ return+ }++ unavailable = true+ } catch (retryErr) {+ surfaced = retryErr+ unavailable = isCompressedAwayError(retryErr) || isStaleTargetError(retryErr)+ }+ }+// Roll the optimistic edit/truncation back to the original history so the// UI stays in sync with what's persisted instead of stranding a partial// timeline.diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.tsindex de69b180847,f1158f34c17..8e2f8b90f2f--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts@@@ -155,6 -160,6 +160,21 @@@ describe('survivorRowIdsFrom', () =>it('keeps integer ids and nulls anything else', () => {expect(survivorRowIdsFrom({ survivor_user_row_ids: [7, null, 9.5, '11', 12] })).toEqual([7, null, null, null, 12])})++++ it('prefers the explicit old-to-new row id map', () => {++ const parsed = survivorRowIdsFrom({++ survivor_user_row_ids: [100, 200],++ survivor_row_id_map: { '11': 101, '21': 201, '31': null }++ })++++ expect(parsed).toEqual(++ new Map([++ [11, 101],++ [21, 201],++ [31, null]++ ])++ )++ })})describe('rebindSurvivorRowIds', () => {@@@ -209,6 -214,6 +229,29 @@@expect(rebindSurvivorRowIds(messages, [7])[0]).toBe(messages[0])})++++ it('rebinds a paged tail by previous row id instead of global position', () => {++ const messages = [++ user('archived-u250', 800),++ user('tail-u298', 901),++ assistant('tail-a298', 902),++ user('edited', 903)++ ]++ const rebound = rebindSurvivorRowIds(++ messages,++ new Map([++ [901, 1001],++ [902, 1002],++ [903, null]++ ])++ )++++ expect(rebound[0]).toBe(messages[0])++ expect(rebound[0].rowId).toBe(800)++ expect(rebound[1].rowId).toBe(1001)++ expect(rebound[2].rowId).toBe(1002)++ expect(rebound[3].rowId).toBeUndefined()++ })})describe('finalizeInterruptedMessages', () => {@@@ -261,3 -266,222 +304,235 @@@expect(message.completedAt).toBe(11.25)})})++ describe('failed-turn-aware ordinal space', () => {+ const user = (id: string, rowId?: number): ChatMessage => ({+ id,+ role: 'user',+ parts: [textPart(`text ${id}`)],+ ...(rowId !== undefined ? { rowId } : {})+ })++ const assistant = (id: string, rowId?: number): ChatMessage => ({+ id,+ role: 'assistant',+ parts: [textPart(`reply ${id}`)],+ ...(rowId !== undefined ? { rowId } : {})+ })++ const failedAssistant = (id: string): ChatMessage => ({+ id,+ role: 'assistant',+ parts: [textPart(`err ${id}`)],+ error: 'provider down'+ })++ it('planEdit/planReload skip failed turns when counting ordinals (#41275)', () => {+ // u0 failed (never persisted), u1/u2 succeeded. Backend counts u1 before+ // u2, so editing u2 must aim at ordinal 1, not 2.+ const messages: ChatMessage[] = [+ user('u0', undefined),+ failedAssistant('a0'),+ user('u1', 11),+ assistant('a1', 12),+ user('u2', 13),+ assistant('a2', 14)+ ]++ const reload = planReload(messages, 'a2')++ expect(reload?.truncateOrdinal).toBe(1)+ expect(reload?.truncateRowId).toBe(13)+ })++ it('planEdit still flags failed turns via the shared helper', () => {+ const messages: ChatMessage[] = [user('u0', 11), assistant('a0', 12), user('u1', undefined), failedAssistant('a1')]++ const plan = planEdit(messages, {+ role: 'user',+ sourceId: 'u1',+ parentId: null,+ content: [{ type: 'text', text: 'better text' }]+ } as never)++ expect(plan?.isFailedTurn).toBe(true)+ expect(plan?.truncateOrdinal).toBeUndefined()+ expect(plan?.sourceText).toBe('text u1')+ })++ it('planReload degrades a failed turn to a plain resubmit (#86623)', () => {+ const messages: ChatMessage[] = [user('u0', 11), assistant('a0', 12), user('u1', undefined), failedAssistant('a1')]++ const reload = planReload(messages, 'a1')++ expect(reload?.text).toBe('text u1')+ expect(reload?.truncateOrdinal).toBeUndefined()+ expect(reload?.truncateRowId).toBeUndefined()+ expect(reload?.truncateMessageId).toBeUndefined()+ })++ it('planRestore degrades a failed turn to a plain resubmit', () => {+ const messages: ChatMessage[] = [user('u0', 11), assistant('a0', 12), user('u1', undefined), failedAssistant('a1')]++ const plan = planRestore(messages, 'u1')++ expect(plan.truncateOrdinal).toBeUndefined()+ expect(plan.truncateRowId).toBeUndefined()+ expect(plan.truncateMessageId).toBeUndefined()+ })++ it('rebindSurvivorRowIds skips failed turns — they hold no survivor slot', () => {+ const messages: ChatMessage[] = [user('u0', 1), failedAssistant('a0'), user('u1', 3), assistant('a1', 4)]+ const rebound = rebindSurvivorRowIds(messages, [9])++ // u0 failed: untouched. u1 is survivor ordinal 0.+ expect(rebound[0].rowId).toBe(1)+ expect(rebound[2].rowId).toBe(9)+ })+ })++ describe('resolveDurableRowId', () => {+ const gatewayWith = (messages: unknown[]) => {+ const request = (async (method: string) => {+ expect(method).toBe('session.history')++ return { messages }+ }) as <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>++ return request+ }++ it('resolves a unique content match to its durable row id', async () => {+ const request = gatewayWith([+ { role: 'user', text: 'first prompt', row_id: 11 },+ { role: 'assistant', text: 'reply', row_id: 12 },+ { role: 'user', text: 'typo prompt', row_id: 13 }+ ])++ expect(await resolveDurableRowId(request, 'sid', 'typo prompt', 1)).toBe(13)+ })++ it('ignores synthetic user-role injections (display_kind rows)', async () => {+ const request = gatewayWith([+ { role: 'user', text: 'real prompt', row_id: 11 },+ { role: 'user', text: 'real prompt', row_id: 12, display_kind: 'auto_continue' }+ ])++ expect(await resolveDurableRowId(request, 'sid', 'real prompt', 0)).toBe(11)+ })++ it('refuses ambiguous matches unless the target is provably the newest turn', async () => {+ const request = gatewayWith([+ { role: 'user', text: 'same text', row_id: 11 },+ { role: 'user', text: 'same text', row_id: 13 }+ ])++ // Ambiguous + target not the latest -> undefined (plain resubmit).+ expect(await resolveDurableRowId(request, 'sid', 'same text', 0)).toBeUndefined()+ // Ambiguous + target IS the latest persisted turn -> last match wins.+ expect(await resolveDurableRowId(request, 'sid', 'same text', 1)).toBe(13)+ })++ it('returns undefined on gateway failure or empty text', async () => {+ const failing = (async () => {+ throw new Error('boom')+ }) as <T>(method: string) => Promise<T>++ expect(await resolveDurableRowId(failing, 'sid', 'text', 0)).toBeUndefined()+ expect(await resolveDurableRowId(gatewayWith([]), 'sid', ' ', 0)).toBeUndefined()+ })+ })++ describe('runRewindSubmit durable-address discipline (#87059)', () => {+ interface Call {+ method: string+ params?: Record<string, unknown>+ }++ const historyMessages = [+ { role: 'user', text: 'first prompt', row_id: 11 },+ { role: 'assistant', text: 'ok', row_id: 12 },+ { role: 'user', text: 'typo prompt', row_id: 13 }+ ]++ const makeGateway = (calls: Call[]) =>+ (async (method: string, params?: Record<string, unknown>) => {+ calls.push({ method, params })++ if (method === 'session.history') {+ return { messages: historyMessages }+ }++ return { status: 'streaming' }+ }) as <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>++ it('resolves a missing rowId by content before submitting, and drops the client ordinal', async () => {+ const calls: Call[] = []++ await runRewindSubmit(+ makeGateway(calls),+ 'sid',+ 'fixed prompt',+ 5,+ undefined,+ false,+ undefined,+ undefined,+ 'typo prompt'+ )++ const submit = calls.find(call => call.method === 'prompt.submit')++ expect(submit?.params?.truncate_before_row_id).toBe(13)+ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()+ expect(submit?.params?.confirm_truncate).toBe(true)+ })++ it('degrades to a plain resubmit when the row id cannot be resolved', async () => {+ const calls: Call[] = []++ await runRewindSubmit(+ makeGateway(calls),+ 'sid',+ 'fixed prompt',+ 5,+ undefined,+ false,+ undefined,+ undefined,+ 'unknown text'+ )++ const submit = calls.find(call => call.method === 'prompt.submit')++ expect(submit?.params?.truncate_before_row_id).toBeUndefined()+ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()+ expect(submit?.params?.confirm_truncate).toBeUndefined()+ })+- it('leaves a bound durable rowId untouched (no extra history call)', async () => {++ it('uses a bound durable rowId without a tail-local ordinal or extra history call', async () => {+ const calls: Call[] = []+- await runRewindSubmit(makeGateway(calls), 'sid', 'fixed prompt', 1, undefined, false, undefined, 13, 'typo prompt')++ await runRewindSubmit(++ makeGateway(calls),++ 'sid',++ 'fixed prompt',++ 1,++ undefined,++ false,++ undefined,++ 13,++ 'typo prompt',++ [11, 12, 13]++ )++ expect(calls.some(call => call.method === 'session.history')).toBe(false)++ const submit = calls.find(call => call.method === 'prompt.submit')++ expect(submit?.params?.truncate_before_row_id).toBe(13)- expect(submit?.params?.truncate_before_user_ordinal).toBe(1)++ expect(submit?.params?.truncate_before_user_ordinal).toBeUndefined()++ expect(submit?.params?.confirm_empty_truncate).toBe(true)++ expect(submit?.params?.rebind_survivor_row_ids).toEqual([11, 12, 13])+ })+ })diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.tsindex 890071624ee,6cde8c434ba..7ff9dc6db8e--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts@@@ -34,24 -35,24 +35,41 @@@ importtype RequestGateway = <T = unknown>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>/**-- * Post-rewrite durable ids of the surviving visible user turns, in visible-user-- * ordinal order — the gateway's `survivor_user_row_ids` on a truncating-- * `prompt.submit`. A rewind's `replace_messages` re-inserts the kept prefix as-- * NEW SQLite rows, so every pre-rewind `ChatMessage.rowId` on a surviving-- * bubble is stale the moment the rewind lands; targeting one on the next-- * rewind/edit/regenerate gets a fail-closed 4018 from the gateway. `null`-- * means that turn has no durable id (drop the cached one, don't keep a stale-- * one). Absent entirely = the submit didn't truncate a durable session (or an-- * older gateway) — leave state untouched.++ * Post-rewrite durable identity information from a truncating `prompt.submit`.++ * New gateways return an old-to-new map for every surviving physical row;++ * older gateways return visible-user ids in ordinal order. A rewind's++ * `replace_messages` re-inserts the kept prefix as NEW SQLite rows, so every++ * cached rowId is stale the moment the rewind lands.*/--export type SurvivorUserRowIds = readonly (null | number)[]++export type SurvivorUserRowIds = readonly (null | number)[] | Map<number, null | number>interface PromptSubmitResult {status?: stringsurvivor_user_row_ids?: unknown++ survivor_row_id_map?: unknown}export function survivorRowIdsFrom(result: PromptSubmitResult | undefined): SurvivorUserRowIds | undefined {++ const rawMap = result?.survivor_row_id_map++++ if (rawMap && typeof rawMap === 'object' && !Array.isArray(rawMap)) {++ const parsed = new Map<number, null | number>()++++ for (const [oldId, newId] of Object.entries(rawMap)) {++ const previous = Number(oldId)++++ if (Number.isInteger(previous)) {++ if (newId === null) {++ parsed.set(previous, null)++ } else if (typeof newId === 'number' && Number.isInteger(newId)) {++ parsed.set(previous, newId)++ }++ }++ }++++ return parsed++ }++const raw = result?.survivor_user_row_idsif (!Array.isArray(raw)) {@@@ -70,10 -71,13 +88,34 @@@* stale id now addresses an archived row and would be refused with 4018.*/export function rebindSurvivorRowIds(messages: ChatMessage[], survivorRowIds: SurvivorUserRowIds): ChatMessage[] {++ if (survivorRowIds instanceof Map) {++ return messages.map(message => {++ if (message.rowId === undefined) {++ return message++ }++ if (!survivorRowIds.has(message.rowId)) {++ // Requested rows outside the active tip (compacted/ancestor history)++ // were not rewritten and keep their durable identity.++ return message++ }++++ const next = survivorRowIds.get(message.rowId)++++ return next === null || next === undefined++ ? { ...message, rowId: undefined }++ : message.rowId === next++ ? message++ : { ...message, rowId: next }++ })++ }+++ // Same ordinal space as the truncate math: visible AND persisted (failed+ // turns never reached the gateway, so they hold no survivor slot).+ const indices = new Set(visibleUserMessageIndices(messages))let ordinal = 0- return messages.map(message => {- if (!isVisibleUserMessage(message)) {+ return messages.map((message, index) => {+ if (!indices.has(index)) {return message}@@@ -88,6 -92,21 +130,31 @@@})}++export function durableRowIdsForRebind(messages: readonly ChatMessage[]): number[] {++ return [++ ...new Set(++ messages.flatMap(message =>++ typeof message.rowId === 'number' && Number.isInteger(message.rowId) ? [message.rowId] : []++ )++ )++ ]++}+++ /**+ * Renderer-synthetic message ids (`${timestamp}-${index}-${role}` from+ * chat-messages.ts, plus older `user-…` / `assistant-…` shapes). Gateway+ * history never carries them — only durable `row_id` / platform message_id.+ */+ export function isSyntheticRendererId(messageId: string | undefined): boolean {+ return (+ typeof messageId === 'string' &&+ (messageId.startsWith('user-') ||+ messageId.startsWith('assistant-') ||+ messageId.includes('-synthetic-') ||+ /^\d+-\d+-(user|assistant|tools)\b/.test(messageId))+ )+ }+/*** Build `prompt.submit` truncation params. `confirm_truncate` states that this* submit really is a rewind/edit/regenerate: the gateway drops history only for@@@ -147,12 -222,46 +270,55 @@@ export async function runRewindSubmittruncateMessageId: string | undefined,interruptFirst: boolean,recovery?: { storedSessionId?: null | string; onSessionRecovered?: (sessionId: string) => void },- truncateRowId?: number+ truncateRowId?: number,- sourceText?: string++ sourceText?: string,++ rebindRowIds?: readonly number[]): Promise<SurvivorUserRowIds | undefined> {// Recovery may rebind the live id mid-flight; interrupt/submit must both// follow it rather than pinning the dead one.let liveSessionId = sessionId+ // A truncation without a durable address is the #87059 shape: the gateway+ // fails it closed (4004) for any persisted session, so sending it can only+ // produce an error. Resolve the row id by content first (the durable row+ // usually exists — the bubble just never learned its id, e.g. edit after an+ // interrupted turn). When resolution fails too, degrade to a PLAIN resubmit:+ // append the corrected text without dropping anything, never guess a cut.+ let resolvedRowId = truncateRowId+ let resolvedOrdinal = truncateOrdinal+ let resolvedMessageId = truncateMessageId++ const wantsTruncation =+ typeof truncateOrdinal === 'number' ||+ typeof truncateRowId === 'number' ||+ (typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticRendererId(truncateMessageId))++ const hasDurableAddress =+ typeof truncateRowId === 'number' ||+ (typeof truncateMessageId === 'string' && truncateMessageId.length > 0 && !isSyntheticRendererId(truncateMessageId))+++ if (typeof resolvedRowId === 'number' && Number.isInteger(resolvedRowId)) {++ // A durable row id is globally stable, while the rendered ordinal can be++ // relative to a paged transcript tail. Do not cross-check those different++ // spaces; the gateway still validates the row against its full transcript.++ resolvedOrdinal = undefined++ resolvedMessageId = undefined++ }+++ if (wantsTruncation && !hasDurableAddress) {+ resolvedRowId =+ sourceText === undefined+ ? undefined+ : await resolveDurableRowId(requestGateway, liveSessionId, sourceText, truncateOrdinal)++ // Either way the client-side ordinal is untrustworthy here (its space can+ // diverge from the gateway's — the #87059 root). Resolved: the row id alone+ // is the address; sending the divergent ordinal too would trip the+ // gateway's 4030 cross-check. Unresolved: plain resubmit, no truncation.+ resolvedOrdinal = undefined+ resolvedMessageId = undefined+ }+const interrupt = async () => {try {await requestGateway('session.interrupt', { session_id: liveSessionId })@@@ -167,7 -276,15 +333,15 @@@{session_id: targetId,text,- ...truncateSubmitParams(truncateOrdinal, truncateMessageId, truncateRowId)+ ...truncateSubmitParams(resolvedOrdinal, resolvedMessageId, resolvedRowId),+ // A first-turn rewind resolves to an empty transcript, which the+ // gateway additionally gates behind confirm_empty_truncate. In- // resolved-row-id mode the ordinal was dropped (see above), so carry- // the flag from the caller's ordinal-0 belief: required when right,- // ignored by the gateway when the cut isn't actually empty.- ...(resolvedRowId !== undefined && resolvedOrdinal === undefined && truncateOrdinal === 0- ? { confirm_empty_truncate: true }- : {})++ // In resolved-row-id mode the tail-local ordinal was dropped (see++ // above). The durable target is authoritative, so explicitly allow a++ // first-active-tip cut; the gateway ignores this when the prefix is++ // non-empty.++ ...(resolvedRowId !== undefined && resolvedOrdinal === undefined ? { confirm_empty_truncate: true } : {}),++ ...(rebindRowIds ? { rebind_survivor_row_ids: [...new Set(rebindRowIds.filter(Number.isInteger))] } : {})},PROMPT_SUBMIT_REQUEST_TIMEOUT_MS)diff --cc apps/desktop/src/lib/chat-messages.test.tsindex 38bc2aca889,38bc2aca889..c6bc0b28b1b--- a/apps/desktop/src/lib/chat-messages.test.ts+++ b/apps/desktop/src/lib/chat-messages.test.ts@@@ -323,6 -323,6 +323,28 @@@ describe('toChatMessages', () =>}})++ it('projects persisted composite compaction carriers to their live user turn', () => {++ const messages = toChatMessages([++ {++ id: 71,++ role: 'user',++ content: 'internal summary scaffold\n\nREAL ASK',++ display_content: 'REAL ASK',++ timestamp: 1++ },++ {++ id: 72,++ role: 'user',++ content: 'prior live ask\n\ninternal summary scaffold',++ display_content: 'prior live ask',++ timestamp: 2++ }++ ])++++ expect(messages.map(chatMessageText)).toEqual(['REAL ASK', 'prior live ask'])++ expect(messages.map(message => message.rowId)).toEqual([71, 72])++ })++it('projects durable timeline kinds without inspecting their text', () => {const messages = toChatMessages([{ role: 'user', content: 'real user turn', timestamp: 1 },diff --cc apps/desktop/src/lib/chat-messages.tsindex 52eb1cf1e27,52eb1cf1e27..eeaf42e279c--- a/apps/desktop/src/lib/chat-messages.ts+++ b/apps/desktop/src/lib/chat-messages.ts@@@ -1120,7 -1120,7 +1120,10 @@@ export function toChatMessages(messagesreturn}-- const content = message.content || message.text || message.context || message.name++ const content =++ message.display_content !== undefined++ ? message.display_content++ : message.content || message.text || message.context || message.nameconst rawDisplayContent = transcriptContent(message.display_kind,diff --cc apps/desktop/src/types/hermes.tsindex b6291e84553,5535265d2c3..ad64d7d355f--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@@ -556,6 -561,6 +561,8 @@@ export interface SessionMessageargs?: unknowncodex_reasoning_items?: unknowncontent: unknown++ /** Backend-projected user-visible content when a physical row also carries internal model scaffolding. */++ display_content?: unknowncontext?: unknownname?: stringreasoning?: null | stringdiff --cc hermes_cli/web_routers/sessions.pyindex 8b37f9fa908,8b37f9fa908..2e88a3ea8e1--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@@ -642,14 -642,14 +642,33 @@@ async def get_session_messagesif result is None:raise HTTPException(status_code=404, detail="Session not found")sid, _limit, messages = result++ from agent.context_compressor import split_user_originated_turn++++ projected_messages = []++ for message in messages:++ handoff, live_view = split_user_originated_turn(message)++ if handoff is None:++ projected_messages.append(message)++ continue++ projected = message.copy()++ if live_view is None:++ if not projected.get("display_kind"):++ projected["display_kind"] = "hidden"++ else:++ # Keep the physical content for inspection/export compatibility;++ # Desktop consumes this display-only projection. A legacy hidden++ # wrapper must not hide a successfully recovered live ask.++ projected["display_content"] = live_view.get("content")++ projected.pop("display_kind", None)++ projected_messages.append(projected)return {"session_id": sid,-- "messages": messages,++ "messages": projected_messages,"pagination": {"limit": _limit,"offset": offset,"order": order or ("latest" if limit is None else "oldest"),-- "returned": len(messages),++ "returned": len(projected_messages),},}diff --cc hermes_state.pyindex 5ad8753343f,834a56b91f1..4b8e9749025--- a/hermes_state.py+++ b/hermes_state.py@@@ -8868,29 -9079,25 +9079,53 @@@ class SessionDB(SessionSearchMixin, Sescompression_lock_holder: Optional[str],turn_lease_holder: Optional[str] = None,turn_lease_ttl_seconds: float = 300.0,+ reject_active_turn_lease: bool = False,++ reject_active_compression_lock: bool = False,) -> None:- """Transcript-append admission checks, run INSIDE the write txn.+ """Transcript-write admission checks, run INSIDE the write txn.Shared by :meth:`append_message` and :meth:`append_messages_batch` sothe two writers can never diverge on these correctness invariants- (this guard has already needed targeted fixes — see the #74478- patience note below).+ (this guard has already needed targeted fixes — see the #74478 patience+ note below). User-initiated transcript mutations may opt in to rejecting+ an active unowned turn lease in that same transaction."""- active_lock = conn.execute(- "SELECT holder FROM compression_locks "- "WHERE session_id = ? AND expires_at > ?",- (session_id, time.time()),- ).fetchone()- if (- active_lock is not None- and active_lock["holder"] != compression_lock_holder- ):- raise SessionCompressionInProgressError(- f"Session {session_id!r} is being compressed by another writer"- )+ # NOTE (#75316 redesign): appends do NOT check compression_locks.+ # The lock's job is to stop two COMPRESSIONS colliding, not to fence+ # ordinary transcript writes. Concurrent appends during a compression+ # are safe by construction: archive_and_compact() commits against a+ # watermark captured at compression start and clones every row that+ # arrived after it back into the live transcript, in the same write+ # transaction. Blocking appends here was the root cause of a whole+ # symptom family — turns dying as session_persistence_failed while a+ # slow provider summary held the lease (#74568, #77386), including+ # stale locks from dead PIDs blocking writes for the full TTL.- if turn_lease_holder:++ # Destructive user mutations are different: a compressor that already++ # captured its watermark can otherwise publish the pre-rewind snapshot++ # after the mutation and resurrect the removed turn. Keep that narrow++ # fence opt-in so ordinary appends retain the watermark behavior.++ if reject_active_compression_lock:++ active_lock = conn.execute(++ "SELECT holder, expires_at FROM compression_locks "++ "WHERE session_id = ?",++ (session_id,),++ ).fetchone()++ if active_lock is not None:++ current_holder = active_lock["holder"]++ if (++ float(active_lock["expires_at"]) <= time.time()++ or _compression_lock_holder_process_is_dead(current_holder)++ ):++ conn.execute(++ "DELETE FROM compression_locks "++ "WHERE session_id = ? AND holder = ?",++ (session_id, current_holder),++ )++ elif current_holder != compression_lock_holder:++ raise SessionCompressionInProgressError(++ f"Session {session_id!r} is being compressed by another writer"++ )+ if turn_lease_holder or reject_active_turn_lease:conversation_id = self._session_turn_lease_key_on_conn(conn, session_id)lease = conn.execute("SELECT holder, expires_at FROM session_turn_leases "@@@ -9604,24 -9785,16 +9839,25 @@@active_clause = " AND active = 1" if active_only else ""def _do(conn):- session = conn.execute(- "SELECT ended_at, end_reason FROM sessions WHERE id = ?",- (session_id,),- ).fetchone()- if (- session is not None- and session["ended_at"] is not None- and session["end_reason"] == "compression"- ):- raise CompressionSessionClosedError(session_id)+ if reject_active_turn_lease:+ self._check_transcript_write_guards(+ conn,+ session_id,+ None,+ reject_active_turn_lease=True,++ reject_active_compression_lock=True,+ )+ else:+ session = conn.execute(+ "SELECT ended_at, end_reason FROM sessions WHERE id = ?",+ (session_id,),+ ).fetchone()+ if (+ session is not None+ and session["ended_at"] is not None+ and session["end_reason"] == "compression"+ ):+ raise CompressionSessionClosedError(session_id)if archive_dropped:# Content-preserving UPDATE: the rows keep their FTS entries# (the messages_fts triggers fire on INSERT / DELETE / UPDATE@@@ -9854,13 -10132,13 +10195,30 @@@all_rows = cursor.fetchall()seen: dict = {}for row in all_rows:++ dedupe_content = row["content"]++ if row["role"] == "user":++ from agent.context_compressor import split_user_originated_turn++++ candidate = {++ "role": "user",++ "content": self._decode_content(row["content"]),++ "display_kind": row["display_kind"],++ "display_metadata": self._decode_display_metadata(++ row["display_metadata"]++ ),++ }++ handoff, live_view = split_user_originated_turn(candidate)++ if handoff is not None and live_view is not None:++ dedupe_content = self._encode_content(++ live_view.get("content")++ )# Tool fields participate in the dedupe key: compaction copies# them verbatim, so identical tool messages across generations# still collapse, while distinct tool calls that happen to# share role/content/timestamp are never merged.key = (row["role"],-- row["content"],++ dedupe_content,row["timestamp"],row["tool_call_id"],row["tool_calls"],@@@ -10185,6 -10463,6 +10543,11 @@@desired session set / active state by the caller."""messages = []++ # Watermark rotation column-clones concurrent tail rows into the child++ # after the new summary, so the copies need not be adjacent. Index the++ # exact durable clone identity while decoding instead of rescanning the++ # whole accumulated lineage for every user row.++ exact_user_clones: Dict[Tuple[Any, str], Dict[str, Any]] = {}for row in rows:content = self._decode_content(row["content"])if row["role"] in {"user", "assistant"} and isinstance(content, str):@@@ -10263,9 -10541,9 +10626,47 @@@except (json.JSONDecodeError, TypeError):logger.warning("Failed to deserialize codex_message_items, falling back to None")msg["codex_message_items"] = None-- if include_ancestors and self._is_duplicate_replayed_user_message(messages, msg):-- continue++ if include_ancestors:++ canonical_content, _is_composite = (++ self._canonical_replayed_user_content(msg)++ )++ exact_clone_key = self._exact_replayed_user_clone_key(++ msg.get("timestamp"), canonical_content++ )++ previous_exact = (++ exact_user_clones.get(exact_clone_key)++ if exact_clone_key is not None++ else None++ )++ duplicate = None++ if previous_exact is not None:++ previous_index = next(++ (++ index++ for index, candidate in enumerate(messages)++ if candidate is previous_exact++ ),++ None,++ )++ if previous_index is not None:++ duplicate = (previous_index, True)++ if duplicate is None:++ duplicate = self._find_duplicate_replayed_user_message(++ messages, msg++ )++ if duplicate is not None:++ duplicate_index, prefer_current = duplicate++ if prefer_current:++ # A rotated compression child can carry the same live++ # ask as the parent row plus the only surviving summary++ # scaffold. Keep the child carrier (and its durable row++ # id), not the simpler ancestor copy.++ messages.pop(duplicate_index)++ else:++ continuemessages.append(msg)++ if include_ancestors and exact_clone_key is not None:++ exact_user_clones[exact_clone_key] = msg# DEFENSE-IN-DEPTH against background-review session pollution: a forked# skill/memory review that (in older builds, before the _persist_disabled# fix) shared the parent's session_id wrote its harness turn into this@@@ -10476,15 -10754,15 +10877,28 @@@"ORDER BY id",tuple(session_ids),).fetchall()-- ancestor_rows = [r for r in rows if r["session_id"] != session_id]-- if not ancestor_rows:++ ancestor_ids = {++ int(row["id"])++ for row in rows++ if row["session_id"] != session_id and row["id"] is not None++ }++ if not ancestor_ids:return []-- return self._rows_to_conversation(-- ancestor_rows,++ lineage = self._rows_to_conversation(++ rows,session_id=session_id,include_ancestors=True,repair_alternation=False,++ include_row_ids=True,)++ prefix: List[Dict[str, Any]] = []++ for message in lineage:++ if message.get("_row_id") not in ancestor_ids:++ continue++ projected = message.copy()++ projected.pop("_row_id", None)++ prefix.append(projected)++ return prefixdef _is_explicit_branch_session(self, session_id: str) -> bool:"""Return whether *session_id* is a copied user-facing branch.@@@ -10550,18 -10828,18 +10964,82 @@@return list(reversed(chain)) or [session_id]@staticmethod-- def _is_duplicate_replayed_user_message(messages: List[Dict[str, Any]], msg: Dict[str, Any]) -> bool:++ def _canonical_replayed_user_content(++ msg: Dict[str, Any],++ ) -> Tuple[Any, bool]:++ """Return canonical live content and whether *msg* is composite."""if msg.get("role") != "user":-- return False-- content = msg.get("content")-- if not isinstance(content, str) or not content:-- return False-- for prev in reversed(messages):-- if prev.get("role") == "user" and prev.get("content") == content:-- return True++ return None, False++++ from agent.context_compressor import split_user_originated_turn++++ handoff, live_view = split_user_originated_turn(msg)++ is_composite = handoff is not None and live_view is not None++ return (++ live_view.get("content")++ if is_composite and live_view is not None++ else msg.get("content"),++ is_composite,++ )++++ @staticmethod++ def _exact_replayed_user_clone_key(++ timestamp: Any, content: Any++ ) -> Optional[Tuple[Any, str]]:++ """Return a hashable key for a column-exact rotation clone."""++ if timestamp is None or content in (None, "", []):++ return None++ try:++ encoded = json.dumps(++ content,++ ensure_ascii=False,++ sort_keys=True,++ separators=(",", ":"),++ )++ except (TypeError, ValueError):++ return None++ return timestamp, encoded++++ @staticmethod++ def _find_duplicate_replayed_user_message(++ messages: List[Dict[str, Any]], msg: Dict[str, Any]++ ) -> Optional[Tuple[int, bool]]:++ """Return an adjacent replay duplicate and whether *msg* must win.++++ Compression rotation may persist the current ask once in the parent++ and again inside a composite child carrier. Compare the canonical live++ payload for that carrier, while retaining the historical exact-string++ dedupe for ordinary replayed users. The child carrier wins because it++ owns both the current durable row identity and the retained scaffold.++ """++ if msg.get("role") != "user":++ return None++++ content, prefer_current = SessionDB._canonical_replayed_user_content(msg)++ if content in (None, "", []):++ return None++++ for index in range(len(messages) - 1, -1, -1):++ prev = messages[index]++ if prev.get("role") == "user":++ prev_content, prev_is_composite = (++ SessionDB._canonical_replayed_user_content(prev)++ )++ if prev_content == content and (++ prefer_current++ or prev_is_composite++ or isinstance(content, str)++ ):++ return index, prefer_currentif prev.get("role") == "assistant" and (prev.get("content") or prev.get("tool_calls")):-- return False-- return False++ return None++ return None++++ @staticmethod++ def _is_duplicate_replayed_user_message(++ messages: List[Dict[str, Any]], msg: Dict[str, Any]++ ) -> bool:++ return SessionDB._find_duplicate_replayed_user_message(messages, msg) is not None# =========================================================================# Rewind (soft-delete) — see /rewind slash command + issue #21910@@@ -10637,30 -10874,9 +11115,31 @@@target is a no-op on row state but still bumps the counter."""- # 1) Validate target up-front (read-only, outside the write txn).- with self._lock:- row = self._conn.execute(+ def _do(conn):+ # Rewind changes the active transcript and must honor the same+ # compression/closed-parent and cross-process turn guards as+ # append writers.+ self._check_transcript_write_guards(+ conn,+ session_id,+ None,+ reject_active_turn_lease=True,++ reject_active_compression_lock=True,+ )++ if expected_active_ids is not None:+ active_rows = conn.execute(+ "SELECT id FROM messages "+ "WHERE session_id = ? AND active = 1 ORDER BY id",+ (session_id,),+ ).fetchall()+ active_ids = [int(active_row[0]) for active_row in active_rows]+ if active_ids != expected_active_ids:+ raise RuntimeError(+ "active transcript changed before the rewind could be persisted"+ )++ row = conn.execute("SELECT * FROM messages WHERE id = ? AND session_id = ?",(target_message_id, session_id),).fetchone()diff --cc tests/hermes_cli/test_web_server.pyindex 04c375e32e1,42e3860dd6b..c74ec743828--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@@ -2009,6 -2009,6 +2009,56 @@@ class TestWebServerEndpointscontents = [m["content"] for m in resp.json()["messages"]]assert contents == ["old q", "old a", "summary", "live q", "live a"]++ def test_get_session_messages_projects_and_dedupes_composite_carrier(self):++ from agent.context_compressor import (++ HISTORICAL_TASK_HEADING,++ SUMMARY_PREFIX,++ _SUMMARY_END_MARKER,++ )++ from hermes_state import SessionDB++++ handoff = (++ f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold task\n\n"++ f"{_SUMMARY_END_MARKER}"++ )++ carrier = f"{handoff}\n\nREAL ASK"++ db = SessionDB()++ try:++ db.create_session(session_id="compacted-carrier-display", source="desktop")++ db.append_message(++ "compacted-carrier-display",++ "user",++ "REAL ASK",++ timestamp=123.0,++ )++ db.archive_and_compact(++ "compacted-carrier-display",++ [{"role": "user", "content": carrier, "timestamp": 123.0}],++ )++ db.append_message(++ "compacted-carrier-display",++ "user",++ handoff,++ timestamp=124.0,++ )++ active_id = db.get_messages("compacted-carrier-display")[0]["id"]++ finally:++ db.close()++++ resp = self.client.get(++ "/api/sessions/compacted-carrier-display/messages"++ "?include_compacted=true"++ )++ assert resp.status_code == 200++ messages = resp.json()["messages"]++ assert len(messages) == 2++ assert messages[0]["id"] == active_id++ assert messages[0]["content"] == carrier++ assert messages[0]["display_content"] == "REAL ASK"++ assert not messages[0].get("display_kind")++ assert messages[1]["content"] == handoff++ assert messages[1]["display_kind"] == "hidden"++def test_get_session_messages_latest_page_with_compacted_rows(self):"""The desktop's real read path (getLatestSessionMessages: limit +order=latest + include_compacted=true) pages back from the newestdiff --cc tests/hermes_state/test_composite_carrier_rewind.pyindex 09ab7c97ffc,00000000000..b086e463eecmode 100644,000000..100644--- a/tests/hermes_state/test_composite_carrier_rewind.py+++ b/tests/hermes_state/test_composite_carrier_rewind.py@@@ -1,306 -1,0 +1,381 @@@+"""Transactional persistence contracts for composite compaction carriers."""++from __future__ import annotations++import os++import pytest++from agent.context_compressor import (+ HISTORICAL_TASK_HEADING,+ SUMMARY_PREFIX,+ _MERGED_SUMMARY_DELIMITER,+ _SUMMARY_END_MARKER,+)+from hermes_state import (+ CompressionSessionClosedError,+ SessionCompressionInProgressError,+ SessionDB,+ SessionTurnLeaseLostError,+)+++def _carrier(ask: str = "REAL ASK") -> str:+ return (+ f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold task\n\n"+ f"{_SUMMARY_END_MARKER}\n\n{ask}"+ )+++def db(tmp_path):+ state = SessionDB(db_path=tmp_path / "state.db")+ yield state+ state.close()+++def _session_counts(db: SessionDB, session_id: str) -> tuple[int, int, int]:+ row = db._conn.execute(+ "SELECT message_count, tool_call_count, rewind_count "+ "FROM sessions WHERE id = ?",+ (session_id,),+ ).fetchone()+ return row["message_count"], row["tool_call_count"], row["rewind_count"]+++def _row_state(db: SessionDB, session_id: str) -> list[tuple]:+ return [+ tuple(row)+ for row in db._conn.execute(+ "SELECT id, role, content, active, display_kind "+ "FROM messages WHERE session_id = ? ORDER BY id",+ (session_id,),+ ).fetchall()+ ]+++def _active_ids(db: SessionDB, session_id: str) -> list[int]:+ return [+ int(message["_row_id"])+ for message in db.get_messages_as_conversation(+ session_id, include_row_ids=True+ )+ ]+++def test_composite_rewind_archives_tail_and_inserts_its_hidden_scaffold(db):+ sid = "carrier-rewind"+ db.create_session(sid, source="tui")+ db.append_message(sid, "user", "older ask")+ db.append_message(+ sid,+ "assistant",+ None,+ tool_calls=[{"id": "call-1", "function": {"name": "terminal"}}],+ )+ db.append_message(sid, "tool", "ok", tool_call_id="call-1")+ target_id = db.append_message(sid, "user", _carrier())+ db.append_message(sid, "assistant", "failed")+ expected_active_ids = _active_ids(db, sid)++ result = db.rewind_to_message(+ sid,+ target_id,+ preserve_compaction_handoff=True,+ expected_active_ids=expected_active_ids,+ expected_target_content="REAL ASK",+ )++ assert result["rewound_count"] == 2+ assert result["replacement_message_id"] == result["new_head_id"]+ active = db.get_messages_as_conversation(sid, include_row_ids=True)+ assert len(active) == 4+ assert active[-1]["_row_id"] == result["replacement_message_id"]+ assert active[-1]["display_kind"] == "hidden"+ assert SUMMARY_PREFIX in active[-1]["content"]+ assert "REAL ASK" not in active[-1]["content"]+ archived = db._conn.execute(+ "SELECT active FROM messages WHERE id IN (?, ?) ORDER BY id",+ (target_id, target_id + 1),+ ).fetchall()+ assert [row[0] for row in archived] == [0, 0]+ assert _session_counts(db, sid) == (4, 1, 1)++++def test_lineage_display_prefers_tip_carrier_over_replayed_parent_ask(db):++ parent = "carrier-parent"++ child = "carrier-child"++ db.create_session(parent, source="tui")++ db.append_message(parent, "user", "REAL ASK")++ db.end_session(parent, "compression")++ db.create_session(child, source="tui", parent_session_id=parent)++ carrier_id = db.append_message(child, "user", _carrier())++++ model_history, display_history = db.get_resume_conversations(child)++++ from agent.context_compressor import user_originated_turn_view++++ visible_users = [++ user_originated_turn_view(message)++ for message in display_history++ if user_originated_turn_view(message) is not None++ ]++ assert [message["content"] for message in visible_users] == ["REAL ASK"]++ assert display_history[-1]["_row_id"] == carrier_id++ assert model_history[-1]["_row_id"] == carrier_id++ assert db.get_ancestor_display_prefix(child) == []++++++def test_lineage_display_dedupes_multimodal_ask_in_tip_carrier(db):++ parent = "media-carrier-parent"++ child = "media-carrier-child"++ ask = [++ {"type": "text", "text": "inspect this"},++ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}},++ ]++ carrier = [++ {"type": "text", "text": f"{_carrier('')}\n"},++ *ask,++ ]++ db.create_session(parent, source="tui")++ db.append_message(parent, "user", ask)++ db.end_session(parent, "compression")++ db.create_session(child, source="tui", parent_session_id=parent)++ carrier_id = db.append_message(child, "user", carrier)++++ _, display_history = db.get_resume_conversations(child)++++ from agent.context_compressor import user_originated_turn_view++++ visible_users = [++ user_originated_turn_view(message)++ for message in display_history++ if user_originated_turn_view(message) is not None++ ]++ assert [message["content"] for message in visible_users] == [ask]++ assert display_history[-1]["_row_id"] == carrier_id+++++def test_default_rewind_return_shape_and_active_counters_remain_compatible(db):+ sid = "default-rewind"+ db.create_session(sid, source="cli")+ db.append_message(sid, "user", "first")+ db.append_message(sid, "assistant", "answer")+ target_id = db.append_message(sid, "user", "second")+ db.append_message(+ sid,+ "assistant",+ None,+ tool_calls=[{"id": "call-2", "function": {"name": "terminal"}}],+ )++ result = db.rewind_to_message(sid, target_id)++ assert set(result) == {"rewound_count", "target_message", "new_head_id"}+ assert result["rewound_count"] == 2+ assert _session_counts(db, sid) == (2, 0, 1)+++def test_guarded_composite_rewind_rejects_append_without_inserting_scaffold(db):+ sid = "guarded-rewind-append"+ db.create_session(sid, source="cli")+ db.append_message(sid, "user", "first")+ db.append_message(sid, "assistant", "answer")+ target_id = db.append_message(sid, "user", _carrier())+ db.append_message(sid, "assistant", "failed")+ snapshot = db.get_messages_as_conversation(sid, include_row_ids=True)+ expected_active_ids = [int(message["_row_id"]) for message in snapshot]+ assert snapshot[-2]["_row_id"] == target_id++ # Deterministic validation -> write race: a sibling writer commits after+ # the snapshot but before rewind_to_message begins its write transaction.+ sibling = SessionDB(db_path=db.db_path)+ sibling.append_message(sid, "assistant", "concurrent append")+ sibling.close()+ before_rows = _row_state(db, sid)+ before_counts = _session_counts(db, sid)++ with pytest.raises(RuntimeError, match="active transcript changed"):+ db.rewind_to_message(+ sid,+ target_id,+ preserve_compaction_handoff=True,+ expected_active_ids=expected_active_ids,+ expected_target_content=_carrier(),+ )++ assert _row_state(db, sid) == before_rows+ assert _session_counts(db, sid) == before_counts++def test_guarded_rewind_rejects_selected_target_content_change(db):+ sid = "guarded-rewind-in-place"+ db.create_session(sid, source="cli")+ db.append_message(sid, "user", "first")+ db.append_message(sid, "assistant", "answer")+ target_id = db.append_message(sid, "user", "second")+ db.append_message(sid, "assistant", "failed")+ expected_active_ids = _active_ids(db, sid)++ sibling = SessionDB(db_path=db.db_path)+ sibling._execute_write(+ lambda conn: conn.execute(+ "UPDATE messages SET content = ? WHERE id = ?",+ ("changed second", target_id),+ )+ )+ sibling.close()+ before_rows = _row_state(db, sid)+ before_counts = _session_counts(db, sid)++ with pytest.raises(RuntimeError, match="rewind target changed"):+ db.rewind_to_message(+ sid,+ target_id,+ expected_active_ids=expected_active_ids,+ expected_target_content="second",+ )++ assert _row_state(db, sid) == before_rows+ assert _session_counts(db, sid) == before_counts+++def test_guarded_rewind_ignores_reaction_metadata_change(db):+ sid = "guarded-rewind-reaction"+ db.create_session(sid, source="cli")+ target_id = db.append_message(sid, "user", "second")+ db.append_message(sid, "assistant", "failed")+ expected_active_ids = _active_ids(db, sid)++ assert db.set_message_reaction(sid, target_id + 1, "👍", author="user")++ result = db.rewind_to_message(+ sid,+ target_id,+ expected_active_ids=expected_active_ids,+ expected_target_content="second",+ )++ assert result["rewound_count"] == 2+ assert db.get_messages_as_conversation(sid) == []+++def test_rewind_guard_rejects_foreign_live_compression_without_any_change(db):+ sid = "locked-rewind"+ db.create_session(sid, source="tui")+ target_id = db.append_message(sid, "user", _carrier())+ db.append_message(sid, "assistant", "failed")+ assert db.try_acquire_compression_lock(sid, "foreign-writer", ttl_seconds=60)+ before_rows = _row_state(db, sid)+ before_counts = _session_counts(db, sid)++ with pytest.raises(SessionCompressionInProgressError):+ db.rewind_to_message(+ sid, target_id, preserve_compaction_handoff=True+ )++ assert _row_state(db, sid) == before_rows+ assert _session_counts(db, sid) == before_counts+++def test_rewind_guard_rejects_foreign_turn_lease_without_any_change(db):+ sid = "leased-rewind"+ db.create_session(sid, source="tui")+ target_id = db.append_message(sid, "user", _carrier())+ expected_active_ids = _active_ids(db, sid)+ holder = f"pid={os.getpid()}:turn=active"+ assert db.try_acquire_session_turn_lease(sid, holder, ttl_seconds=60)+ before_rows = _row_state(db, sid)+ before_counts = _session_counts(db, sid)++ with pytest.raises(SessionTurnLeaseLostError, match="active turn lease"):+ db.rewind_to_message(+ sid,+ target_id,+ preserve_compaction_handoff=True,+ expected_active_ids=expected_active_ids,+ expected_target_content="REAL ASK",+ )++ assert _row_state(db, sid) == before_rows+ assert _session_counts(db, sid) == before_counts++ db.release_session_turn_lease(sid, holder)+ result = db.rewind_to_message(+ sid,+ target_id,+ preserve_compaction_handoff=True,+ expected_active_ids=expected_active_ids,+ expected_target_content="REAL ASK",+ )+ assert result["rewound_count"] == 1+++def test_guarded_replace_rejects_foreign_turn_lease_without_any_change(db):+ sid = "leased-replace"+ db.create_session(sid, source="tui")+ db.append_message(sid, "user", "old ask")+ holder = f"pid={os.getpid()}:turn=active"+ assert db.try_acquire_session_turn_lease(sid, holder, ttl_seconds=60)+ before_rows = _row_state(db, sid)+ before_counts = _session_counts(db, sid)++ with pytest.raises(SessionTurnLeaseLostError, match="active turn lease"):+ db.replace_messages(+ sid,+ [{"role": "user", "content": "replacement"}],+ active_only=True,+ archive_dropped=True,+ reject_active_turn_lease=True,+ )++ assert _row_state(db, sid) == before_rows+ assert _session_counts(db, sid) == before_counts++ db.release_session_turn_lease(sid, holder)+ db.replace_messages(+ sid,+ [{"role": "user", "content": "replacement"}],+ active_only=True,+ archive_dropped=True,+ reject_active_turn_lease=True,+ )+ assert [m[2] for m in _row_state(db, sid) if m[3] == 1] == ["replacement"]++++def test_guarded_replace_rejects_foreign_live_compression_without_any_change(db):++ sid = "compression-locked-replace"++ db.create_session(sid, source="tui")++ db.append_message(sid, "user", "old ask")++ assert db.try_acquire_compression_lock(sid, "foreign-writer", ttl_seconds=60)++ before_rows = _row_state(db, sid)++ before_counts = _session_counts(db, sid)++++ with pytest.raises(SessionCompressionInProgressError):++ db.replace_messages(++ sid,++ [{"role": "user", "content": "replacement"}],++ active_only=True,++ archive_dropped=True,++ reject_active_turn_lease=True,++ )++++ assert _row_state(db, sid) == before_rows++ assert _session_counts(db, sid) == before_counts+++++def test_rewind_guard_rejects_compression_ended_parent_without_any_change(db):+ sid = "closed-rewind"+ db.create_session(sid, source="tui")+ target_id = db.append_message(sid, "user", _carrier())+ db.append_message(sid, "assistant", "failed")+ db.end_session(sid, "compression")+ before_rows = _row_state(db, sid)+ before_counts = _session_counts(db, sid)++ with pytest.raises(CompressionSessionClosedError):+ db.rewind_to_message(+ sid, target_id, preserve_compaction_handoff=True+ )++ assert _row_state(db, sid) == before_rows+ assert _session_counts(db, sid) == before_countsdiff --cc tests/test_compression_watermark_commit.pyindex 00000000000,c7e677fbc2d..c35fda2d31dmode 000000,100644..100644--- a/tests/test_compression_watermark_commit.py+++ b/tests/test_compression_watermark_commit.py@@@ -1,0 -1,314 +1,340 @@@+ """Watermark commit: concurrent appends survive in-place compaction (#75316).++ The provider summary call is external and slow. Messages that arrive while it+ runs must (a) persist immediately — appends are not fenced by the compression+ lock — and (b) survive the commit: ``archive_and_compact(watermark=...)``+ re-sequences every active row above the watermark after the compacted set+ instead of archiving it. The commit is holder-fenced: a compression whose+ lease was reclaimed cannot publish a stale compaction.+ """++ from __future__ import annotations++ import json+ import sqlite3+ import threading+ import time+ from pathlib import Path++ import pytest++ from hermes_state import SessionCompressionInProgressError, SessionDB+++ @pytest.fixture+ def db(tmp_path: Path) -> SessionDB:+ d = SessionDB(tmp_path / "state.db")+ d.create_session("sess1", source="test")+ return d+++ def _seed(db: SessionDB, n: int = 6) -> None:+ for i in range(n):+ role = "user" if i % 2 == 0 else "assistant"+ db.append_message("sess1", role=role, content=f"turn {i}")+++ SUMMARY = [+ {"role": "user", "content": "[CONTEXT COMPACTION] summary of turns 0-5"},+ {"role": "assistant", "content": "Continuing from the summary."},+ ]+++ class TestWatermarkCommit:+ def test_concurrent_tail_survives_compaction(self, db: SessionDB) -> None:+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ # Simulate the slow summary window: two messages land after capture.+ db.append_message("sess1", role="user", content="mid-compression steer")+ db.append_message("sess1", role="assistant", content="mid-compression reply")++ count = db.archive_and_compact("sess1", SUMMARY, watermark=watermark)++ live = db.get_messages("sess1")+ contents = [r["content"] for r in live]+ assert contents == [+ "[CONTEXT COMPACTION] summary of turns 0-5",+ "Continuing from the summary.",+ "mid-compression steer",+ "mid-compression reply",+ ], "tail must follow the summary, in arrival order"+ assert count == 4++ def test_tail_clone_preserves_every_column(self, db: SessionDB) -> None:+ """The pure-SQL clone must carry sidecar fields byte-exact."""+ _seed(db, 2)+ watermark = db.get_active_message_watermark("sess1")+ db.append_message(+ "sess1",+ role="assistant",+ content="tool caller",+ tool_calls=[{"id": "c1", "type": "function",+ "function": {"name": "terminal", "arguments": "{}"}}],+ )+ db.append_message(+ "sess1", role="tool", content="tool output",+ tool_call_id="c1", tool_name="terminal",+ )++ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)++ live = db.get_messages("sess1")+ by_content = {r["content"]: r for r in live}+ caller = by_content["tool caller"]+ result = by_content["tool output"]+ parsed = caller["tool_calls"]+ if isinstance(parsed, str):+ parsed = json.loads(parsed)+ assert parsed and parsed[0]["id"] == "c1"+ assert result["tool_call_id"] == "c1"+ assert result["tool_name"] == "terminal"++ def test_conversation_load_is_correct_after_commit(self, db: SessionDB) -> None:+ """The live conversation projection sees summary + tail, in order."""+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ db.append_message("sess1", role="user", content="late arrival")++ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)++ convo = db.get_messages_as_conversation("sess1")+ assert [m["content"] for m in convo] == [+ "[CONTEXT COMPACTION] summary of turns 0-5",+ "Continuing from the summary.",+ "late arrival",+ ]++ def test_no_tail_behaves_identically_to_legacy(self, db: SessionDB) -> None:+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ count = db.archive_and_compact("sess1", SUMMARY, watermark=watermark)+ assert count == 2+ assert [r["content"] for r in db.get_messages("sess1")] == [+ SUMMARY[0]["content"], SUMMARY[1]["content"],+ ]++ def test_none_watermark_preserves_historical_behavior(self, db: SessionDB) -> None:+ """watermark=None archives everything — the pre-#75316 contract."""+ _seed(db)+ db.append_message("sess1", role="user", content="gets archived")+ count = db.archive_and_compact("sess1", SUMMARY, watermark=None)+ assert count == 2+ contents = [r["content"] for r in db.get_messages("sess1")]+ assert "gets archived" not in contents++ def test_archived_rows_stay_recoverable(self, db: SessionDB) -> None:+ """Originals (snapshot AND tail source rows) survive as archived."""+ _seed(db, 4)+ watermark = db.get_active_message_watermark("sess1")+ db.append_message("sess1", role="user", content="tail row")+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)++ everything = db.get_messages("sess1", include_inactive=True)+ archived = [r for r in everything if not r["active"]]+ assert sum(1 for r in archived if r["content"] == "turn 0") == 1+ # The tail original is archived; its clone is the live copy.+ tail_rows = [r for r in everything if r["content"] == "tail row"]+ assert sorted(bool(r["active"]) for r in tail_rows) == [False, True]++ def test_session_counters_include_tail(self, db: SessionDB) -> None:+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ db.append_message(+ "sess1", role="assistant", content="tail with tools",+ tool_calls=[{"id": "t1", "type": "function",+ "function": {"name": "x", "arguments": "{}"}}],+ )+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)+ info = db.get_session("sess1")+ assert info["message_count"] == 3+ assert info["tool_call_count"] == 1+++ class TestCommitFence:+ def test_commit_refused_when_lease_lost(self, db: SessionDB) -> None:+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ assert db.try_acquire_compression_lock("sess1", "worker-A") is True+ # Lease reclaimed by another writer while worker-A's summary ran.+ db.release_compression_lock("sess1", "worker-A")+ assert db.try_acquire_compression_lock("sess1", "worker-B") is True++ with pytest.raises(SessionCompressionInProgressError):+ db.archive_and_compact(+ "sess1", SUMMARY, watermark=watermark, lock_holder="worker-A"+ )+ # Nothing committed: original transcript intact.+ assert [r["content"] for r in db.get_messages("sess1")] == [+ f"turn {i}" for i in range(6)+ ]++ def test_commit_refused_when_lease_expired(self, db: SessionDB) -> None:+ _seed(db)+ assert db.try_acquire_compression_lock(+ "sess1", "worker-A", ttl_seconds=0.05+ ) is True+ time.sleep(0.1)+ with pytest.raises(SessionCompressionInProgressError):+ db.archive_and_compact("sess1", SUMMARY, lock_holder="worker-A")++ def test_commit_allowed_for_live_holder(self, db: SessionDB) -> None:+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ assert db.try_acquire_compression_lock("sess1", "worker-A") is True+ count = db.archive_and_compact(+ "sess1", SUMMARY, watermark=watermark, lock_holder="worker-A"+ )+ assert count == 2++ def test_refused_commit_rolls_back_atomically(self, db: SessionDB) -> None:+ """Failure injection: the fence raise must leave zero partial writes."""+ _seed(db)+ before = db.get_messages("sess1", include_inactive=True)+ with pytest.raises(SessionCompressionInProgressError):+ db.archive_and_compact("sess1", SUMMARY, lock_holder="never-held")+ after = db.get_messages("sess1", include_inactive=True)+ assert len(before) == len(after)+ assert all(r["active"] for r in after)+++ class TestConcurrentAppendDuringCompaction:+ def test_append_racing_the_commit_transaction(self, db: SessionDB) -> None:+ """An append serialized behind the commit lands AFTER it — never lost.++ SQLite's write lock serializes the two transactions; whichever side+ wins, the append must end up in the live transcript.+ """+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")++ barrier = threading.Barrier(2, timeout=10)+ append_err: list = []++ def _racer():+ barrier.wait()+ try:+ db.append_message("sess1", role="user", content="racer")+ except Exception as exc: # pragma: no cover+ append_err.append(exc)++ t = threading.Thread(target=_racer, daemon=True)+ t.start()+ barrier.wait()+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)+ t.join(timeout=10)++ assert not append_err, f"append died during commit race: {append_err}"+ contents = [r["content"] for r in db.get_messages("sess1")]+ assert "racer" in contents, "racing append was lost"+++ class TestRotationPathWatermark:+ """Legacy (non-in-place) compression rotates to a child session —+ the concurrent tail must follow the rotation instead of stranding in+ the closed parent."""+- def test_tail_clones_into_the_child(self, db: SessionDB) -> None:++ @pytest.mark.parametrize(++ "tail_content",++ [++ "mid-rotation steer",++ [++ {"type": "text", "text": "inspect this"},++ {++ "type": "image_url",++ "image_url": {"url": "data:image/png;base64,AA=="},++ },++ ],++ ],++ ids=["text", "multimodal"],++ )++ def test_tail_clones_into_the_child(self, db: SessionDB, tail_content) -> None:+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ assert db.try_acquire_compression_lock("sess1", "rotator") is True- db.append_message("sess1", role="user", content="mid-rotation steer")++ db.append_message("sess1", role="user", content=tail_content)+ # Ceiling captured AFTER the foreign append, BEFORE the rotation+ # path's own pre-publish flush (which this test has none of).+ ceiling = db.get_active_message_watermark("sess1")++ db.publish_compression_child(+ parent_session_id="sess1",+ child_session_id="child1",+ source="test",+ messages=SUMMARY,+ compression_lock_holder="rotator",+ require_compression_lease=True,+ watermark=watermark,+ watermark_ceiling=ceiling,+ )++ child = db.get_messages_as_conversation("child1")+ assert [m["content"] for m in child] == [+ SUMMARY[0]["content"],+ SUMMARY[1]["content"],- "mid-rotation steer",++ tail_content,+ ]++ model_history, display_history = db.get_resume_conversations("child1")++ visible_steers = [++ message++ for message in display_history++ if message.get("content") == tail_content++ ]++ assert len(visible_steers) == 1++ assert visible_steers[0]["_row_id"] == model_history[-1]["_row_id"]++ assert all(++ message.get("content") != tail_content++ for message in db.get_ancestor_display_prefix("child1")++ )+ info = db.get_session("child1")+ assert info["message_count"] == 3+ # Parent keeps its copy for lineage recovery; parent is closed.+ parent_info = db.get_session("sess1")+ assert parent_info["end_reason"] == "compression"++ def test_ceiling_excludes_the_rotators_own_flush(self, db: SessionDB) -> None:+ """Rows the rotation path flushes AFTER the ceiling (its own input+ transcript, already inside the handoff) must NOT be cloned."""+ _seed(db)+ watermark = db.get_active_message_watermark("sess1")+ assert db.try_acquire_compression_lock("sess1", "rotator") is True+ db.append_message("sess1", role="user", content="foreign steer")+ ceiling = db.get_active_message_watermark("sess1")+ # Simulates the #47202 pre-publish flush of the rotator's own input.+ db.append_message(+ "sess1", role="user", content="rotator's own flush",+ compression_lock_holder="rotator",+ )++ db.publish_compression_child(+ parent_session_id="sess1",+ child_session_id="child1",+ source="test",+ messages=SUMMARY,+ compression_lock_holder="rotator",+ require_compression_lease=True,+ watermark=watermark,+ watermark_ceiling=ceiling,+ )++ child_contents = [+ m["content"] for m in db.get_messages_as_conversation("child1")+ ]+ assert "foreign steer" in child_contents+ assert "rotator's own flush" not in child_contents++ def test_no_watermark_keeps_historical_rotation(self, db: SessionDB) -> None:+ _seed(db)+ assert db.try_acquire_compression_lock("sess1", "rotator") is True+ db.append_message("sess1", role="user", content="stranded either way")+ db.publish_compression_child(+ parent_session_id="sess1",+ child_session_id="child1",+ source="test",+ messages=SUMMARY,+ compression_lock_holder="rotator",+ require_compression_lease=True,+ )+ child = db.get_messages_as_conversation("child1")+ assert [m["content"] for m in child] == [+ SUMMARY[0]["content"], SUMMARY[1]["content"],+ ]diff --cc tests/test_tui_gateway_server.pyindex 37250052d0f,d193f66c47f..c44326cb376--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@@ -11184,6 -11233,223 +11399,255 @@@ def test_prompt_submit_truncate_ordinalserver._sessions.pop("sid", None)+ def test_prompt_submit_truncate_translates_display_prefix_ordinal(monkeypatch):+ """Full-lineage Desktop ordinals must truncate the tip segment (#82462).++ After compression, session["history"] is the tip while display_history_prefix+ still holds ancestor user turns the UI shows. A client ordinal that includes+ those ancestors must map into the tip, not 4018.+ """++ seen = {}++ class _Agent:+ def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kwargs):+ seen["prompt"] = prompt+ seen["history"] = conversation_history+ return {+ "final_response": "edited reply",+ "messages": [+ *(conversation_history or []),+ {"role": "user", "content": prompt},+ {"role": "assistant", "content": "edited reply"},+ ],+ }++ class _ImmediateThread:+ def __init__(self, target=None, daemon=None):+ self._target = target++ def start(self):+ self._target()++ tip_history = [+ {"role": "user", "content": "post-compress A"},+ {"role": "assistant", "content": "reply A"},+ {"role": "user", "content": "post-compress B"},+ {"role": "assistant", "content": "reply B"},+ ]+ display_prefix = [+ {"role": "user", "content": "pre-compress 1"},+ {"role": "assistant", "content": "pre reply 1"},+ {"role": "user", "content": "pre-compress 2"},+ {"role": "assistant", "content": "pre reply 2"},+ ]+ # Desktop lineage: pre1=0, pre2=1, postA=2, postB=3+ desktop_ordinal_for_post_b = 3++ server._sessions["sid"] = _session(+ agent=_Agent(),+ history=tip_history,+ display_history_prefix=display_prefix,+ )++ class _StubDb:+ def __init__(self):+ self.replaced = []++ def get_messages_as_conversation(self, *_args, **_kwargs):+ # Empty durable transcript: proves this ephemeral-style session+ # may take the ordinal-only path past the durability gate.+ return []+- def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):++ def replace_messages(++ self,++ session_id,++ messages,++ active_only=False,++ archive_dropped=False,++ reject_active_turn_lease=False,++ ):++ assert reject_active_turn_lease is True+ self.replaced.append((session_id, list(messages)))++ stub_db = _StubDb()++ try:+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(server, "_get_usage", lambda _a: {})+ monkeypatch.setattr(server, "render_message", lambda _t, _c: "")+ monkeypatch.setattr(server, "_emit", lambda *a: None)+ monkeypatch.setattr(server, "_get_db", lambda: stub_db)++ resp = server.handle_request(+ {+ "id": "1",+ "method": "prompt.submit",+ "params": {+ "session_id": "sid",+ "text": "edited post B",+ "truncate_before_user_ordinal": desktop_ordinal_for_post_b,+ "confirm_truncate": True,+ },+ }+ )+ assert resp.get("result"), f"got error: {resp.get('error')}"+ assert seen["prompt"] == "edited post B"+ assert seen["history"] == tip_history[:2]+ assert stub_db.replaced == [("session-key", tip_history[:2])]+ finally:+ server._sessions.pop("sid", None)+++ def test_prompt_submit_truncate_oor_includes_structured_user_turn_count(monkeypatch):+ """4018 after compaction must carry recovery fields for Desktop (#82462)."""++ tip_history = [+ {"role": "user", "content": "post-compress A"},+ {"role": "assistant", "content": "reply A"},+ ]+ display_prefix = [+ {"role": "user", "content": "pre-compress 1"},+ {"role": "assistant", "content": "pre reply 1"},+ ]+ # Ordinal 0 points at the ancestor prefix — not editable from the tip.+ server._sessions["sid"] = _session(+ history=tip_history,+ display_history_prefix=display_prefix,+ )++ try:+ monkeypatch.setattr(+ server, "_start_inflight_turn", lambda *a, **k: pytest.fail("must not start a turn")+ )+ resp = server.handle_request(+ {+ "id": "1",+ "method": "prompt.submit",+ "params": {+ "session_id": "sid",+ "text": "edit ancestor",+ "truncate_before_user_ordinal": 0,+ "confirm_truncate": True,+ },+ }+ )+ err = resp.get("error") or {}+ assert err.get("code") == 4018+ assert "no longer in session history" in (err.get("message") or "")+ data = err.get("data") or {}+ assert data.get("user_turn_count") == 1+ assert data.get("ordinal") == 0+ assert data.get("segment_ordinal") == -1+ assert data.get("prefix_user_count") == 1+ finally:+ server._sessions.pop("sid", None)+++ def test_prompt_submit_row_id_accepts_full_lineage_ordinal(monkeypatch):+ """Desktop sends rowId + a full-lineage ordinal; both must agree (#82462).++ After compression the client's visible-user ordinal counts the ancestor+ prefix turns while the gateway resolves the row id tip-relative. The+ reconcile cross-check must treat `tip_ordinal + prefix_user_count` as+ agreement, not #82756 drift — and the cut stays aimed by the row id.+ """++ from agent.context_compressor import (++ HISTORICAL_TASK_HEADING,++ SUMMARY_PREFIX,++ _SUMMARY_END_MARKER,++ )+++ tip_history = [+ {"_row_id": 501, "role": "user", "content": "post-compress A"},+ {"_row_id": 502, "role": "assistant", "content": "reply A"},+ {"_row_id": 503, "role": "user", "content": "post-compress B"},+ {"_row_id": 504, "role": "assistant", "content": "reply B"},+ ]+ display_prefix = [+ {"role": "user", "content": "pre-compress 1"},+ {"role": "assistant", "content": "pre reply 1"},++ {++ # Legacy pure handoffs did not always carry display_kind=hidden.++ # They are physically user rows but not visible/user-originated++ # turns, so they must not shift the Desktop lineage ordinal.++ "role": "user",++ "content": (++ f"{SUMMARY_PREFIX}\n{HISTORICAL_TASK_HEADING}\nold task\n\n"++ f"{_SUMMARY_END_MARKER}"++ ),++ },+ {"role": "user", "content": "pre-compress 2"},+ {"role": "assistant", "content": "pre reply 2"},+ ]++ replaced = []++ class _FakeDB:- def replace_messages(self, key, messages, active_only=False, archive_dropped=False):++ def replace_messages(++ self,++ key,++ messages,++ active_only=False,++ archive_dropped=False,++ reject_active_turn_lease=False,++ ):++ assert reject_active_turn_lease is True+ replaced.append((key, list(messages)))++ sess = _session(history=list(tip_history), display_history_prefix=display_prefix)+ server._sessions["lineage-row-sid"] = sess+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)++ try:+ resp = server.handle_request(+ {+ "id": "1",+ "method": "prompt.submit",+ "params": {+ "session_id": "lineage-row-sid",+ "text": "edited post B",+ # Row id resolves to tip ordinal 1; the client counted the+ # 2 ancestor user turns, so its lineage ordinal is 3.+ "truncate_before_row_id": 503,+ "truncate_before_user_ordinal": 3,+ "confirm_truncate": True,+ },+ }+ )+ assert resp.get("error") is None, f"got error: {resp.get('error')}"+ assert sess["history"] == tip_history[:2]+ finally:+ server._sessions.pop("lineage-row-sid", None)++ # A genuinely stale ordinal (matches neither the tip space nor the+ # lineage space) must still refuse with the #82756 mismatch.+ sess2 = _session(history=list(tip_history), display_history_prefix=display_prefix)+ server._sessions["lineage-row-sid-2"] = sess2+ monkeypatch.setattr(+ server, "_start_agent_build", lambda *a, **k: pytest.fail("must not start a turn")+ )+ try:+ resp = server.handle_request(+ {+ "id": "2",+ "method": "prompt.submit",+ "params": {+ "session_id": "lineage-row-sid-2",+ "text": "edited post B",+ "truncate_before_row_id": 503,+ "truncate_before_user_ordinal": 2,+ "confirm_truncate": True,+ },+ }+ )+ assert resp.get("error") is not None+ assert resp["error"]["code"] == 4030+ finally:+ server._sessions.pop("lineage-row-sid-2", None)++# ---------------------------------------------------------------------------# session.interrupt must only cancel pending prompts owned by the calling# session — it must not blast-resolve clarify/sudo/secret prompts on@@@ -18910,6 -19177,6 +19410,7 @@@ def test_prompt_submit_row_id_misalignedb._insert_message_rows(db._conn, session_key, msgs)db._conn.commit()rid_b = msgs[2]["_row_id"]++ original_row_ids = [message["_row_id"] for message in msgs]# Same length + same role pattern, but content positions swapped: a# positional stamp would mark live "B" with durable A's row id and the@@@ -18941,6 -19208,6 +19442,7 @@@"session_id": sid,"text": "rewind B","truncate_before_row_id": rid_b,++ "rebind_survivor_row_ids": [*original_row_ids, 999_999],"confirm_truncate": True,},}@@@ -18979,6 -19246,6 +19481,7 @@@ def test_prompt_submit_row_id_misalignedb._insert_message_rows(db._conn, session_key, msgs)db._conn.commit()rid_b = msgs[2]["_row_id"]++ original_row_ids = [message["_row_id"] for message in msgs]live_history = [{"role": "user", "content": "A"},@@@ -19002,6 -19269,6 +19505,7 @@@"session_id": sid,"text": "rewind B","truncate_before_row_id": rid_b,++ "rebind_survivor_row_ids": [*original_row_ids, 999_999],"confirm_truncate": True,},}@@@ -19018,6 -19285,6 +19522,13 @@@("assistant", "ra"),("assistant", "rb"),]++ # The live list was too misaligned to bind old survivors to their new++ # physical rows safely. All requested IDs known to the pre-write active++ # transcript are therefore cleared; an unrelated archived/ancestor ID++ # remains absent from the bounded map and keeps its identity.++ assert resp["result"]["survivor_row_id_map"] == {++ str(row_id): None for row_id in original_row_ids++ }finally:server._sessions.pop(sid, None)@@@ -19098,8 -19358,8 +19609,9 @@@ def test_prompt_submit_row_id_db_fallbaserver._sessions.pop(sid, None)[email protected]("turn_isolation", [False, True])def test_prompt_submit_consecutive_rewinds_with_returned_survivor_row_ids(-- monkeypatch, tmp_path++ monkeypatch, tmp_path, turn_isolation):"""#83202 review (consecutive-rewind staleness): replace_messages re-insertsthe surviving prefix as NEW rows, so the pre-rewind client row ids die on@@@ -19128,6 -19388,6 +19640,16 @@@sid = "real-db-consec-rewind-sid"server._sessions[sid] = sessmonkeypatch.setattr(server, "_get_db", lambda: db)++ monkeypatch.setattr(++ server,++ "_load_cfg",++ lambda: {"dashboard": {"turn_isolation": turn_isolation}},++ )++ monkeypatch.setattr(++ server,++ "_submit_prompt_to_compute_host",++ lambda *_args, **_kwargs: server._ok("host", {"status": "streaming"}),++ )monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)monkeypatch.setattr(server, "_start_inflight_turn", lambda *a, **k: None)@@@ -19143,17 -19403,17 +19665,30 @@@"text": "rewound third","truncate_before_row_id": original_row_ids[4],"truncate_before_user_ordinal": 2,++ "rebind_survivor_row_ids": [*original_row_ids, 999_999],"confirm_truncate": True,},})assert resp1.get("error") is None, resp1-- survivors = resp1["result"].get("survivor_user_row_ids")-- # Fresh ids for the two surviving user turns, in visible-user order.-- assert isinstance(survivors, list) and len(survivors) == 2-- assert all(isinstance(r, int) for r in survivors)++ assert "survivor_user_row_ids" not in resp1["result"]++ row_id_map = resp1["result"].get("survivor_row_id_map")++ assert isinstance(row_id_map, dict)++ survivors = [++ row_id_map[str(original_row_ids[0])],++ row_id_map[str(original_row_ids[2])],++ ]# They must be NEW rows — the old ids are archived (active=0) now.assert set(survivors).isdisjoint(set(original_row_ids))++ assert row_id_map == {++ str(original_row_ids[0]): survivors[0],++ str(original_row_ids[1]): sess["history"][1]["_row_id"],++ str(original_row_ids[2]): survivors[1],++ str(original_row_ids[3]): sess["history"][3]["_row_id"],++ str(original_row_ids[4]): None,++ str(original_row_ids[5]): None,++ }++ assert "999999" not in row_id_mapsess["running"] = False# Rewind 2a: the STALE pre-rewind id for "second" must fail closed.diff --cc tui_gateway/methods_prompt.pyindex 79251dad9ce,745a855e3d6..8d45f0092c0--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@@ -362,6 -364,6 +377,17 @@@ def _(rid, params: dict) -> dict# the fresh post-rewrite row ids of the surviving user turns, for client# rowId rebinding (see comment at the assignment site).survivor_user_row_ids = None++ survivor_row_id_map = None++ raw_rebind_ids = params.get("rebind_survivor_row_ids")++ requested_rebind_ids = (++ {++ row_id++ for row_id in raw_rebind_ids++ if isinstance(row_id, int) and not isinstance(row_id, bool)++ }++ if isinstance(raw_rebind_ids, list)++ else None++ )with session["history_lock"]:# A watch session's run lives in the PARENT turn, so its own running# flag is False — without this, typing mid-run builds a second agent@@@ -439,6 -439,21 +465,19 @@@"an ordinary prompt.submit must not drop session history ""(update your Hermes client if a rewind was intended)",)+ # Desktop/TUI ordinals count the full displayed lineage. After+ # compression, session["history"] holds only the tip segment while+ # display_history_prefix holds the immutable ancestor display rows+ # still shown in the transcript (#82462 / #69107). Count the+ # ancestor user turns once so every comparison between a client+ # ordinal and a tip-relative ordinal below can translate, instead+ # of loading ancestors into the tip (which would duplicate+ # compressed history on later resumes).- prefix_user_count = sum(- 1- for message in session.get("display_history_prefix") or []- if isinstance(message, dict)- and message.get("role") == "user"- and not message.get("display_kind")++ prefix_user_count = len(++ _history_user_indices(++ session.get("display_history_prefix") or []++ )+ )user_indices = _history_user_indices(history)@@@ -546,12 -592,13 +616,17 @@@# truncating history to everything before it and persisting that loss# via replace_messages — an unrecoverable overwrite of the session DB.if ordinal < 0 or ordinal >= len(user_indices):- return _err(rid, 4018, "target user message is no longer in session history")+ return _err(+ rid,+ 4018,+ "target user message is no longer in session history",+ data=_stale_target_data(resolved_ordinal=ordinal),+ )- truncated = history[: user_indices[ordinal]]+ from agent.context_compressor import history_before_user_originated_turn++ truncated, _live_view = history_before_user_originated_turn(+ history, user_indices[ordinal]+ )# Second gate, on top of confirm_truncate: ordinal 0 resolves to# history[:0] == [] and replace_messages() DELETEs every durable# row. A confirmed rewind that happens to erase the whole@@@ -615,6 -662,6 +690,36 @@@# sessions created before the session_key default fix have no# key, and replace_messages(None) triggers an FK violation.truncation_key = session.get("session_key") or sid++ old_active_row_ids = {++ row_id++ for message in history++ if isinstance((row_id := _message_row_id(message)), int)++ }++ if requested_rebind_ids is not None and any(++ _message_row_id(message) is None for message in history++ ):++ # Row-id fallback can resolve a durable target even++ # when the live list is too misaligned to stamp safely.++ # Read the authoritative pre-write active-id set so a++ # rewritten row is never mistaken for an untouched++ # archived/ancestor row by the bounded client map.++ durable_rebind_history = _load_durable_truncation_history(++ session, truncation_key++ )++ if durable_rebind_history is None:++ raise RuntimeError(++ "could not load durable row identities for truncation"++ )++ old_active_row_ids.update(++ row_id++ for message in durable_rebind_history++ if isinstance(++ (row_id := _message_row_id(message)), int++ )++ )++ old_survivor_row_ids = [++ _message_row_id(message) for message in truncated++ ]db.replace_messages(truncation_key,truncated,@@@ -644,6 -701,6 +749,21 @@@_message_row_id(truncated[i])for i in _history_user_indices(truncated)]++ if requested_rebind_ids is not None:++ survivor_row_id_map = {++ str(old_row_id): new_row_id++ for old_row_id, new_row_id in zip(++ old_survivor_row_ids,++ (_message_row_id(message) for message in truncated),++ )++ if isinstance(old_row_id, int)++ and isinstance(new_row_id, int)++ and old_row_id in requested_rebind_ids++ }++ for dropped_row_id in requested_rebind_ids.intersection(++ old_active_row_ids++ ):++ survivor_row_id_map.setdefault(str(dropped_row_id), None)session["running"] = Truesession["_turn_cancel_requested"] = Falsesession["last_active"] = time.time()@@@ -652,13 -709,13 +772,15 @@@if turn_isolation:isolated_response = _submit_prompt_to_compute_host(rid, sid, session, text)if not isolated_response.get("error"):-- if survivor_user_row_ids is not None:++ if survivor_user_row_ids is not None and requested_rebind_ids is None:# The truncation already happened inline above (memory + DB),# before compute-host dispatch — the rebind payload applies to# this path exactly as it does to the inline one.isolated_response["result"]["survivor_user_row_ids"] = survivor_user_row_ids++ if survivor_row_id_map is not None:++ isolated_response["result"]["survivor_row_id_map"] = survivor_row_id_mapreturn isolated_responselogger.warning("compute-host dispatch failed for session %s; falling back inline: %s",@@@ -750,6 -807,6 +872,12 @@@**({"survivor_user_row_ids": survivor_user_row_ids}if survivor_user_row_ids is not None++ and requested_rebind_ids is None++ else {}++ ),++ **(++ {"survivor_row_id_map": survivor_row_id_map}++ if survivor_row_id_map is not Noneelse {}),},