@deepseek-ai/dsh-session-persistence 0.0.1-rc.1 → 0.0.1-rc.3

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/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # pnpm run verify-translation-pairing --write packages/session/session-persistence/README.md
5
- README.md: 391548b1b896dca14cbe4f4ae55cf4180c4e0ac2
6
- README.zh.md: 7213e1ee71ba418ffacc3685df371dcba33588a7
5
+ README.md: 914e94a7adc83fba963ae651a81ac527cbc7b995
6
+ README.zh.md: 75aeec3c6a31e87b27cc2df3493e3fca9f808fbf
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English | [中文](README.zh.md)
4
4
 
5
- Session persistence is a capability seam. The abstract `SessionPersistence` service (`ctx.sessionPersistence`) is its Service Definition. It requires a persistence backend to store, reload, and list sessions durably without defining the storage implementation. The seam follows the `dsh-bash` roles ([capability seams](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): this package owns the Service Definition, a sibling package owns the Service provider, and Consumers inject the service.
5
+ Session persistence is a capability seam. The abstract `SessionPersistence` service (`ctx.sessionPersistence`) is its Service Definition. It requires a persistence backend to store, reload, and list sessions durably without defining the storage implementation. The seam follows the `dsh-shell` roles ([capability seams](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): this package owns the Service Definition, a sibling package owns the Service provider, and Consumers inject the service.
6
6
 
7
7
  The persisted unit IS the existing `SessionEvent` (event-sourced model — the log is the single source of truth), so there is no parallel "persisted message" type. Metadata that is NOT replayable conversation state (format version, cwd, lineage, seed boundary, origin, delegation depth) travels separately as `SessionHeader`, owned by `dsh-session` and re-exported here.
8
8
 
@@ -11,12 +11,14 @@ The persisted unit IS the existing `SessionEvent` (event-sourced model — the l
11
11
  | Method | Contract |
12
12
  |---|---|
13
13
  | `locate(meta): SessionLocation \| undefined` | Resolve an absolute per-session artifact target without I/O or materialization. Backends without an independent local artifact return `undefined`. |
14
+ | `supportsRawArtifacts: boolean` | State explicitly whether this backend exposes one verbatim artifact per session. Consumers check this capability before calling `readRaw`; `false` is not session absence. |
15
+ | `readRaw(id, signal?): Promise<SessionRawArtifact \| undefined>` | Read a supported backend's own artifact text verbatim, decoded from its physical encoding but never reconstructed from events. `undefined` means only that the requested artifact is absent; an unsupported backend rejects. |
14
16
  | `create(meta): Promise<void>` | Register a new session's metadata. MAY defer the physical write until the first `append` (lazy materialization). |
15
17
  | `append(id, events): Promise<void>` | Durably persist a batch. Append-only; first event `seq` == stored next-seq after any repair; rejects non-JSON-serializable data naming the offending type. |
16
18
  | `prepare(id, signal?): Promise<SessionPreparation>` | Reserve the exact unpublished Session used by resume. A coordinator reuses an earlier inspection when available, commits pending recovery, and releases an unpublished reservation back to its bounded cache on disposal. |
17
- | `load(id): Promise<{ meta; events }>` | Return an immutable balanced logical log after converting supported older records from the same format version and committing cold recovery. A live load first flushes its snapshot and rejects while its turn is open; a cold load preserves an interrupted final turn and durably closes it with synthetic `tool/result`/`step/end?`/`turn/end {interrupted}` events. Only a torn tail fragment is dropped; committed corruption, malformed records, and unknown `version` reject. |
19
+ | `load(id): Promise<{ meta; events }>` | Return an immutable balanced logical log after converting supported older records from the same format version and committing cold recovery. A live load first flushes its snapshot and rejects while its turn is open; a cold load preserves an interrupted final turn and durably closes it with synthetic `tool/result`/`step/end?`/`turn/end {interrupted}` events. Only a torn tail fragment is dropped; committed corruption and malformed records reject as `SessionPersistenceCorruptionError`, while an unsupported format `version` or an event type unknown to this build (without the envelope's `ignorable` marker) refuses as `SessionFormatUnsupportedError`, naming the refusal direction and the raw log path when the backend keeps one artifact per session. |
18
20
  | `inspect(id, signal?): Promise<{ meta; events }>` | Return an upgraded, validated, deeply frozen logical view without committing recovery or publishing a Session. A cold view receives in-memory synthetic recovery closers while its physical torn tail remains untouched; an already-live view is its current immutable snapshot and may contain an open turn. Coordinator-backed implementations retain the exact cold unpublished Session in a bounded LRU for later `prepare`, but discard and reload it when the stored revision changes. Same-id inspections share an in-flight read. |
19
- | `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | Return valid stored events with `seq >= fromSeq` without preparation caching, truncation, closers, or coordinator state. A `fromSeq` at or past the stored end returns an empty event list; a negative or non-safe-integer `fromSeq` rejects. Seek-capable backends (SQLite) read only the suffix unless converting a supported older record requires earlier records; sequential backends (JSONL) parse the whole artifact and skip forward. Intended for checkpoint consumers that apply only events after a stored sequence number. |
21
+ | `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | Return valid stored events with `seq >= fromSeq` without preparation caching, truncation, closers, or coordinator state. A `fromSeq` at or past the stored end returns an empty event list; a negative or non-safe-integer `fromSeq` rejects. Seek-capable backends (SQLite) read only the suffix unless converting a supported older record requires earlier records; sequential backends (JSONL) parse the whole artifact and skip forward. Unknown-type refusal follows that access pattern: a seek read checks only the returned suffix, while the sequential fallback also refuses on an unknown required event below the window. Intended for checkpoint consumers that apply only events after a stored sequence number. |
20
22
  | `list(signal?): Promise<SessionHeader[]>` | Lightweight listing from metadata, no full-log parse. The optional signal cancels backend listing work. A zero-event lazily-materialized session is absent from `list`. |
21
23
  | `listSnapshots(signal?): Promise<SessionPersistenceSnapshot[]>` | Lightweight metadata plus an opaque branded per-log revision, without loading event logs. A revision stays equal while that log and its backing store are unchanged, changes after append or mutating load repair, and cannot collide solely because two stores use the same local counter. The optional signal requests cancellation of backend discovery work; first-party backends settle any started listing work before rejecting so an awaited call is quiescent. |
22
24
 
@@ -78,6 +80,6 @@ Persistence does not mutate live request prefixes. A resumed loop can reuse prov
78
80
 
79
81
  ## Known Limitations and Deferred Work
80
82
 
81
- - **No deletion or retention surface** — pruning stored sessions is out-of-band backend maintenance.
83
+ - **No deletion or retention API** — pruning stored sessions is out-of-band backend maintenance.
82
84
  - **`list()` is unpaginated and unfiltered** — it returns every stored session's header; fine for local stores, unindexed at scale.
83
85
  - **Repair-time synthetic closers are the only crash story** — a backend must synthesize `tool/result`/`step/end`/`turn/end` closers on load; there is no partial-turn resume that continues an interrupted turn instead of closing it.
package/README.zh.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | 中文
4
4
 
5
- 会话持久化是一项能力 seam。抽象的 `SessionPersistence` 服务(`ctx.sessionPersistence`)是其 Service Definition。它要求持久化后端持久存储、重新加载和列出会话,但不规定具体存储实现。该 seam 采用与 `dsh-bash` 相同的角色划分(见[能力 seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)):本包负责 Service Definition,同级包负责 Service provider,Consumer 注入该服务。
5
+ 会话持久化是一项能力 seam。抽象的 `SessionPersistence` 服务(`ctx.sessionPersistence`)是其 Service Definition。它要求持久化后端持久存储、重新加载和列出会话,但不规定具体存储实现。该 seam 采用与 `dsh-shell` 相同的角色划分(见[能力 seam](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)):本包负责 Service Definition,同级包负责 Service provider,Consumer 注入该服务。
6
6
 
7
7
  持久化单元就是现有 `SessionEvent`(事件溯源模型:日志是唯一真源),因此不存在另一套并行的「持久消息」类型。不属于可回放对话状态的元数据(格式版本、cwd、血缘、种子边界、origin、委托深度)作为 `SessionHeader` 单独传输,该类型归 `dsh-session` 所有,并在此重新导出。
8
8
 
@@ -10,34 +10,36 @@
10
10
 
11
11
  | 方法 | 约定 |
12
12
  |---|---|
13
- | `locate(meta): SessionLocation \| undefined` | 在不执行 I/O 或实体化的情况下解析绝对的每会话产物目标。没有独立本地产物的后端返回 `undefined`。 |
13
+ | `locate(meta): SessionLocation \| undefined` | 在不执行 I/O 或实体化的情况下解析每个会话的绝对产物目标。没有独立本地产物的后端返回 `undefined`。 |
14
+ | `supportsRawArtifacts: boolean` | 明确说明该后端是否为每个会话暴露一份逐字工件。Consumer 在调用 `readRaw` 前检查此能力;`false` 并不表示会话缺失。 |
15
+ | `readRaw(id, signal?): Promise<SessionRawArtifact \| undefined>` | 读取受支持后端自身的逐字工件文本;只解码物理编码,绝不从事件重建。`undefined` 仅表示所请求工件缺失;不支持的后端会拒绝。 |
14
16
  | `create(meta): Promise<void>` | 注册新会话元数据。可以将物理写入延迟到第一次 `append`(延迟实体化)。 |
15
17
  | `append(id, events): Promise<void>` | 持久保存一个批次。仅追加;任何修复后,第一个事件 `seq` == 已存储 next-seq;非 JSON 可序列化数据会被拒绝,并命名违规类型。 |
16
- | `prepare(id, signal?): Promise<SessionPreparation>` | 预留恢复所使用的那个未发布 Session。协调器会尽可能复用之前的检查结果、提交待处理恢复,并在 dispose 时将未发布 reservation 释放回有界缓存。 |
17
- | `load(id): Promise<{ meta; events }>` | 转换同一格式版本中受支持的旧记录后,返回不可变、平衡的逻辑日志,并提交冷恢复。实时 load 先 flush 其快照,并在轮次开放时拒绝;冷 load 保留中断的最终轮次,并用合成 `tool/result`/`step/end?`/`turn/end {interrupted}` 事件持久关闭它。只丢弃撕裂尾部碎片;已提交损坏、格式错误的记录和未知 `version` 会被拒绝。 |
18
+ | `prepare(id, signal?): Promise<SessionPreparation>` | 预留恢复所使用的那个未发布 Session。协调器会尽可能复用之前的检查结果、提交待处理恢复,并在 dispose(资源释放)时将未发布 reservation 释放回有界缓存。 |
19
+ | `load(id): Promise<{ meta; events }>` | 转换同一格式版本中受支持的旧记录后,返回不可变、平衡的逻辑日志,并提交冷恢复。实时 load 先 flush 其快照,并在轮次开放时拒绝;冷 load 保留中断的最终轮次,并用合成 `tool/result`/`step/end?`/`turn/end {interrupted}` 事件持久关闭它。只丢弃撕裂尾部碎片;已提交损坏和格式错误的记录以 `SessionPersistenceCorruptionError` 拒绝,不支持的格式 `version` 或本构建不认识且信封未带 `ignorable` 标记的事件类型以 `SessionFormatUnsupportedError` 拒绝,消息说明拒绝方向,并在后端为每个会话保留独立文件时给出原始日志路径。 |
18
20
  | `inspect(id, signal?): Promise<{ meta; events }>` | 返回已经升级、验证和深度冻结的逻辑视图,但不提交恢复或发布 Session。冷视图会获得仅存在于内存的合成恢复 closer,物理撕裂尾部保持不变;实时状态下的视图则是当前不可变快照,可能包含开放的轮次。基于协调器的实现会在有界 LRU 中保留该冷状态下未发布的 Session 本身,供后续 `prepare` 使用,但已存储修订值变化后会丢弃并重新读取。同 id 检查共享进行中的读取。 |
19
- | `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | 返回 `seq >= fromSeq` 的有效已存储事件,不进入 preparation 缓存、不截断、不合成 closer,也不发布协调器状态。`fromSeq` 达到或超过已存储末尾时返回空事件列表;负数或非安全整数 `fromSeq` 会被拒绝。可寻址后端(SQLite)只读后缀,除非转换受支持的旧记录需要读取更早的记录;顺序后端(JSONL)解析整个产物并向前跳过。供 checkpoint 消费方只应用已存序号之后的事件。 |
21
+ | `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | 返回 `seq >= fromSeq` 的有效已存储事件,不进入 preparation 缓存、不截断、不合成 closer,也不发布协调器状态。`fromSeq` 达到或超过已存储末尾时返回空事件列表;负数或非安全整数 `fromSeq` 会被拒绝。可寻址后端(SQLite)只读后缀,除非转换受支持的旧记录需要读取更早的记录;顺序后端(JSONL)解析整个产物并向前跳过。未知类型拒绝遵循同一读取方式:寻址读取只检查返回的后缀,顺序回退路径还会拒绝窗口以下的未知必需事件。供 checkpoint 消费方只应用已存序号之后的事件。 |
20
22
  | `list(signal?): Promise<SessionHeader[]>` | 从元数据轻量列出,不解析完整日志。可选信号取消后端列表工作。零事件延迟实体化会话不在 `list` 中。 |
21
23
  | `listSnapshots(signal?): Promise<SessionPersistenceSnapshot[]>` | 返回轻量元数据和每份日志一个不透明、带品牌类型的修订值,不加载事件日志。日志及其后端存储不变时,修订保持相等;append 或变更性 load 修复后会改变;不会仅因两个存储使用相同本地计数器而冲突。可选信号请求取消后端发现工作;第一方后端会先等待所有已启动的列出工作结束,再予以拒绝,因此调用返回拒绝时,相关工作已完全停稳。 |
22
24
 
23
25
  ## 每个后端必须遵守的不变量
24
26
 
25
- - **仅追加;崩溃轮次会被关闭,而非截断。** 已 flush 事件绝不重写。崩溃可留下未关闭最终轮次,其事件真实且可能很大;`load` 保留它们,并持久追加合成 closer(为每个未回答 assistant 调用添加按风险分类错误 `tool/result`,再添加 `step/end?`+`turn/end {interrupted}`),以平衡日志,并确保重新载入的历史仍是有效的提供方 transcript(文本记录)。只丢弃从未完整写入的撕裂尾部碎片。
27
+ - **仅追加;崩溃轮次会被关闭,而非截断。** 已 flush 事件绝不重写。崩溃可留下未关闭最终轮次,其事件真实且可能很大;`load` 保留它们,并持久追加合成 closer(为每个未获回答的 assistant 调用添加一个带风险分类错误的 `tool/result`,再添加 `step/end?`+`turn/end {interrupted}`),以平衡日志,并确保重新载入的历史仍是有效的提供方 transcript(文本记录)。只丢弃从未完整写入的撕裂尾部碎片。
26
28
  - **连续 seq。**`load` 拒绝日志中间的 `seq` 缺口/解析错误;`append` 的第一个 `seq` 必须等于已存储 next-seq。
27
- - **JSON 可序列化数据。**`append` 通过共享单遍无损 JSON 边界实体化每个直接/回放批次。实时 `Session` 事件已深度冻结,但写入协调器仍将每个事件复制到持久化自有缓冲区。
29
+ - **JSON 可序列化数据。**`append` 通过共享单遍无损 JSON 边界实体化每个直接/回放批次。活动 `Session` 事件已深度冻结,但写入协调器仍将每个事件复制到持久化自有缓冲区。
28
30
  - **持久性。**`append` 只在批次持久后返回。
29
31
 
30
32
  ## 写入协调器
31
33
 
32
- `PersistenceCoordinator` 负责每 id 状态和串行化、每个活动会话各自的有界写入 controller、延迟实体化、崩溃尾部修复、会话接管和完全停稳的 dispose(资源释放)。第一方后端组合一个协调器,实现小型 `PersistenceBackend` 存储钩子接口,并委托其有状态方法。因此 JSONL 和 SQLite 共享生命周期正确性,同时保留不同存储原语;见[协调器 Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)、[flush controller 简化](../../../.agents/notes/implemented/simplification/2026-07-23-collapse-persistence-flush-state.md)和[有界批处理决策](../../../.agents/notes/implemented/architecture/2026-08-08-bounded-session-persistence-write-batching.md)。
34
+ `PersistenceCoordinator` 负责每 id 状态和串行化、每个活动会话各自的有界写入 controller、延迟实体化、崩溃尾部修复、会话接管和完全停稳的 dispose。第一方后端组合一个协调器,实现小型 `PersistenceBackend` 存储钩子接口,并委托其有状态方法。因此 JSONL 和 SQLite 共享生命周期正确性,同时保留不同存储原语;见[协调器 Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)、[flush controller 简化](../../../.agents/notes/implemented/simplification/2026-07-23-collapse-persistence-flush-state.md)和[有界批处理决策](../../../.agents/notes/implemented/architecture/2026-08-08-bounded-session-persistence-write-batching.md)。
33
35
 
34
36
  每个 `session/event` 将事件复制到会话 controller。第一个待处理事件会开启固定批处理窗口;后续事件会加入该批次,但不会重置截止时间。配置的 `writeBatchMaxDelayMs` 只限制这段有意等待,而不限制事件循环、初始化、串行化操作或后端延迟。写入期间接纳的事件会形成一个新的有界批次。`session/flush` 会取消等待,并作为共享的完全停稳屏障,排空屏障运行期间接纳的事件。后台写入失败只记录一次日志,保留顺序不变的批次,并暂停自动重试;新事件会开启新的固定窗口,而显式 flush 或后端拆卸会立即重试,并在失败再次发生时向调用方暴露失败。
35
37
 
36
- 崩溃修复只适用于冷状态。对于实时 id,`load(id)` 为权威内存日志制作快照,等待该快照持久,并只在平衡时返回;开放实时轮次会被拒绝,而不会收到合成中断 closer。对于冷 id,检查只读取、验证、冻结并构造一次未发布 Session;只有来源修订值仍然是当前值时,重复检查才会复用该对象图。`prepare(id)` 在修复前执行相同校验,预留该 Session 本身,提交任何待处理的撕裂尾部或中断轮次修复,并将其返回用于发布。HMR 接管通过 `loadStored` 读取,应用协调器 cwd 检查,并绝不关闭活动轮次。
38
+ 崩溃修复只适用于冷状态。对于已有活动会话的 id,`load(id)` 为权威内存日志制作快照,等待该快照持久,并只在平衡时返回;活动会话中开放的轮次会被拒绝,而不会收到合成中断 closer。对于冷 id,检查只读取、验证、冻结并构造一次未发布 Session;只有来源修订值仍然是当前值时,重复检查才会复用该对象图。`prepare(id)` 在修复前执行相同校验,预留该 Session 本身,提交任何待处理的撕裂尾部或中断轮次修复,并将其返回用于发布。HMR(热模块替换)接管通过 `loadStored` 读取,应用协调器 cwd 检查,并绝不关闭活动轮次。
37
39
 
38
40
  后端读取会在验证当前记录前,转换同一格式版本中明确受支持的旧记录。消息标识机制引入前的消息会获得确定性的 id `legacy-message:<session-id>:<event-seq>`;工具结果的内容替换会继承其目标导入后的 id。react-loop 引入前的 `turn/start` 会移除过时的 trigger,已移除的 steering(中途引导)事件 `steering/message` 会转换为同一条带标识的 `user/message`;旧版 `turn/end` 会映射终止原因,但不会虚构旧记录中没有记载的调用方。协调器对 `load`、`inspect`、`readFrom`、无所有者状态的认领和 HMR 前缀接管使用同一份转换后视图。存储仍然仅追加:读取不会重写旧记录,此后追加的事件使用当前格式。这些是[消息标识机制引入前的消息](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.md)与 [react-loop 引入前会话](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.md)决策所规定的范围受限的导入例外,并不构成通用的 v0 迁移承诺。
39
41
 
40
- 实时会话发出 `session/disposed` 时,协调器等待其 controller,串行化最终 drain,然后释放该精确 `Session` 对象拥有的状态。失败退役会将 controller 保留在实时会话 map 中,使后端拆卸可重试。后端拆卸先停止事件接纳,flush 每个剩余 controller,等待每 id 操作,最后才关闭存储句柄。
42
+ 活动会话发出 `session/disposed` 时,协调器等待其 controller,以串行方式执行最终 drain,然后释放该精确 `Session` 对象拥有的状态。失败退役会将 controller 保留在活动会话 map 中,使后端拆卸可重试。后端拆卸先停止事件接纳,flush 每个剩余 controller,等待每 id 操作,最后才关闭存储句柄。
41
43
 
42
44
  无副作用 `locate`、轻量 `listSnapshots` 和按 id 查询的 `readStoredRevision` 仍由后端负责,因为它们描述存储拓扑和修订身份,而非写入编排。`listSnapshots(signal?)` 将调用方传入的同一个信号传给后端发现流程,使观察者可在不脱离该工作的情况下取消。
43
45
 
@@ -46,15 +48,15 @@
46
48
  | 钩子 | 职责 |
47
49
  |---|---|
48
50
  | `name` | dispose 失败 `AggregateError` 的后端标签。 |
49
- | `loadStored(id, signal?)` | 在全部存储范围中按 id 读取已存储前缀。用于恢复/加载、非修改式 inspect、实时接管和 create 冲突探测。可选信号属于仅观察读取。返回元数据标识 `id`;`revision` 精确标识返回的 header 和事件;当且仅当必须截断撕裂尾部时才存在不透明 `tornMarker`。 |
51
+ | `loadStored(id, signal?)` | 在全部存储范围中按 id 读取已存储前缀。用于恢复/加载、非修改式 inspect、活动会话接管和 create 冲突探测。可选信号属于仅观察读取。返回元数据标识 `id`;`revision` 精确标识返回的 header 和事件;当且仅当必须截断撕裂尾部时才存在不透明 `tornMarker`。 |
50
52
  | `readStoredRevision(id, signal?)` | 在不加载事件日志的情况下读取一个 id 当前的来源限定修订值。它使用与 `loadStored` 相同的修订值表示;id 不存在时返回 `undefined`。 |
51
- | `loadStoredFrom?(id, fromSeq, signal?)` | 服务 `readFrom` 背后的可选可寻址后缀读取:返回 header 和 `seq >= fromSeq` 的已存储事件,非变更、无撕裂标记。SQLite 实现它(`WHERE seq >= ?`);不实现的后端使用协调器回退——`loadStored` 加向前跳过。 |
53
+ | `loadStoredFrom?(id, fromSeq, signal?)` | 服务 `readFrom` 背后的可选可寻址后缀读取:返回 header 和 `seq >= fromSeq` 的已存储事件,非修改式、无撕裂标记。SQLite 实现它(`WHERE seq >= ?`);不实现的后端使用协调器回退——`loadStored` 加向前跳过。 |
52
54
  | `appendBatch(meta, events, isMaterialized)` | 持久追加连续批次;尚未实体化时以原子方式延迟实体化。 |
53
- | `commitRepair(meta, tornMarker, closers)` | 使崩溃修复持久:截断撕裂尾部(当且仅当 `tornMarker !== undefined`;标记可为 falsy,例如 seq/offset `0`),并追加 `closers`。不要求原子性。由 load(截断 + closer)和实时接管(仅截断)使用。 |
55
+ | `commitRepair(meta, tornMarker, closers)` | 使崩溃修复持久:截断撕裂尾部(当且仅当 `tornMarker !== undefined`;标记可为 falsy,例如 seq/offset `0`),并追加 `closers`。不要求原子性。由 load(截断 + closer)和活动会话接管(仅截断)使用。 |
54
56
  | `list(signal?)` | 列出全部已存储元数据,并遵循可选的取消信号。 |
55
- | `close?()` | 可选生命周期拆卸(例如关闭 db 句柄),在 dispose drain 后等待。 |
57
+ | `close?()` | 可选生命周期拆卸(例如关闭 db 句柄),在 dispose drain 后等待其完成。 |
56
58
 
57
- 协调器断言已存储 id,并在修复或实时接管前比较已存储/实时 cwd。其 `inspect()` 路径取得新鲜后端值的所有权,只验证和冻结一次,并在不调用 `commitRepair` 的情况下最多保留配置数量的未发布 Session。只有保留源的修订值仍等于 `readStoredRevision` 时,系统才会复用或修复它;否则协调器会重新读取。该新鲜性校验不会增加跨进程写入排他。持久日志在一次读取与复核往返内保持不变时,修订值重试才能收敛;持续的外部写入可能延迟 `load`、`inspect` 或 `prepare`。`tornMarker` 完全不透明:协调器只测试 `!== undefined`,并将其原样往返给 `commitRepair`,绝不检查值(JSONL 后端使用待截断字节偏移,SQLite 后端使用待删除 seq)。第三方后端可以不用协调器直接实现抽象服务,但必须提供相同非变更检查和可信轻量快照修订。详见[写入协调器 Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)。
59
+ 协调器断言已存储 id,并在修复或活动会话接管前比较已存储/活动会话 cwd。其 `inspect()` 路径取得新鲜后端值的所有权,只验证和冻结一次,并在不调用 `commitRepair` 的情况下最多保留配置数量的未发布 Session。只有保留源的修订值仍等于 `readStoredRevision` 时,系统才会复用或修复它;否则协调器会重新读取。该新鲜性校验不会增加跨进程写入排他。持久日志在一次读取与复核往返内保持不变时,修订值重试才能收敛;持续的外部写入可能延迟 `load`、`inspect` 或 `prepare`。`tornMarker` 完全不透明:协调器只测试 `!== undefined`,并将其原样往返给 `commitRepair`,绝不检查值(JSONL 后端使用待截断字节偏移,SQLite 后端使用待删除 seq)。第三方后端可以不用协调器直接实现抽象服务,但必须提供相同的非修改式检查和可信轻量快照修订。详见[写入协调器 Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md)。
58
60
 
59
61
  ## 元数据与位置类型
60
62
 
@@ -74,7 +76,7 @@
74
76
 
75
77
  #### KV Cache 影响
76
78
 
77
- 持久化不修改实时请求前缀。只有当重建历史、当前 envelope 和模型路由匹配时,恢复 loop 才能重用提供方缓存;崩溃修复结果仅追加,不重写较早历史。
79
+ 持久化不修改当前请求前缀。只有当重建历史、当前 envelope 和模型路由匹配时,恢复 loop 才能重用提供方缓存;崩溃修复结果仅追加,不重写较早历史。
78
80
 
79
81
  ## 已知限制与暂缓事项
80
82
 
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Service } from "@deepseek-ai/cordis";
2
- import { SESSION_FORMAT_VERSION, SessionPreparation, adoptSessionEvent, interruptedTurnClosers, snapshotJsonValue, snapshotSessionEvent } from "@deepseek-ai/dsh-session";
2
+ import { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, SessionPreparation, adoptSessionEvent, interruptedTurnClosers, snapshotJsonValue, snapshotSessionEvent } from "@deepseek-ai/dsh-session";
3
3
  import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
4
4
  //#region lib/types/revision.js
5
5
  /** Opaque revision identity for lightweight persistence observations. */
@@ -447,6 +447,40 @@ var SessionPersistenceCorruptionError = class extends Error {
447
447
  this.name = "SessionPersistenceCorruptionError";
448
448
  }
449
449
  };
450
+ /**
451
+ * The stored log is intact but this runtime cannot faithfully interpret it:
452
+ * the header carries an unsupported format version, or an event's type is
453
+ * unknown to this build and the event is not marked ignorable. Distinct from
454
+ * {@link SessionPersistenceCorruptionError} — nothing is damaged; the raw log
455
+ * remains readable at {@link location} when the backend keeps one artifact
456
+ * per session.
457
+ */
458
+ var SessionFormatUnsupportedError = class extends Error {
459
+ location;
460
+ /**
461
+ * @param message - stable reason the log cannot be interpreted, already
462
+ * including the raw-log path when one exists.
463
+ * @param location - the backend's artifact location, when one exists.
464
+ */
465
+ constructor(message, location) {
466
+ super(message);
467
+ this.location = location;
468
+ this.name = "SessionFormatUnsupportedError";
469
+ }
470
+ };
471
+ /**
472
+ * Direction-aware refusal text for a stored session whose format version this
473
+ * build does not read. Shared by the coordinator's load-time check and by
474
+ * backends that must refuse BEFORE decoding version-dependent structure (a
475
+ * future format may not satisfy today's structural checks at all, and the
476
+ * user must see "upgrade the harness", never "corrupt").
477
+ * @param id - the stored session id, for message context.
478
+ * @param version - the stored format version.
479
+ * @returns the stable refusal text, without a raw-log path suffix.
480
+ */
481
+ function sessionFormatVersionRefusal(id, version) {
482
+ return version > SESSION_FORMAT_VERSION ? `session "${id}" uses log format v${version}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it` : `session "${id}" uses log format v${version}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it`;
483
+ }
450
484
  /** Collect the rejection reasons from a set of promises (none-throwing). */
451
485
  async function settledErrors(promises) {
452
486
  const settled = await Promise.allSettled([...promises]);
@@ -920,9 +954,11 @@ var PersistenceCoordinator = class {
920
954
  events: whole.events.filter((event) => event.seq >= fromSeq)
921
955
  };
922
956
  }
957
+ const events = snapshotStoredEvents(suffix.events, id);
958
+ this.assertEventsSupported(suffix.meta, events);
923
959
  return {
924
960
  meta: structuredClone(suffix.meta),
925
- events: snapshotStoredEvents(suffix.events, id)
961
+ events
926
962
  };
927
963
  }
928
964
  const whole = await this.readStoredPrefix(id, signal);
@@ -939,9 +975,11 @@ var PersistenceCoordinator = class {
939
975
  if (stored === void 0) throw new Error(`session "${id}" not found`);
940
976
  this.assertStoredId(id, stored.meta);
941
977
  this.assertVersion(stored.meta);
978
+ const events = snapshotStoredEvents(stored.events, id);
979
+ this.assertEventsSupported(stored.meta, events);
942
980
  return {
943
981
  meta: structuredClone(stored.meta),
944
- events: snapshotStoredEvents(stored.events, id)
982
+ events
945
983
  };
946
984
  }
947
985
  /** Read, repair in memory, validate, and freeze one cold source once. */
@@ -953,6 +991,7 @@ var PersistenceCoordinator = class {
953
991
  this.assertStoredId(id, meta);
954
992
  this.assertVersion(meta);
955
993
  const storedEvents = adoptStoredEvents(events, id);
994
+ this.assertEventsSupported(meta, storedEvents);
956
995
  const closers = interruptedTurnClosers(storedEvents).map(adoptSessionEvent);
957
996
  const balanced = [...storedEvents, ...closers];
958
997
  const session = this.ctx.sessions.prepare(id, {
@@ -972,6 +1011,7 @@ var PersistenceCoordinator = class {
972
1011
  closers
973
1012
  };
974
1013
  } catch (error) {
1014
+ if (error instanceof SessionFormatUnsupportedError) throw error;
975
1015
  throw new SessionPersistenceCorruptionError(`stored session "${id}" failed validation: ${String(error)}`, { cause: error });
976
1016
  }
977
1017
  }
@@ -1061,7 +1101,29 @@ var PersistenceCoordinator = class {
1061
1101
  }
1062
1102
  }
1063
1103
  assertVersion(meta) {
1064
- if (meta.version !== SESSION_FORMAT_VERSION) throw new Error(`unsupported session format version ${meta.version} for "${meta.id}" (only v${SESSION_FORMAT_VERSION} is supported)`);
1104
+ if (meta.version === SESSION_FORMAT_VERSION) return;
1105
+ throw this.unsupported(meta, sessionFormatVersionRefusal(meta.id, meta.version));
1106
+ }
1107
+ /**
1108
+ * Refuse a log containing an event type this build does not know, unless the
1109
+ * writer marked the event ignorable: an unrecognized required event may
1110
+ * change how the rest of the log must be interpreted, so silently skipping
1111
+ * it would reconstruct a wrong session (the envelope contract on
1112
+ * `SessionEvent.ignorable`). Runs on NORMALIZED events — after
1113
+ * `snapshotStoredEvents`/`adoptStoredEvents` has upgraded the legacy shapes
1114
+ * this build still reads and rejected the ones it does not, so those keep
1115
+ * their specific diagnostics.
1116
+ */
1117
+ assertEventsSupported(meta, events) {
1118
+ for (const event of events) {
1119
+ if (KNOWN_SESSION_EVENT_TYPES.has(event.type) || event.ignorable === true) continue;
1120
+ throw this.unsupported(meta, `session "${meta.id}" contains event type "${event.type}" (seq ${event.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`);
1121
+ }
1122
+ }
1123
+ /** Build a format refusal that points at the raw artifact when the backend has one. */
1124
+ unsupported(meta, reason) {
1125
+ const location = this.backend.locate?.(meta);
1126
+ return new SessionFormatUnsupportedError(location === void 0 ? reason : `${reason} (raw log: ${location.path})`, location);
1065
1127
  }
1066
1128
  /** Reject backend metadata that is not bound to the requested session id. */
1067
1129
  assertStoredId(id, meta) {
@@ -1226,6 +1288,7 @@ var PersistenceCoordinator = class {
1226
1288
  if (meta.cwd !== session.header.cwd) throw new Error(`session "${session.header.id}" is already persisted at a different cwd (persisted: ${String(meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`);
1227
1289
  this.assertVersion(meta);
1228
1290
  const storedEvents = snapshotStoredEvents(events, session.header.id);
1291
+ this.assertEventsSupported(meta, storedEvents);
1229
1292
  if (!seedCoversPrefix(seed, storedEvents)) throw new Error(`session "${session.header.id}" already has a persisted log on disk that does not match this live session (id collision)`);
1230
1293
  if (tornMarker !== void 0) await this.backend.commitRepair(meta, tornMarker, []);
1231
1294
  this.states.set(session.header.id, {
@@ -1288,6 +1351,25 @@ var SessionPersistence = class extends Service {
1288
1351
  super(ctx, "sessionPersistence");
1289
1352
  }
1290
1353
  /**
1354
+ * Read a session's backend-owned artifact text verbatim — the exact durable
1355
+ * bytes the backend wrote (decoded from its physical encoding, e.g. a
1356
+ * decompressed JSONL). The returned `content` is the raw text, not a
1357
+ * reconstruction from parsed events, so it preserves backend-specific
1358
+ * serialization (chunk packing, key order, line breaks). Callers first test
1359
+ * {@link supportsRawArtifacts}; `undefined` then means only that the requested
1360
+ * session has no materialized artifact.
1361
+ * @param _id - the persisted session to read (unused by the default: no
1362
+ * per-session artifact).
1363
+ * @param signal - optional cancellation for backend read work.
1364
+ * @returns the raw artifact plus its parsed header, or `undefined` when the
1365
+ * session is absent.
1366
+ * @throws when this backend does not expose per-session raw artifacts.
1367
+ */
1368
+ readRaw(_id, signal) {
1369
+ if (signal?.aborted === true) return Promise.reject(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
1370
+ return Promise.reject(/* @__PURE__ */ new Error("this session persistence backend does not expose raw artifacts"));
1371
+ }
1372
+ /**
1291
1373
  * Prepare the exact unpublished Session used by resume. Implementations may
1292
1374
  * reuse object graphs retained by an earlier {@link inspect} after confirming
1293
1375
  * their durable revision is still current; disposal releases an unpublished
@@ -1311,4 +1393,4 @@ var SessionPersistence = class extends Service {
1311
1393
  }
1312
1394
  };
1313
1395
  //#endregion
1314
- export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionPersistence, SessionPersistence as default, SessionPersistenceCorruptionError, SessionPersistenceRevision };
1396
+ export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionFormatUnsupportedError, SessionPersistence, SessionPersistence as default, SessionPersistenceCorruptionError, SessionPersistenceRevision, sessionFormatVersionRefusal };
@@ -7,7 +7,7 @@
7
7
  import { Context } from '@deepseek-ai/cordis';
8
8
  import { SessionPreparation } from '@deepseek-ai/dsh-session';
9
9
  import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session';
10
- import type { SessionInspection } from './index.ts';
10
+ import type { SessionInspection, SessionLocation } from './index.ts';
11
11
  import type { SessionPersistenceRevision } from './revision.ts';
12
12
  /** Default number of detached session preparations retained by a coordinator. */
13
13
  export declare const DEFAULT_PREPARED_SESSION_CACHE_SIZE = 5;
@@ -23,6 +23,34 @@ export declare class SessionPersistenceCorruptionError extends Error {
23
23
  */
24
24
  constructor(message: string, options: ErrorOptions);
25
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;
26
54
  /** Coordinator policy supplied by a concrete persistence backend. */
27
55
  export interface PersistenceCoordinatorOptions {
28
56
  /** Maximum completed unpublished preparations retained for reuse. */
@@ -100,6 +128,11 @@ export interface PersistenceBackend<TornMarker = unknown> {
100
128
  * contains a supported legacy shape whose normalization needs earlier
101
129
  * message-identity facts, in which case the coordinator falls back
102
130
  * to the complete stored prefix.
131
+ * Unknown-type refusal follows the same suffix scope: a seek-capable
132
+ * backend's `readFrom` checks only the returned suffix, while the
133
+ * sequential fallback parses the whole artifact and refuses on an unknown
134
+ * required event anywhere in it — over-refusal on the sequential side is
135
+ * accepted rather than widening the seek read.
103
136
  * @param id - persisted session id to resolve.
104
137
  * @param fromSeq - first event seq to include (non-negative safe integer,
105
138
  * validated by the coordinator before this hook runs).
@@ -126,6 +159,13 @@ export interface PersistenceBackend<TornMarker = unknown> {
126
159
  * @param signal - optional cancellation for backend listing work.
127
160
  */
128
161
  list(signal?: AbortSignal): Promise<SessionHeader[]>;
162
+ /**
163
+ * Optional side-effect-free artifact locator, used to point refusal
164
+ * diagnostics ({@link SessionFormatUnsupportedError}) at the raw log.
165
+ * Backends without one artifact per session omit it or return `undefined`.
166
+ * @param meta - the header whose artifact is requested.
167
+ */
168
+ locate?(meta: SessionHeader): SessionLocation | undefined;
129
169
  /**
130
170
  * Optional lifecycle teardown (e.g. close a database handle). Awaited by the
131
171
  * coordinator's dispose effect AFTER the quiescence drain. A stateless file
@@ -248,6 +288,19 @@ export declare class PersistenceCoordinator<TornMarker = unknown> {
248
288
  /** Build a state for a session discovered in storage but not yet in memory. */
249
289
  private adopt;
250
290
  private assertVersion;
291
+ /**
292
+ * Refuse a log containing an event type this build does not know, unless the
293
+ * writer marked the event ignorable: an unrecognized required event may
294
+ * change how the rest of the log must be interpreted, so silently skipping
295
+ * it would reconstruct a wrong session (the envelope contract on
296
+ * `SessionEvent.ignorable`). Runs on NORMALIZED events — after
297
+ * `snapshotStoredEvents`/`adoptStoredEvents` has upgraded the legacy shapes
298
+ * this build still reads and rejected the ones it does not, so those keep
299
+ * their specific diagnostics.
300
+ */
301
+ private assertEventsSupported;
302
+ /** Build a format refusal that points at the raw artifact when the backend has one. */
303
+ private unsupported;
251
304
  /** Reject backend metadata that is not bound to the requested session id. */
252
305
  private assertStoredId;
253
306
  private installWritePath;
@@ -24,7 +24,16 @@ export interface SessionInspection {
24
24
  /** Validated contiguous logical event log. */
25
25
  readonly events: readonly SessionEvent[];
26
26
  }
27
- export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionPersistenceCorruptionError, } from './coordinator.ts';
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';
28
37
  export type { PersistenceBackend, PersistenceCoordinatorOptions, StoredPrefix, StoredSuffix, } from './coordinator.ts';
29
38
  declare module '@deepseek-ai/cordis' {
30
39
  interface Context {
@@ -58,6 +67,27 @@ export declare abstract class SessionPersistence extends Service {
58
67
  * @returns the backend-specific absolute location, when one exists.
59
68
  */
60
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>;
61
91
  /**
62
92
  * Register a new session's metadata. A backend MAY defer the physical write
63
93
  * until the first {@link append} (lazy materialization), in which case a
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-session-persistence",
3
3
  "description": "Abstract durable session persistence seam (ctx.sessionPersistence) for the DeepSeek Harness",
4
- "version": "0.0.1-rc.1",
4
+ "version": "0.0.1-rc.3",
5
5
  "publishConfig": {
6
6
  "access": "restricted"
7
7
  },
@@ -32,18 +32,18 @@
32
32
  ],
33
33
  "license": "BSD-3-Clause",
34
34
  "peerDependencies": {
35
- "@deepseek-ai/dsh-brand": "^0.0.1-rc.1",
36
- "@deepseek-ai/dsh-invariants": "^0.0.1-rc.1",
37
- "@deepseek-ai/dsh-session": "^0.0.1-rc.1",
38
- "@deepseek-ai/dsh-timeout": "^0.0.1-rc.1",
35
+ "@deepseek-ai/dsh-invariants": "^0.0.1-rc.3",
36
+ "@deepseek-ai/dsh-brand": "^0.0.1-rc.3",
37
+ "@deepseek-ai/dsh-session": "^0.0.1-rc.3",
38
+ "@deepseek-ai/dsh-timeout": "^0.0.1-rc.3",
39
39
  "@deepseek-ai/cordis": "^4.0.1-rc.1"
40
40
  },
41
41
  "devDependencies": {
42
- "@deepseek-ai/dsh-brand": "^0.0.1-rc.1",
43
- "@deepseek-ai/dsh-invariants": "^0.0.1-rc.1",
44
- "@deepseek-ai/dsh-scope": "^0.0.1-rc.1",
45
- "@deepseek-ai/dsh-session": "^0.0.1-rc.1",
46
- "@deepseek-ai/dsh-timeout": "^0.0.1-rc.1",
42
+ "@deepseek-ai/dsh-invariants": "^0.0.1-rc.3",
43
+ "@deepseek-ai/dsh-brand": "^0.0.1-rc.3",
44
+ "@deepseek-ai/dsh-scope": "^0.0.1-rc.3",
45
+ "@deepseek-ai/dsh-session": "^0.0.1-rc.3",
46
+ "@deepseek-ai/dsh-timeout": "^0.0.1-rc.3",
47
47
  "@deepseek-ai/cordis": "^4.0.1-rc.1"
48
48
  }
49
49
  }