diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 0c438e3a..9a247486 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -335,7 +335,13 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] } const headEvents = headSkeleton(events, head) if (headEvents === undefined) return undefined - const keepStart = enclosingTurnStart(events, keepFirst) + 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 @@ -435,9 +441,44 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] return undefined } if (!turnSequenceValid(seed)) return undefined + if (!inboxSplicesValid(seed)) return undefined return seed } +/** + * 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) + const inbox = data.target === 'next-step' ? nextStep : nextTurn + const rawStart = data.start + const rawRemoved = data.removedCount + const removedCount = typeof rawRemoved === 'number' ? rawRemoved : 0 + const inserted = Array.isArray(data.inserted) ? data.inserted as Array> : [] + const start = typeof rawStart === 'number' ? rawStart : Number.NaN + if (!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') continue + 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 diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 31318a2b..5a4a32b5 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -582,6 +582,48 @@ describe('buildSidechatInheritance compaction tail', () => { 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 + // Session.create rejects the seed (caught on the real deployment's + // main session during e2e). + 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('reuses the previous compaction when the newest summary is orphaned', () => { const events = compactedLog() const at = events.length