@hasna-internal/kai-session-persistence 0.1.1-rc.2

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.
@@ -0,0 +1,23 @@
1
+ //#region lib/types/invariant.js
2
+ /**
3
+ * Package-owned invariant companion for `@hasna-internal/kai-session-persistence`.
4
+ * @module @hasna-internal/kai-session-persistence/invariant
5
+ */
6
+ const PACKAGE_NAME = "@hasna-internal/kai-session-persistence";
7
+ /** Cordis companion plugin name. */
8
+ const name = "session-persistence-invariant";
9
+ /** Service required before the companion can reserve package ownership. */
10
+ const inject = ["invariants"];
11
+ /**
12
+ * No runtime invariant: persistence correctness requires backend round-trip and crash-tail tests;
13
+ * this package exposes no continuously observable in-process relation.
14
+ */
15
+ const install = () => {};
16
+ /**
17
+ * Register this package's invariant companion.
18
+ * @param ctx - Cordis context carrying the invariant service.
19
+ * @returns the installed registration's disposer after setup succeeds.
20
+ */
21
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
22
+ //#endregion
23
+ export { apply, inject, name };
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Shared buffering, serialization, adoption, repair, and disposal orchestration
3
+ * for first-party backends. Third-party backends may implement the public
4
+ * persistence seam directly.
5
+ * @module @hasna-internal/kai-session-persistence/coordinator
6
+ */
7
+ import { Context } from '@deepseek-ai/cordis';
8
+ import { SessionPreparation } from '@hasna-internal/kai-session';
9
+ import type { SessionEvent, SessionId, SessionHeader } from '@hasna-internal/kai-session';
10
+ import type { SessionInspection, SessionLocation } from './index.ts';
11
+ import type { SessionPersistenceRevision } from './revision.ts';
12
+ /** Default number of detached session preparations retained by a coordinator. */
13
+ export declare const DEFAULT_PREPARED_SESSION_CACHE_SIZE = 5;
14
+ /** Default maximum intentional wait before a live session batch starts writing. */
15
+ export declare const DEFAULT_WRITE_BATCH_MAX_DELAY_MS = 200;
16
+ /** Largest write batching delay accepted by Node's timer implementation. */
17
+ export declare const MAX_WRITE_BATCH_DELAY_MS = 2147483647;
18
+ /** Durable session contents failed validation after a successful backend read. */
19
+ export declare class SessionPersistenceCorruptionError extends Error {
20
+ /**
21
+ * @param message - stable corruption context.
22
+ * @param options - original validation failure.
23
+ */
24
+ constructor(message: string, options: ErrorOptions);
25
+ }
26
+ /**
27
+ * The stored log is intact but this runtime cannot faithfully interpret it:
28
+ * the header carries an unsupported format version, or an event's type is
29
+ * unknown to this build and the event is not marked ignorable. Distinct from
30
+ * {@link SessionPersistenceCorruptionError} — nothing is damaged; the raw log
31
+ * remains readable at {@link location} when the backend keeps one artifact
32
+ * per session.
33
+ */
34
+ export declare class SessionFormatUnsupportedError extends Error {
35
+ readonly location?: SessionLocation | undefined;
36
+ /**
37
+ * @param message - stable reason the log cannot be interpreted, already
38
+ * including the raw-log path when one exists.
39
+ * @param location - the backend's artifact location, when one exists.
40
+ */
41
+ constructor(message: string, location?: SessionLocation | undefined);
42
+ }
43
+ /**
44
+ * Direction-aware refusal text for a stored session whose format version this
45
+ * build does not read. Shared by the coordinator's load-time check and by
46
+ * backends that must refuse BEFORE decoding version-dependent structure (a
47
+ * future format may not satisfy today's structural checks at all, and the
48
+ * user must see "upgrade the harness", never "corrupt").
49
+ * @param id - the stored session id, for message context.
50
+ * @param version - the stored format version.
51
+ * @returns the stable refusal text, without a raw-log path suffix.
52
+ */
53
+ export declare function sessionFormatVersionRefusal(id: string, version: number): string;
54
+ /** Coordinator policy supplied by a concrete persistence backend. */
55
+ export interface PersistenceCoordinatorOptions {
56
+ /** Maximum completed unpublished preparations retained for reuse. */
57
+ readonly preparedSessionCacheSize: number;
58
+ /** Maximum intentional batching wait after an idle live queue receives work. */
59
+ readonly writeBatchMaxDelayMs: number;
60
+ }
61
+ /**
62
+ * A stored session's header, valid contiguous event prefix, source-qualified
63
+ * revision, and optional opaque torn-tail marker. The revision identifies the
64
+ * exact detached prefix. The coordinator only checks marker presence and
65
+ * returns its value to {@link PersistenceBackend.commitRepair}; each backend
66
+ * owns the marker type.
67
+ */
68
+ export interface StoredPrefix<TornMarker = unknown> {
69
+ meta: SessionHeader;
70
+ events: SessionEvent[];
71
+ /** Revision observed for exactly this detached prefix. */
72
+ revision: SessionPersistenceRevision;
73
+ tornMarker?: TornMarker;
74
+ }
75
+ /**
76
+ * A stored session's header plus the events at or past a requested seq — the
77
+ * return shape of the optional seek-capable
78
+ * {@link PersistenceBackend.loadStoredFrom} hook. Non-mutating reads carry no
79
+ * torn marker: there is nothing to repair.
80
+ */
81
+ export interface StoredSuffix {
82
+ meta: SessionHeader;
83
+ events: SessionEvent[];
84
+ }
85
+ /**
86
+ * The storage contract between {@link PersistenceCoordinator} and a concrete
87
+ * backend: the minimal set of durable primitives the orchestration calls. A
88
+ * backend implements these (over files, rows, an object store, …); the
89
+ * coordinator supplies everything else (buffering, serialization, cursors,
90
+ * adoption, crash repair sequencing, dispose quiescence).
91
+ *
92
+ * @typeParam TornMarker - the backend's opaque torn-tail repair token (see
93
+ * {@link StoredPrefix}). The coordinator treats it as fully opaque.
94
+ */
95
+ export interface PersistenceBackend<TornMarker = unknown> {
96
+ /** Human-readable backend name, used in the dispose-failure AggregateError. */
97
+ readonly name: string;
98
+ /**
99
+ * Read a stored prefix by id, scanning every backend storage scope. Returns
100
+ * `undefined` if no stored artifact exists. Returned metadata must identify
101
+ * `id` before repair or state publication. Used by resume/load, live adoption,
102
+ * and — via `!== undefined` — the create-collision probe. The returned
103
+ * `tornMarker` is present iff there is a torn tail to truncate. Every header
104
+ * and event graph must be fresh, mutually unaliased, and unretained by the
105
+ * backend because preparation freezes and publishes them in place. The
106
+ * returned revision must identify exactly those values and use the same
107
+ * representation as {@link readStoredRevision}.
108
+ * @param id - persisted session id to resolve.
109
+ * @param signal - optional cancellation for backend read work.
110
+ */
111
+ loadStored(id: SessionId, signal?: AbortSignal): Promise<StoredPrefix<TornMarker> | undefined>;
112
+ /**
113
+ * Read the current source-qualified revision for one stored session without
114
+ * loading its event log. Returns `undefined` when the identity is absent.
115
+ * @param id - persisted session id to observe.
116
+ * @param signal - optional cancellation for backend read work.
117
+ */
118
+ readStoredRevision(id: SessionId, signal?: AbortSignal): Promise<SessionPersistenceRevision | undefined>;
119
+ /**
120
+ * Optional seek-capable suffix read behind the service's `readFrom`: return
121
+ * the header plus the stored events with `seq >= fromSeq` without reading
122
+ * the whole log. A backend whose medium can address events by seq (SQLite)
123
+ * implements this so `readFrom` scales with the suffix; sequential backends
124
+ * omit it and the coordinator falls back to {@link loadStored} plus a
125
+ * forward skip. Non-mutating (no truncation, no closers). Validation of the
126
+ * region strictly below `fromSeq` is limited to seq contiguity — the
127
+ * service contract scopes this read to the suffix — unless that suffix
128
+ * contains a supported legacy shape whose normalization needs earlier
129
+ * message-identity facts, in which case the coordinator falls back
130
+ * to the complete stored prefix.
131
+ * Unknown-type refusal follows the same suffix scope: a seek-capable
132
+ * backend's `readFrom` checks only the returned suffix, while the
133
+ * sequential fallback parses the whole artifact and refuses on an unknown
134
+ * required event anywhere in it — over-refusal on the sequential side is
135
+ * accepted rather than widening the seek read.
136
+ * @param id - persisted session id to resolve.
137
+ * @param fromSeq - first event seq to include (non-negative safe integer,
138
+ * validated by the coordinator before this hook runs).
139
+ * @param signal - optional cancellation for backend read work.
140
+ */
141
+ loadStoredFrom?(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<StoredSuffix | undefined>;
142
+ /**
143
+ * Durably append a CONTIGUOUS batch, lazily materializing the session first
144
+ * when `!isMaterialized`. The materialize-write and the first event batch MUST
145
+ * commit ATOMICALLY (a crash between them must not leave a materialized-but-
146
+ * empty session). Returns once the batch is durable.
147
+ */
148
+ appendBatch(meta: SessionHeader, events: readonly SessionEvent[], isMaterialized: boolean): Promise<void>;
149
+ /**
150
+ * Make a crash repair durable: truncate the torn tail (iff
151
+ * `tornMarker !== undefined`) and append `closers` (iff any). NOT required to
152
+ * be atomic — a file backend may truncate-then-append in two fsync'd steps.
153
+ * Used by load (truncate + synthetic closers) and by live-adoption (truncate
154
+ * only, `closers = []`).
155
+ */
156
+ commitRepair(meta: SessionHeader, tornMarker: TornMarker | undefined, closers: readonly SessionEvent[]): Promise<void>;
157
+ /**
158
+ * List all stored (materialized) sessions' metadata.
159
+ * @param signal - optional cancellation for backend listing work.
160
+ */
161
+ list(signal?: AbortSignal): Promise<SessionHeader[]>;
162
+ /**
163
+ * Optional side-effect-free artifact locator, used to point refusal
164
+ * diagnostics ({@link SessionFormatUnsupportedError}) at the raw log.
165
+ * Backends without one artifact per session omit it or return `undefined`.
166
+ * @param meta - the header whose artifact is requested.
167
+ */
168
+ locate?(meta: SessionHeader): SessionLocation | undefined;
169
+ /**
170
+ * Optional lifecycle teardown (e.g. close a database handle). Awaited by the
171
+ * coordinator's dispose effect AFTER the quiescence drain. A stateless file
172
+ * backend omits it.
173
+ */
174
+ close?(): Promise<void>;
175
+ }
176
+ /**
177
+ * Owns the backend-agnostic session write-path orchestration. A backend
178
+ * constructs one (`new PersistenceCoordinator(ctx, this)`), implements
179
+ * {@link PersistenceBackend}, and delegates its write/read service methods to
180
+ * the matching coordinator methods.
181
+ *
182
+ * All per-id operations are serialized (a per-id promise chain) so concurrent
183
+ * flushes / a flush racing a load never interleave storage writes. The
184
+ * constructor installs the write-path listeners, per-session retirement, and
185
+ * the backend dispose effect.
186
+ *
187
+ * @typeParam TornMarker - the backend's opaque torn-tail repair token.
188
+ */
189
+ export declare class PersistenceCoordinator<TornMarker = unknown> {
190
+ private ctx;
191
+ private backend;
192
+ /** Backend bookkeeping keyed by session id (NOT the live Session object). */
193
+ private states;
194
+ /** Lifecycle and write-behind state keyed by the exact live Session. */
195
+ private live;
196
+ /** Exact disposed lifecycles whose buffered tail is still draining. */
197
+ private retirements;
198
+ /** Shared cold reads, unpublished reservations, and completed LRU entries. */
199
+ private readonly preparations;
200
+ /**
201
+ * Per-session serialization: every operation chains onto the prior one for the
202
+ * same id, so writes for one session never interleave. Keyed by session id.
203
+ */
204
+ private chains;
205
+ /** Resolved fixed write-batching window shared by per-session controllers. */
206
+ private readonly writeBatchMaxDelayMs;
207
+ constructor(ctx: Context, backend: PersistenceBackend<TornMarker>, options?: PersistenceCoordinatorOptions);
208
+ /**
209
+ * Register detached session metadata for lazy creation on the first append.
210
+ * @param meta - header to snapshot; duplicate tracked or persisted ids reject.
211
+ */
212
+ create(meta: SessionHeader): Promise<void>;
213
+ private createCore;
214
+ /**
215
+ * Durably persist a batch of events. Honors the append-only and contiguous-seq
216
+ * contracts; rejects non-JSON-serializable `event.data`.
217
+ * @param id - the session the batch belongs to.
218
+ * @param events - the contiguous batch to persist, in seq order; materialized
219
+ * as a detached lossless-JSON snapshot at call time.
220
+ */
221
+ append(id: SessionId, events: readonly SessionEvent[]): Promise<void>;
222
+ private appendCore;
223
+ /**
224
+ * Prepare and reserve the exact unpublished Session used by resume.
225
+ * Revision retries converge once the durable log remains unchanged for one
226
+ * read/check round trip; continuous external writers may delay completion.
227
+ * @param id - persisted session to prepare.
228
+ * @param signal - optional cancellation for reading and repair.
229
+ * @returns an owned preparation released after publication or rollback.
230
+ */
231
+ prepare(id: SessionId, signal?: AbortSignal): Promise<SessionPreparation>;
232
+ /**
233
+ * Commit recovery and return its immutable logical view without publication.
234
+ * Revision retries converge once the durable log remains unchanged for one
235
+ * read/check round trip; continuous external writers may delay completion.
236
+ * @param id - persisted session to load.
237
+ * @returns prepared header and balanced events.
238
+ */
239
+ load(id: SessionId): Promise<SessionInspection>;
240
+ /**
241
+ * Inspect a logical session without publishing it or committing recovery.
242
+ * A stale ready source is reloaded. A source already committing or reserved
243
+ * for resume remains exclusive, and inspection may borrow its immutable view.
244
+ * Revision retries converge once the log is stable for one read/check round
245
+ * trip; continuous external writers may delay completion.
246
+ * @param id - persisted session to inspect.
247
+ * @param signal - optional cancellation for preparation work.
248
+ * @returns immutable prepared metadata and events; a live view may have an open turn.
249
+ */
250
+ inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>;
251
+ /**
252
+ * Read the stored events from `fromSeq` onward, detached and non-mutating
253
+ * (the read-from-seq primitive behind the service's `readFrom`). Runs on
254
+ * the same per-id chain as writes; a backend with the seek-capable
255
+ * {@link PersistenceBackend.loadStoredFrom} hook reads only the suffix,
256
+ * every other backend reads its stored prefix and skips forward here.
257
+ * @param id - persisted session to read.
258
+ * @param fromSeq - first event seq to include; a non-negative safe integer.
259
+ * @param signal - optional cancellation for queued and backend read work.
260
+ * @returns stored header and the valid stored events with `seq >= fromSeq`.
261
+ */
262
+ readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{
263
+ meta: SessionHeader;
264
+ events: SessionEvent[];
265
+ }>;
266
+ private readFromCore;
267
+ /** Read one detached physical prefix without logical recovery or caching. */
268
+ private readStoredPrefix;
269
+ /** Read, repair in memory, validate, and freeze one cold source once. */
270
+ private prepareCore;
271
+ /** Commit one prepared repair and establish its ownerless durable cursor. */
272
+ private commitPrepared;
273
+ /** Whether one cached source still names the current durable log revision. */
274
+ private isPreparedSourceCurrent;
275
+ /** Return one durable immutable view of an already-live Session. */
276
+ private loadLiveSnapshot;
277
+ /** Borrow one immutable view from an already-live Session. */
278
+ private inspectLive;
279
+ /** Await one retiring lifecycle with caller cancellation. */
280
+ private waitForRetirement;
281
+ /**
282
+ * Run `op` after any in-flight operation for the same session id, so writes for
283
+ * one session never interleave. Errors do not poison the chain. NOTE: serialized
284
+ * public methods must NOT call each other (deadlock); they call the unserialized
285
+ * `*Core` helpers instead.
286
+ */
287
+ private serialize;
288
+ /** Build a state for a session discovered in storage but not yet in memory. */
289
+ private adopt;
290
+ private assertVersion;
291
+ /**
292
+ * Refuse a log containing an event type this build does not know, unless the
293
+ * writer marked the event ignorable: an unrecognized required event may
294
+ * change how the rest of the log must be interpreted, so silently skipping
295
+ * it would reconstruct a wrong session (the envelope contract on
296
+ * `SessionEvent.ignorable`). Runs on NORMALIZED events — after
297
+ * `snapshotStoredEvents`/`adoptStoredEvents` has upgraded the legacy shapes
298
+ * this build still reads and rejected the ones it does not, so those keep
299
+ * their specific diagnostics.
300
+ */
301
+ private assertEventsSupported;
302
+ /** Build a format refusal that points at the raw artifact when the backend has one. */
303
+ private unsupported;
304
+ /** Reject backend metadata that is not bound to the requested session id. */
305
+ private assertStoredId;
306
+ private installWritePath;
307
+ /** Start and observe one disposed session's final drain. */
308
+ private retire;
309
+ /** Drain and release state owned by one exact disposed Session lifecycle. */
310
+ private retireCore;
311
+ /** Return the one lifecycle controller for a live session, creating it if needed. */
312
+ private initFor;
313
+ /** Bind one exact prepared Session and persist only its unpublished suffix. */
314
+ private attachPrepared;
315
+ /**
316
+ * Whether a live session's `seed` reproduces the first `cursor` persisted
317
+ * events. A `cursor` of 0 (nothing persisted yet) trivially matches. Used when
318
+ * a live session claims ownerless state left by a prior `load()`/`create()`.
319
+ */
320
+ private seedMatchesPersisted;
321
+ /**
322
+ * On session/created: sync the backend's in-memory state to a live Session.
323
+ *
324
+ * Cases, by whether this backend tracks the id and whether an artifact exists:
325
+ * 1. Already tracked → no-op (or claim ownerless state if the seed matches,
326
+ * or reclaim a truly-abandoned id, else reject as a collision).
327
+ * 2. Not tracked, an artifact EXISTS at the same cwd and is a seq-aligned
328
+ * PREFIX of the live events → ADOPT it, persisting any live suffix.
329
+ * 3. Not tracked, an artifact EXISTS at another cwd or is NOT a prefix →
330
+ * REJECT (collision).
331
+ * 4. Not tracked and NO artifact → a genuinely new session: register meta
332
+ * (lazy) and persist its seed once.
333
+ */
334
+ private onCreated;
335
+ /**
336
+ * Adopt a stored prefix as a live session's history (HMR/reload): verify the
337
+ * seed covers the stored prefix, truncate any torn tail (NOT the open turn —
338
+ * the live Session is still the authority), bind ownership, and persist the
339
+ * live suffix that was ahead of the stored prefix.
340
+ */
341
+ private adoptLivePrefix;
342
+ private flush;
343
+ /** Build one package-private write controller around initialization and id serialization. */
344
+ private createWriteBehind;
345
+ /** Append one controller-owned prefix after filtering events initialization already stored. */
346
+ private appendLiveBatch;
347
+ }
348
+ //# sourceMappingURL=coordinator.d.ts.map
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Durable session-persistence Service Definition (`ctx.sessionPersistence`). Backends store
3
+ * {@link SessionEvent}s as the event-sourced log and carry non-replayable
4
+ * {@link SessionHeader} metadata separately.
5
+ * @module @hasna-internal/kai-session-persistence
6
+ */
7
+ import { Context, Service } from '@deepseek-ai/cordis';
8
+ import { SessionPreparation } from '@hasna-internal/kai-session';
9
+ import type { SessionEvent, SessionId, SessionHeader } from '@hasna-internal/kai-session';
10
+ import type { SessionPersistenceRevision } from './revision.ts';
11
+ export type { SessionHeader } from '@hasna-internal/kai-session';
12
+ export { SessionPersistenceRevision } from './revision.ts';
13
+ /** Lightweight immutable source identity returned without loading a full log. */
14
+ export interface SessionPersistenceSnapshot {
15
+ /** Detached metadata for one materialized session. */
16
+ header: SessionHeader;
17
+ /** Opaque source-qualified token that changes whenever this stored log changes. */
18
+ revision: SessionPersistenceRevision;
19
+ }
20
+ /** Immutable logical session prepared from persistence or a live owner. */
21
+ export interface SessionInspection {
22
+ /** Validated immutable session metadata. */
23
+ readonly meta: SessionHeader;
24
+ /** Validated contiguous logical event log. */
25
+ readonly events: readonly SessionEvent[];
26
+ }
27
+ /** A backend's own raw artifact text for one session, verbatim. */
28
+ export interface SessionRawArtifact {
29
+ /** The session header parsed from the artifact's own first line. */
30
+ readonly meta: SessionHeader;
31
+ /** The artifact's base filename on disk, without any physical encoding suffix. */
32
+ readonly filename: string;
33
+ /** The artifact's full text content, decoded from the backend's physical encoding. */
34
+ readonly content: string;
35
+ }
36
+ export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionFormatUnsupportedError, SessionPersistenceCorruptionError, sessionFormatVersionRefusal, } from './coordinator.ts';
37
+ export type { PersistenceBackend, PersistenceCoordinatorOptions, StoredPrefix, StoredSuffix, } from './coordinator.ts';
38
+ declare module '@deepseek-ai/cordis' {
39
+ interface Context {
40
+ sessionPersistence: SessionPersistence;
41
+ }
42
+ }
43
+ /**
44
+ * A backend-resolved, per-session local artifact location. The path is an
45
+ * absolute target path and can name an artifact that has not materialized yet.
46
+ * Consumers must treat it as a location hint, never as an authorization token.
47
+ */
48
+ export interface SessionLocation {
49
+ /** Backend-specific artifact kind, for example `jsonl`. */
50
+ readonly kind: string;
51
+ /** Absolute path to this session's backend-owned artifact. */
52
+ readonly path: string;
53
+ }
54
+ /**
55
+ * Durable append-only session storage. Implementations preserve contiguous,
56
+ * losslessly JSON-serializable events; {@link append} resolves only after
57
+ * durability, and {@link load} balances a complete interrupted tail without
58
+ * rewriting committed events.
59
+ */
60
+ export declare abstract class SessionPersistence extends Service {
61
+ constructor(ctx: Context);
62
+ /**
63
+ * Resolve this backend's independent local artifact for a session without
64
+ * reading, creating, flushing, or otherwise materializing it. Backends such
65
+ * as SQLite that do not own one artifact per session return `undefined`.
66
+ * @param meta - the immutable session header whose artifact is requested.
67
+ * @returns the backend-specific absolute location, when one exists.
68
+ */
69
+ abstract locate(meta: SessionHeader): SessionLocation | undefined;
70
+ /**
71
+ * Whether this backend exposes one verbatim raw artifact per session.
72
+ * A backend that declares `true` must override {@link readRaw}.
73
+ */
74
+ abstract readonly supportsRawArtifacts: boolean;
75
+ /**
76
+ * Read a session's backend-owned artifact text verbatim — the exact durable
77
+ * bytes the backend wrote (decoded from its physical encoding, e.g. a
78
+ * decompressed JSONL). The returned `content` is the raw text, not a
79
+ * reconstruction from parsed events, so it preserves backend-specific
80
+ * serialization (chunk packing, key order, line breaks). Callers first test
81
+ * {@link supportsRawArtifacts}; `undefined` then means only that the requested
82
+ * session has no materialized artifact.
83
+ * @param _id - the persisted session to read (unused by the default: no
84
+ * per-session artifact).
85
+ * @param signal - optional cancellation for backend read work.
86
+ * @returns the raw artifact plus its parsed header, or `undefined` when the
87
+ * session is absent.
88
+ * @throws when this backend does not expose per-session raw artifacts.
89
+ */
90
+ readRaw(_id: SessionId, signal?: AbortSignal): Promise<SessionRawArtifact | undefined>;
91
+ /**
92
+ * Register a new session's metadata. A backend MAY defer the physical write
93
+ * until the first {@link append} (lazy materialization), in which case a
94
+ * created-but-never-appended session is absent from {@link list}
95
+ * — abandoned sessions leave nothing behind.
96
+ * @param meta - the immutable header (id, version, cwd, lineage) to record.
97
+ */
98
+ abstract create(meta: SessionHeader): Promise<void>;
99
+ /**
100
+ * Durably persist a batch of events. Honors the append-only and contiguous-
101
+ * seq contracts: the first event's `seq` MUST equal the stored next-seq
102
+ * (after `load` has durably closed any interrupted turn). Rejects non-JSON-
103
+ * serializable `event.data` with an error naming the offending event type.
104
+ * @param id - the session the batch belongs to.
105
+ * @param events - the contiguous batch to persist, in seq order.
106
+ */
107
+ abstract append(id: SessionId, events: readonly SessionEvent[]): Promise<void>;
108
+ /**
109
+ * Prepare the exact unpublished Session used by resume. Implementations may
110
+ * reuse object graphs retained by an earlier {@link inspect} after confirming
111
+ * their durable revision is still current; disposal releases an unpublished
112
+ * reservation. Revision retries require the durable log to remain unchanged
113
+ * for one read/check round trip; continuous external writers may delay completion.
114
+ * @param id - persisted session to prepare.
115
+ * @param signal - optional cancellation for preparation work.
116
+ * @returns one owned unpublished Session preparation.
117
+ */
118
+ prepare(id: SessionId, signal?: AbortSignal): Promise<SessionPreparation>;
119
+ /**
120
+ * Load an immutable balanced logical view and commit any required cold
121
+ * recovery. A complete interrupted final turn is preserved and durably
122
+ * closed with missing tool errors plus any open step and turn boundaries;
123
+ * only a torn final record is discarded. Unknown versions and corruption in
124
+ * the committed prefix reject. Implementations MUST NOT crash-repair an
125
+ * identity still bound to a live Session: a balanced live log may return as a
126
+ * durable snapshot, while an open live turn rejects. Returned values may be
127
+ * shared with immutable live or prepared state and must not be mutated.
128
+ * Revision-based implementations may wait for one stable read/check round trip.
129
+ * @param id - the persisted session to reload.
130
+ * @returns the header and a log ending on a balanced `turn/end`.
131
+ */
132
+ abstract load(id: SessionId): Promise<SessionInspection>;
133
+ /**
134
+ * Inspect an immutable logical session without committing recovery or
135
+ * publishing it. A cold complete interrupted turn receives synthetic closers
136
+ * in memory and a torn physical tail remains untouched. An already-live
137
+ * Session instead yields its current immutable snapshot, which may contain an
138
+ * open turn and its `session/end-seed` boundary. Coordinator-backed
139
+ * implementations retain the exact cold unpublished Session for bounded
140
+ * reuse by a later {@link prepare}. A stale ready source is reloaded; a source
141
+ * already committing or reserved for resume remains exclusive, and inspection
142
+ * may borrow its immutable view. Callers borrow only the immutable header and
143
+ * log. Continuous external writers may delay revision convergence.
144
+ * @param id - the persisted session to inspect.
145
+ * @param signal - optional cancellation for queued and backend read work.
146
+ * @returns the validated header and current logical event log.
147
+ */
148
+ abstract inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>;
149
+ /**
150
+ * Read the stored events from `fromSeq` onward — the read-from-seq
151
+ * primitive for read models that resume from a watermark (e.g. a persisted
152
+ * projection cache folding only the tail past its checkpoint). Unlike
153
+ * {@link inspect}, it is a detached physical suffix read: no preparation
154
+ * cache, torn-tail truncation, synthetic closers, or coordinator-state
155
+ * publication. Only events from the valid contiguous stored prefix are
156
+ * returned, so a torn fragment never reaches the caller. `fromSeq` at or
157
+ * beyond the stored prefix returns an empty event list (never an error).
158
+ * Backends whose medium can seek by seq
159
+ * (SQLite) read only the suffix; sequential media (JSONL, both encodings)
160
+ * still parse the whole artifact and skip forward — the primitive bounds
161
+ * what is RETURNED and refolded, not every backend's physical read.
162
+ * @param id - the persisted session to read.
163
+ * @param fromSeq - first event seq to include; a non-negative safe integer.
164
+ * @param signal - optional cancellation for queued and backend read work.
165
+ * @returns the header and the stored events with `seq >= fromSeq`.
166
+ */
167
+ abstract readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{
168
+ meta: SessionHeader;
169
+ events: SessionEvent[];
170
+ }>;
171
+ /**
172
+ * Lightweight listing from metadata, without a full-log parse.
173
+ * @param signal - optional cancellation for backend listing work.
174
+ * @returns one header per materialized session.
175
+ */
176
+ abstract list(signal?: AbortSignal): Promise<SessionHeader[]>;
177
+ /**
178
+ * List materialized sessions with cheap per-log change tokens.
179
+ *
180
+ * Repeated observations of an unchanged log return the same revision. A
181
+ * successful mutating {@link load} repair changes the next listed revision.
182
+ * Revisions also distinguish independently backed stores so backend-local
183
+ * counters cannot compare equal across different persistence sources.
184
+ * @param signal - optional cancellation for backend snapshot-listing work.
185
+ * @returns one header and opaque revision per materialized session without loading full logs.
186
+ */
187
+ abstract listSnapshots(signal?: AbortSignal): Promise<SessionPersistenceSnapshot[]>;
188
+ }
189
+ export default SessionPersistence;
190
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@hasna-internal/kai-session-persistence`.
3
+ * @module @hasna-internal/kai-session-persistence/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "session-persistence-invariant";
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map