diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 05e5dd2d..f2bb9e9b 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -374,6 +374,60 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] 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 runSeq = data.sourceEventSeq + const runKept = (typeof id === 'string' && keptRunIds.has(id)) + || (typeof runSeq === 'number' && emittedSeqs.has(runSeq) && events[runSeq]?.type === 'command/run') + if (!runKept) 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 @@ -421,13 +475,17 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] for (let index = keepStart; index < cut; index++) { const event = events[index] if (event === undefined || isCompactionGroupEvent(event, groupId)) continue - if (isSurfaceEligibleType(event.type) && !surviving.has(event.seq) && !replaceCovered.has(event.seq)) continue - if (event.type === 'tool/call' && !survivingCallIds.has(String(dataOf(event).callId))) 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)) emit(event) + 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 @@ -496,8 +554,9 @@ function inboxSplicesValid(seed: readonly SeedEvent[]): boolean { if (data.target !== 'next-turn' && data.target !== 'next-step') return false const inbox = data.target === 'next-step' ? nextStep : nextTurn const rawStart = data.start - const rawRemoved = data.removedCount - const removedCount = typeof rawRemoved === 'number' ? rawRemoved : Number.NaN + // 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 diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 1ca189f8..0ef434a6 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -624,13 +624,14 @@ describe('buildSidechatInheritance compaction tail', () => { ) }) - it('falls back when a kept compaction group would lose its summary to the dropped span', () => { + 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) shadows cp0's checkpoint; cp0's records ride in the keep window - // but its citations name the dropped span, so dropping only the summary - // would strand a successful compaction/end — the bracket gate falls - // back to the full copy instead of shipping a seed the host's - // compaction invariant companion rejects. + // 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 }), @@ -671,19 +672,28 @@ describe('buildSidechatInheritance compaction tail', () => { lo('turn/end', 19, { turn: 2, reason: { kind: 'completed' } }), ...turn(20, 3, { callId: 'c-tail', result: 'tail result' }).events, ] - // The consumed compaction shadows cp0's checkpoint plus turn 1's nodes. - events.push(...compactionGroup(events.length, [3, 4, 14])) - const { seed } = buildSidechatInheritance(events) - expect(seed.length).toBe(events.length) + // 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 trims — only the bracket split, not - // the log, disables the optimization. + // 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('falls back when a command/run is dropped while its command/done survives', () => { + 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 @@ -716,7 +726,13 @@ describe('buildSidechatInheritance compaction tail', () => { ] events.push(...compactionGroup(events.length, [4, 5])) const { seed } = buildSidechatInheritance(events) - expect(seed.length).toBe(events.length) + // 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 cites the rebased run.