@crazx/dsh-session-persistence 0.1.0-rc.7.zw.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 `@deepseek-ai/dsh-session-persistence`.
4
+ * @module @deepseek-ai/dsh-session-persistence/invariant
5
+ */
6
+ const PACKAGE_NAME = "@deepseek-ai/dsh-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,359 @@
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 @deepseek-ai/dsh-session-persistence/coordinator
6
+ */
7
+ import { Context } from '@deepseek-ai/cordis';
8
+ import { SessionPreparation } from '@deepseek-ai/dsh-session';
9
+ import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-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
+ * Besides validating retained preparations, the coordinator compares it
116
+ * before and after every append so a log advanced by an external writer (a
117
+ * second harness process sharing the sessions root) rejects loudly.
118
+ * @param id - persisted session id to observe.
119
+ * @param signal - optional cancellation for backend read work.
120
+ */
121
+ readStoredRevision(id: SessionId, signal?: AbortSignal): Promise<SessionPersistenceRevision | undefined>;
122
+ /**
123
+ * Optional seek-capable suffix read behind the service's `readFrom`: return
124
+ * the header plus the stored events with `seq >= fromSeq` without reading
125
+ * the whole log. A backend whose medium can address events by seq (SQLite)
126
+ * implements this so `readFrom` scales with the suffix; sequential backends
127
+ * omit it and the coordinator falls back to {@link loadStored} plus a
128
+ * forward skip. Non-mutating (no truncation, no closers). Validation of the
129
+ * region strictly below `fromSeq` is limited to seq contiguity — the
130
+ * service contract scopes this read to the suffix — unless that suffix
131
+ * contains a supported legacy shape whose normalization needs earlier
132
+ * message-identity facts, in which case the coordinator falls back
133
+ * to the complete stored prefix.
134
+ * Unknown-type refusal follows the same suffix scope: a seek-capable
135
+ * backend's `readFrom` checks only the returned suffix, while the
136
+ * sequential fallback parses the whole artifact and refuses on an unknown
137
+ * required event anywhere in it — over-refusal on the sequential side is
138
+ * accepted rather than widening the seek read.
139
+ * @param id - persisted session id to resolve.
140
+ * @param fromSeq - first event seq to include (non-negative safe integer,
141
+ * validated by the coordinator before this hook runs).
142
+ * @param signal - optional cancellation for backend read work.
143
+ */
144
+ loadStoredFrom?(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<StoredSuffix | undefined>;
145
+ /**
146
+ * Durably append a CONTIGUOUS batch, lazily materializing the session first
147
+ * when `!isMaterialized`. The materialize-write and the first event batch MUST
148
+ * commit ATOMICALLY (a crash between them must not leave a materialized-but-
149
+ * empty session). Returns once the batch is durable. A rejection must leave
150
+ * the stored log unchanged (roll partial work back): the coordinator keeps
151
+ * its cursor across the failure and retries the same batch.
152
+ */
153
+ appendBatch(meta: SessionHeader, events: readonly SessionEvent[], isMaterialized: boolean): Promise<void>;
154
+ /**
155
+ * Make a crash repair durable: truncate the torn tail (iff
156
+ * `tornMarker !== undefined`) and append `closers` (iff any). NOT required to
157
+ * be atomic — a file backend may truncate-then-append in two fsync'd steps.
158
+ * Used by load (truncate + synthetic closers) and by live-adoption (truncate
159
+ * only, `closers = []`).
160
+ */
161
+ commitRepair(meta: SessionHeader, tornMarker: TornMarker | undefined, closers: readonly SessionEvent[]): Promise<void>;
162
+ /**
163
+ * List all stored (materialized) sessions' metadata.
164
+ * @param signal - optional cancellation for backend listing work.
165
+ */
166
+ list(signal?: AbortSignal): Promise<SessionHeader[]>;
167
+ /**
168
+ * Optional side-effect-free artifact locator, used to point refusal
169
+ * diagnostics ({@link SessionFormatUnsupportedError}) at the raw log.
170
+ * Backends without one artifact per session omit it or return `undefined`.
171
+ * @param meta - the header whose artifact is requested.
172
+ */
173
+ locate?(meta: SessionHeader): SessionLocation | undefined;
174
+ /**
175
+ * Optional lifecycle teardown (e.g. close a database handle). Awaited by the
176
+ * coordinator's dispose effect AFTER the quiescence drain. A stateless file
177
+ * backend omits it.
178
+ */
179
+ close?(): Promise<void>;
180
+ }
181
+ /**
182
+ * Owns the backend-agnostic session write-path orchestration. A backend
183
+ * constructs one (`new PersistenceCoordinator(ctx, this)`), implements
184
+ * {@link PersistenceBackend}, and delegates its write/read service methods to
185
+ * the matching coordinator methods.
186
+ *
187
+ * All per-id operations are serialized (a per-id promise chain) so concurrent
188
+ * flushes / a flush racing a load never interleave storage writes. The
189
+ * constructor installs the write-path listeners, per-session retirement, and
190
+ * the backend dispose effect.
191
+ *
192
+ * @typeParam TornMarker - the backend's opaque torn-tail repair token.
193
+ */
194
+ export declare class PersistenceCoordinator<TornMarker = unknown> {
195
+ private ctx;
196
+ private backend;
197
+ /** Backend bookkeeping keyed by session id (NOT the live Session object). */
198
+ private states;
199
+ /** Lifecycle and write-behind state keyed by the exact live Session. */
200
+ private live;
201
+ /** Exact disposed lifecycles whose buffered tail is still draining. */
202
+ private retirements;
203
+ /** Shared cold reads, unpublished reservations, and completed LRU entries. */
204
+ private readonly preparations;
205
+ /**
206
+ * Per-session serialization: every operation chains onto the prior one for the
207
+ * same id, so writes for one session never interleave. Keyed by session id.
208
+ */
209
+ private chains;
210
+ /** Resolved fixed write-batching window shared by per-session controllers. */
211
+ private readonly writeBatchMaxDelayMs;
212
+ constructor(ctx: Context, backend: PersistenceBackend<TornMarker>, options?: PersistenceCoordinatorOptions);
213
+ /**
214
+ * Register detached session metadata for lazy creation on the first append.
215
+ * @param meta - header to snapshot; duplicate tracked or persisted ids reject.
216
+ */
217
+ create(meta: SessionHeader): Promise<void>;
218
+ private createCore;
219
+ /**
220
+ * Durably persist a batch of events. Honors the append-only and contiguous-seq
221
+ * contracts; rejects non-JSON-serializable `event.data`.
222
+ * @param id - the session the batch belongs to.
223
+ * @param events - the contiguous batch to persist, in seq order; materialized
224
+ * as a detached lossless-JSON snapshot at call time.
225
+ */
226
+ append(id: SessionId, events: readonly SessionEvent[]): Promise<void>;
227
+ private appendCore;
228
+ /**
229
+ * Re-read one state's durable-revision baseline. An absent stored identity
230
+ * degrades the append-time guard to its in-memory cursor until the next
231
+ * confirmed read.
232
+ */
233
+ private refreshRevision;
234
+ /**
235
+ * Prepare and reserve the exact unpublished Session used by resume.
236
+ * Revision retries converge once the durable log remains unchanged for one
237
+ * read/check round trip; continuous external writers may delay completion.
238
+ * @param id - persisted session to prepare.
239
+ * @param signal - optional cancellation for reading and repair.
240
+ * @returns an owned preparation released after publication or rollback.
241
+ */
242
+ prepare(id: SessionId, signal?: AbortSignal): Promise<SessionPreparation>;
243
+ /**
244
+ * Commit recovery and return its immutable logical view without publication.
245
+ * Revision retries converge once the durable log remains unchanged for one
246
+ * read/check round trip; continuous external writers may delay completion.
247
+ * @param id - persisted session to load.
248
+ * @returns prepared header and balanced events.
249
+ */
250
+ load(id: SessionId): Promise<SessionInspection>;
251
+ /**
252
+ * Inspect a logical session without publishing it or committing recovery.
253
+ * A stale ready source is reloaded. A source already committing or reserved
254
+ * for resume remains exclusive, and inspection may borrow its immutable view.
255
+ * Revision retries converge once the log is stable for one read/check round
256
+ * trip; continuous external writers may delay completion.
257
+ * @param id - persisted session to inspect.
258
+ * @param signal - optional cancellation for preparation work.
259
+ * @returns immutable prepared metadata and events; a live view may have an open turn.
260
+ */
261
+ inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>;
262
+ /**
263
+ * Read the stored events from `fromSeq` onward, detached and non-mutating
264
+ * (the read-from-seq primitive behind the service's `readFrom`). Runs on
265
+ * the same per-id chain as writes; a backend with the seek-capable
266
+ * {@link PersistenceBackend.loadStoredFrom} hook reads only the suffix,
267
+ * every other backend reads its stored prefix and skips forward here.
268
+ * @param id - persisted session to read.
269
+ * @param fromSeq - first event seq to include; a non-negative safe integer.
270
+ * @param signal - optional cancellation for queued and backend read work.
271
+ * @returns stored header and the valid stored events with `seq >= fromSeq`.
272
+ */
273
+ readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{
274
+ meta: SessionHeader;
275
+ events: SessionEvent[];
276
+ }>;
277
+ private readFromCore;
278
+ /** Read one detached physical prefix without logical recovery or caching. */
279
+ private readStoredPrefix;
280
+ /** Read, repair in memory, validate, and freeze one cold source once. */
281
+ private prepareCore;
282
+ /** Commit one prepared repair and establish its ownerless durable cursor. */
283
+ private commitPrepared;
284
+ /** Whether one cached source still names the current durable log revision. */
285
+ private isPreparedSourceCurrent;
286
+ /** Return one durable immutable view of an already-live Session. */
287
+ private loadLiveSnapshot;
288
+ /** Borrow one immutable view from an already-live Session. */
289
+ private inspectLive;
290
+ /** Await one retiring lifecycle with caller cancellation. */
291
+ private waitForRetirement;
292
+ /**
293
+ * Run `op` after any in-flight operation for the same session id, so writes for
294
+ * one session never interleave. Errors do not poison the chain. NOTE: serialized
295
+ * public methods must NOT call each other (deadlock); they call the unserialized
296
+ * `*Core` helpers instead.
297
+ */
298
+ private serialize;
299
+ /** Build a state for a session discovered in storage but not yet in memory. */
300
+ private adopt;
301
+ private assertVersion;
302
+ /**
303
+ * Refuse a log containing an event type this build does not know, unless the
304
+ * writer marked the event ignorable: an unrecognized required event may
305
+ * change how the rest of the log must be interpreted, so silently skipping
306
+ * it would reconstruct a wrong session (the envelope contract on
307
+ * `SessionEvent.ignorable`). Runs on NORMALIZED events — after
308
+ * `snapshotStoredEvents`/`adoptStoredEvents` has upgraded the legacy shapes
309
+ * this build still reads and rejected the ones it does not, so those keep
310
+ * their specific diagnostics.
311
+ */
312
+ private assertEventsSupported;
313
+ /** Build a format refusal that points at the raw artifact when the backend has one. */
314
+ private unsupported;
315
+ /** Reject backend metadata that is not bound to the requested session id. */
316
+ private assertStoredId;
317
+ private installWritePath;
318
+ /** Start and observe one disposed session's final drain. */
319
+ private retire;
320
+ /** Drain and release state owned by one exact disposed Session lifecycle. */
321
+ private retireCore;
322
+ /** Return the one lifecycle controller for a live session, creating it if needed. */
323
+ private initFor;
324
+ /** Bind one exact prepared Session and persist only its unpublished suffix. */
325
+ private attachPrepared;
326
+ /**
327
+ * Whether a live session's `seed` reproduces the first `cursor` persisted
328
+ * events. A `cursor` of 0 (nothing persisted yet) trivially matches. Used when
329
+ * a live session claims ownerless state left by a prior `load()`/`create()`.
330
+ */
331
+ private seedMatchesPersisted;
332
+ /**
333
+ * On session/created: sync the backend's in-memory state to a live Session.
334
+ *
335
+ * Cases, by whether this backend tracks the id and whether an artifact exists:
336
+ * 1. Already tracked → no-op (or claim ownerless state if the seed matches,
337
+ * or reclaim a truly-abandoned id, else reject as a collision).
338
+ * 2. Not tracked, an artifact EXISTS at the same cwd and is a seq-aligned
339
+ * PREFIX of the live events → ADOPT it, persisting any live suffix.
340
+ * 3. Not tracked, an artifact EXISTS at another cwd or is NOT a prefix →
341
+ * REJECT (collision).
342
+ * 4. Not tracked and NO artifact → a genuinely new session: register meta
343
+ * (lazy) and persist its seed once.
344
+ */
345
+ private onCreated;
346
+ /**
347
+ * Adopt a stored prefix as a live session's history (HMR/reload): verify the
348
+ * seed covers the stored prefix, truncate any torn tail (NOT the open turn —
349
+ * the live Session is still the authority), bind ownership, and persist the
350
+ * live suffix that was ahead of the stored prefix.
351
+ */
352
+ private adoptLivePrefix;
353
+ private flush;
354
+ /** Build one package-private write controller around initialization and id serialization. */
355
+ private createWriteBehind;
356
+ /** Append one controller-owned prefix after filtering events initialization already stored. */
357
+ private appendLiveBatch;
358
+ }
359
+ //# sourceMappingURL=coordinator.d.ts.map
@@ -0,0 +1,193 @@
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 @deepseek-ai/dsh-session-persistence
6
+ */
7
+ import { Context, Service } from '@deepseek-ai/cordis';
8
+ import { SessionPreparation } from '@deepseek-ai/dsh-session';
9
+ import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session';
10
+ import type { SessionPersistenceRevision } from './revision.ts';
11
+ export type { SessionHeader } from '@deepseek-ai/dsh-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
+ * Coordinator-backed implementations also reject when the durable log
105
+ * advanced since this process last observed it — another harness process
106
+ * sharing the sessions root — rather than interleave duplicate seqs.
107
+ * @param id - the session the batch belongs to.
108
+ * @param events - the contiguous batch to persist, in seq order.
109
+ */
110
+ abstract append(id: SessionId, events: readonly SessionEvent[]): Promise<void>;
111
+ /**
112
+ * Prepare the exact unpublished Session used by resume. Implementations may
113
+ * reuse object graphs retained by an earlier {@link inspect} after confirming
114
+ * their durable revision is still current; disposal releases an unpublished
115
+ * reservation. Revision retries require the durable log to remain unchanged
116
+ * for one read/check round trip; continuous external writers may delay completion.
117
+ * @param id - persisted session to prepare.
118
+ * @param signal - optional cancellation for preparation work.
119
+ * @returns one owned unpublished Session preparation.
120
+ */
121
+ prepare(id: SessionId, signal?: AbortSignal): Promise<SessionPreparation>;
122
+ /**
123
+ * Load an immutable balanced logical view and commit any required cold
124
+ * recovery. A complete interrupted final turn is preserved and durably
125
+ * closed with missing tool errors plus any open step and turn boundaries;
126
+ * only a torn final record is discarded. Unknown versions and corruption in
127
+ * the committed prefix reject. Implementations MUST NOT crash-repair an
128
+ * identity still bound to a live Session: a balanced live log may return as a
129
+ * durable snapshot, while an open live turn rejects. Returned values may be
130
+ * shared with immutable live or prepared state and must not be mutated.
131
+ * Revision-based implementations may wait for one stable read/check round trip.
132
+ * @param id - the persisted session to reload.
133
+ * @returns the header and a log ending on a balanced `turn/end`.
134
+ */
135
+ abstract load(id: SessionId): Promise<SessionInspection>;
136
+ /**
137
+ * Inspect an immutable logical session without committing recovery or
138
+ * publishing it. A cold complete interrupted turn receives synthetic closers
139
+ * in memory and a torn physical tail remains untouched. An already-live
140
+ * Session instead yields its current immutable snapshot, which may contain an
141
+ * open turn and its `session/end-seed` boundary. Coordinator-backed
142
+ * implementations retain the exact cold unpublished Session for bounded
143
+ * reuse by a later {@link prepare}. A stale ready source is reloaded; a source
144
+ * already committing or reserved for resume remains exclusive, and inspection
145
+ * may borrow its immutable view. Callers borrow only the immutable header and
146
+ * log. Continuous external writers may delay revision convergence.
147
+ * @param id - the persisted session to inspect.
148
+ * @param signal - optional cancellation for queued and backend read work.
149
+ * @returns the validated header and current logical event log.
150
+ */
151
+ abstract inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>;
152
+ /**
153
+ * Read the stored events from `fromSeq` onward — the read-from-seq
154
+ * primitive for read models that resume from a watermark (e.g. a persisted
155
+ * projection cache folding only the tail past its checkpoint). Unlike
156
+ * {@link inspect}, it is a detached physical suffix read: no preparation
157
+ * cache, torn-tail truncation, synthetic closers, or coordinator-state
158
+ * publication. Only events from the valid contiguous stored prefix are
159
+ * returned, so a torn fragment never reaches the caller. `fromSeq` at or
160
+ * beyond the stored prefix returns an empty event list (never an error).
161
+ * Backends whose medium can seek by seq
162
+ * (SQLite) read only the suffix; sequential media (JSONL, both encodings)
163
+ * still parse the whole artifact and skip forward — the primitive bounds
164
+ * what is RETURNED and refolded, not every backend's physical read.
165
+ * @param id - the persisted session to read.
166
+ * @param fromSeq - first event seq to include; a non-negative safe integer.
167
+ * @param signal - optional cancellation for queued and backend read work.
168
+ * @returns the header and the stored events with `seq >= fromSeq`.
169
+ */
170
+ abstract readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{
171
+ meta: SessionHeader;
172
+ events: SessionEvent[];
173
+ }>;
174
+ /**
175
+ * Lightweight listing from metadata, without a full-log parse.
176
+ * @param signal - optional cancellation for backend listing work.
177
+ * @returns one header per materialized session.
178
+ */
179
+ abstract list(signal?: AbortSignal): Promise<SessionHeader[]>;
180
+ /**
181
+ * List materialized sessions with cheap per-log change tokens.
182
+ *
183
+ * Repeated observations of an unchanged log return the same revision. A
184
+ * successful mutating {@link load} repair changes the next listed revision.
185
+ * Revisions also distinguish independently backed stores so backend-local
186
+ * counters cannot compare equal across different persistence sources.
187
+ * @param signal - optional cancellation for backend snapshot-listing work.
188
+ * @returns one header and opaque revision per materialized session without loading full logs.
189
+ */
190
+ abstract listSnapshots(signal?: AbortSignal): Promise<SessionPersistenceSnapshot[]>;
191
+ }
192
+ export default SessionPersistence;
193
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@deepseek-ai/dsh-session-persistence`.
3
+ * @module @deepseek-ai/dsh-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