@x1a0f3n9/dsh-session-persistence-jsonl 0.1.5-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/LICENSE +21 -0
- package/README.i18n.yaml +6 -0
- package/README.md +170 -0
- package/README.zh.md +170 -0
- package/lib/index.js +3726 -0
- package/lib/types/format.d.ts +209 -0
- package/lib/types/generation.d.ts +163 -0
- package/lib/types/history-suffix.d.ts +16 -0
- package/lib/types/index.d.ts +304 -0
- package/lib/types/lease.d.ts +57 -0
- package/lib/types/migration-verifier.d.ts +15 -0
- package/lib/types/storage.d.ts +263 -0
- package/lib/types/testing/generation.d.ts +8 -0
- package/lib/types/win32.d.ts +48 -0
- package/lib/types/worker.d.ts +3 -0
- package/lib/types/zstd-private-decoder.d.ts +33 -0
- package/lib/types/zstd-public-decoder.d.ts +15 -0
- package/lib/types/zstd.d.ts +68 -0
- package/lib/worker.cjs +1246 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.i18n.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
|
2
|
+
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
|
3
|
+
# after editing either side, bring the other along and re-record with:
|
|
4
|
+
# pnpm run verify-translation-pairing --write packages/session/session-persistence-jsonl/README.md
|
|
5
|
+
README.md: 0bb86e0acca502b174675fdfec7e0e67ef8a3bee
|
|
6
|
+
README.zh.md: 77063838de8efe50b9fb88f6534d8881f7093195
|
package/README.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "The shipped JSONL session-persistence backend for deployments and maintainers choosing, configuring, or debugging per-session durable logs with optional Zstandard compression."
|
|
3
|
+
kind: "package-reference"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @x1a0f3n9/dsh-session-persistence-jsonl
|
|
7
|
+
|
|
8
|
+
English | [中文](README.zh.md)
|
|
9
|
+
|
|
10
|
+
## Summary
|
|
11
|
+
|
|
12
|
+
`dsh-session-persistence-jsonl` stores each session in a current JSONL log and retains immutable historical format generations — checksummed Zstandard frames by default, raw newline-delimited lines when compression is disabled. Ordinary writes append; explicit destructive deletion rewrites only the current generation's retained prefix. It serves the current logical `SessionEvent` stream through persistence handles, so format migration, compression, historical decoding, and crash recovery remain storage-internal details. Choose it when consumers need a per-session file on disk; the logs are readable as plain lines when `compression: 'none'` is selected. A root directory is the one required configuration; durability, lazy materialization, [supported historical-format migration](../session-format-catalog/README.md), and torn-tail crash recovery come with the backend.
|
|
13
|
+
|
|
14
|
+
## Table of Contents
|
|
15
|
+
|
|
16
|
+
- [Use this package](#use-this-package)
|
|
17
|
+
- [Understand the implementation](#understand-the-implementation)
|
|
18
|
+
- [Further Exploration](#further-exploration)
|
|
19
|
+
- [Model Experience](#model-experience)
|
|
20
|
+
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
|
21
|
+
- [Dev Note](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## Use this package
|
|
27
|
+
|
|
28
|
+
Mount this backend when a composition needs durable sessions backed by per-session files. The common path is explicit: load the session service, mount the backend, and give it a root directory.
|
|
29
|
+
|
|
30
|
+
### When to choose it
|
|
31
|
+
|
|
32
|
+
Choose this backend when consumers benefit from one artifact per session — navigation, external tooling, or a raw line-readable log. It is the sole first-party Session-persistence provider. The backend keeps sessions under a deployment-controlled root: project-local, shared, temporary, or centralized.
|
|
33
|
+
|
|
34
|
+
### Minimal configuration
|
|
35
|
+
|
|
36
|
+
```yaml
|
|
37
|
+
- name: '@x1a0f3n9/dsh-session'
|
|
38
|
+
- name: '@x1a0f3n9/dsh-session-persistence-jsonl'
|
|
39
|
+
config:
|
|
40
|
+
root: /absolute/path/to/session-logs
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`root` is required and has no default: a `process.cwd()` default would scatter session files as the process's cwd changes. An existing root must be a readable directory; an absent root is created on first materialization.
|
|
44
|
+
|
|
45
|
+
| Field | Default | Meaning |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| `root` | required | Root directory for all session files |
|
|
48
|
+
| `compression` | `'zstd'` | Physical encoding: `'zstd'` checksummed frames, or `'none'` newline-delimited UTF-8 text |
|
|
49
|
+
|
|
50
|
+
Live-event write batching is not configuration: the batching window is the seam's internal scheduling policy inside each write handle.
|
|
51
|
+
|
|
52
|
+
The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-persistence-jsonl) is the exhaustive source for every accepted field and its JSDoc.
|
|
53
|
+
|
|
54
|
+
### On-disk layout
|
|
55
|
+
|
|
56
|
+
Each session gets a session-owned directory under a readable project directory. Every canonical generation starts with a physical header whose version equals its filename. The current format stores one physical row per durable event; the frozen v0 and v1 readers also understand their historical packed Assistant-delta rows. The current format stores `isSeeded` in the header and derives the inherited cut from the last tagged `session/end-seed` marker, while historical codecs translate their numeric `seedLength`. The format catalog completes that translation before a handle exposes current logical values. Current storage records use the lossless provenance representation described below:
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
<root>/
|
|
60
|
+
--<normalized-cwd>--/ # readable project directory (or _no-cwd/)
|
|
61
|
+
<encoded-id>/ # session-owned directory
|
|
62
|
+
session.jsonl.zstd # released v0, compressed root
|
|
63
|
+
session.v1.jsonl.zstd # released v1, compressed root
|
|
64
|
+
session.v2.jsonl.zstd # released v2, compressed root
|
|
65
|
+
session.jsonl # released v0, raw root
|
|
66
|
+
session.v1.jsonl # released v1, raw root
|
|
67
|
+
session.v2.jsonl # released v2, raw root; later versions use vN
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Session ids are injectively escaped to one safe path segment before use (no traversal, no collision). The normalized cwd keeps the project directory readable for navigation; cwd strings that normalize alike share a project directory while session ids still select distinct session directories. Runtime operations select the numerically highest canonical generation, and format-refusal diagnostics name that absolute path so an operator can find the raw log a build refused to interpret.
|
|
71
|
+
|
|
72
|
+
### Durability and crash semantics
|
|
73
|
+
|
|
74
|
+
A session is materialized lazily: `create(header)` writes nothing and returns the owned write handle, and the handle's first `append` writes and `fsync`s the encoded header and first batch through a no-overwrite publish — so a created-but-never-appended session leaves nothing on disk unless its owner calls `handle.flush()`, which publishes one header frame without an event. Each subsequent batch appends lines or one compressed frame and `fsync`s before the append resolves; a caught write or sync failure rolls the file back to its prior length. Committed events are never rewritten. After a crash, the stored log keeps its interrupted final turn — every record in the committed prefix survives, and the resuming reader appends synthetic closers through its write handle. An incomplete final raw line is discarded. A torn final Zstandard frame contributes only its complete decoded JSONL records; a write handle truncates the torn bytes and durably rewrites those recovered records before its first new batch. Checksum, decompression, or structural failure in a complete committed frame rejects as corruption.
|
|
75
|
+
|
|
76
|
+
The current-generation scanner applies the current codec owner’s structural admission checks before recoverable-tail handling. Retired required PTC tags and `request/header.header.system` refuse the file even after an earlier malformed row; recovery never truncates them as ordinary damaged tail data.
|
|
77
|
+
|
|
78
|
+
### Reading the logs
|
|
79
|
+
|
|
80
|
+
`open(id, 'read'|'write')` selects the highest canonical generation. Current input follows the ordinary fast path. For historical input, a read open decodes and migrates the source once, validates the current logical result, and returns it without publishing a successor. A write open reuses that revision-keyed preparation when available, or performs the same preparation, then encodes a same-directory temporary file in bounded chunks, verifies it in a Worker Thread, rechecks the source revision, and publishes the current successor without overwrite before returning. The source remains byte-identical. Source drift after preparation rejects that write open without replacing the logical history already returned to readers; a later write open prepares the new revision. The backend marks decoded event graphs `shared-frozen` when it freezes them before memoization; handle reads and slices preserve that state, including empty slices. Only an unmaterialized pending log reports `detached`. `stat(id)` and `list()` select and translate only the highest generation header without reading event rows or starting migration; snapshots carry `sizeBytes` and a best-effort stat-derived revision for the selected file. With `compression: 'none'`, the log is newline-delimited text an external reader can consume directly; the compressed default must be read through the backend.
|
|
81
|
+
|
|
82
|
+
-----
|
|
83
|
+
|
|
84
|
+
<a id="understand-the-implementation"></a>
|
|
85
|
+
## Understand the implementation
|
|
86
|
+
|
|
87
|
+
<details>
|
|
88
|
+
<summary>Implementation internals — click to expand</summary>
|
|
89
|
+
|
|
90
|
+
This section explains the physical encoding and write path; the observable contract is covered in [Use this package](#use-this-package).
|
|
91
|
+
|
|
92
|
+
### Design concept
|
|
93
|
+
|
|
94
|
+
The backend owns its complete storage runtime (`src/storage.ts`): `JsonlSessionHandle` carries the per-handle mutation chain, the routed live-event buffer with its fixed batching window and single-flight drain, monotonic reads, and idempotent close; a tracker holds the in-process single-writer claims, the open-handle set teardown sweeps, and the created-but-unmaterialized pending sessions the backend's own session listeners route into. Historical body reads share one per-session Decode/Migrate preparation, and a bounded revision-keyed memo lets an immediate observe-to-resume handoff reuse that parse; the backend deep-freezes each event graph once before memoization, so later handle reads reuse it without copying or freezing. Only a write open publishes the prepared successor. The package deliberately exposes only its default plugin export plus configuration types — the concrete class is not a named export, so consumers couple to `ctx.sessionPersistence`, and the shared seam suites (`runPersistenceContract`/`runLiveWritePathContract`) pin its observable behavior. Its change token is a best-effort file revision: device, inode, size, and nanosecond timestamps identify one log for `stat`/`list`, for the stable-read loop that retries a read torn by a concurrent append, and for the pre-publication source check.
|
|
95
|
+
|
|
96
|
+
### Physical encoding
|
|
97
|
+
|
|
98
|
+
The default artifact is a standard concatenation of independent [Zstandard frames](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md): one checksummed frame containing only the header line, then one checksummed frame per durable append batch, using Node's built-in Zstandard API at its default compression level (no level knob). The current format writes one event per row; `sourceEventSeqs` uses a lossless storage representation in which consecutive runs of at least three sequence numbers become `[start, end]` pairs, any other list stays verbatim, and reading expands the exact in-memory array. Historical migration reuses one Zstandard decoder, passes parsed rows through stateful format stages, and streams current records through one compression context in about 1 MiB main-thread slices while retaining only final current events, bounded decoder state, and the required sequence-remap table. Listing reads and validates only the header frame. `compression: 'none'` keeps the same storage-form logical lines without frame compression. A root belongs to one encoding: startup discovery and targeted lookup reject generations with the other suffix; format migration preserves the configured encoding, while compression conversion, mixed-root fallback, and dual write remain unsupported. Frozen v0 and v1 codecs retain their packed-row decoders solely for historical generations.
|
|
99
|
+
|
|
100
|
+
### Source map
|
|
101
|
+
|
|
102
|
+
| File | Role |
|
|
103
|
+
|---|---|
|
|
104
|
+
| [`src/index.ts`](src/index.ts) | Plugin entry: `Config` schema, the backend service class, and file storage primitives |
|
|
105
|
+
| [`src/storage.ts`](src/storage.ts) | The JSONL handle, routed live-event buffer, in-process writer bookkeeping, listeners, teardown |
|
|
106
|
+
| [`src/format.ts`](src/format.ts) | Log path derivation, header encoding, and current record scanning |
|
|
107
|
+
| [`src/generation.ts`](src/generation.ts) | Single-pass historical restore, bounded stage encoding, source revision check, and exclusive successor publication |
|
|
108
|
+
| [`src/migration-verifier.ts`](src/migration-verifier.ts) | Worker lifecycle for staged and competing-generation verification |
|
|
109
|
+
| [`src/zstd.ts`](src/zstd.ts) | Zstandard frame compression, decoding, and frame scanning |
|
|
110
|
+
| [`src/win32.ts`](src/win32.ts) | Windows write-through publish and directory creation |
|
|
111
|
+
| — | No runtime invariant companion is published; persistence correctness requires backend round-trip and crash-tail tests; this package exposes no continuously observable in-process relation. |
|
|
112
|
+
|
|
113
|
+
</details>
|
|
114
|
+
|
|
115
|
+
-----
|
|
116
|
+
|
|
117
|
+
<a id="further-exploration"></a>
|
|
118
|
+
## Further Exploration
|
|
119
|
+
|
|
120
|
+
Read these pages when the package-level contract is not enough. They move from the shared persistence model to the sibling backend and the physical-format decisions.
|
|
121
|
+
|
|
122
|
+
- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — backend-neutral service semantics and provider relationships.
|
|
123
|
+
- [Session persistence seam](../session-persistence/README.md) — the service contract this backend implements.
|
|
124
|
+
- [Project-session directory decision](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) — the layout tradeoff behind project and session directories.
|
|
125
|
+
- [Zstandard JSONL session logs](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md) — the checksummed-frame encoding rationale.
|
|
126
|
+
- [Released Session format migrations](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md) — immutable generations, adjacent migration edges, and publication rules.
|
|
127
|
+
|
|
128
|
+
-----
|
|
129
|
+
|
|
130
|
+
<a id="model-experience"></a>
|
|
131
|
+
## Model Experience
|
|
132
|
+
|
|
133
|
+
### Resumed conversation history
|
|
134
|
+
|
|
135
|
+
#### What the model sees
|
|
136
|
+
|
|
137
|
+
JSONL storage contributes no live prompt or schema. Loading restores stored surface history and preserves prior request headers for reconstruction; the new loop composes its current envelope. Recovery balances an assistant request without a durable call with `TOOL_NOT_STARTED`; a durable call without a result becomes `TOOL_OUTCOME_UNKNOWN`, which tells the model to retry only read-only or idempotent work and to verify possible side effects or ask the user. Embedded Assistant streams and log-only attempts do not duplicate messages.
|
|
138
|
+
|
|
139
|
+
#### Token effect
|
|
140
|
+
|
|
141
|
+
Zero live-request tokens. A resumed agent pays for retained history and its current envelope, plus the quoted repair result for each interrupted call.
|
|
142
|
+
|
|
143
|
+
#### KV Cache effect
|
|
144
|
+
|
|
145
|
+
JSONL storage does not mutate live request prefixes. A resumed loop can reuse provider cache only when its reconstructed history, current envelope, and model route match; crash-repair results append.
|
|
146
|
+
|
|
147
|
+
## Known Limitations and Deferred Work
|
|
148
|
+
|
|
149
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
These limits define when this backend is a poor fit or needs special operational care. They are current package constraints, not a task backlog.
|
|
153
|
+
|
|
154
|
+
- **Format migration preserves the configured encoding and supports only the catalogued chain** — this build migrates supported historical generations to the current format; changing compression requires a separate root, and retained predecessors do not provide automatic fallback or downgrade support.
|
|
155
|
+
- **The flat-file storage layout does not load** — use a separate root or move pre-release artifacts into the project/session directory layout before loading.
|
|
156
|
+
- **Compressed files are not directly line-readable** — use the backend to load them, or select `compression: 'none'` before writing a fresh root when external line readers are required.
|
|
157
|
+
- **Nothing deletes session files** — logs accumulate under `root` until removed externally; the seam has no deletion API.
|
|
158
|
+
- **One live writer per session** — the write-handle claim excludes a second writer inside the owning backend instance, and a kernel lock (non-blocking `flock(2)` on `session.lock`; on Windows a named kernel semaphore derived from that path, with no filesystem footprint) excludes every other instance and process; the lock is taken at write-open of an existing artifact and, for a created session, only right before its first materializing write, so an unmaterialized session leaves no filesystem footprint. A crashed holder's lock dies with its process, so its session is writable again immediately, while a live-but-wedged holder blocks writers until its process exits (on POSIX, removing the lock file forfeits that exclusion; release itself never removes it). Advisory `flock` is unreliable on some network filesystems (NFSv3), and the Windows semaphore name is per login session.
|
|
159
|
+
- **POSIX materialization requires hard-link support** — first append uses `link()` so same-id races fail instead of overwriting a committed log; Windows uses write-through rename without replacement.
|
|
160
|
+
- **POSIX writes require the matching prebuilt system addon** — [`node-addon-system`](../../../native/system/README.md) supplies asynchronous flock without consumer-side compilation. A missing addon rejects write ownership; Windows retains its semaphore implementation.
|
|
161
|
+
|
|
162
|
+
<a id="dev-note"></a>
|
|
163
|
+
### Dev Note
|
|
164
|
+
|
|
165
|
+
<details>
|
|
166
|
+
<summary>Working context for maintainers — click to expand</summary>
|
|
167
|
+
|
|
168
|
+
None.
|
|
169
|
+
|
|
170
|
+
</details>
|
package/README.zh.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "面向部署方与维护者的随产品交付 JSONL 会话持久化后端说明,用于选择、配置或排查带可选 Zstandard 压缩的逐会话持久日志。"
|
|
3
|
+
kind: "package-reference"
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @x1a0f3n9/dsh-session-persistence-jsonl
|
|
7
|
+
|
|
8
|
+
[English](README.md) | 中文
|
|
9
|
+
|
|
10
|
+
## 概述
|
|
11
|
+
|
|
12
|
+
`dsh-session-persistence-jsonl` 把每个会话存为当前 JSONL 日志,并保留不可变的历史格式 generation——默认以带校验和的 Zstandard 帧存储,禁用压缩时以换行分隔的原始文本行存储。普通写入仍是追加;显式破坏性删除只重写当前 generation 的保留前缀。它通过持久化句柄提供当前逻辑 `SessionEvent` 流,因此格式迁移、压缩、历史解码与崩溃恢复仍是存储内部细节。当消费方需要按会话的磁盘文件时选择它;选择 `compression: 'none'` 后日志可作为纯文本按行读取。根目录是唯一必填配置;持久性、延迟实体化、[受支持的历史格式迁移](../session-format-catalog/README.zh.md)与撕裂尾部崩溃恢复都随后端提供。
|
|
13
|
+
|
|
14
|
+
## 目录
|
|
15
|
+
|
|
16
|
+
- [使用本包](#use-this-package)
|
|
17
|
+
- [理解实现](#understand-the-implementation)
|
|
18
|
+
- [进一步探索](#further-exploration)
|
|
19
|
+
- [模型体验](#model-experience)
|
|
20
|
+
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
|
21
|
+
- [开发备注](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## 使用本包
|
|
27
|
+
|
|
28
|
+
当组合需要由按会话文件支撑的持久会话时挂载此后端。常用路径是显式的:加载会话服务、挂载后端,然后给出根目录。
|
|
29
|
+
|
|
30
|
+
### 何时选择
|
|
31
|
+
|
|
32
|
+
当消费方受益于每会话一份产物——导航、外部工具或可逐行读取的原始日志——时选择此后端。它是随产品交付的唯一 Session 持久化 provider。后端把会话保存在部署控制的根下:项目本地、共享、临时或集中式。
|
|
33
|
+
|
|
34
|
+
### 最小配置
|
|
35
|
+
|
|
36
|
+
```yaml
|
|
37
|
+
- name: '@x1a0f3n9/dsh-session'
|
|
38
|
+
- name: '@x1a0f3n9/dsh-session-persistence-jsonl'
|
|
39
|
+
config:
|
|
40
|
+
root: /absolute/path/to/session-logs
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`root` 必填且无默认值:`process.cwd()` 默认值会随进程 cwd 变更而分散会话文件。现有根必须是可读目录;缺失根在第一次实体化时创建。
|
|
44
|
+
|
|
45
|
+
| 字段 | 默认值 | 含义 |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| `root` | 必填 | 所有会话文件的根目录 |
|
|
48
|
+
| `compression` | `'zstd'` | 物理编码:`'zstd'` 带校验和帧,或 `'none'` 换行分隔 UTF-8 文本 |
|
|
49
|
+
|
|
50
|
+
实时事件的写入批处理不是配置:批处理窗口是该 seam 在每个写句柄内部的调度策略。
|
|
51
|
+
|
|
52
|
+
生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-persistence-jsonl)是每个受支持字段及其 JSDoc 的穷尽式真源。
|
|
53
|
+
|
|
54
|
+
### 磁盘布局
|
|
55
|
+
|
|
56
|
+
每个会话在可读项目目录下获得一个会话自有目录。每个规范 generation 都以版本与文件名一致的物理 header 开始。当前格式为每个持久事件存储一行;冻结的 v0 与 v1 reader 也能理解其历史 packed Assistant delta 行。当前格式在 header 中存储 `isSeeded`,并从最后一个带标记的 `session/end-seed` 推导 inherited cut;历史 codec 则转换其数字 `seedLength`。格式 catalog 会在句柄暴露当前逻辑值之前完成该转换。当前存储记录使用下文所述的无损来源序列表示:
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
<root>/
|
|
60
|
+
--<normalized-cwd>--/ # readable project directory (or _no-cwd/)
|
|
61
|
+
<encoded-id>/ # session-owned directory
|
|
62
|
+
session.jsonl.zstd # released v0, compressed root
|
|
63
|
+
session.v1.jsonl.zstd # released v1, compressed root
|
|
64
|
+
session.v2.jsonl.zstd # released v2, compressed root
|
|
65
|
+
session.jsonl # released v0, raw root
|
|
66
|
+
session.v1.jsonl # released v1, raw root
|
|
67
|
+
session.v2.jsonl # released v2, raw root; later versions use vN
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
会话 id 在使用前被单射转义为一个安全路径段(无遍历、无冲突)。规范化 cwd 让项目目录保持可读、便于导航;规范化相同的 cwd 字符串共享项目目录,而会话 id 仍选择不同会话目录。runtime 操作选择数值最高的规范 generation,格式拒绝诊断会点名该绝对路径,让操作者能找到构建拒绝解读的原始日志。
|
|
71
|
+
|
|
72
|
+
### 持久性与崩溃语义
|
|
73
|
+
|
|
74
|
+
会话延迟实体化:`create(header)` 不写入任何内容并返回持有的写句柄,句柄的第一次 `append` 通过无覆盖发布写入并 `fsync` 编码后的 header 与第一批——因此已创建但从未 append 的会话不留下任何磁盘内容,除非其所有者调用 `handle.flush()`,以无事件的单个 header 帧发布它。后续每个批次追加行或一个压缩帧,并在 append 完成前 `fsync`;捕获到写入或同步失败时把文件回滚到之前的字节长度。已提交事件绝不重写。崩溃后,已存储日志保留被中断的最终轮次——已提交前缀中的每条记录都保留下来,由执行恢复的读方通过其写句柄追加合成 closer。不完整的最终原始行会被丢弃。撕裂的最终 Zstandard 帧只贡献其中完整解码出的 JSONL 记录;写句柄会截掉撕裂字节,并在第一次新批次之前持久重写这些恢复出的记录。完整已提交帧中的校验和、解压或结构失败以损坏拒绝。
|
|
75
|
+
|
|
76
|
+
当前代际扫描器在处理可恢复尾部之前,执行当前编解码器所有者的结构准入检查。已退役的必需 PTC 标签与 `request/header.header.system` 即使出现在较早的畸形行之后也会导致文件被拒绝;恢复绝不将它们作为普通损坏尾部数据截断。
|
|
77
|
+
|
|
78
|
+
### 读取日志
|
|
79
|
+
|
|
80
|
+
`open(id, 'read'|'write')` 选择最高规范 generation。当前格式输入走普通快速路径。对于历史输入,只读 open 会单遍解码并迁移源、校验当前逻辑结果,然后在不发布后继的情况下返回。写 open 会在可用时复用按 revision 为键的 preparation,否则执行同一套 preparation,再按有界分片编码同目录临时文件、在 Worker Thread 中校验、复查源修订,并在返回前以不覆盖方式发布当前后继。源保持逐字节不变。如果源在 preparation 后发生变化,该次写 open 会失败,已经返回给读方的逻辑历史不会被替换;后续写 open 会针对新的 revision 重新执行 preparation。Backend 在 memo 化前冻结已解码的 event graph,并在此时将其标记为 `shared-frozen`;句柄读取和 slice 即使为空也保留该状态。只有尚未实体化的 pending 空日志报告 `detached`。`stat(id)` 与 `list()` 只选择并转换最高 generation 的 header,不读取事件行,也不启动迁移;快照携带所选文件的 `sizeBytes` 与尽力而为的 stat 派生修订号。选择 `compression: 'none'` 后,日志是外部读取方可直接消费的换行分隔文本;压缩默认值必须经后端读取。
|
|
81
|
+
|
|
82
|
+
-----
|
|
83
|
+
|
|
84
|
+
<a id="understand-the-implementation"></a>
|
|
85
|
+
## 理解实现
|
|
86
|
+
|
|
87
|
+
<details>
|
|
88
|
+
<summary>实现细节——点击展开</summary>
|
|
89
|
+
|
|
90
|
+
本节说明物理编码与写入路径;可观察约定已在[使用本包](#use-this-package)中说明。
|
|
91
|
+
|
|
92
|
+
### 设计理念
|
|
93
|
+
|
|
94
|
+
该后端拥有自己完整的存储运行时(`src/storage.ts`):`JsonlSessionHandle` 承载逐句柄修改链、带固定批处理窗口与 single-flight 排空的已路由实时事件缓冲、单调读取与幂等 close;一个 tracker 持有进程内单写者认领、teardown 清扫所遍历的打开句柄集合,以及后端自己的会话监听器所路由进的已创建但未实体化待定会话。历史正文读取共享每个 Session 唯一的一次 Decode/Migrate preparation,按 revision 为键的有界 memo 让紧接的观察到恢复交接复用该解析;backend 在 memo 化前只对每个 event graph 深度冻结一次,因此后续 handle read 无需复制或再次冻结。只有写 open 才发布准备好的后继。本包有意只暴露默认插件导出与配置类型——具体类不是具名导出,因此消费方只耦合 `ctx.sessionPersistence`,其可观察行为由共享 seam 测试套件(`runPersistenceContract`/`runLiveWritePathContract`)钉住。其变更令牌是尽力而为的文件修订值:device、inode、size 与纳秒时间戳标识一份日志,供 `stat`/`list`、在并发 append 撕裂读取时重试的稳定读取循环,以及发布前源检查使用。
|
|
95
|
+
|
|
96
|
+
### 物理编码
|
|
97
|
+
|
|
98
|
+
默认产物是独立 [Zstandard 帧](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md) 的标准拼接:一个仅包含 header 行的带校验和帧,后跟每个持久 append 批次一个带校验和帧,使用 Node 内置 Zstandard API 的默认压缩级别(无级别开关)。当前格式为每个事件写一行;`sourceEventSeqs` 使用无损存储形式:至少包含三个序列号的连续段会变成 `[start, end]` 区间对,其他列表原样保留;读取时会展开回精确的内存数组。历史迁移会复用一个 Zstandard decoder,让已解析行流经有状态格式 Stage,并通过一个压缩 context 以约 1 MiB 主线程分片流式写入当前记录,同时只保留最终当前事件、有界 decoder 状态与必需的序号重映射表。列表只读取并验证 header 帧。`compression: 'none'` 保留相同的存储形式逻辑行,但不使用帧压缩。一个根只属于一种编码:启动发现与定向查找会拒绝使用另一后缀的 generation;格式迁移保留已配置编码,而压缩转换、混合根回退与双写仍不受支持。冻结的 v0 与 v1 codec 仅为历史 generation 保留 packed-row decoder。
|
|
99
|
+
|
|
100
|
+
### 源码地图
|
|
101
|
+
|
|
102
|
+
| 文件 | 职责 |
|
|
103
|
+
|---|---|
|
|
104
|
+
| [`src/index.ts`](src/index.ts) | 插件入口:`Config` schema、后端服务类与文件存储原语 |
|
|
105
|
+
| [`src/storage.ts`](src/storage.ts) | JSONL 句柄、已路由实时事件缓冲、进程内写入者记账、监听器、teardown |
|
|
106
|
+
| [`src/format.ts`](src/format.ts) | 日志路径派生、header 编码与当前记录扫描 |
|
|
107
|
+
| [`src/generation.ts`](src/generation.ts) | 单遍历史还原、有界 stage 编码、源 revision 检查与排他后继发布 |
|
|
108
|
+
| [`src/migration-verifier.ts`](src/migration-verifier.ts) | stage 与竞争 generation 校验的 Worker 生命周期 |
|
|
109
|
+
| [`src/zstd.ts`](src/zstd.ts) | Zstandard 帧压缩、解码与帧扫描 |
|
|
110
|
+
| [`src/win32.ts`](src/win32.ts) | Windows write-through 发布与目录创建 |
|
|
111
|
+
| — | 不发布运行时不变式伴生入口;身份在存储层强制。 |
|
|
112
|
+
|
|
113
|
+
</details>
|
|
114
|
+
|
|
115
|
+
-----
|
|
116
|
+
|
|
117
|
+
<a id="further-exploration"></a>
|
|
118
|
+
## 进一步探索
|
|
119
|
+
|
|
120
|
+
当包级约定不够用时阅读以下页面。它们从共享持久化模型逐步进入同级后端与物理格式决策。
|
|
121
|
+
|
|
122
|
+
- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——后端无关的服务语义与提供方关系。
|
|
123
|
+
- [会话持久化 seam](../session-persistence/README.zh.md)——本后端实现的服务约定。
|
|
124
|
+
- [项目会话目录决策](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md)——项目与会话目录布局背后的取舍。
|
|
125
|
+
- [Zstandard JSONL 会话日志](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md)——带校验和帧编码的理由。
|
|
126
|
+
- [已发布 Session 格式迁移](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)——不可变 generation、相邻迁移边与发布规则。
|
|
127
|
+
|
|
128
|
+
-----
|
|
129
|
+
|
|
130
|
+
<a id="model-experience"></a>
|
|
131
|
+
## 模型体验
|
|
132
|
+
|
|
133
|
+
### 恢复的对话历史
|
|
134
|
+
|
|
135
|
+
#### 模型看到什么
|
|
136
|
+
|
|
137
|
+
JSONL 存储不会向实时请求提供提示词或 schema。加载会恢复已存储的表层历史,并保留之前的请求 header 用于重建;新 loop 组合当前 envelope。恢复会用 `TOOL_NOT_STARTED` 平衡没有持久调用的 assistant 请求;持久调用无结果时则变为 `TOOL_OUTCOME_UNKNOWN`,它要求模型只重试只读或幂等工作,并验证可能的副作用或询问用户。嵌入式 Assistant stream 与仅日志 attempt 不会重复生成消息。
|
|
138
|
+
|
|
139
|
+
#### Token 影响
|
|
140
|
+
|
|
141
|
+
实时请求不新增 token。恢复后的 agent(智能体)会因保留的历史、当前 envelope,以及每个中断调用中以引用形式加入的修复结果文本而消耗 token。
|
|
142
|
+
|
|
143
|
+
#### KV Cache 影响
|
|
144
|
+
|
|
145
|
+
JSONL 存储不修改实时请求前缀。只有重建历史、当前 envelope 与模型路由匹配时,恢复 loop 才能重用提供方缓存;崩溃修复结果仅追加。
|
|
146
|
+
|
|
147
|
+
## 已知限制与延期工作
|
|
148
|
+
|
|
149
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
这些限制说明本后端何时不合适,或何时需要特别的运维注意。它们是当前包约束,不是任务积压。
|
|
153
|
+
|
|
154
|
+
- **格式迁移保留已配置编码,且只支持 catalog 中的链**——本 build 把受支持的历史代迁移到当前格式;更改压缩需要独立根,保留的前任不提供自动 fallback 或 downgrade 支持。
|
|
155
|
+
- **平铺文件存储布局不加载**——加载前使用独立根,或将预发布产物移入项目/会话目录布局。
|
|
156
|
+
- **压缩文件不能直接按行读取**——使用后端加载;或在写入新根前选择 `compression: 'none'`,供外部行读取方使用。
|
|
157
|
+
- **不删除会话文件**——日志在 `root` 下累积,直到外部移除;seam 无删除接口。
|
|
158
|
+
- **每会话一个活动写入方**——写句柄认领在所属后端实例内排除第二个写入方,内核锁(`session.lock` 上的非阻塞 `flock(2)`;Windows 上为由该路径派生的命名内核信号量,零文件系统足迹)排除其他所有实例与进程;锁在写打开既有工件时立即获取,新建会话则仅在首次物化写入之前获取,因此未物化的会话不留任何文件系统足迹。崩溃持有者的锁随其进程消亡,会话立即可再写入,而活着但卡死的持有者会阻塞写入方直到其进程退出(POSIX 上删除锁文件即放弃该排他;释放本身从不删除它)。咨询式 `flock` 在部分网络文件系统(NFSv3)上不可靠,Windows 信号量名按登录会话隔离。
|
|
159
|
+
- **POSIX 实体化需要硬链接支持**——第一次 append 使用 `link()`,使同 id 竞态失败而不覆盖已提交日志;Windows 使用无替换 write-through rename。
|
|
160
|
+
- **POSIX 写入需要匹配的预编译系统 addon**——[`node-addon-system`](../../../native/system/README.zh.md) 提供异步 flock,无须在用户侧编译。addon 缺失时拒绝写入所有权;Windows 保留其信号量实现。
|
|
161
|
+
|
|
162
|
+
<a id="dev-note"></a>
|
|
163
|
+
### 开发备注
|
|
164
|
+
|
|
165
|
+
<details>
|
|
166
|
+
<summary>维护者的工作上下文——点击展开</summary>
|
|
167
|
+
|
|
168
|
+
无。
|
|
169
|
+
|
|
170
|
+
</details>
|