@qilin-agent/session-projection 0.0.0-stage → 3.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,437 @@
1
+ import { Service } from "@qilin-agent/kylin";
2
+ import { SessionLogOffset, SessionSeq } from "@qilin-agent/session";
3
+ //#region lib/types/index.js
4
+ /**
5
+ * Service Definition and drive registry for the session-projection capability seam: the merge-extensible state and client-view type
6
+ * tables, the `ProjectionDefinition` state-driven computation unit contract,
7
+ * and the `ctx.sessionProjections` registry that DRIVES every registered unit
8
+ * forward eagerly over committed session events. Domain host plugins
9
+ * contribute pure folds and optional client views; the framework owns the
10
+ * subscription, the per-session watermark cache, and change notification;
11
+ * carriers consume the snapshot read face and the change feed. Neither side
12
+ * knows the other
13
+ * (capability-seam three-way split). Design authority: the session-projection
14
+ * RFC (.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md).
15
+ *
16
+ * Whole-value event rule (load-bearing): a state-carrying log event MUST
17
+ * carry the complete post-change state, never a bare delta — it keeps every
18
+ * unit's transition trivially cheap and every served value self-describing.
19
+ *
20
+ * @module @qilin-agent/session-projection
21
+ */
22
+ /** Convert a log offset to the inclusive cursor immediately before it. */
23
+ function cursorBefore(offset) {
24
+ return offset === 0 ? -1 : SessionSeq(offset - 1);
25
+ }
26
+ /**
27
+ * `ctx.sessionProjections`: the projection unit table and its drive. The
28
+ * service subscribes to `session/event` once; every committed event passes
29
+ * every registered unit's `apply` (eager drive). A changed state reference
30
+ * computes the next client view; the change feed is notified only when its
31
+ * raw result changes by `Object.is`.
32
+ * Cells build lazily — a unit registered after events flowed, or a session
33
+ * older than the registry, folds `init` over the in-memory log on first
34
+ * touch (event or read). Registration is an effect (disposer rides the
35
+ * calling fiber): an unloaded domain plugin's key disappears from snapshots
36
+ * and clients read it as capability absence. A host reader either declares
37
+ * `sessionProjections` in its plugin `inject` or fails explicitly when the
38
+ * registry or required key is absent. Contributors may preserve optional
39
+ * registration through `ctx.inject(['sessionProjections'], ...)`. Registrants sharing a key
40
+ * share one unit and are counted: the same tool package mounted in N agent
41
+ * presets registers N times, and the key survives until the last one
42
+ * unloads.
43
+ */
44
+ var SessionProjectionRegistry = class extends Service {
45
+ registrations = /* @__PURE__ */ new Map();
46
+ listeners = /* @__PURE__ */ new Set();
47
+ /**
48
+ * Create and install the registry as `ctx.sessionProjections`.
49
+ * @param ctx - Cordis context that owns the service.
50
+ */
51
+ constructor(ctx) {
52
+ super(ctx, "sessionProjections");
53
+ ctx.on("session/created", (session) => {
54
+ if (session.seq !== 0) return;
55
+ for (const registration of this.registrations.values()) {
56
+ if (registration.cells.has(session)) continue;
57
+ registration.cells.set(session, {
58
+ state: registration.def.init(session.header, session.inheritedEventCount),
59
+ observedSeq: -1,
60
+ views: [void 0, void 0]
61
+ });
62
+ }
63
+ });
64
+ ctx.on("session/event", (session, event) => {
65
+ this.drive(session, event);
66
+ });
67
+ }
68
+ register(definition) {
69
+ const wire = definition.wire;
70
+ const erased = {
71
+ key: definition.key,
72
+ stateSchema: definition.stateSchema,
73
+ init: (header, inheritedEventCount) => definition.init(header, inheritedEventCount),
74
+ apply: (state, event) => definition.apply(state, event),
75
+ wire: wire === void 0 ? void 0 : {
76
+ viewSchema: wire.viewSchema,
77
+ view: (state) => wire.view(state)
78
+ },
79
+ stateVersion: definition.stateVersion
80
+ };
81
+ if (!Number.isSafeInteger(definition.stateVersion) || definition.stateVersion < 0) throw new Error(`session projection ${JSON.stringify(definition.key)} stateVersion must be a non-negative integer, got ${String(definition.stateVersion)}`);
82
+ const dispose = this.ctx.effect(function* () {
83
+ const key = erased.key;
84
+ const existing = this.registrations.get(key);
85
+ if (existing === void 0) this.registrations.set(key, {
86
+ def: erased,
87
+ cells: /* @__PURE__ */ new WeakMap(),
88
+ refs: 1
89
+ });
90
+ else {
91
+ if (existing.def.stateVersion !== erased.stateVersion) throw new Error(`session projection key ${JSON.stringify(key)} is already registered at stateVersion ${String(existing.def.stateVersion)}; refusing to share it with stateVersion ${String(erased.stateVersion)}`);
92
+ existing.refs += 1;
93
+ }
94
+ yield () => {
95
+ const live = this.registrations.get(key);
96
+ /* v8 ignore next -- the disposer runs once per successful registration, so the entry it counted is still here */
97
+ if (live === void 0) return;
98
+ live.refs -= 1;
99
+ if (live.refs === 0) this.registrations.delete(key);
100
+ };
101
+ }.bind(this), "sessionProjections.register()");
102
+ return () => void dispose();
103
+ }
104
+ /**
105
+ * Subscribe to the change feed. The registration is an effect on the
106
+ * calling context's fiber.
107
+ * @param listener - called once per client-visible unit whose raw view changed by `Object.is`, per committed event.
108
+ * @returns the exact disposer that unsubscribes.
109
+ */
110
+ onChanged(listener) {
111
+ const dispose = this.ctx.effect(() => {
112
+ this.listeners.add(listener);
113
+ return () => {
114
+ this.listeners.delete(listener);
115
+ };
116
+ }, "sessionProjections.onChanged()");
117
+ return () => void dispose();
118
+ }
119
+ /**
120
+ * Read one unit's current host state after materializing every registered
121
+ * unit at the Session cursor. Unrelated wire views are not produced.
122
+ * The returned value is live; callers must not mutate it.
123
+ * @param session - the session whose state is read.
124
+ * @param key - the registered unit key.
125
+ * @returns current state, or `undefined` when the key is not registered.
126
+ */
127
+ stateOf(session, key) {
128
+ const registration = this.registrations.get(key);
129
+ if (registration === void 0) return void 0;
130
+ this.materializeCells(session);
131
+ return this.cellFor(registration, session).state;
132
+ }
133
+ /**
134
+ * One consistent cut over every registered client-visible unit for one session, read from
135
+ * the watermark cache (missing cells fold lazily over the in-memory log).
136
+ * Fully synchronous — every value and `asOfSeq` reflect the same log
137
+ * position. Each value passes its unit's `viewSchema` before leaving.
138
+ * @param session - the session whose projection values are read.
139
+ * @param keys - optional client-visible outputs; state materialization remains complete.
140
+ * @returns the snapshot; `values` is empty when no selected client-visible unit is registered.
141
+ */
142
+ snapshot(session, keys) {
143
+ const values = {};
144
+ const selected = keys === void 0 ? void 0 : new Set(keys);
145
+ this.materializeCells(session);
146
+ for (const registration of this.registrations.values()) {
147
+ if (registration.def.wire === void 0) continue;
148
+ if (selected !== void 0 && !selected.has(registration.def.key)) continue;
149
+ const cell = this.cellFor(registration, session);
150
+ values[registration.def.key] = this.viewCell(registration, cell);
151
+ }
152
+ return {
153
+ asOfSeq: cursorBefore(session.seq),
154
+ values
155
+ };
156
+ }
157
+ /**
158
+ * Read only already-materialized client-visible cells without folding history.
159
+ * Values may trail the live Session and are therefore hints, not a complete
160
+ * baseline. Missing cells are omitted.
161
+ * @param session - attached Session whose cached cells are inspected.
162
+ * @param keys - optional wire keys to view.
163
+ * @returns the lowest common cached cut, or `undefined` when no wire cell exists.
164
+ */
165
+ cachedSnapshot(session, keys) {
166
+ const values = {};
167
+ let asOfSeq;
168
+ const selected = keys === void 0 ? void 0 : new Set(keys);
169
+ for (const registration of this.registrations.values()) {
170
+ if (registration.def.wire === void 0) continue;
171
+ if (selected !== void 0 && !selected.has(registration.def.key)) continue;
172
+ const cell = registration.cells.get(session);
173
+ if (cell === void 0) continue;
174
+ values[registration.def.key] = this.viewCell(registration, cell);
175
+ if (asOfSeq === void 0 || cell.observedSeq < asOfSeq) asOfSeq = cell.observedSeq;
176
+ }
177
+ return asOfSeq === void 0 ? void 0 : {
178
+ asOfSeq,
179
+ values
180
+ };
181
+ }
182
+ /**
183
+ * State-level checkpoint of every persisted unit for one session, read
184
+ * from the watermark cache (missing cells fold lazily over the in-memory
185
+ * log). This is the write side of the persisted projection cache: the
186
+ * returned rows are the `(key → {ver, seq, val})` part of the durable
187
+ * `(sessionId, key, ver, seq, val)`
188
+ * rows. Every `val` is a DETACHED structured clone — never the live
189
+ * cell reference: the watermark cache is this registry's authoritative
190
+ * mutable state, and a caller reaching the live reference could corrupt
191
+ * every subsequent snapshot and frame through it (plain JSON by the unit
192
+ * contract, so the clone is total).
193
+ * @param session - the session whose unit states are checkpointed.
194
+ * @returns one row per registered key.
195
+ */
196
+ checkpoint(session) {
197
+ const rows = {};
198
+ for (const registration of this.registrations.values()) {
199
+ const cell = this.cellFor(registration, session);
200
+ rows[registration.def.key] = {
201
+ ver: registration.def.stateVersion,
202
+ seq: cell.observedSeq,
203
+ val: structuredClone(cell.state)
204
+ };
205
+ }
206
+ return rows;
207
+ }
208
+ /**
209
+ * The stored seq a {@link restore} tail read over `checkpoint` must start
210
+ * at: one event BELOW the lowest usable watermark (a row is usable when
211
+ * its `ver` matches the live unit's `stateVersion`; an absent or mismatched row
212
+ * pulls the floor to `0` — that key must refold the full log). The
213
+ * one-below anchor is load-bearing: the tail then proves how far the
214
+ * stored log still extends, so {@link restore} can detect a log that
215
+ * shrank below a row's watermark (crash-repair truncation) instead of
216
+ * serving the stale row as current — an empty tail read from the anchor
217
+ * yields an end below every watermark and the restore rejects for a full
218
+ * re-read.
219
+ * @param checkpoint - persisted rows for one session (possibly stale or empty).
220
+ * @returns the offset for the stored-log suffix read (`SessionHandle.read`),
221
+ * or `undefined` when no unit is registered (no read needed —
222
+ * {@link restore} would serve empty values regardless).
223
+ */
224
+ restoreFloor(checkpoint) {
225
+ let floor;
226
+ for (const registration of this.registrations.values()) {
227
+ const row = checkpoint[registration.def.key];
228
+ const need = row !== void 0 && row.ver === registration.def.stateVersion ? Math.max(row.seq + 1, 0) : 0;
229
+ floor = floor === void 0 ? need : Math.min(floor, need);
230
+ }
231
+ return floor === void 0 ? void 0 : SessionLogOffset(Math.max(floor - 1, 0));
232
+ }
233
+ /**
234
+ * View a checkpoint's rows without any log read: for every registered
235
+ * client-visible unit whose row's `ver` matches, serve the schema-validated
236
+ * `view` of the schema-validated stored state; mismatched, malformed, or absent rows leave their key
237
+ * absent (a cold or listing consumer treats it as not-yet-available and a
238
+ * fuller read path refolds it). The zero-I/O rung of the read ladder —
239
+ * values are as stale as their rows, never wrong.
240
+ * @param checkpoint - persisted rows for one session (possibly stale or empty).
241
+ * @param keys - optional wire keys to view.
242
+ * @returns whole values per key with a usable row; empty when none.
243
+ */
244
+ viewCheckpoint(checkpoint, keys) {
245
+ const values = {};
246
+ const selected = keys === void 0 ? void 0 : new Set(keys);
247
+ for (const registration of this.registrations.values()) {
248
+ const def = registration.def;
249
+ if (def.wire === void 0) continue;
250
+ if (selected !== void 0 && !selected.has(def.key)) continue;
251
+ const row = checkpoint[def.key];
252
+ if (row === void 0 || row.ver !== def.stateVersion) continue;
253
+ let state;
254
+ try {
255
+ state = def.stateSchema.parse(row.val);
256
+ } catch {
257
+ continue;
258
+ }
259
+ values[def.key] = def.wire.viewSchema.parse(def.wire.view(state));
260
+ }
261
+ return values;
262
+ }
263
+ /**
264
+ * Cold read: fold every persisted unit over a stored log suffix, seeding
265
+ * each from its checkpoint row when usable — the one read recipe (cached
266
+ * state + forward tail replay + `view`) applied without a live `Session`.
267
+ * Call with the stored events at or past `restoreFloor(checkpoint)` (a
268
+ * `SessionHandle.read` slice) and that same floor as
269
+ * `baseSeq`; the floor's one-below anchor makes the supplied end honest,
270
+ * so a shrunk log is detected here. A row is usable iff its
271
+ * `ver` matches the live unit's `stateVersion`, it does not predate `baseSeq`
272
+ * (`seq >= baseSeq - 1`), and it does not claim events past the
273
+ * supplied end (`seq <= endSeq`); an unusable row is discarded
274
+ * and its key refolds from `init` — which is only sound over the full
275
+ * log, so a discarded row with `baseSeq > 0` throws (the caller re-reads
276
+ * from seq 0, e.g. after a crash-repair truncation shrank the log below
277
+ * a row's watermark).
278
+ * @param checkpoint - persisted rows for one session (possibly stale or empty).
279
+ * @param events - the stored events with `seq >= baseSeq`, in seq order.
280
+ * @param baseSeq - the seq `events` starts at (its first event's seq when non-empty).
281
+ * @param header - immutable metadata for the Session being restored.
282
+ * @param inheritedEventCount - exact fork-inherited prefix length supplied to unit initialization.
283
+ * @returns the snapshot cut at the supplied log end (`asOfSeq` is the last
284
+ * supplied event's seq, `baseSeq - 1` for an empty tail) plus the
285
+ * refreshed checkpoint rows at that cut, ready for a durable write-back.
286
+ */
287
+ restore(checkpoint, events, baseSeq, header, inheritedEventCount) {
288
+ const endSeq = events.at(-1)?.seq ?? cursorBefore(baseSeq);
289
+ const beforeBase = cursorBefore(baseSeq);
290
+ const values = {};
291
+ const refreshed = {};
292
+ for (const registration of this.registrations.values()) {
293
+ const def = registration.def;
294
+ const row = checkpoint[def.key];
295
+ const usable = row !== void 0 && row.ver === def.stateVersion && row.seq >= beforeBase && row.seq <= endSeq;
296
+ if (!usable && baseSeq > 0) throw new Error(`session projection ${JSON.stringify(def.key)} cannot restore from seq ${baseSeq}: its checkpoint row is missing, version-mismatched, or beyond the supplied log end; re-read from seq 0`);
297
+ let state = usable ? def.stateSchema.parse(row.val) : def.init(header, inheritedEventCount);
298
+ const startIndex = (usable ? row.seq : beforeBase) - baseSeq + 1;
299
+ for (let index = startIndex; index < events.length; index++) {
300
+ const event = events[index];
301
+ const expectedSeq = SessionSeq(baseSeq + index);
302
+ if (event === void 0 || event.seq !== expectedSeq) throw new Error(`session projection ${JSON.stringify(def.key)} cannot restore across missing seq ${String(expectedSeq)}`);
303
+ state = def.apply(state, event);
304
+ }
305
+ if (def.wire !== void 0) values[def.key] = def.wire.viewSchema.parse(def.wire.view(state));
306
+ refreshed[def.key] = {
307
+ ver: def.stateVersion,
308
+ seq: endSeq,
309
+ val: state
310
+ };
311
+ }
312
+ return {
313
+ snapshot: {
314
+ asOfSeq: endSeq,
315
+ values
316
+ },
317
+ checkpoint: refreshed
318
+ };
319
+ }
320
+ /**
321
+ * Restore an exact cut and install its states on the supplied prepared Session.
322
+ * A later publication reuses these cells; ordinary live reads and event drive
323
+ * advance any constructor-owned suffix exactly once.
324
+ * @param session - exact prepared Session that owns the restored log prefix.
325
+ * @param checkpoint - persisted rows for this Session lifecycle.
326
+ * @param events - exact events at the observation cut.
327
+ * @param baseSeq - first supplied event sequence.
328
+ * @returns all projection values at the supplied cut.
329
+ */
330
+ hydrate(session, checkpoint, events, baseSeq) {
331
+ const endSeq = events.at(-1)?.seq ?? cursorBefore(baseSeq);
332
+ let complete = true;
333
+ for (const registration of this.registrations.values()) if (registration.cells.get(session)?.observedSeq !== endSeq) {
334
+ complete = false;
335
+ break;
336
+ }
337
+ if (complete) {
338
+ const values = {};
339
+ for (const registration of this.registrations.values()) {
340
+ if (registration.def.wire === void 0) continue;
341
+ const current = registration.cells.get(session);
342
+ values[registration.def.key] = this.viewCell(registration, current);
343
+ }
344
+ return {
345
+ asOfSeq: endSeq,
346
+ values
347
+ };
348
+ }
349
+ const restored = this.restore(checkpoint, events, baseSeq, session.header, session.inheritedEventCount);
350
+ for (const registration of this.registrations.values()) {
351
+ const row = restored.checkpoint[registration.def.key];
352
+ if (row === void 0) continue;
353
+ const current = registration.cells.get(session);
354
+ if (current !== void 0 && current.observedSeq > row.seq) continue;
355
+ registration.cells.set(session, {
356
+ state: row.val,
357
+ observedSeq: row.seq,
358
+ views: [void 0, void 0]
359
+ });
360
+ }
361
+ return restored.snapshot;
362
+ }
363
+ /** Materialize every registered unit cell at the Session's current cursor. */
364
+ materializeCells(session) {
365
+ for (const registration of this.registrations.values()) this.cellFor(registration, session);
366
+ }
367
+ /** Fold one unit from init over `events`, producing a cell watermarked at the last folded event. */
368
+ buildCell(def, header, inheritedEventCount, events) {
369
+ let state = def.init(header, inheritedEventCount);
370
+ for (const event of events) state = def.apply(state, event);
371
+ return {
372
+ state,
373
+ observedSeq: events.at(-1)?.seq ?? -1,
374
+ views: [void 0, void 0]
375
+ };
376
+ }
377
+ /** Read (or lazily build, folding the full in-memory log) one unit's cell. */
378
+ cellFor(registration, session) {
379
+ let cell = registration.cells.get(session);
380
+ if (cell === void 0) {
381
+ cell = this.buildCell(registration.def, session.header, session.inheritedEventCount, session.snapshotEvents());
382
+ registration.cells.set(session, cell);
383
+ } else this.advanceCell(registration.def, cell, session, cursorBefore(session.seq));
384
+ return cell;
385
+ }
386
+ /** Advance one existing cell through a contiguous Session prefix. */
387
+ advanceCell(def, cell, session, throughSeq) {
388
+ if (cell.observedSeq >= throughSeq) return;
389
+ for (let seq = cell.observedSeq + 1; seq <= throughSeq; seq++) {
390
+ const event = session.eventAt(SessionSeq(seq));
391
+ if (event === void 0 || event.seq !== seq) throw new Error(`session projection ${JSON.stringify(def.key)} cannot advance across missing seq ${String(seq)}`);
392
+ const next = def.apply(cell.state, event);
393
+ if (!Object.is(next, cell.state)) {
394
+ cell.views[0] = cell.views[1];
395
+ cell.views[1] = void 0;
396
+ }
397
+ cell.state = next;
398
+ cell.observedSeq = SessionSeq(seq);
399
+ }
400
+ }
401
+ /** Eager drive: pass one committed event through every unit; notify on changed raw view references. */
402
+ drive(session, event) {
403
+ for (const registration of this.registrations.values()) {
404
+ let cell = registration.cells.get(session);
405
+ if (cell !== void 0 && cell.observedSeq >= event.seq) continue;
406
+ if (cell === void 0) {
407
+ cell = this.buildCell(registration.def, session.header, session.inheritedEventCount, session.snapshotEvents(SessionLogOffset(0), SessionLogOffset(event.seq)));
408
+ registration.cells.set(session, cell);
409
+ } else this.advanceCell(registration.def, cell, session, event.seq === 0 ? -1 : SessionSeq(event.seq - 1));
410
+ const previousState = cell.state;
411
+ const next = registration.def.apply(previousState, event);
412
+ const changed = !Object.is(next, previousState);
413
+ cell.state = next;
414
+ cell.observedSeq = event.seq;
415
+ const wire = registration.def.wire;
416
+ if (changed && wire !== void 0) {
417
+ const views = cell.views;
418
+ views[0] = views[1];
419
+ if (this.listeners.size > 0) {
420
+ views[1] = wire.view(next);
421
+ if (!Object.is(views[0], views[1])) {
422
+ const value = wire.viewSchema.parse(views[1]);
423
+ for (const listener of this.listeners) listener(session, registration.def.key, value, event.seq);
424
+ }
425
+ } else views[1] = void 0;
426
+ }
427
+ }
428
+ }
429
+ /** Return one schema-validated wire value. */
430
+ viewCell(registration, cell) {
431
+ const wire = registration.def.wire;
432
+ if (wire === void 0) throw new Error(`session projection ${JSON.stringify(registration.def.key)} has no wire view`);
433
+ return wire.viewSchema.parse(wire.view(cell.state));
434
+ }
435
+ };
436
+ //#endregion
437
+ export { SessionProjectionRegistry, SessionProjectionRegistry as default };