feat(session-query): checkpoint build round 1

This commit is contained in:
Hypatia May
2026-07-10 16:51:19 +08:00
parent 42ebbfdf8f
commit aa1dc0e2c7
40 changed files with 3174 additions and 102 deletions

View File

@@ -20,8 +20,8 @@ export * from './types.ts'
export { isJsonValue } from './json.ts'
export type { JsonValue } from './json.ts'
export { interruptedTurnClosers } from './repair.ts'
export type { SurfaceNode } from './surface.ts'
export { isSurfaceEvent, isSurfaceEligibleType } from './surface.ts'
export type { SurfaceFoldReplacement, SurfaceFoldResult, SurfaceNode } from './surface.ts'
export { foldSurface, isSurfaceEvent, isSurfaceEligibleType } from './surface.ts'
export { isToolPairingBalanced } from './tool-pairing.ts'
export { applyHeaderDelta, canonicalHeader, diffHeader, foldRequestHeader, headerEquals } from './request-header.ts'
@@ -37,6 +37,14 @@ declare module 'cordis' {
* @mode emit
*/
'session/created'(session: Session): void
/**
* A session left the live store. The header is snapshotted after the store
* entry is removed; listener failures are contained and cannot break the
* owning fiber's teardown.
* @param header - immutable identity and lineage of the removed session.
* @mode parallel
*/
'session/removed'(header: SessionHeader): Promise<void> | void
/**
* An event was appended to a session log (sync, fire-and-forget). This is
* the per-append feed a UI or invariant plugin tails.
@@ -501,8 +509,15 @@ export class SessionStore extends Service {
session.onAppend = (event) => { this.ctx.emit('session/event', session, event) }
this.store.set(session.id, session)
return () => {
if (this.store.get(session.id) !== session) return
session.onAppend = undefined
this.store.delete(session.id)
const header = structuredClone(session.header)
void Promise.resolve()
.then(() => this.ctx.parallel('session/removed', header))
.catch((error: unknown) => {
this.ctx.logger.warn(`session store: session/removed listener failed for "${session.id}": ${String(error)}`)
})
}
}

View File

@@ -61,6 +61,125 @@ export interface SurfaceNode {
next: number | null
}
/** One replacement operation observed while folding a session surface. */
export interface SurfaceFoldReplacement {
/** Seq of the event that replaced the prior surface range. */
seq: number
/** Declared inclusive start seq of the replaced surface range. */
start: number
/** Declared inclusive end seq of the replaced surface range. */
end: number
/** Actual surface nodes removed by the operation, in surface order. */
shadowedSeqs: number[]
}
/** Complete result of replaying the surface operations in a session log. */
export interface SurfaceFoldResult {
/** Current surface nodes in linked-list order. */
nodes: SurfaceNode[]
/** Replacement operations in event order. */
replacements: SurfaceFoldReplacement[]
}
/** Mutable state shared by the incremental manager and the full-log fold. */
interface SurfaceFoldState {
nodes: SurfaceNode[]
nodeBySeq: Map<number, SurfaceNode>
replacements: SurfaceFoldReplacement[]
replaceGeneration: number
}
/** Create an empty surface fold state. */
function createFoldState(replaceGeneration = 0): SurfaceFoldState {
return {
nodes: [],
nodeBySeq: new Map(),
replacements: [],
replaceGeneration,
}
}
/** Apply one event to a surface fold state. */
function applySurfaceEvent(state: SurfaceFoldState, event: SessionEvent): void {
if (!isSurfaceEvent(event)) return
if (event.surfaceOp === 'append') {
const tail = state.nodes.length > 0 ? state.nodes[state.nodes.length - 1] : undefined
const node: SurfaceNode = { seq: event.seq, prev: tail?.seq ?? null, next: null }
if (tail) tail.next = event.seq
state.nodes.push(node)
state.nodeBySeq.set(event.seq, node)
return
}
const shadowedSeqs = replaceSurface(state, event.seq, event.surfaceOp)
state.replacements.push({
seq: event.seq,
start: event.surfaceOp.start,
end: event.surfaceOp.end,
shadowedSeqs,
})
}
/** Apply one positional replacement and return the nodes it removed. */
function replaceSurface(
state: SurfaceFoldState,
newSeq: number,
op: Extract<SurfaceOp, { op: 'replace' }>,
): number[] {
const startNode = state.nodeBySeq.get(op.start)
if (!startNode) {
throw new Error(`surface replace: start seq ${op.start} not found in surface`)
}
const endNode = state.nodeBySeq.get(op.end)
if (!endNode) {
throw new Error(`surface replace: end seq ${op.end} not found in surface`)
}
const startIdx = state.nodes.indexOf(startNode)
const endIdx = state.nodes.indexOf(endNode)
if (startIdx > endIdx) {
throw new Error(`surface replace: start seq ${op.start} (index ${startIdx}) is after end seq ${op.end} (index ${endIdx})`)
}
const removed = state.nodes.splice(startIdx, endIdx - startIdx + 1)
for (const node of removed) state.nodeBySeq.delete(node.seq)
const prevNode = startIdx > 0 ? state.nodes[startIdx - 1] : undefined
const nextNode = startIdx < state.nodes.length ? state.nodes[startIdx] : undefined
const newNode: SurfaceNode = {
seq: newSeq,
prev: prevNode?.seq ?? null,
next: nextNode?.seq ?? null,
}
if (prevNode) prevNode.next = newSeq
if (nextNode) nextNode.prev = newSeq
state.nodes.splice(startIdx, 0, newNode)
state.nodeBySeq.set(newSeq, newNode)
state.replaceGeneration += 1
return removed.map(node => node.seq)
}
/**
* Replay a complete session log through the canonical surface fold.
*
* The returned arrays and nodes are detached snapshots. The incremental
* {@link SurfaceManager} uses the same transition functions, so query read
* models cannot disagree with `deriveMessages()` about replacement ranges.
* @param events - session events in contiguous seq order.
* @returns the current surface and every positional replacement.
*/
export function foldSurface(events: readonly SessionEvent[]): SurfaceFoldResult {
const state = createFoldState()
for (const event of events) applySurfaceEvent(state, event)
return {
nodes: state.nodes.map(node => ({ ...node })),
replacements: state.replacements.map(replacement => ({
...replacement,
shadowedSeqs: [...replacement.shadowedSeqs],
})),
}
}
/**
* Maintains a cached linked list of surface nodes, rebuilt lazily from
* `surfaceOp` markers in the event log. Because the log is append-only, it
@@ -69,16 +188,11 @@ export interface SurfaceNode {
* whole log.
*/
export class SurfaceManager {
/** Surface nodes in linked-list order (head to tail). Empty until first access. */
private _nodes: SurfaceNode[] = []
/** Map from event seq → node. */
private _nodeBySeq = new Map<number, SurfaceNode>()
/** Incremental state shared with the complete surface fold. */
private _state = createFoldState()
/** The last processed seq. -1 forces a full rebuild on first access. */
private _lastProcessedSeq = -1
/** Rewrite generation — see {@link replaceGeneration}. */
private _replaceGeneration = 0
constructor(private log: readonly SessionEvent[]) {}
/**
@@ -88,11 +202,9 @@ export class SurfaceManager {
*/
invalidate(): void {
this._lastProcessedSeq = -1
this._nodes = []
this._nodeBySeq.clear()
// A wholesale rebuild is a rewrite: bump the generation so incremental
// consumers (the session's derived-message cache) discard their view.
this._replaceGeneration += 1
this._state = createFoldState(this._state.replaceGeneration + 1)
}
/**
@@ -106,13 +218,13 @@ export class SurfaceManager {
*/
get replaceGeneration(): number {
if (this._lastProcessedSeq < this.log.length - 1) this._processDelta()
return this._replaceGeneration
return this._state.replaceGeneration
}
/** The surface nodes in linked-list order (head to tail). */
get nodes(): readonly SurfaceNode[] {
if (this._lastProcessedSeq < this.log.length - 1) this._processDelta()
return this._nodes
return this._state.nodes
}
/**
@@ -124,61 +236,8 @@ export class SurfaceManager {
// Index is bounded by i < this.log.length — never undefined.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const event = this.log[i]!
// isSurfaceEvent checks event.type first (is it a surface-eligible type?)
// then checks that surfaceOp is present. Only after both pass do we treat
// it as a SurfaceEvent with mandatory surfaceOp.
if (!isSurfaceEvent(event)) continue
if (event.surfaceOp === 'append') {
const tail = this._nodes.length > 0 ? this._nodes[this._nodes.length - 1] : undefined
const node: SurfaceNode = { seq: event.seq, prev: tail?.seq ?? null, next: null }
if (tail) tail.next = event.seq
this._nodes.push(node)
this._nodeBySeq.set(event.seq, node)
} else {
this._replace(event.seq, event.surfaceOp)
}
applySurfaceEvent(this._state, event)
}
this._lastProcessedSeq = this.log.length - 1
}
/** Apply a replace operation to the in-progress surface. */
private _replace(
newSeq: number,
op: Extract<SurfaceOp, { op: 'replace' }>,
): void {
const startNode = this._nodeBySeq.get(op.start)
if (!startNode) {
throw new Error(`surface replace: start seq ${op.start} not found in surface`)
}
const endNode = this._nodeBySeq.get(op.end)
if (!endNode) {
throw new Error(`surface replace: end seq ${op.end} not found in surface`)
}
const startIdx = this._nodes.indexOf(startNode)
const endIdx = this._nodes.indexOf(endNode)
if (startIdx > endIdx) {
throw new Error(`surface replace: start seq ${op.start} (index ${startIdx}) is after end seq ${op.end} (index ${endIdx})`)
}
// Remove shadowed nodes from `[startIdx, endIdx]` inclusive.
const count = endIdx - startIdx + 1
const removed = this._nodes.splice(startIdx, count)
for (const r of removed) this._nodeBySeq.delete(r.seq)
// Insert the new node where the removed range was.
const prevNode = startIdx > 0 ? this._nodes[startIdx - 1] : undefined
const nextNode = startIdx < this._nodes.length ? this._nodes[startIdx] : undefined
const newNode: SurfaceNode = {
seq: newSeq,
prev: prevNode?.seq ?? null,
next: nextNode?.seq ?? null,
}
if (prevNode) prevNode.next = newSeq
if (nextNode) nextNode.prev = newSeq
this._nodes.splice(startIdx, 0, newNode)
this._nodeBySeq.set(newSeq, newNode)
this._replaceGeneration += 1
}
}