@deepseek-ai/dsh-session-persistence-jsonl 0.2.2-rc.5 → 0.2.3-alpha.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-session-persistence-jsonl",
3
3
  "description": "JSONL durable session persistence backend for the DeepSeek Harness",
4
- "version": "0.2.2-rc.5",
4
+ "version": "0.2.3-alpha.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -33,24 +33,25 @@
33
33
  ],
34
34
  "license": "MIT",
35
35
  "peerDependencies": {
36
- "@deepseek-ai/dsh-session": "0.2.2-rc.5",
37
- "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.5",
38
- "@deepseek-ai/cordis": "~4.1.0"
36
+ "@deepseek-ai/dsh-session": "0.2.3-alpha.2",
37
+ "@deepseek-ai/dsh-session-persistence": "0.2.3-alpha.2",
38
+ "@deepseek-ai/cordis": "~4.2.0-alpha.1"
39
39
  },
40
40
  "dependencies": {
41
- "@deepseek-ai/dsh-llm": "0.2.2-rc.5",
42
- "@deepseek-ai/dsh-session-format": "0.2.2-rc.5",
43
- "@deepseek-ai/dsh-session-format-catalog": "0.2.2-rc.5",
44
- "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.2-rc.5",
41
+ "@deepseek-ai/dsh-brand": "0.2.3-alpha.2",
42
+ "@deepseek-ai/dsh-llm": "0.2.3-alpha.2",
43
+ "@deepseek-ai/dsh-session-format": "0.2.3-alpha.2",
44
+ "@deepseek-ai/dsh-session-format-catalog": "0.2.3-alpha.2",
45
+ "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.3-alpha.2",
45
46
  "@deepseek-ai/node-addon-system": "~0.1.2",
46
- "@deepseek-ai/schemastery": "~3.19.0",
47
+ "@deepseek-ai/schemastery": "~3.20.0-alpha.1",
47
48
  "koffi": "3.1.1",
48
49
  "p-limit": "7.3.3"
49
50
  },
50
51
  "devDependencies": {
51
- "@deepseek-ai/dsh-session": "0.2.2-rc.5",
52
- "@deepseek-ai/dsh-session-format-v0-to-v1": "0.2.2-rc.5",
53
- "@deepseek-ai/dsh-session-persistence": "0.2.2-rc.5",
54
- "@deepseek-ai/cordis": "~4.1.0"
52
+ "@deepseek-ai/dsh-session": "0.2.3-alpha.2",
53
+ "@deepseek-ai/dsh-session-format-v0-to-v1": "0.2.3-alpha.2",
54
+ "@deepseek-ai/dsh-session-persistence": "0.2.3-alpha.2",
55
+ "@deepseek-ai/cordis": "~4.2.0-alpha.1"
55
56
  }
56
57
  }
package/src/generation.ts CHANGED
@@ -25,7 +25,7 @@ import { pipeline, Readable } from 'node:stream'
25
25
  import { scheduler } from 'node:timers/promises'
26
26
  import { isDeepStrictEqual } from 'node:util'
27
27
  import { constants, createZstdCompress } from 'node:zlib'
28
- import { Session } from '@deepseek-ai/dsh-session'
28
+ import { validateSessionLog } from '@deepseek-ai/dsh-session'
29
29
  import type { SessionEvent } from '@deepseek-ai/dsh-session'
30
30
  import { BlockAssembler, expandAssistantStream } from '@deepseek-ai/dsh-llm'
31
31
  import { SessionFormatError } from '@deepseek-ai/dsh-session-format'
@@ -534,10 +534,9 @@ async function verifyCurrentGeneration(
534
534
  `current session generation contains ${generation.events.length} events, expected ${expectedEventCount}`,
535
535
  )
536
536
  }
