@x1a0f3n9/dsh-session-persistence 0.1.2-alpha.6

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