diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index b69349da..e2b71397 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -4,20 +4,25 @@ * node test environment can import it. * * A side thread is a child session the plugin creates ITSELF with a custom - * seed — the parent session's FULL event log up to the click moment - * (completed turns, the unanswered user message, and — when the parent is - * mid-turn — the in-progress assistant output and tool activity). The log - * model forbids open-turn seeds, so an in-flight parent turn is copied - * verbatim and CLOSED with synthetic `step/end` + `turn/end{reason: - * 'interrupted'}` events: the child sees the partial turn as honestly - * frozen ("cut off"), never as a completed answer. The one case that cannot - * be closed honestly — a tool call still executing (no `tool/result` yet; - * providers reject dangling assistant calls) — falls back to cutting before - * the open turn and carrying the partial content as a structured text - * snapshot inside the boundary prompt. + * seed — the parent's model-visible history up to the click moment. When the + * parent has summarized (its last compaction checkpoint replaces the + * shadowed span on the surface), the seed is REBASED onto that checkpoint: + * surviving pre-cut surface nodes, the checkpoint, and the post-compaction + * tail — proven equivalent to a full-log fork by folding both (compactionTail) + * — instead of physically duplicating the whole log. Without a compaction, + * or whenever the rebasing cannot be proven, the seed is the parent's FULL + * event log verbatim. The log model forbids open-turn seeds, so an + * in-flight parent turn is copied verbatim and CLOSED with synthetic + * `step/end` + `turn/end{reason: 'interrupted'}` events: the child sees the + * partial turn as honestly frozen ("cut off"), never as a completed answer. + * The one case that cannot be closed honestly — a tool call still executing + * (no `tool/result` yet; providers reject dangling assistant calls) — falls + * back to cutting before the open turn and carrying the partial content as + * a structured text snapshot inside the boundary prompt. */ import type { SidebarHistoryEntry, SidebarSessionSummary } from './context-types.ts' import type { AssistantLiveChunk } from './assistant-live.ts' +import { foldSurface, isSurfaceEligibleType } from '@deepseek-ai/dsh-session/surface' /** The durable thread-label prefix (also the row filter in the client list). */ export const SIDE_LABEL_PREFIX = 'Side: ' @@ -273,9 +278,638 @@ const SNAPSHOT_RESULT_CAP = 2000 /** Cap applied to the whole snapshot (prompt budget). */ const SNAPSHOT_TOTAL_CAP = 8000 +/** + * Rebase the parent's log onto its last summarizing compaction: the + * checkpoint `user/message` already REPLACES the shadowed span on the + * model-visible surface, so a child needs only the surviving head skeleton + * (with its turn/step scaffolding — the session relational invariants demand + * it), the checkpoint itself, and the keep-window + post-compaction tail + * VERBATIM — the forgotten span never has to be physically copied again, + * while every kept event keeps its enclosing structure. The result is + * verified with the real fold before it is used: the rebased sequence must + * produce the SAME visible nodes as the parent, which keeps the child's + * model context (and provider context-cache prefix) identical to a + * full-log fork. + * + * Returns a seq-contiguous event array, or undefined to fall back to the + * verbatim full copy — no compaction in the log, a reference the rebase + * cannot resolve, or any fold the construction cannot prove equivalent. + * Failures degrade to today's behavior, never to a wrong child. + * @param events - the parent's log (live or persisted). + * @returns the rebased log, or undefined when the full copy is required. + */ +function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] | undefined { + const cut = lastCheckpointIndex(events) + if (cut === undefined) return undefined + const checkpoint = events[cut] + if (checkpoint === undefined) return undefined + let parentNodes: readonly number[] + try { + const fold = foldSurface(events as unknown as Parameters[0]) + parentNodes = fold.nodes + } catch { + return undefined + } + const surfaceIndex = parentNodes.indexOf(checkpoint.seq) + // The checkpoint must sit on the surface, and every node before its + // surface slot must predate the cut (a post-cut node reordered ahead of + // the checkpoint would need the very shadowing we are removing). + if (surfaceIndex === -1) return undefined + const head: number[] = [] + let keepFirst: number | undefined + let sawTailNode = false + for (let index = 0; index < parentNodes.length; index++) { + if (index === surfaceIndex) continue + const seq = parentNodes[index] as number + if (seq >= cut) { + if (index < surfaceIndex) return undefined + sawTailNode = true + continue + } + // Surface order is [head nodes][checkpoint][keep-window nodes][tail in + // log order]; anything else cannot be reproduced and degrades to the + // full copy. + if (sawTailNode) return undefined + if (index < surfaceIndex) head.push(seq) + else if (keepFirst === undefined) keepFirst = seq + } + const headEvents = headSkeleton(events, head) + if (headEvents === undefined) return undefined + let keepStart = enclosingTurnStart(events, keepFirst) + // The loop writes a turn's inbox INSERT before its turn/start and the + // CLAIM right after it; starting the keep window at the turn/start would + // keep the claim while dropping its insert, and the host's positional + // inbox fold would reject the seed. Swallow the contiguous splices that + // precede the skeleton root — they replay cleanly from an empty inbox. + while (keepStart > 0 && events[keepStart - 1]?.type === 'agent/inbox/spliced') keepStart -= 1 + const groupId = dataOf(events[cut - 1]!).compactionId + // The keep interval is a LOG range; the region may have ended mid-turn, + // so the interval can re-carry surface nodes the checkpoint already + // shadowed (they precede the surviving ones inside the same turn). Skip + // exactly those, plus tool/calls whose result did not survive — an + // orphaned call fails the relational invariants just like a bare one. + const surviving = new Set(parentNodes as readonly number[]) + const survivingCallIds = new Set() + for (const seq of parentNodes as readonly number[]) { + const node = events[seq] + if (node === undefined || node.type !== 'tool/result') continue + const callId = toolResultCallIdOf(node) + if (callId !== undefined) survivingCallIds.add(callId) + } + // Surface nodes a KEPT replacement still targets are not skippable: the + // replacement's fold transition (node appears, then is replaced) must + // replay — skipping its target would degrade the replacement to an + // append stranded after the step closed, which the relational rules + // reject. (The pruner's tool/result rewrites are exactly this shape.) + const replaceCovered = new Set() + for (const [from, to] of [[keepStart, cut], [cut + 1, events.length]] as const) { + for (let index = from; index < to; index++) { + const event = events[index] + if (event === undefined || isCompactionGroupEvent(event, groupId)) continue + const op = (event as { surfaceOp?: unknown }).surfaceOp + if (op === null || typeof op !== 'object' || (op as { op?: unknown }).op !== 'replace') continue + const start = (op as { startSeq?: unknown }).startSeq + const end = (op as { endSeq?: unknown }).endSeq + if (typeof start !== 'number' || typeof end !== 'number' || start > end) continue + for (let seq = Math.max(0, start); seq <= Math.min(end, events.length - 1); seq++) replaceCovered.add(seq) + } + } + // The set of parent seqs the seed will carry, decided BEFORE emission: a + // grouped record whose citations cannot remap drops ATOMICALLY — its + // compaction bracket (start/summary/end) or its command pair goes + // together, never a lone partner that the host's invariant companions + // reject. Real multi-compaction sessions hit this on every mid-keep group + // (its summary cites nodes later groups re-shadowed), so record-level + // dropping would strand brackets on every real parent. + const emittedSeqs = new Set() + for (const event of headEvents) emittedSeqs.add(event.seq) + emittedSeqs.add(checkpoint.seq) + const keepSkip = (event: SidechatLogEvent): boolean => + (isSurfaceEligibleType(event.type) && !surviving.has(event.seq) && !replaceCovered.has(event.seq)) + || (event.type === 'tool/call' && !survivingCallIds.has(String(dataOf(event).callId))) + for (const [from, to] of [[keepStart, cut], [cut + 1, events.length]] as const) { + for (let index = from; index < to; index++) { + const event = events[index] + if (event === undefined) continue + if (isCompactionGroupEvent(event, groupId)) continue + if (index < cut && keepSkip(event)) continue + emittedSeqs.add(event.seq) + } + } + const droppedGroups = new Set() + const keptRunIds = new Set() + for (const seq of emittedSeqs) { + const event = events[seq] + if (event === undefined || event.type !== 'command/run') continue + const id = dataOf(event).commandId + if (typeof id === 'string') keptRunIds.add(id) + } + const droppedDones = new Set() + for (const seq of emittedSeqs) { + const event = events[seq] + if (event === undefined) continue + const data = dataOf(event) + if (event.type === 'compaction/summary' || event.type === 'compaction/prune') { + const range = data.shadowedRange as { start?: unknown; end?: unknown } | undefined + const cited = data.shadowedSeqs + if (range === null || typeof range !== 'object' || !Array.isArray(cited)) continue + const start = typeof range.start === 'number' ? emittedSeqs.has(range.start) : true + const end = typeof range.end === 'number' ? emittedSeqs.has(range.end) : true + const citedAll = cited.every(item => typeof item !== 'number' || emittedSeqs.has(item)) + if (!start || !end || !citedAll) { + const id = data.compactionId + if (typeof id === 'string') droppedGroups.add(id) + } + } else if (event.type === 'command/done') { + const id = data.commandId + const sourceSeq = data.sourceEventSeq + // The host contract: sourceEventSeq cites an earlier NON-command + // event, and the commands invariant rejects a stale or out-of-range + // citation. A done whose run or whose cited source falls in the + // dropped span drops ATOMICALLY with it. + const runKept = typeof id === 'string' && keptRunIds.has(id) + const sourceKept = typeof sourceSeq !== 'number' || emittedSeqs.has(sourceSeq) + if (!runKept || !sourceKept) droppedDones.add(event.seq) + } + } + // Turn renumbering: the host's turn counter must run 1, 2, 3… over the + // seed, but the dropped span leaves a gap between the head skeleton's + // turn and the keep window's first turn/start. Every kept event carrying + // a turn number at or past that first kept turn shifts down by the gap; + // head-side numbers (below it) stay untouched. `step` numbers restart per + // turn, so verbatim scaffolding inside a kept turn stays correct. + const headOwnsTurn1 = headEvents.some(event => event.type === 'turn/start') + const expectedFirstKeptTurn = headOwnsTurn1 ? 2 : 1 + let firstKeptTurn: number | undefined + // The first kept turn/start can sit in the keep interval OR — when every + // pre-cut survivor is the protected head — only in the tail after the + // consumed group; scan both ranges. + for (const [from, to] of [[keepStart, cut], [cut + 1, events.length]] as const) { + for (let index = from; index < to; index++) { + const event = events[index] + if (event === undefined || event.type !== 'turn/start') continue + const turn = dataOf(event).turn + if (typeof turn === 'number') firstKeptTurn = turn + break + } + if (firstKeptTurn !== undefined) break + } + const turnOffset = firstKeptTurn === undefined ? 0 : Math.max(0, firstKeptTurn - expectedFirstKeptTurn) + // Positional renumbering over the kept set; every emitted event passes the + // same rebase: seq references remap when the map can serve them, and a + // reference into the dropped span degrades honestly (replace → append, + // dropped citations) — except `developer/message.headerSeq`, whose + // referent cannot be degraded: that aborts the whole tail. + const rebase = new Map() + const seed: SeedEvent[] = [] + let aborted = false + const emit = (event: SidechatLogEvent | undefined): void => { + if (aborted || event === undefined) return + const rebased: RebasedEvent = rebaseEvent(event, seed.length, rebase, turnOffset, firstKeptTurn) + if (rebased === DROPPED) return + if (rebased === undefined) { + aborted = true + return + } + rebase.set(event.seq, seed.length) + seed.push(rebased) + } + for (const event of headEvents) emit(event) + emit(checkpoint) + for (let index = keepStart; index < cut; index++) { + const event = events[index] + if (event === undefined || isCompactionGroupEvent(event, groupId)) continue + if (keepSkip(event)) continue + if (droppedGroups.has(String(dataOf(event).compactionId))) continue + if (droppedDones.has(event.seq)) continue + emit(event) + } + for (let index = cut + 1; index < events.length; index++) { + const event = events[index] + if (event === undefined || isCompactionGroupEvent(event, groupId)) continue + if (droppedGroups.has(String(dataOf(event).compactionId))) continue + if (droppedDones.has(event.seq)) continue + emit(event) + } + if (aborted) return undefined + // Prove equivalence before the caller relies on it: the rebased sequence + // must fold without error and to the same visible nodes as the parent, + // and its turn/step skeleton must satisfy the host's relational counter + // rules (turn/start runs 1, 2, …; steps open and close inside their turn; + // a trailing open turn is the caller's to close). + try { + const child = foldSurface(seed as unknown as Parameters[0]) + if (!sameVisibleSequence(events, parentNodes, child.nodes, seed)) return undefined + } catch { + return undefined + } + if (!turnSequenceValid(seed)) return undefined + if (!inboxSplicesValid(seed)) return undefined + if (!bracketsValid(seed)) return undefined + return seed +} + +/** + * Relational pre-check mirroring the host's grouped-record rules: a + * successful `compaction/end` requires a `compaction/summary` of the same + * compactionId earlier in the log, and a `command/done` requires its + * `command/run` (same commandId) before it. Dropping a summary or a run + * with the forgotten span while keeping its partner would ship a seed the + * host's invariant companions reject, so any unmatched partner falls back + * to the full copy. + */ +function bracketsValid(seed: readonly SeedEvent[]): boolean { + const summarized = new Set() + const ranCommands = new Set() + for (const event of seed) { + const data = dataOf(event) + if (event.type === 'compaction/summary') { + const id = data.compactionId + if (typeof id === 'string') summarized.add(id) + } else if (event.type === 'compaction/end') { + const id = data.compactionId + if (data.error === undefined && (typeof id !== 'string' || !summarized.has(id))) return false + } else if (event.type === 'command/run') { + const id = data.commandId + if (typeof id === 'string') ranCommands.add(id) + } else if (event.type === 'command/done') { + const id = data.commandId + if (typeof id !== 'string' || !ranCommands.has(id)) return false + } + } + return true +} + +/** + * Relational pre-check mirroring the host's durable-inbox fold: every kept + * `agent/inbox/spliced` event replays POSITIONALLY over the pending inbox + * (splice.start/removedCount must stay in range, message ids unique). A + * seed whose splice history cannot replay from an empty inbox falls back + * to the full copy. + */ +function inboxSplicesValid(seed: readonly SeedEvent[]): boolean { + const nextTurn: Array> = [] + const nextStep: Array> = [] + for (const event of seed) { + if (event.type !== 'agent/inbox/spliced') continue + const data = dataOf(event) + // Host strictness: only the two known targets, a numeric start and + // removedCount, and an array of messages with string ids. + if (data.target !== 'next-turn' && data.target !== 'next-step') return false + const inbox = data.target === 'next-step' ? nextStep : nextTurn + const rawStart = data.start + // The host contract makes removedCount optional and defaults it to 0 + // (its own writer omits it for pure inserts — 54% of real splices). + const removedCount = typeof data.removedCount === 'number' ? data.removedCount : 0 + const inserted = Array.isArray(data.inserted) ? data.inserted as Array> : undefined + const start = typeof rawStart === 'number' ? rawStart : Number.NaN + if (inserted === undefined + || !Number.isSafeInteger(start) || start < 0 || start > inbox.length + || !Number.isSafeInteger(removedCount) || removedCount < 0 + || start + removedCount > inbox.length) return false + inbox.splice(start, removedCount, ...inserted) + const ids = new Set() + for (const message of [...nextTurn, ...nextStep]) { + const id = message.id + if (typeof id !== 'string') return false + if (ids.has(id)) return false + ids.add(id) + } + } + return true +} + +/** + * Relational pre-check mirroring the CORE of the session invariant's + * counters and tool pairing: turn numbers run 1, 2, … with no nested open + * turn; steps run 1, 2, … inside the open turn and close before their turn; + * in-turn message and tool/call events name the open turn/step when they + * carry numbers — except a NON-append tool/result, which the host exempts + * from step naming (pruner replacements carry their original step); a + * tool/result must consume a pending call of its step, and a step cannot + * close with calls pending. A trailing open turn or step is legal — the + * caller closes it. This is a core mirror, not the full host contract; + * anything it cannot prove falls back to the full copy. + */ +function turnSequenceValid(seed: readonly SeedEvent[]): boolean { + let nextTurn = 1 + let nextStep = 1 + let openTurn: number | undefined + let openStep: number | undefined + let pendingCalls = new Set() + for (const event of seed) { + const data = dataOf(event) + if (event.type === 'turn/start') { + if (openTurn !== undefined || data.turn !== nextTurn) return false + openTurn = nextTurn + nextTurn += 1 + nextStep = 1 + openStep = undefined + pendingCalls = new Set() + } else if (event.type === 'turn/end') { + if (openTurn === undefined || data.turn !== openTurn || openStep !== undefined) return false + openTurn = undefined + } else if (event.type === 'step/start') { + if (openTurn === undefined || data.turn !== openTurn || openStep !== undefined) return false + if (data.step !== nextStep) return false + openStep = nextStep + nextStep += 1 + pendingCalls = new Set() + } else if (event.type === 'step/end') { + if (openTurn === undefined || openStep === undefined || data.turn !== openTurn || data.step !== openStep) return false + if (pendingCalls.size > 0) return false + openStep = undefined + } else if (event.type === 'tool/call') { + if (typeof data.turn === 'number' && data.turn !== openTurn) return false + if (typeof data.step === 'number' && data.step !== openStep) return false + const callId = data.callId + if (typeof callId === 'string' && callId !== '') pendingCalls.add(callId) + } else if (event.type === 'tool/result') { + const op = (event as { surfaceOp?: unknown }).surfaceOp + if (op !== 'append') { + // The host exempts a replacing tool/result from step naming and + // pairing: it shadows the original call's slot, not a new one. + if (openTurn === undefined) return false + continue + } + if (typeof data.turn === 'number' && data.turn !== openTurn) return false + if (typeof data.step === 'number' && data.step !== openStep) return false + const callId = toolResultCallIdOf(event) + if (callId !== undefined && !pendingCalls.delete(callId)) return false + } else if (isSurfaceEligibleType(event.type)) { + if (typeof data.turn === 'number' && data.turn !== openTurn) return false + if (typeof data.step === 'number' && data.step !== openStep) return false + } + } + return true +} + +/** The callId a tool/result event's message cites, when it carries one. */ +function toolResultCallIdOf(event: SidechatLogEvent): string | undefined { + if (event.type !== 'tool/result') return undefined + const message = dataOf(event).message as { source?: { callId?: unknown } } | undefined + const callId = message?.source?.callId + return typeof callId === 'string' && callId !== '' ? callId : undefined +} + +/** + * The surviving pre-cut head as a state-machine-complete event list: the + * head nodes (surface order == log order for surviving appends) wrapped in + * a turn/step skeleton NORMALIZED to turn 1 step 1 — the seed is a fresh + * log, the host's turn/step counters must start there, and the head node's + * original numbers are envelope metadata the rebase is free to rewrite + * (the protected system head can be a mid-session rewrite living in a later + * turn/step). Closers are recovered from the log when the skeleton's own + * closers were dropped with the span. A head wider than one step/turn (or + * numbers that disagree) is not a shape this builder represents and falls + * back to the full copy. + * @param events - the parent's log. + * @param head - seqs of the surviving pre-cut surface nodes before the + * checkpoint's surface slot. + * @returns the head segment's events, or undefined when the shape is not + * representable. + */ +function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number[]): SidechatLogEvent[] | undefined { + if (head.length === 0) return [] + const first = events[head[0] as number] + const last = events[head[head.length - 1] as number] + if (first === undefined || last === undefined) return undefined + let turnStart: SidechatLogEvent | undefined + let stepStart: SidechatLogEvent | undefined + for (let index = head[0]! - 1; index >= 0; index--) { + const event = events[index] + if (event === undefined) break + if (event.type === 'turn/end') break + // The NEAREST step/start below the node is the one that encloses it. + if (event.type === 'step/start' && stepStart === undefined) stepStart = event + if (event.type === 'turn/start') { + turnStart = event + break + } + } + // Rewrite envelope turn/step in place of the originals — only where the + // event already carries numbers (a user/message never does, and its whole + // data object IS the model-visible message, so injecting fields there + // would change the child's context) — keeping the data losslessly + // JSON-serializable (never writing explicit undefined). + const normalized = (event: SidechatLogEvent, over: { turn?: number; step?: number }): SidechatLogEvent => { + const data = { ...dataOf(event) } + if (over.turn !== undefined && typeof data.turn === 'number') data.turn = over.turn + if (over.step !== undefined && typeof data.step === 'number') data.step = over.step + return { ...event, data } as SidechatLogEvent + } + const parts: SidechatLogEvent[] = [] + if (turnStart !== undefined) { + const turn = dataOf(turnStart).turn + if (typeof turn !== 'number') return undefined + const step = stepStart !== undefined ? dataOf(stepStart).step : undefined + if (stepStart !== undefined && typeof step !== 'number') return undefined + // Nodes must all sit in this ONE step/turn (by their ORIGINAL numbers); + // a wider head is not a shape this builder represents. + for (const seq of head) { + const node = events[seq] + if (node === undefined) return undefined + const nodeData = dataOf(node) + if (nodeData.turn !== turn && nodeData.turn !== undefined) return undefined + if (stepStart !== undefined && nodeData.step !== step && nodeData.step !== undefined) return undefined + } + parts.push(normalized(turnStart, { turn: 1 })) + if (stepStart !== undefined) parts.push(normalized(stepStart, { turn: 1, step: 1 })) + for (const seq of head) parts.push(normalized(events[seq]!, { turn: 1, ...(stepStart !== undefined ? { step: 1 } : {}) })) + // Close the skeleton when its closers are dropped with the span: the + // first step/end / turn/end of this step/turn after the last node. + let closedStep = false + for (let index = head[head.length - 1]! + 1; index < events.length; index++) { + const event = events[index] + if (event === undefined) break + if (!closedStep && event.type === 'step/end' && typeof step === 'number' + && dataOf(event).step === step && dataOf(event).turn === turn) { + parts.push(normalized(event, { turn: 1, step: 1 })) + closedStep = true + continue + } + if (event.type === 'turn/end' && dataOf(event).turn === turn) { + parts.push(normalized(event, { turn: 1 })) + break + } + if (event.type === 'turn/start') break + } + return closedStep || step === undefined ? parts : undefined + } + // No enclosing turn: out-of-turn events are legal as-is. + for (const seq of head) { + const node = events[seq] + if (node === undefined) return undefined + parts.push(node) + } + return parts +} + +/** Log index of the turn/start enclosing one seq, the seq itself when the + * node sits between turns (the keep window then starts verbatim at its own + * skeleton root), or the log length when there is no keep window at all. */ +function enclosingTurnStart(events: readonly SidechatLogEvent[], seq: number | undefined): number { + if (seq === undefined) return events.length + for (let index = seq - 1; index >= 0; index--) { + const event = events[index] + if (event === undefined) return seq + if (event.type === 'turn/start') return index + if (event.type === 'turn/end') return seq + } + return seq +} + +/** Whether one event belongs to the compaction group being consumed (its + * log-only start/summary/end records leave with the span they priced). + * Other groups' records stay — they meter history the child keeps. A + * summary without a `compactionId` is malformed; nothing is excluded for + * it and the equivalence check decides. */ +function isCompactionGroupEvent(event: SidechatLogEvent, groupId: unknown): boolean { + if (!event.type.startsWith('compaction/')) return false + if (typeof groupId !== 'string') return false + return dataOf(event).compactionId === groupId +} + +/** Index of the checkpoint user/message of the last summarizing compaction: + * the event right after a `compaction/summary` — that adjacency is the + * shadow-price contract. An orphaned summary (its replacement never + * landed) is skipped in favor of the previous complete one. */ +function lastCheckpointIndex(events: readonly SidechatLogEvent[]): number | undefined { + for (let index = events.length - 1; index >= 0; index--) { + if (events[index]?.type !== 'compaction/summary') continue + if (events[index + 1]?.type === 'user/message') return index + 1 + } + return undefined +} + +/** One `type` + model-visible-content token per visible node, mirroring the + * renderer's projection: a user/message IS its whole data object, every + * other surface event projects `data.message` (its envelope turn/step and + * headerSeq are rewritten by the rebase and never reach the model). */ +function visibleToken(event: SidechatLogEvent | undefined): string { + if (event === undefined) return 'missing' + if (event.type === 'user/message') return `${event.type}:${JSON.stringify(dataOf(event))}` + const message = dataOf(event).message + return `${event.type}:${JSON.stringify(message ?? null)}` +} + +/** Compare the parent's visible nodes with the rebased child's by content. */ +function sameVisibleSequence( + parent: readonly SidechatLogEvent[], + parentNodes: readonly number[], + childNodes: readonly number[], + child: readonly SidechatLogEvent[], +): boolean { + if (parentNodes.length !== childNodes.length) return false + for (let index = 0; index < parentNodes.length; index++) { + if (visibleToken(parent[parentNodes[index] as number]) !== visibleToken(child[childNodes[index] as number])) { + return false + } + } + return true +} + +/** + * Copy one kept event into the rebased sequence: envelope seq references + * are remapped through the rebase map, `data.turn` numbers at or past the + * first kept turn shift down by the gap the dropped span left (the host's + * turn counter must stay contiguous), and a seq reference the map cannot + * serve (it points into the dropped span) degrades the event honestly — a + * replace whose shadowed nodes are gone becomes an append, dropped + * citations vanish — except `developer/message.headerSeq`, whose referent + * cannot be degraded: that aborts the whole tail. + * @param event - the kept event to copy. + * @param seq - the event's position in the rebased sequence. + * @param rebase - old seq → rebased position over the kept set. + * @param turnOffset - turns removed before the keep window (0 = no shift). + * @param firstKeptTurn - the first kept turn number; smaller numbers are + * head-side and never shift. + * @returns the rebased event, or undefined when the tail is not provable. + */ +/** Sentinel: the event is log-only metering whose referenced span did not + * survive the rebase — drop it instead of aborting the whole tail. */ +const DROPPED: unique symbol = Symbol('dropped') + +type RebasedEvent = SeedEvent | undefined | typeof DROPPED + +function rebaseEvent( + event: SidechatLogEvent, + seq: number, + rebase: Map, + turnOffset: number, + firstKeptTurn: number | undefined, +): RebasedEvent { + const source = event as SidechatLogEvent & { ignorable?: true } + const seed: SeedEvent = { type: source.type, seq, time: source.time, data: dataOf(source) } + if (source.ignorable === true) seed.ignorable = true + const sourceData = dataOf(event) + if (turnOffset > 0 && typeof sourceData.turn === 'number' + && firstKeptTurn !== undefined && sourceData.turn >= firstKeptTurn) { + seed.data = { ...seed.data, turn: sourceData.turn - turnOffset } + } + // A settled command cites an earlier non-command event by seq; remap it + // alongside, and drop the done when the cited event did not survive — a + // stale citation is something the host's commands invariant rejects. + if (event.type === 'command/done' && typeof sourceData.sourceEventSeq === 'number') { + const mapped = rebase.get(sourceData.sourceEventSeq) + if (mapped === undefined) return DROPPED + seed.data = { ...seed.data, sourceEventSeq: mapped } + } + // Compaction metering records cite the surface span they priced. When the + // span survived the rebase, remap the citations; when it did not (the + // record predates the consumed compaction and its span lies in the + // dropped region), the record meters nothing that exists in the child — + // drop it rather than shipping stale seq references. + if (event.type === 'compaction/summary' || event.type === 'compaction/prune') { + const range = sourceData.shadowedRange as { start?: unknown; end?: unknown } | undefined + const cited = sourceData.shadowedSeqs + if (range === null || typeof range !== 'object' || !Array.isArray(cited)) return seed + const start = typeof range.start === 'number' ? rebase.get(range.start) : undefined + const end = typeof range.end === 'number' ? rebase.get(range.end) : undefined + const mapped = cited.map(item => typeof item === 'number' ? rebase.get(item) : undefined) + if (start === undefined || end === undefined || mapped.includes(undefined)) return DROPPED + seed.data = { + ...seed.data, + shadowedRange: { start, end }, + shadowedSeqs: mapped as number[], + } + } + const headerSeq = sourceData.headerSeq + if (event.type === 'developer/message' && typeof headerSeq === 'number') { + const mapped = rebase.get(headerSeq) + if (mapped === undefined) return undefined + seed.data = { ...seed.data, headerSeq: mapped } + } + const op = (event as { surfaceOp?: unknown }).surfaceOp + if (op === 'append') { + seed.surfaceOp = 'append' + } else if (op !== null && typeof op === 'object' && 'op' in op && (op as { op: unknown }).op === 'replace') { + const replace = op as { startSeq?: unknown; endSeq?: unknown } + const start = typeof replace.startSeq === 'number' ? rebase.get(replace.startSeq) : undefined + const end = typeof replace.endSeq === 'number' ? rebase.get(replace.endSeq) : undefined + // A range the rebase cannot resolve lost its shadowed nodes with the + // dropped span; appending the replacement is exactly what remains + // visible (the equivalence check still has to confirm it). + seed.surfaceOp = start !== undefined && end !== undefined && start <= end + ? { op: 'replace', startSeq: start, endSeq: end } + : 'append' + } + const cited = (event as { sourceEventSeqs?: unknown }).sourceEventSeqs + if (Array.isArray(cited)) { + const mapped = cited.map(item => typeof item === 'number' ? rebase.get(item) : undefined) + // Citations the rebase cannot serve referenced the dropped span; the + // field is optional and only has to cover a live replace range. + if (!mapped.includes(undefined)) seed.sourceEventSeqs = mapped as number[] + } + return seed +} + /** * Build the side-thread inheritance for one parent log: the full event log * up to the click moment, honestly closed when it ends inside an open turn. + * When the parent has compacted, the log is first rebased onto its last + * summarizing compaction (`compactionTail`) — same model-visible surface, a + * fraction of the durable copy. * @param events - the parent's log (live or persisted). * @param live - the parent's in-flight stream chunks (DSH 0.1.5+ publishes * them outside the log); used only by the snapshot fallback. @@ -285,26 +919,28 @@ export function buildSidechatInheritance( live: readonly AssistantLiveChunk[] = [], ): SidechatInheritance { if (events.length === 0) return { seed: [], snapshot: null } - const boundary = lastTurnBoundary(events) - if (boundary < 0 || events[boundary]?.type === 'turn/end') { + const trimmed = compactionTail(events) + const log = trimmed ?? events + const boundary = lastTurnBoundary(log) + if (boundary < 0 || log[boundary]?.type === 'turn/end') { // Ends outside any turn (or has no turns at all): the whole log is a // valid, balanced seed — possibly ending with a pending user message. - return { seed: copyEvents(events), snapshot: null } + return { seed: copyEvents(log), snapshot: null } } // Ends inside the open turn starting at `boundary`. - if (hasDanglingToolCall(events, boundary)) { + if (hasDanglingToolCall(log, boundary)) { // Cannot close honestly: cut before the open turn; the caller attaches // the structured snapshot to the boundary prompt instead. return { - seed: copyEvents(events.slice(0, boundary)), - snapshot: buildOpenTurnSnapshot(events, live), + seed: copyEvents(log.slice(0, boundary)), + snapshot: buildOpenTurnSnapshot(log, live), } } - const seed = copyEvents(events) - const last = events[events.length - 1] - const turn = numberAt(dataOf(events[boundary]!), 'turn') + const seed = copyEvents(log) + const last = log[log.length - 1] + const turn = numberAt(dataOf(log[boundary]!), 'turn') const now = last?.time ?? 0 - const openStep = openStepInTurn(events, boundary) + const openStep = openStepInTurn(log, boundary) if (openStep !== undefined) { seed.push({ type: 'step/end', seq: seed.length, time: now, data: { turn, step: openStep } }) } diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts new file mode 100644 index 00000000..3e1fa8b5 --- /dev/null +++ b/tests/sidechat-compaction-seed.spec.ts @@ -0,0 +1,793 @@ +/** + * Compaction-tail seed spec: {@link buildSidechatInheritance} must reuse the + * parent's last summarizing compaction instead of copying its whole log. + * + * Why this is sound: the compaction checkpoint `user/message` REPLACES the + * shadowed span on the model-visible surface, so a child seeded with + * [surviving head skeleton + checkpoint + keep-window + tail verbatim] + * folds to the SAME surface as the parent — identical model-visible + * conversation, same provider context-cache prefix — while the shadowed + * bulk never lands in the durable copy. The construction is verified with + * the REAL fold (`foldSurface` from `@deepseek-ai/dsh-session/surface`) and + * pinned against the REAL session relational invariants + * (`@deepseek-ai/dsh-session/invariant`): when the tail cannot be proven + * equivalent, the builder falls back to today's verbatim full copy. + */ +import { describe, expect, it } from 'vitest' +import { deriveEventMessage, foldSurface } from '@deepseek-ai/dsh-session/surface' +import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' +import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +import { buildSidechatInheritance } from '../src/sidechat-core.ts' +import type { SidebarSessionEvent } from '../src/context-types.ts' + +/** Log-only event (no surface marker; folds to nothing visible). */ +function lo(type: string, seq: number, data: Record = {}): SidebarSessionEvent { + return { type, seq, time: seq * 1000, data } as SidebarSessionEvent +} + +/** Surface-eligible event appended the way the live pipeline appends it. */ +function sf(type: string, seq: number, data: Record): SidebarSessionEvent { + return { type, seq, time: seq * 1000, data, surfaceOp: 'append' } as SidebarSessionEvent +} + +function userMessage(id: string, text: string): Record { + return { id, role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } } +} + +function assistantMessage(text: string, over: { callId?: string } = {}): Record { + const content: Array> = [{ type: 'text', text }] + if (over.callId !== undefined) { + content.unshift({ type: 'tool-call', callId: over.callId, name: 'bash', arguments: {} }) + } + return { + id: `m-${text}`, + role: 'assistant', + content, + source: { kind: 'model', provider: 'test', model: 'model-x' }, + } +} + +function toolResultMessage(callId: string, text: string): Record { + return { + id: `m-${callId}`, + role: 'tool', + source: { kind: 'tool', callId }, + toolCallId: callId, + content: [{ type: 'text', text }], + isError: false, + } +} + +/** One completed turn with an optional tool pair; returns its events plus + * the seqs of its surface-visible nodes (user, result, assistant). */ +function turn( + seq: number, + turnNumber: number, + over: { text?: string; callId?: string; result?: string; assistantCall?: string } = {}, +): { events: SidebarSessionEvent[]; nodes: number[] } { + const text = over.text ?? `q${turnNumber}` + const events: SidebarSessionEvent[] = [ + lo('turn/start', seq, { turn: turnNumber }), + lo('step/start', seq + 1, { turn: turnNumber, step: 1 }), + ] + const nodes: number[] = [seq + 2] + events.push(sf('user/message', seq + 2, userMessage(`m-q${turnNumber}`, text))) + let next = seq + 3 + if (over.callId !== undefined) { + events.push(lo('tool/call', next, { turn: turnNumber, step: 1, callId: over.callId, name: 'bash', arguments: '{}' })) + events.push(sf('tool/result', next + 1, { turn: turnNumber, step: 1, message: toolResultMessage(over.callId, over.result ?? 'ok') })) + nodes.push(next + 1) + next += 2 + } + events.push(sf('assistant/message', next, { + turn: turnNumber, + step: 1, + message: assistantMessage(`a${turnNumber}`, over.assistantCall !== undefined ? { callId: over.assistantCall } : {}), + stream: [], + })) + nodes.push(next) + events.push(lo('step/end', next + 1, { turn: turnNumber, step: 1 })) + events.push(lo('turn/end', next + 2, { turn: turnNumber, reason: { kind: 'completed' } })) + return { events, nodes } +} + +/** The compaction group appended at `at`: start + summary + checkpoint + + * end, shadowing `shadowed` (the span's surface-node seqs). `turn: null` + * is the manual between-turns form; a number is the automatic mid-turn + * form, and the checkpoint adjacency is the shadow-price contract. */ +function compactionGroup( + at: number, + shadowed: readonly number[], + over: { id?: string; turn?: number | null; summary?: string } = {}, +): SidebarSessionEvent[] { + const id = over.id ?? 'cp1' + const first = shadowed[0] ?? 0 + const last = shadowed[shadowed.length - 1] ?? 0 + const summaryText = over.summary ?? 'old turns summarized' + const turnValue = over.turn === undefined ? null : over.turn + return [ + lo('compaction/start', at, { compactionId: id, turn: turnValue }), + lo('compaction/summary', at + 1, { + compactionId: id, + summary: [{ type: 'text', text: summaryText }], + shadowedRange: { start: first, end: last }, + shadowedSeqs: [...shadowed], + shadowedTokenCount: 100, + provider: 'deepseek', + model: 'test-model', + rawOutput: [], + llmStreamCall: true, + }), + { + type: 'user/message', + seq: at + 2, + time: (at + 2) * 1000, + data: { + id: `m-${id}`, + role: 'user', + content: [{ type: 'text', text: summaryText }], + source: { kind: 'compact-checkpoint', compactionId: id }, + }, + surfaceOp: { op: 'replace', startSeq: first, endSeq: last }, + sourceEventSeqs: [...shadowed], + } as SidebarSessionEvent, + lo('compaction/end', at + 3, { compactionId: id, turn: turnValue }), + ] +} + +/** + * Turn 1's opening, host-shaped: the protected `system/message` (carrying + * its turn/step) is the first request's first message, and the shadowable + * old span continues in the SAME step — `oldTurn` supplies the rest. + */ +function systemHead(): SidebarSessionEvent[] { + return [ + lo('turn/start', 0, { turn: 1 }), + lo('step/start', 1, { turn: 1, step: 1 }), + sf('system/message', 2, { + turn: 1, + step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } }, + }), + ] +} + +/** The old span continuing turn 1's step: a tool pair + assistant, closed. */ +function oldSpan(): { events: SidebarSessionEvent[]; nodes: number[] } { + const events: SidebarSessionEvent[] = [ + sf('user/message', 3, userMessage('m-q1', 'q1')), + lo('tool/call', 4, { turn: 1, step: 1, callId: 'c-old', name: 'bash', arguments: '{}' }), + sf('tool/result', 5, { turn: 1, step: 1, message: toolResultMessage('c-old', 'old result') }), + sf('assistant/message', 6, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 7, { turn: 1, step: 1 }), + lo('turn/end', 8, { turn: 1, reason: { kind: 'completed' } }), + ] + return { events, nodes: [3, 5, 6] } +} + +/** + * The canonical compacted parent, host-shaped: turn 1 carries the protected + * system head, turn 2 is the shadowed old span (with a tool pair), turn 3 + * is the keep window with its own tool pair, then the manual compaction + * group, then one closed tail turn. + */ +function compactedLog(): SidebarSessionEvent[] { + const events = [...systemHead(), ...oldSpan().events] + // A whole shadowed turn between the head and the keep window: the seed's + // turn numbers must be renumbered to run 1, 2, 3… over the gap. + const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) + events.push(...shadowTurn.events) + // The keep window is appended BEFORE the compaction group (the group + // lands at the log's end at compaction time); the tail follows it. + const keep = turn(17, 3, { callId: 'c-keep', result: 'keep result' }) + events.push(...keep.events) + // The region shadows the old span's and the middle turn's nodes but NOT + // the protected head. + events.push(...compactionGroup(events.length, [3, 5, 6, 11, 13, 14])) + events.push(...turn(events.length, 4, { callId: 'c-tail', result: 'tail result' }).events) + return events +} + +/** + * The mid-span shape: the region ends INSIDE the keep window's first turn + * (the host's boundary is only tool-pairing balanced, not turn aligned), so + * that turn's early nodes are shadowed while its later ones survive — the + * keep interval must skip the shadowed surface events and the orphaned + * tool/call instead of re-emitting them. + */ +function midSpanLog(): SidebarSessionEvent[] { + const events = [...systemHead(), ...oldSpan().events] + // Turn 2's first step is shadowed (user + tool pair); its second step's + // assistant survives — the region ends inside the keep window's first + // turn, which precedes the compaction group like every keep window does. + events.push( + lo('turn/start', 9, { turn: 2 }), + lo('step/start', 10, { turn: 2, step: 1 }), + sf('user/message', 11, userMessage('m-q2', 'q2 mid')), + lo('tool/call', 12, { turn: 2, step: 1, callId: 'c-mid', name: 'bash', arguments: '{}' }), + sf('tool/result', 13, { turn: 2, step: 1, message: toolResultMessage('c-mid', 'mid result') }), + lo('step/end', 14, { turn: 2, step: 1 }), + lo('step/start', 15, { turn: 2, step: 2 }), + sf('assistant/message', 16, { turn: 2, step: 2, message: assistantMessage('a2 kept'), stream: [] }), + lo('step/end', 17, { turn: 2, step: 2 }), + lo('turn/end', 18, { turn: 2, reason: { kind: 'completed' } }), + ) + events.push(...compactionGroup(19, [3, 5, 6, 11, 13])) + events.push(...turn(23, 3, { callId: 'c-tail', result: 'tail result' }).events) + return events +} + +/** + * The automatic-compaction shape: the group fires INSIDE a still-open turn + * (that turn's skeleton and first message sit BEFORE the cut), and the log + * ends inside that turn — `kind` picks how: a plain pending assistant + * message (synthetic closers) or a dangling tool call (structured + * snapshot). + */ +function midTurnLog(kind: 'closers' | 'dangling'): SidebarSessionEvent[] { + const events = [...systemHead(), ...oldSpan().events] + const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) + events.push(...shadowTurn.events) + const seq = events.length + events.push( + lo('turn/start', seq, { turn: 3 }), + lo('step/start', seq + 1, { turn: 3, step: 1 }), + sf('user/message', seq + 2, userMessage('m-q3', 'q3')), + ) + events.push(...compactionGroup(seq + 3, [3, 5, 6, 11, 13, 14], { id: 'cp-auto', turn: 3, summary: 'auto summarized' })) + const tail = events.length + if (kind === 'closers') { + events.push(sf('assistant/message', tail, { turn: 3, step: 1, message: assistantMessage('open answer'), stream: [] })) + } else { + events.push( + sf('assistant/message', tail, { turn: 3, step: 1, message: assistantMessage('with tool', { callId: 'c-open' }), stream: [] }), + lo('tool/call', tail + 1, { turn: 3, step: 1, callId: 'c-open', name: 'bash', arguments: '{}' }), + ) + } + return events +} + +/** The model-visible sequence a fold produces, using the HOST's own + * `deriveEventMessage` projection as the oracle so the spec cannot share a + * projection bug with the implementation under test. */ +function visibleSequence(events: readonly SidebarSessionEvent[]): string[] { + const fold = foldSurface(events as unknown as readonly SessionEvent[]) + return fold.nodes.map(seq => { + const event = events[seq] + if (event === undefined) return `missing:${seq}` + return `${event.type}:${JSON.stringify(deriveEventMessage(event as unknown as SessionEvent))}` + }) +} + +function expectContiguous(seed: readonly { seq: number }[]): void { + seed.forEach((event, index) => expect(event.seq).toBe(index)) +} + +/** Run the REAL session relational invariants over one candidate log and + * return the failure messages (empty = the log satisfies them). */ +function invariantFailures(log: readonly SidebarSessionEvent[]): string[] { + const failures: string[] = [] + const session = { snapshotEvents: () => log } + const ctx = { + sessions: { list: () => [session] }, + on: () => {}, + invariants: { + register: (_pkg: string, installer: (c: unknown, f: (m: string) => void) => void) => { + installer(ctx, (message: string) => { failures.push(message) }) + return () => {} + }, + }, + } + void SessionInvariant.apply(ctx as never) + return failures +} + +describe('buildSidechatInheritance compaction tail', () => { + it('reuses the last summarizing compaction instead of copying the shadowed span', () => { + const events = compactedLog() + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + // The shadowed old turn is dropped entirely — its visible nodes AND its + // log-only scaffolding and tool/call — while the protected head keeps + // its turn/step skeleton (closed, because the closers were dropped too). + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('c-old'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('shadow result'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('c-shadow'))).toBe(false) + expect(seed.map(event => event.type).slice(0, 5)).toEqual([ + 'turn/start', 'step/start', 'system/message', 'step/end', 'turn/end', + ]) + // The keep window survives VERBATIM: its own tool call stays right + // before its result. + const keepCall = seed.findIndex(event => JSON.stringify(event).includes('c-keep')) + const keepResult = seed.findIndex(event => JSON.stringify(event).includes('keep result')) + expect(keepCall).toBeGreaterThanOrEqual(0) + expect(keepResult).toBeGreaterThan(keepCall) + // The checkpoint survives as a plain append (its replace targets are gone). + const cp = seed.find(event => JSON.stringify(event).includes('old turns summarized')) + expect(cp).toBeDefined() + expect((cp as { surfaceOp?: unknown }).surfaceOp).toBe('append') + expect((cp as { sourceEventSeqs?: unknown }).sourceEventSeqs).toBeUndefined() + expectContiguous(seed) + }) + + it('folds to the same model-visible sequence as the parent (surface equivalence)', () => { + const events = compactedLog() + const parent = visibleSequence(events) + expect(parent.length).toBeGreaterThan(0) + const { seed } = buildSidechatInheritance(events) + const child = visibleSequence(seed) + expect(child).toEqual(parent) + }) + + it('satisfies the real session relational invariants', () => { + const events = compactedLog() + const { seed } = buildSidechatInheritance(events) + expect(seed.length).toBeLessThan(events.length) + expect(invariantFailures(events)).toEqual([]) + expect(invariantFailures(seed)).toEqual([]) + expect(invariantFailures(buildSidechatInheritance(turn(0, 1, { callId: 'c1' }).events).seed)).toEqual([]) + }) + + it('is accepted by the real dsh-session seed validator', () => { + const events = compactedLog() + const { seed } = buildSidechatInheritance(events) + // The REAL validator, exactly as the routes call it (isSeeded + the + // inherited cut) — this is the layer that once rejected a seed whose + // surfaceOp markers were stripped, so it gates every envelope decision + // the rebasing makes. + const id = 'session-compaction-seed-acceptance' + const session = Session.create( + id as SessionId, + seed as never, + { version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true }, + SessionLogOffset(seed.length), + ) + // The constructor appends the inherited-cut marker right after the seed, + // and that marker is the child's first own event (log position = the + // inherited count) — same shape as today's full-copy threads. + expect(session.snapshotEvents()).toHaveLength(seed.length + 1) + expect(session.ownEvents()).toHaveLength(1) + expect(session.ownEvents()[0]?.type).toBe('session/end-seed') + }) + + it('falls back to the verbatim full copy when the log has no compaction', () => { + const events = turn(0, 1, { callId: 'c1' }).events + const { seed } = buildSidechatInheritance(events) + expectContiguous(seed) + expect(seed.map(event => event.type)).toEqual(events.map(event => event.type)) + }) + + it('falls back to the verbatim full copy when a tail event references the dropped span', () => { + const events = compactedLog() + // A developer/message citing a pre-cut request/header: the reference + // cannot be renumbered, so the tail is not provably equivalent. The + // fallback must equal TODAY's behavior on this very log: the verbatim + // copy, event for event. + const withDangling = [...events, sf('developer/message', events.length, { + id: 'm-dev', + role: 'developer', + content: [{ type: 'text', text: 'dev' }], + source: { kind: 'developer' }, + headerSeq: 1, + })] + const { seed, snapshot } = buildSidechatInheritance(withDangling) + expect(snapshot).toBeNull() + // Event-for-event deep equality with the verbatim copy (envelope fields + // plus the shared data objects), not just a type sequence. + expect(seed.map(event => [event.type, event.seq, event.time, event.data])).toEqual( + withDangling.map(event => [event.type, event.seq, event.time, event.data]), + ) + }) + + it('falls back to the verbatim full copy when a tail replace reorders surviving nodes', () => { + const events = compactedLog() + // A replacement whose range covers a SURVIVING pre-cut node: the parent + // fold removes that node and repositions the replacement at its slot, + // which dropping the span cannot reproduce. + const keepUserSeq = events.findIndex(event => JSON.stringify(event).includes('m-q2')) + const replacementSeq = events.length + events.push({ + type: 'user/message', + seq: replacementSeq, + time: replacementSeq * 1000, + data: userMessage('m-resurfaced', 'resurfaced edit'), + surfaceOp: { op: 'replace', startSeq: keepUserSeq, endSeq: keepUserSeq }, + sourceEventSeqs: [keepUserSeq], + } as SidebarSessionEvent) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.map(event => [event.type, event.seq, event.time, event.data])).toEqual( + events.map(event => [event.type, event.seq, event.time, event.data]), + ) + }) + + it('keeps the open-turn closers on the trimmed tail (mid-turn compaction)', () => { + const events = midTurnLog('closers') + // Automatic compaction ran inside the still-open turn; the fork happens + // mid-turn with a plain pending assistant message. The trim must fire + // AND the synthetic interrupted-closers must land — the open turn's + // skeleton is kept verbatim, so the open-turn detection still sees it. + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + expectContiguous(seed) + expect(seed.at(-2)?.type).toBe('step/end') + expect(seed.at(-1)?.type).toBe('turn/end') + expect((seed.at(-1) as { data?: { reason?: { kind?: string } } }).data?.reason?.kind).toBe('interrupted') + expect(invariantFailures(seed)).toEqual([]) + }) + + it('delivers the dangling-tool snapshot on the trimmed tail (mid-turn compaction)', () => { + const events = midTurnLog('dangling') + // Same shape but the open turn ends on a tool call with no result yet: + // providers reject dangling assistant calls, so the builder must cut + // before the open turn and deliver the structured snapshot — exactly as + // the full-copy path does. + const { seed, snapshot } = buildSidechatInheritance(events) + expect(seed.length).toBeLessThan(events.length) + expectContiguous(seed) + expect(seed.at(-1)?.type).not.toBe('tool/call') + expect(snapshot).not.toBeNull() + expect(JSON.stringify(snapshot)).toContain('bash') + }) + + it('skips shadowed nodes and orphaned calls when the region ends mid-turn', () => { + const events = midSpanLog() + const { seed, snapshot } = buildSidechatInheritance(events) + // The region ended inside turn 2: its early user+tool pair are shadowed, + // the later assistant survives. The trim must fire, the keep interval + // must NOT re-emit the shadowed events (nor the orphaned tool/call), + // and the skeleton of the partially-shadowed turn stays complete. + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => JSON.stringify(event).includes('q2 mid'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('c-mid'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('mid result'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('a2 kept'))).toBe(true) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expectContiguous(seed) + expect(invariantFailures(seed)).toEqual([]) + }) + + it('remaps replace operations that stay inside the tail', () => { + const events = compactedLog() + // One more closed tail turn, then a replacement user/message whose + // replace range covers ONLY that turn's tail nodes: the range rebases + // intact, the fold still shows the same transitions, the trim fires. + const tailTurn = turn(events.length, 5) + const replacedSeqs = tailTurn.nodes + events.push(...tailTurn.events) + const replacementSeq = events.length + events.push({ + type: 'user/message', + seq: replacementSeq, + time: replacementSeq * 1000, + data: userMessage('m-edited', 'edited tail question'), + surfaceOp: { op: 'replace', startSeq: replacedSeqs[0] ?? 0, endSeq: replacedSeqs[replacedSeqs.length - 1] ?? 0 }, + sourceEventSeqs: replacedSeqs, + } as SidebarSessionEvent) + const parent = visibleSequence(events) + const { seed } = buildSidechatInheritance(events) + // The trim must still fire here (the replace reorders only tail nodes — + // no fallback), which is what makes the remap assertions meaningful. + expect(seed.length).toBeLessThan(events.length) + expect(visibleSequence(seed)).toEqual(parent) + const rebased = seed.find(event => { + const op = (event as { surfaceOp?: unknown }).surfaceOp + return typeof op === 'object' && op !== null && (op as { op?: unknown }).op === 'replace' + }) as { surfaceOp?: { startSeq: number; endSeq: number }; seq?: number } | undefined + // Not degraded: the range survived as a REMAPPED replace bound to the + // rebased positions (not to the parent's dropped-span seq space). + expect(rebased).toBeDefined() + expect(rebased?.surfaceOp?.startSeq).toBeLessThan(rebased?.seq ?? 0) + expect(rebased?.surfaceOp?.endSeq).toBeLessThan(rebased?.seq ?? 0) + }) + + it('trims when the protected head was rewritten mid-session (turn 1, later step)', () => { + // Host shape: SystemPromptProjection.replace rewrites surface node 0 in + // a LATER step of turn 1 — the surviving head node carries turn 1 / step + // >= 2. The skeleton normalizes to turn 1 step 1 (envelope numbers only; + // a user/message never gains fields) and the trim still fires. + const events = [ + lo('turn/start', 0, { turn: 1 }), + lo('step/start', 1, { turn: 1, step: 1 }), + sf('system/message', 2, { + turn: 1, step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'original prompt' }], source: { kind: 'system-prompt' } }, + }), + sf('user/message', 3, userMessage('m-q1', 'q1')), + sf('assistant/message', 4, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 5, { turn: 1, step: 1 }), + lo('step/start', 6, { turn: 1, step: 2 }), + { + ...sf('system/message', 7, { + turn: 1, step: 2, + message: { id: 'm-sys2', role: 'system', content: [{ type: 'text', text: 'rewritten prompt' }], source: { kind: 'system-prompt' } }, + }), + surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 }, + sourceEventSeqs: [2], + } as SidebarSessionEvent, + lo('step/end', 8, { turn: 1, step: 2 }), + lo('turn/end', 9, { turn: 1, reason: { kind: 'completed' } }), + ] + const keep = turn(10, 2, { callId: 'c-keep', result: 'keep result' }) + events.push(...keep.events) + events.push(...compactionGroup(events.length, [3, 4])) + events.push(...turn(events.length, 3, { callId: 'c-tail', result: 'tail result' }).events) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // The surviving head is the REWRITTEN prompt, skeleton-normalized to + // turn 1 step 1; the original shadowed prompt is gone. + expect(seed.some(event => JSON.stringify(event).includes('rewritten prompt'))).toBe(true) + expect(seed.some(event => JSON.stringify(event).includes('original prompt'))).toBe(false) + const head = seed.find(event => event.type === 'system/message') as { data?: { turn?: number; step?: number } } + expect(head?.data?.turn).toBe(1) + expect(head?.data?.step).toBe(1) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + }) + + it('trims when the pruner rewrote a keep-window tool result mid-turn', () => { + // Host shape: the tool-result-pruner appends a tool/result REPLACEMENT + // between steps, carrying the ORIGINAL turn/step and a replace op over + // its target. The target is not on the final surface, but it is the + // replacement's fold target — it must be emitted so the transition + // replays, and the record's citations must rebase. + const events = [...systemHead(), ...oldSpan().events] + // Turn 2 has two steps; the pruner runs at the pre-step boundary between + // them (turn still open) and rewrites step 1's over-budget result. + events.push( + lo('turn/start', 9, { turn: 2 }), + lo('step/start', 10, { turn: 2, step: 1 }), + sf('user/message', 11, userMessage('m-q2', 'q2')), + lo('tool/call', 12, { turn: 2, step: 1, callId: 'c-keep', name: 'bash', arguments: '{}' }), + sf('tool/result', 13, { turn: 2, step: 1, message: toolResultMessage('c-keep', 'keep result') }), + lo('step/end', 14, { turn: 2, step: 1 }), + lo('compaction/prune', 15, { + shadowedRange: { start: 13, end: 13 }, + shadowedSeqs: [13], + shadowedTokenCount: 40, + }), + { + ...sf('tool/result', 16, { turn: 2, step: 1, message: toolResultMessage('c-keep', 'pruned stub') }), + surfaceOp: { op: 'replace', startSeq: 13, endSeq: 13 }, + sourceEventSeqs: [13], + } as SidebarSessionEvent, + lo('step/start', 17, { turn: 2, step: 2 }), + sf('assistant/message', 18, { turn: 2, step: 2, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 19, { turn: 2, step: 2 }), + lo('turn/end', 20, { turn: 2, reason: { kind: 'completed' } }), + ) + events.push(...compactionGroup(events.length, [3, 5, 6])) + events.push(...turn(events.length, 3, { callId: 'c-tail', result: 'tail result' }).events) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // Both the original result (fold target) and its replacement survive, + // the replacement keeps its replace op REMAPPED, and the prune record's + // citations rebase to the seed's seq space. + expect(seed.some(event => JSON.stringify(event).includes('keep result'))).toBe(true) + expect(seed.some(event => JSON.stringify(event).includes('pruned stub'))).toBe(true) + const replacement = seed.find(event => JSON.stringify(event).includes('pruned stub')) as { surfaceOp?: { op?: string; startSeq?: number }; seq?: number } + expect(replacement?.surfaceOp?.op).toBe('replace') + expect(replacement?.surfaceOp?.startSeq).toBeLessThan(replacement?.seq ?? 0) + const record = seed.find(event => event.type === 'compaction/prune') as { data?: { shadowedSeqs?: number[] } } + expect(record?.data?.shadowedSeqs?.[0]).toBe(replacement?.surfaceOp?.startSeq) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + }) + + it('trims when the keep window opens on a turn whose inbox insert precedes its turn/start', () => { + // Real loop order: [insert q][turn/start][claim q][step/start][user]. + // The keep window must swallow the insert ahead of the turn/start so + // the positional inbox fold replays; without it the claim dangles and + // the host's durable-inbox projection rejects the seed during thread + // creation (caught on the real deployment's main session during e2e; + // Session.create itself does not validate this face). + const events = [...systemHead(), ...oldSpan().events] + const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) + events.push(...shadowTurn.events) + const at = events.length + events.push( + lo('agent/inbox/spliced', at, { target: 'next-turn', start: 0, removedCount: 0, inserted: [userMessage('m-q3', 'q3')] }), + lo('turn/start', at + 1, { turn: 3 }), + lo('agent/inbox/spliced', at + 2, { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }), + lo('step/start', at + 3, { turn: 3, step: 1 }), + sf('user/message', at + 4, userMessage('m-q3', 'q3')), + sf('assistant/message', at + 5, { turn: 3, step: 1, message: assistantMessage('a3'), stream: [] }), + lo('step/end', at + 6, { turn: 3, step: 1 }), + lo('turn/end', at + 7, { turn: 3, reason: { kind: 'completed' } }), + ) + events.push(...compactionGroup(events.length, [3, 5, 6, 11, 13, 14])) + events.push(...turn(events.length, 4, { callId: 'c-tail', result: 'tail result' }).events) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // The insert rode along ahead of the keep window's turn/start, so the + // claim finds its message and the inbox fold replays. + const splices = seed.filter(event => event.type === 'agent/inbox/spliced') + expect(splices.length).toBeGreaterThanOrEqual(2) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + // The real validator accepts (this is the layer that rejected the + // pre-fix seed on the real session). + const id = 'session-inbox-splice-acceptance' + Session.create( + id as SessionId, + seed as never, + { version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true }, + SessionLogOffset(seed.length), + ) + }) + + it('drops a mid-keep compaction group atomically when its citations fall in the dropped span', () => { + // Same-turn double compaction: cp0 completes mid-turn, cp1 (the consumed + // one) swallows cp0's checkpoint; cp0's records ride in the keep window + // but its citations name the dropped span. Record-level dropping would + // strand a successful compaction/end (the host's compaction invariant + // companion rejects it) — the group drops ATOMICALLY and the trim still + // fires, which is what real multi-compaction parents need (every + // mid-keep group cites nodes a later group re-shadowed). + const events = [ + lo('turn/start', 0, { turn: 1 }), + lo('step/start', 1, { turn: 1, step: 1 }), + sf('system/message', 2, { + turn: 1, step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } }, + }), + sf('user/message', 3, userMessage('m-q1', 'q1')), + sf('assistant/message', 4, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 5, { turn: 1, step: 1 }), + lo('turn/end', 6, { turn: 1, reason: { kind: 'completed' } }), + lo('turn/start', 7, { turn: 2 }), + lo('step/start', 8, { turn: 2, step: 1 }), + sf('user/message', 9, userMessage('m-q2', 'q2')), + sf('assistant/message', 10, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 11, { turn: 2, step: 1 }), + lo('compaction/start', 12, { compactionId: 'cp0', turn: 2 }), + lo('compaction/summary', 13, { + compactionId: 'cp0', + summary: [{ type: 'text', text: 'summary cp0' }], + shadowedRange: { start: 3, end: 4 }, + shadowedSeqs: [3, 4], + shadowedTokenCount: 10, + provider: 'deepseek', + model: 'model-x', + rawOutput: [], + llmStreamCall: true, + }), + { + ...sf('user/message', 14, { id: 'm-cp0', role: 'user', content: [{ type: 'text', text: 'summary cp0' }], source: { kind: 'compact-checkpoint', compactionId: 'cp0' } }), + surfaceOp: { op: 'replace', startSeq: 3, endSeq: 4 }, + sourceEventSeqs: [3, 4], + } as SidebarSessionEvent, + lo('compaction/end', 15, { compactionId: 'cp0', turn: 2 }), + lo('step/start', 16, { turn: 2, step: 2 }), + sf('assistant/message', 17, { turn: 2, step: 2, message: assistantMessage('a2b'), stream: [] }), + lo('step/end', 18, { turn: 2, step: 2 }), + lo('turn/end', 19, { turn: 2, reason: { kind: 'completed' } }), + ...turn(20, 3, { callId: 'c-tail', result: 'tail result' }).events, + ] + // The consumed compaction swallows the surface span as it exists at ITS + // fold moment: cp0's checkpoint (which replaced turn 1's nodes) plus + // turn 2 step 1's messages. + events.push(...compactionGroup(events.length, [14, 9, 10])) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // cp0's whole bracket is gone — no lone end without its summary. + expect(seed.some(event => JSON.stringify(event).includes('cp0'))).toBe(false) + expect(seed.some(event => event.type === 'compaction/end' && (event.data as { compactionId?: string }).compactionId === 'cp1')).toBe(false) + const seedGroups = seed.filter(event => event.type === 'compaction/start' || event.type === 'compaction/summary' || event.type === 'compaction/end') + expect(seedGroups).toEqual([]) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + // Control: the same log without the consumed group (its four trailing + // events) cuts at cp0 instead and also trims. + const control = events.slice(0, -4) + const controlSeed = buildSidechatInheritance(control).seed + expect(controlSeed.length).toBeLessThan(control.length) + }) + + it('drops a command/done atomically when its run falls in the dropped span', () => { + // A slash command runs before turn 1 and settles inside turn 2; the + // consumed compaction shadows turn 1's surface, so the keep window + // keeps the done without its run — the bracket gate falls back instead + // of shipping a seed the host's commands invariant rejects. When both + // records ride the keep window, the done's sourceEventSeq remaps onto + // the rebased run. + const base = [ + lo('command/run', 0, { commandId: 'cmd1', name: 'compact', source: { kind: 'user' } }), + lo('turn/start', 1, { turn: 1 }), + lo('step/start', 2, { turn: 1, step: 1 }), + sf('system/message', 3, { + turn: 1, step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } }, + }), + sf('user/message', 4, userMessage('m-q1', 'q1')), + sf('assistant/message', 5, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 6, { turn: 1, step: 1 }), + lo('turn/end', 7, { turn: 1, reason: { kind: 'completed' } }), + ] + const events = [ + ...base, + lo('turn/start', 8, { turn: 2 }), + lo('command/done', 9, { commandId: 'cmd1', kind: 'success', text: 'ok', sourceEventSeq: 4 }), + lo('step/start', 10, { turn: 2, step: 1 }), + sf('user/message', 11, userMessage('m-q2', 'q2')), + sf('assistant/message', 12, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 13, { turn: 2, step: 1 }), + lo('turn/end', 14, { turn: 2, reason: { kind: 'completed' } }), + ...turn(15, 3, { callId: 'c-tail', result: 'tail result' }).events, + ] + events.push(...compactionGroup(events.length, [4, 5])) + const { seed } = buildSidechatInheritance(events) + // The done drops ATOMICALLY with its dropped run — no lone done the + // host's commands invariant rejects, and the trim still fires. + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => event.type === 'command/done')).toBe(false) + expect(seed.some(event => event.type === 'command/run')).toBe(false) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + + // Together: a command that runs INSIDE the keep window and settles + // there — both records ride, and the done's citation remaps onto the + // rebased event it names. The host contract: sourceEventSeq cites an + // earlier NON-command event, and commandIds are unique per run. + const together = [ + ...base, + lo('turn/start', 8, { turn: 2 }), + lo('step/start', 9, { turn: 2, step: 1 }), + sf('user/message', 10, userMessage('m-q2', 'q2')), + lo('command/run', 11, { commandId: 'cmd2', name: 'compact', source: { kind: 'user' } }), + lo('command/done', 12, { commandId: 'cmd2', kind: 'success', text: 'ok', sourceEventSeq: 10 }), + sf('assistant/message', 13, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 14, { turn: 2, step: 1 }), + lo('turn/end', 15, { turn: 2, reason: { kind: 'completed' } }), + ...turn(16, 3, { callId: 'c-tail', result: 'tail result' }).events, + ] + together.push(...compactionGroup(together.length, [4, 5])) + const trimmed = buildSidechatInheritance(together) + expect(trimmed.seed.length).toBeLessThan(together.length) + const done = trimmed.seed.find(event => event.type === 'command/done') as { data?: { sourceEventSeq?: number } } + const citedIdx = trimmed.seed.findIndex((event, index) => index === (done?.data?.sourceEventSeq ?? -1)) + expect(citedIdx).toBeGreaterThanOrEqual(0) + // The citation names a non-command event (the user message), not the run. + expect(trimmed.seed[citedIdx]?.type).toBe('user/message') + expect(visibleSequence(trimmed.seed)).toEqual(visibleSequence(together)) + expect(invariantFailures(trimmed.seed)).toEqual([]) + }) + + it('reuses the previous compaction when the newest summary is orphaned', () => { + const events = compactedLog() + const at = events.length + // A second compaction whose replacement never landed (summary + error + // end, no checkpoint): the builder must fall back to the EARLIER + // complete compaction instead of the full copy. + events.push( + lo('compaction/start', at, { compactionId: 'cp-dead', turn: null }), + lo('compaction/summary', at + 1, { + compactionId: 'cp-dead', + summary: [{ type: 'text', text: 'never landed' }], + shadowedRange: { start: 3, end: 3 }, + shadowedSeqs: [3], + shadowedTokenCount: 10, + provider: 'deepseek', + model: 'test-model', + rawOutput: [], + llmStreamCall: true, + }), + lo('compaction/end', at + 2, { compactionId: 'cp-dead', turn: null, error: 'summarizer failed' }), + ) + const { seed } = buildSidechatInheritance(events) + // The trim fired through the EARLIER compaction: the old span is gone + // while the orphaned group's log-only records may ride along (the fold + // never sees them, and they keep the parent's metering history honest). + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(false) + }) +})