537
- Session.fromRestore(
538
- generation.meta.id,
539
- generation.events,
537
+ validateSessionLog(
540
538
  generation.meta,
539
+ generation.events,
541
540
  generation.inheritedEventCount,
542
541
  'detached',
543
542
  currentSessionMessageProjections,
@@ -809,7 +808,7 @@ async function removeCommittedTemporary(
809
808
  ): Promise<void> {
810
809
  try {
811
810
  await internals.fs.rm(path)
812
- } catch {
811
+ } catch (_redundantStageRemoveFailed) {
813
812
  // The validated target owns the committed bytes; a redundant link cannot turn success into failure.
814
813
  }
815
814
  }
package/src/index.ts CHANGED
@@ -21,7 +21,7 @@ import { scheduler } from 'node:timers/promises'
21
21
  import { createHash, randomBytes } from 'node:crypto'
22
22
  import pLimit, { type LimitFunction } from 'p-limit'
23
23
  import {
24
- SessionPersistence, SessionPersistenceRevision, SessionFormatUnsupportedError,
24
+ SessionPersistence, SessionFormatUnsupportedError,
25
25
  SessionPersistenceCorruptionError,
26
26
  SessionAlreadyExistsError, SessionPersistenceNotFoundError,
27
27
  assertStoredId, materializeCreateHeader, sessionFormatVersionRefusal, validateStoredEvents,
@@ -34,7 +34,8 @@ import {
34
34
  } from '@deepseek-ai/dsh-session-persistence'
35
35
  import { JsonlBackendTracker, JsonlSessionHandle, type StorageHandleState } from './storage.ts'
36
36
  import { SessionWriteLease } from './lease.ts'
37
- import { SESSION_FORMAT_VERSION, SessionId as makeSessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
37
+ import { brandString } from '@deepseek-ai/dsh-brand'
38
+ import { SESSION_FORMAT_VERSION, SessionLogOffset } from '@deepseek-ai/dsh-session'
38
39
  import type { SessionEvent, SessionId, SessionHeader, SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
39
40
  import {
40
41
  assertNoRetiredHeaderFields, encodeSegment, eventLines, generationLogFilename, generationLogPath, logPath, logSuffix,
@@ -57,6 +58,18 @@ import {
57
58
  type PreparedJsonlMigration,
58
59
  } from './generation.ts'
59
60
 
61
+ /** Logical JSONL history retained until its destination commits under write ownership. */
62
+ interface LegacySessionSnapshot {
63
+ readonly header: SessionHeader
64
+ readonly inheritedEventCount: SessionLogOffsetType
65
+ readonly events: readonly SessionEvent[]
66
+ }
67
+
68
+ /** Prepared legacy history whose related sources are checked before destination publication. */
69
+ interface PreparedLegacySession {
70
+ commit(publish: (snapshot: LegacySessionSnapshot) => Promise<void>): Promise<void>
71
+ }
72
+
60
73
  export type { JsonlCompression } from './format.ts'
61
74
 
62
75
  /**
@@ -186,6 +199,13 @@ interface ResolvedJsonlGeneration {
186
199
  readonly currentPath: string
187
200
  }
188
201
 
202
+ /** One listed generation header and the file revision it was read from. */
203
+ interface ListedHeader {
204
+ readonly revision: PersistenceRevision
205
+ /** `undefined` when the log is unreadable as a listed Session. */
206
+ readonly metadata: GenerationHeader | undefined
207
+ }
208
+
189
209
  /** One backend-owned historical preparation shared by its current callers. */
190
210
  interface MigrationPreparation {
191
211
  readonly sourcePath: string
@@ -198,7 +218,7 @@ interface MigrationPreparation {
198
218
 
199
219
  /** Build the stat-derived best-effort change token shared by full and lightweight reads. */
200
220
  function fileRevision(identity: JsonlPhysicalIdentity): PersistenceRevision {
201
- return SessionPersistenceRevision([
221
+ return brandString<PersistenceRevision>([
202
222
  identity.dev,
203
223
  identity.ino,
204
224
  identity.size,
@@ -207,6 +227,20 @@ function fileRevision(identity: JsonlPhysicalIdentity): PersistenceRevision {
207
227
  ].join(':'))
208
228
  }
209
229
 
230
+ /**
231
+ * Fingerprint a generation corpus independently of listing order.
232
+ * @param revisions - each generation path with its file revision or `missing`.
233
+ * @returns the hex digest.
234
+ */
235
+ function corpusDigest(revisions: ReadonlyArray<readonly [string, string]>): string {
236
+ const hash = createHash('sha256')
237
+ const byPath = new Map(revisions)
238
+ for (const path of [...byPath.keys()].sort()) {
239
+ hash.update(JSON.stringify([path, byPath.get(path)]))
240
+ }
241
+ return hash.digest('hex')
242
+ }
243
+
210
244
  /** Whether a filesystem error means absence; every non-ENOENT failure must surface. */
211
245
  function isENOENT(error: unknown): boolean {
212
246
  return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
@@ -283,15 +317,12 @@ function waitWithAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<
283
317
  }
284
318
 
285
319
  /**
286
- * The JSONL backend registered as `ctx.sessionPersistence` by the plugin.
320
+ * JSONL Session persistence with historical-format migration.
287
321
  * Sessions materialize lazily: a created session is
288
322
  * visible to this process immediately, reaches disk on its first append or
289
323
  * flush, and never existed if the process crashes before that.
290
324
  */
291
- class JsonlSessionPersistence extends SessionPersistence {
292
- /** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
293
- override readonly name = 'session-persistence-jsonl'
294
-
325
+ export class JsonlSessionPersistence extends SessionPersistence {
295
326
  private root: string
296
327
  private compression: JsonlCompression
297
328
  /**
@@ -310,10 +341,29 @@ class JsonlSessionPersistence extends SessionPersistence {
310
341
  * revision guard.
311
342
  */
312
343
  private readonly coldLogMemo = new Map<SessionId, StoredLog>()
344
+ /**
345
+ * Generation headers observed by the latest complete listing, keyed by
346
+ * source path and guarded by the stat-derived revision, so a listing reads
347
+ * only the first frame of logs whose file changed. Each complete listing
348
+ * replaces the map, which drops deleted paths.
349
+ *
350
+ * Reuse relies on this backend never rewriting a generation's header line
351
+ * in place: publication creates a new file, append grows it, and repair
352
+ * truncates its tail, so every content change moves the revision. The
353
+ * revision is file metadata, not a byte checksum. A reused entry also
354
+ * reuses the path-identity check its first read passed.
355
+ */
356
+ private listedHeaders = new Map<string, ListedHeader>()
313
357
  /** One joinable decode/migration operation per selected historical Session file revision. */
314
358
  private readonly migrationPreparations = new Map<SessionId, MigrationPreparation>()
315
359
 
316
- constructor(ctx: Context, public config: Config, private readonly tracker: JsonlBackendTracker) {
360
+ /**
361
+ * @param ctx - context used for scoped diagnostics and filesystem reads.
362
+ * @param config - JSONL root, physical encoding, and listing concurrency.
363
+ * @param tracker - handle bookkeeping; omitted creates bookkeeping for legacy reads.
364
+ */
365
+ constructor(ctx: Context, public config: Config,
366
+ private readonly tracker = new JsonlBackendTracker('session-persistence-jsonl')) {
317
367
  super(ctx)
318
368
  /* v8 ignore next 5 -- generated catalog and Session source share one build-time version owner. */
319
369
  if (sessionFormatCatalog.currentVersion !== SESSION_FORMAT_VERSION) {
@@ -346,20 +396,51 @@ class JsonlSessionPersistence extends SessionPersistence {
346
396
  return { kind: 'jsonl', path: logPath(this.root, meta.cwd, meta.id, this.compression) }
347
397
  }
348
398
 
399
+ /**
400
+ * Prepare logical history while the caller retains Session write ownership.
401
+ * @param id - stored Session identity.
402
+ * @param signal - optional cancellation for decoding and destination publication.
403
+ * @returns a commit operation that validates related sources before publishing the history.
404
+ */
405
+ async prepare(id: SessionId, signal?: AbortSignal): Promise<PreparedLegacySession> {
406
+ await this.ensureRootEncoding()
407
+ signal?.throwIfAborted()
408
+ const stored = await this.requireStoredLog(id, signal)
409
+ const snapshot = { header: stored.meta, inheritedEventCount: stored.inheritedEventCount, events: stored.events }
410
+ return { commit: async (publish) => {
411
+ signal?.throwIfAborted()
412
+ if (stored.status === 'prepared') await stored.validateRelatedSources()
413
+ signal?.throwIfAborted()
414
+ await publish(snapshot)
415
+ } }
416
+ }
417
+
418
+ /**
419
+ * Check whether a JSONL artifact occupies the Session identity.
420
+ * @param id - stored Session identity.
421
+ * @returns whether the artifact exists.
422
+ */
423
+ async hasStoredJsonl(id: SessionId): Promise<boolean> {
424
+ await this.ensureRootEncoding()
425
+ return await this.findLog(id) !== undefined
426
+ }
427
+
349
428
  // --- SessionPersistence service API ---
350
429
 
351
430
  /**
352
431
  * Create a new stored session and take its write ownership. The session is
353
432
  * visible to this process immediately; the physical artifact appears on the
354
- * first append or flush.
433
+ * first append or flush. A fork source copies its complete history into
434
+ * the child artifact before creation resolves.
355
435
  * @param header - the immutable header to store; must be losslessly
356
436
  * JSON-serializable with a non-negative safe-integer `createdAt`.
357
- * @param options - optional cancellation.
437
+ * @param options - optional cancellation, inherited prefix length, and fork source.
358
438
  * @returns the owned write handle.
359
439
  */
360
440
  async create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle> {
361
441
  options?.signal?.throwIfAborted()
362
442
  const snapshot = materializeCreateHeader(header)
443
+ const seed = options?.parentSource?.events
363
444
  // Fail fast on a seeded/cut mismatch with the exact refusal the header
364
445
  // line encoder enforces at materialization.
365
446
  toHeaderLine(snapshot, options?.inheritedEventCount)
@@ -375,7 +456,17 @@ class JsonlSessionPersistence extends SessionPersistence {
375
456
  // before its first log bytes publish (ensureLease); an unmaterialized
376
457
  // session leaves no filesystem footprint at all.
377
458
  this.tracker.registerCreated(snapshot, inheritedEventCount)
378
- return this.tracker.adopt(new JsonlSessionHandle(this, snapshot.id, snapshot, 'write', { cursor: 0, materialized: false, inheritedEventCount }))
459
+ const handle = this.tracker.adopt(new JsonlSessionHandle(this, snapshot.id, snapshot, 'write', { cursor: 0, materialized: false, inheritedEventCount }))
460
+ if (seed === undefined) return handle
461
+ try {
462
+ if (seed.length === 0) await handle.flush(options)
463
+ else await handle.append(seed, options)
464
+ return handle
465
+ } catch (error: unknown) {
466
+ try { await handle.close() }
467
+ catch (closeError: unknown) { throw new AggregateError([error, closeError], 'Fork creation and handle cleanup failed') }
468
+ throw error
469
+ }
379
470
  }
380
471
 
381
472
  /**
@@ -389,6 +480,8 @@ class JsonlSessionPersistence extends SessionPersistence {
389
480
  options?.signal?.throwIfAborted()
390
481
  await this.ensureRootEncoding()
391
482
  options?.signal?.throwIfAborted()
483
+ if (access === 'read') await this.tracker.closeCompletion(id)
484
+ options?.signal?.throwIfAborted()
392
485
  const pending = this.tracker.pendingOf(id)
393
486
  if (access === 'read') {
394
487
  if (pending !== undefined) {
@@ -501,7 +594,7 @@ class JsonlSessionPersistence extends SessionPersistence {
501
594
  return {
502
595
  ...metadata,
503
596
  revision: selected.sourceVersion < SESSION_FORMAT_VERSION
504
- ? SessionPersistenceRevision(`${fileRevision(identity)}:${await this.historicalCorpusRevision(options?.signal)}`)
597
+ ? brandString<PersistenceRevision>(`${fileRevision(identity)}:${await this.historicalCorpusRevision(options?.signal)}`)
505
598
  : fileRevision(identity),
506
599
  sizeBytes: Number(identity.size),
507
600
  location: { kind: 'jsonl', path: selected.sourcePath },
@@ -527,30 +620,18 @@ class JsonlSessionPersistence extends SessionPersistence {
527
620
  // append lands mid-scan is then still in this snapshot (its artifact may
528
621
  // predate the scan), so create-to-list visibility never has a hole.
529
622
  const pending = [...this.tracker.pendingEntries()]
530
- const artifacts = await this.listArtifacts(signal)
623
+ const { artifacts, revisions } = await this.listArtifacts(signal)
531
624
  const corpusRevision = artifacts.some(artifact => artifact.sourceVersion < SESSION_FORMAT_VERSION)
532
- ? await this.historicalCorpusRevision(signal) : undefined
533
- const statted = settledValues(await settleLimited(this.listLimit, artifacts, async (artifact) => {
534
- signal?.throwIfAborted()
535
- try {
536
- const identity = await stat(artifact.path, { bigint: true })
537
- signal?.throwIfAborted()
538
- return { artifact, identity }
539
- } catch (error: unknown) {
540
- signal?.throwIfAborted()
541
- if (!isENOENT(error)) throw error
542
- return undefined
543
- }
544
- }))
545
- for (const entry of statted) {
546
- if (entry === undefined) continue
547
- const { artifact, identity } = entry
625
+ ? corpusDigest(revisions) : undefined
626
+ for (const artifact of artifacts) {
627
+ const { identity } = artifact
548
628
  listed.add(artifact.header.id)
549
629
  snapshots.push({
550
- header: artifact.header,
630
+ // Detached from the header the listing cache retains.
631
+ header: { ...artifact.header },
551
632
  formatStatus: artifact.formatStatus,
552
633
  revision: artifact.sourceVersion < SESSION_FORMAT_VERSION
553
- ? SessionPersistenceRevision(`${fileRevision(identity)}:${corpusRevision}`)
634
+ ? brandString<PersistenceRevision>(`${fileRevision(identity)}:${corpusRevision}`)
554
635
  : fileRevision(identity),
555
636
  sizeBytes: Number(identity.size),
556
637
  location: { kind: 'jsonl', path: artifact.path },
@@ -567,6 +648,8 @@ class JsonlSessionPersistence extends SessionPersistence {
567
648
 
568
649
  /** Resolve and read one stored log, refusing loudly when the artifact is absent. */
569
650
  private async requireStoredLog(id: SessionId, signal?: AbortSignal): Promise<StoredLog> {
651
+ await this.tracker.closeCompletion(id)
652
+ signal?.throwIfAborted()
570
653
  const selected = await this.findLog(id, signal)
571
654
  if (selected === undefined) throw new SessionPersistenceNotFoundError(id)
572
655
  if (selected.sourceVersion < SESSION_FORMAT_VERSION) {
@@ -684,12 +767,12 @@ class JsonlSessionPersistence extends SessionPersistence {
684
767
  let prepared: Awaited<ReturnType<typeof prepareJsonlMigration>>
685
768
  let validateRelatedSources: () => Promise<void>
686
769
  try {
687
- const children = async () => (await this.listArtifacts(signal))
770
+ const children = async () => (await this.listArtifacts(signal)).artifacts
688
771
  .filter(source => source.header.origin === 'subagent' && source.header.parentSession === id)
689
772
  const sources = await children()
690
773
  const related = await prepareCatalogFacts(id, sources, this.compression, signal)
691
774
  for (const failure of related.failures) {
692
- this.ctx.logger.warn(`${this.name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`)
775
+ this.ctx.logger.warn(`${name}: session "${id}" catalog retained a child with unknown descriptor (raw log: ${failure.path}): ${String(failure.error)}`)
693
776
  }
694
777
  const membership = sources.map(source => source.path).sort()
695
778
  validateRelatedSources = async () => {
@@ -944,7 +1027,7 @@ class JsonlSessionPersistence extends SessionPersistence {
944
1027
  async truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void> {
945
1028
  this.coldLogMemo.delete(header.id)
946
1029
  await this.repair(header, truncateTo)
947
- this.ctx.logger.warn(`${this.name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`)
1030
+ this.ctx.logger.warn(`${name}: session "${header.id}" recovered from a torn tail; incomplete tail bytes were discarded`)
948
1031
  }
949
1032
 
950
1033
  /**
@@ -1119,54 +1202,87 @@ class JsonlSessionPersistence extends SessionPersistence {
1119
1202
 
1120
1203
  /** Historical logical events depend on the corpus, including members with unreadable headers. */
1121
1204
  private async historicalCorpusRevision(signal?: AbortSignal): Promise<string> {
1122
- const paths = (await this.listGenerations(signal)).map(source => source.sourcePath).sort()
1205
+ const paths = (await this.listGenerations(signal)).map(source => source.sourcePath)
1123
1206
  const entries = settledValues(await settleLimited(this.listLimit, paths, async (path) => {
1124
1207
  signal?.throwIfAborted()
1125
1208
  try {
1126
- return { path, revision: fileRevision(await stat(path, { bigint: true })) }
1209
+ return [path, fileRevision(await stat(path, { bigint: true }))] as const
1127
1210
  } catch (error: unknown) {
1128
1211
  if (!isENOENT(error)) throw error
1129
- return { path, revision: 'missing' }
1212
+ return [path, 'missing'] as const
1130
1213
  }
1131
1214
  }))
1132
- const hash = createHash('sha256')
1133
- for (const { path, revision } of entries) hash.update(JSON.stringify([path, revision]))
1134
1215
  signal?.throwIfAborted()
1135
- return hash.digest('hex')
1216
+ return corpusDigest(entries)
1136
1217
  }
1137
1218
 
1138
- private async listArtifacts(
1139
- signal?: AbortSignal,
1140
- ): Promise<Array<GenerationHeader & { path: string; sourceVersion: number }>> {
1219
+ /**
1220
+ * Read every listed Session's generation header with one stat per generation.
1221
+ * @param signal - optional cancellation.
1222
+ * @returns the readable artifacts, and the revision of every generation
1223
+ * (`missing` when it vanished) for {@link corpusDigest}.
1224
+ */
1225
+ private async listArtifacts(signal?: AbortSignal): Promise<{
1226
+ artifacts: Array<GenerationHeader & { path: string; sourceVersion: number; identity: JsonlPhysicalIdentity }>
1227
+ revisions: Array<readonly [string, string]>
1228
+ }> {
1141
1229
  signal?.throwIfAborted()
1142
1230
  await this.ensureRootEncoding()
1143
1231
  signal?.throwIfAborted()
1144
1232
  const generations = await this.listGenerations(signal)
1233
+ const previous = this.listedHeaders
1234
+ const listed = new Map<string, ListedHeader>()
1145
1235
  const headers = await settleLimited(this.listLimit, generations, async (selected) => {
1146
1236
  signal?.throwIfAborted()
1237
+ let identity: JsonlPhysicalIdentity
1147
1238
  try {
1148
- return { selected, metadata: await this.readGenerationHeader(selected, undefined, signal) }
1239
+ identity = await stat(selected.sourcePath, { bigint: true })
1149
1240
  } catch (error: unknown) {
1150
- if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) {
1151
- return { selected, metadata: undefined }
1152
- }
1153
- throw error
1241
+ signal?.throwIfAborted()
1242
+ if (!isENOENT(error)) throw error
1243
+ return { selected, revision: 'missing', identity: undefined, metadata: undefined }
1154
1244
  }
1245
+ signal?.throwIfAborted()
1246
+ const revision = fileRevision(identity)
1247
+ const memo = previous.get(selected.sourcePath)
1248
+ const metadata = memo !== undefined && memo.revision === revision
1249
+ ? memo.metadata
1250
+ : await this.readListedHeader(selected, signal)
1251
+ listed.set(selected.sourcePath, { revision, metadata })
1252
+ return { selected, revision, identity, metadata }
1155
1253
  })
1156
- const artifacts: Array<GenerationHeader & { path: string; sourceVersion: number }> = []
1254
+ const artifacts: Array<GenerationHeader & { path: string; sourceVersion: number; identity: JsonlPhysicalIdentity }> = []
1255
+ const revisions: Array<readonly [string, string]> = []
1157
1256
  const ids = new Set<SessionId>()
1158
1257
  for (const outcome of headers) {
1159
1258
  if (outcome.status === 'rejected') throw outcome.reason
1160
- const { selected, metadata } = outcome.value
1161
- if (metadata === undefined) continue
1259
+ const { selected, revision, identity, metadata } = outcome.value
1260
+ revisions.push([selected.sourcePath, revision])
1261
+ if (identity === undefined || metadata === undefined) continue
1162
1262
  if (ids.has(metadata.header.id)) {
1163
1263
  throw new Error(`duplicate JSONL session id "${metadata.header.id}" appears in multiple project directories`)
1164
1264
  }
1165
1265
  ids.add(metadata.header.id)
1166
- artifacts.push({ ...metadata, path: selected.sourcePath, sourceVersion: selected.sourceVersion })
1266
+ artifacts.push({ ...metadata, path: selected.sourcePath, sourceVersion: selected.sourceVersion, identity })
1167
1267
  }
1168
1268
  signal?.throwIfAborted()
1169
- return artifacts
1269
+ this.listedHeaders = listed
1270
+ return { artifacts, revisions }
1271
+ }
1272
+
1273
+ /** Read one listed generation header; an unsupported or corrupt log is not a listed Session. */
1274
+ private async readListedHeader(
1275
+ selected: ResolvedJsonlGeneration,
1276
+ signal?: AbortSignal,
1277
+ ): Promise<GenerationHeader | undefined> {
1278
+ try {
1279
+ return await this.readGenerationHeader(selected, undefined, signal)
1280
+ } catch (error: unknown) {
1281
+ if (error instanceof SessionFormatUnsupportedError || error instanceof SessionPersistenceCorruptionError) {
1282
+ return undefined
1283
+ }
1284
+ throw error
1285
+ }
1170
1286
  }
1171
1287
 
1172
1288
  /** Read and translate one selected generation header without inspecting its body. */
@@ -1246,12 +1362,12 @@ class JsonlSessionPersistence extends SessionPersistence {
1246
1362
  }
1247
1363
  return {
1248
1364
  version: SESSION_FORMAT_VERSION,
1249
- id: makeSessionId(header.id),
1365
+ id: brandString<SessionId>(header.id),
1250
1366
  createdAt: header.createdAt,
1251
1367
  ...(header.cwd === undefined ? {} : { cwd: header.cwd }),
1252
1368
  ...(header.parentSession === undefined
1253
1369
  ? {}
1254
- : { parentSession: makeSessionId(header.parentSession) }),
1370
+ : { parentSession: brandString<SessionId>(header.parentSession) }),
1255
1371
  isSeeded: header.isSeeded,
1256
1372
  ...(header.origin === undefined ? {} : { origin: header.origin }),
1257
1373
  delegationDepth: header.delegationDepth,
@@ -1318,7 +1434,7 @@ class JsonlSessionPersistence extends SessionPersistence {
1318
1434
  // append. Swallow only the rm failure; nothing else of consequence runs here.
1319
1435
  try {
1320
1436
  await rm(tmp, { force: true })
1321
- } catch {
1437
+ } catch (_redundantTempRemoveFailed) {
1322
1438
  /* v8 ignore next -- redundant temp link; publish already durable, rm failure is an unreachable IO edge */
1323
1439
  }
1324
1440
  }
@@ -1,5 +1,6 @@
1
1
  /** Isolated verification for a staged or competing current JSONL generation. */
2
2
 
3
+ import { fileURLToPath } from 'node:url'
3
4
  import { Worker } from 'node:worker_threads'
4
5
  import type { WorkerOptions } from 'node:worker_threads'
5
6
  import type { JsonlCompression } from './format.ts'
@@ -71,10 +72,11 @@ class VerificationScheduler {
71
72
  const verificationScheduler = new VerificationScheduler()
72
73
 
73
74
  function workerSpawn(request: VerificationRequest): { readonly entry: string | URL; readonly options: WorkerOptions } {
75
+ // The single-file runtime resolves string Worker entries through its embedded filesystem.
74
76
  /* v8 ignore next 3 -- built-worker coverage owns the bundled path. */
75
77
  if (!import.meta.url.endsWith('.ts')) {
76
78
  return {
77
- entry: new URL('./worker.cjs', import.meta.url),
79
+ entry: fileURLToPath(new URL('./worker.cjs', import.meta.url)),
78
80
  options: { workerData: request, execArgv: [] },
79
81
  }
80
82
  }
package/src/storage.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import type { Context } from '@deepseek-ai/cordis'
13
+ import { brandString } from '@deepseek-ai/dsh-brand'
13
14
  import { errorChain } from '@deepseek-ai/dsh-llm'
14
15
  import type { Session, SessionEvent, SessionHeader, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
15
16
  import {
@@ -19,7 +20,7 @@ import {
19
20
  SessionAlreadyOwnedError,
20
21
  SessionHandleClosedError,
21
22
  SessionPersistenceNotFoundError,
22
- SessionPersistenceRevision,
23
+ type SessionPersistenceRevision,
23
24
  SessionReadOnlyError,
24
25
  } from '@deepseek-ai/dsh-session-persistence'
25
26
  import type {
@@ -108,6 +109,9 @@ export class JsonlSessionHandle implements SessionHandle {
108
109
  return this.state.inheritedEventCount
109
110
  }
110
111
 
112
+ /** Completion of an already-started close, including its final durability drain. */
113
+ get closeCompletion(): Promise<void> | undefined { return this.closing }
114
+
111
115
  /**
112
116
  * Read a slice of the valid contiguous logical log; see the seam contract.
113
117
  * @param offset - first logical seq to include (default 0).
@@ -416,7 +420,7 @@ export class JsonlBackendTracker {
416
420
  this.writers.set(header.id, null)
417
421
  this.pending.set(header.id, {
418
422
  header,
419
- revision: SessionPersistenceRevision(`memory:${this.name}:${++this.counter}`),
423
+ revision: brandString<SessionPersistenceRevision>(`memory:${this.name}:${++this.counter}`),
420
424
  inheritedEventCount,
421
425
  })
422
426
  }
@@ -457,6 +461,15 @@ export class JsonlBackendTracker {
457
461
  return this.pending.has(id)
458
462
  }
459
463
 
464
+ /**
465
+ * Join an already-started writer close before reading its stored history.
466
+ * @param id - Session whose writer may still be draining.
467
+ * @returns completion of that writer's close, or undefined when no close is active.
468
+ */
469
+ closeCompletion(id: SessionId): Promise<void> | undefined {
470
+ return this.writers.get(id)?.closeCompletion
471
+ }
472
+
460
473
  /**
461
474
  * Iterate the pending sessions for listing.
462
475
  * @returns the pending entries, keyed by session id.