dsh-plugin-guide 0.3.2 → 0.3.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.
Files changed (100) hide show
  1. package/README.es.md +1 -1
  2. package/README.hi.md +1 -1
  3. package/README.md +1 -1
  4. package/README.pt.md +1 -1
  5. package/README.zh.md +1 -1
  6. package/dist/dsh-plugin-dev.js +3 -3
  7. package/guide/plugin-dev-guide.md +1 -1
  8. package/guide/quick-reference.es.md +1 -1
  9. package/guide/quick-reference.md +1 -1
  10. package/guide/quick-reference.pt.md +1 -1
  11. package/guide/quick-reference.zh-CN.md +1 -1
  12. package/package.json +3 -3
  13. package/references/official-docs/AGENTS.md +1 -1
  14. package/references/official-docs/SNAPSHOT.md +3 -3
  15. package/references/official-docs/docs/architecture.i18n.yaml +2 -2
  16. package/references/official-docs/docs/architecture.md +2 -1
  17. package/references/official-docs/docs/architecture.zh.md +2 -1
  18. package/references/official-docs/docs/capability-seams.i18n.yaml +2 -2
  19. package/references/official-docs/docs/capability-seams.md +3 -1
  20. package/references/official-docs/docs/capability-seams.zh.md +3 -1
  21. package/references/official-docs/docs/config-catalog.i18n.yaml +2 -2
  22. package/references/official-docs/docs/config-catalog.md +96 -54
  23. package/references/official-docs/docs/config-catalog.zh.md +93 -51
  24. package/references/official-docs/docs/cookbook/adding-a-package.i18n.yaml +2 -2
  25. package/references/official-docs/docs/cookbook/adding-a-package.md +1 -1
  26. package/references/official-docs/docs/cookbook/adding-a-package.zh.md +1 -1
  27. package/references/official-docs/docs/event-producer-consumer.i18n.yaml +2 -2
  28. package/references/official-docs/docs/event-producer-consumer.md +17 -17
  29. package/references/official-docs/docs/event-producer-consumer.zh.md +17 -17
  30. package/references/official-docs/docs/module-graph.i18n.yaml +2 -2
  31. package/references/official-docs/docs/module-graph.md +193 -361
  32. package/references/official-docs/docs/module-graph.zh.md +193 -361
  33. package/references/official-docs/docs/persistence-catalog.i18n.yaml +2 -2
  34. package/references/official-docs/docs/persistence-catalog.md +41 -41
  35. package/references/official-docs/docs/persistence-catalog.zh.md +40 -40
  36. package/references/official-docs/docs/subsystems/agent-team.i18n.yaml +2 -2
  37. package/references/official-docs/docs/subsystems/agent-team.md +4 -3
  38. package/references/official-docs/docs/subsystems/agent-team.zh.md +4 -3
  39. package/references/official-docs/docs/subsystems/code-runtime.i18n.yaml +2 -2
  40. package/references/official-docs/docs/subsystems/code-runtime.md +7 -3
  41. package/references/official-docs/docs/subsystems/code-runtime.zh.md +7 -3
  42. package/references/official-docs/docs/subsystems/commands.i18n.yaml +2 -2
  43. package/references/official-docs/docs/subsystems/commands.md +1 -1
  44. package/references/official-docs/docs/subsystems/commands.zh.md +1 -1
  45. package/references/official-docs/docs/subsystems/compaction.i18n.yaml +2 -2
  46. package/references/official-docs/docs/subsystems/compaction.md +9 -9
  47. package/references/official-docs/docs/subsystems/compaction.zh.md +9 -9
  48. package/references/official-docs/docs/subsystems/core.i18n.yaml +2 -2
  49. package/references/official-docs/docs/subsystems/core.md +4 -3
  50. package/references/official-docs/docs/subsystems/core.zh.md +4 -3
  51. package/references/official-docs/docs/subsystems/feedback.i18n.yaml +2 -2
  52. package/references/official-docs/docs/subsystems/feedback.md +2 -2
  53. package/references/official-docs/docs/subsystems/feedback.zh.md +2 -2
  54. package/references/official-docs/docs/subsystems/persistence.i18n.yaml +2 -2
  55. package/references/official-docs/docs/subsystems/persistence.md +179 -187
  56. package/references/official-docs/docs/subsystems/persistence.zh.md +179 -187
  57. package/references/official-docs/docs/subsystems/schedule.i18n.yaml +2 -2
  58. package/references/official-docs/docs/subsystems/schedule.md +1 -1
  59. package/references/official-docs/docs/subsystems/schedule.zh.md +1 -1
  60. package/references/official-docs/docs/subsystems/session-projection.i18n.yaml +2 -2
  61. package/references/official-docs/docs/subsystems/session-projection.md +21 -17
  62. package/references/official-docs/docs/subsystems/session-projection.zh.md +21 -17
  63. package/references/official-docs/docs/subsystems/session-query.i18n.yaml +2 -2
  64. package/references/official-docs/docs/subsystems/session-query.md +19 -13
  65. package/references/official-docs/docs/subsystems/session-query.zh.md +19 -13
  66. package/references/official-docs/docs/subsystems/session-title.i18n.yaml +2 -2
  67. package/references/official-docs/docs/subsystems/session-title.md +5 -5
  68. package/references/official-docs/docs/subsystems/session-title.zh.md +5 -5
  69. package/references/official-docs/docs/subsystems/session.i18n.yaml +2 -2
  70. package/references/official-docs/docs/subsystems/session.md +94 -34
  71. package/references/official-docs/docs/subsystems/session.zh.md +94 -34
  72. package/references/official-docs/docs/subsystems/slots.i18n.yaml +2 -2
  73. package/references/official-docs/docs/subsystems/slots.md +1 -0
  74. package/references/official-docs/docs/subsystems/slots.zh.md +1 -0
  75. package/references/official-docs/docs/subsystems/storage.i18n.yaml +2 -2
  76. package/references/official-docs/docs/subsystems/storage.md +28 -5
  77. package/references/official-docs/docs/subsystems/storage.zh.md +28 -5
  78. package/references/official-docs/docs/subsystems/subagent.i18n.yaml +2 -2
  79. package/references/official-docs/docs/subsystems/subagent.md +32 -88
  80. package/references/official-docs/docs/subsystems/subagent.zh.md +31 -87
  81. package/references/official-docs/docs/subsystems/token-meter.i18n.yaml +2 -2
  82. package/references/official-docs/docs/subsystems/token-meter.md +2 -2
  83. package/references/official-docs/docs/subsystems/token-meter.zh.md +2 -2
  84. package/references/official-docs/docs/tool-catalog.i18n.yaml +2 -2
  85. package/references/official-docs/docs/tool-catalog.md +9 -63
  86. package/references/official-docs/docs/tool-catalog.zh.md +8 -62
  87. package/references/official-docs/docs/web-styling.i18n.yaml +2 -2
  88. package/references/official-docs/docs/web-styling.md +3 -0
  89. package/references/official-docs/docs/web-styling.zh.md +3 -0
  90. package/references/official-docs/packages/AGENTS.md +2 -2
  91. package/templates/js/README.es.md +1 -1
  92. package/templates/js/README.hi.md +1 -1
  93. package/templates/js/README.md +1 -1
  94. package/templates/js/README.pt.md +1 -1
  95. package/templates/js/README.zh.md +1 -1
  96. package/templates/ts/README.es.md +1 -1
  97. package/templates/ts/README.hi.md +1 -1
  98. package/templates/ts/README.md +1 -1
  99. package/templates/ts/README.pt.md +1 -1
  100. package/templates/ts/README.zh.md +1 -1
@@ -4,29 +4,112 @@ English | [中文](persistence.zh.md)
4
4
 
5
5
  The **durability seam** for the event log. [session.md](session.md) describes the in-memory `Session` — the append-only `SessionEvent` log that is the source of truth. This page describes how that log is made durable: the abstract `SessionPersistence` service, its provider model and shipped JSONL backend, the flush checkpoint, crash recovery, and the metadata header that travels alongside the log. The event vocabulary the log carries is enumerated, member by member, in the generated [persistence log event catalog](../persistence-catalog.md).
6
6
 
7
- The seam is a [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md): one abstract service ([dsh-session-persistence](../../packages/session/session-persistence), `ctx.sessionPersistence`) defines locate/create/append, reusable Session preparation, logical load/inspect, physical suffix reads, and lightweight list/snapshot observation over the existing `SessionEvent` — **no parallel persisted event type**. The repository ships [dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl) as its provider; out-of-tree providers may implement the same service contract. See the [session-persistence Agent Note](../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md).
7
+ The seam is a [capability seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md): one abstract service ([dsh-session-persistence](../../packages/session/session-persistence), `ctx.sessionPersistence`) exposing `create`/`open`/`stat`/`list` over the existing `SessionEvent` — **no parallel persisted event type** — where `create` and `open` return a per-session `SessionHandle` (`read`/`append`/`flush`/`close`) that carries all log access and single-writer ownership. The repository ships [dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl) as its provider; out-of-tree providers may implement the same service contract. See the [handle-based persistence Agent Note](../../.agents/notes/implemented/architecture/2026-08-27-handle-based-session-persistence.md) and the [session-persistence Agent Note](../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md).
8
+
9
+ ## `SessionHandle` — one open channel onto a stored session
10
+
11
+ Every log read and write flows through a handle, never through id-addressed service methods: the handle is the single door a future cross-process write lease will guard. One handle type serves both accesses — a mutation on a `read` handle is a runtime `SessionReadOnlyError` rather than a typed split — and in-process single-writer ownership makes a second `open(id, 'write')` reject with `SessionAlreadyOwnedError` while an owner is active.
12
+
13
+ ```ts type-equiv
14
+ /**
15
+ * One open channel onto a stored session. A handle is single-owner state, not
16
+ * a shared service: `read` never backtracks below what this handle already
17
+ * observed, a `write` handle reads its own successful appends, and `close()`
18
+ * is the one teardown (idempotent, uncancellable; `Symbol.asyncDispose`
19
+ * delegates to it). Every operation on a closed handle rejects with
20
+ * `SessionHandleClosedError`.
21
+ *
22
+ * Freshness across handles: once an `append` or `flush` resolves on a write
23
+ * handle, every read STARTED afterwards on the same backend instance — on any
24
+ * handle, or through `stat`/`list` — observes at least that prefix.
25
+ * Reads concurrent with a mutation carry no ordering promise beyond the valid
26
+ * contiguous prefix.
27
+ */
28
+ interface SessionHandle extends AsyncDisposable {
29
+ /** The stored session this handle addresses. */
30
+ readonly id: SessionId
31
+ /** The immutable stored header, fixed at `create`/`open`. */
32
+ readonly header: SessionHeader
33
+ /**
34
+ * Exact fork-inherited prefix length stored with the log; `0` when
35
+ * `header.isSeeded` is false. Storage metadata paired with the header for
36
+ * every body read, never part of the replayable event log.
37
+ */
38
+ readonly inheritedEventCount: SessionLogOffset
39
+ /** Whether this handle may mutate the log. */
40
+ readonly access: SessionAccess
41
+
42
+ /**
43
+ * Read a slice of the valid contiguous logical log. The slice is a legal log
44
+ * prefix segment: a torn physical tail is never returned, and repeated reads
45
+ * on this handle never observe an older state than a prior read.
46
+ * @param offset - first logical event seq to include; defaults to `0`.
47
+ * @param length - maximum number of events to return; defaults to the rest
48
+ * of the log. An offset at or past the end returns an empty list.
49
+ * @param options - optional cancellation.
50
+ * @returns the events with `seq >= offset`, at most `length` of them.
51
+ */
52
+ read(offset?: number, length?: number, options?: SessionHandleReadOptions): Promise<readonly SessionEvent[]>
53
+
54
+ /**
55
+ * Append a contiguous batch continuing the current logical end. The first
56
+ * event's `seq` MUST equal the stored next-seq; committed events are never
57
+ * rewritten. Persistence is best-effort: on resolution the batch is
58
+ * accepted, ordered, and visible to reads on this backend instance, but
59
+ * only a resolved {@link flush} promises it survives a crash — a backend
60
+ * may buffer or batch physical writes behind append. Rejects with
61
+ * `SessionReadOnlyError` on a read handle and `SessionOwnershipLostError`
62
+ * when write ownership is gone.
63
+ * @param events - the contiguous batch, in seq order.
64
+ * @param options - optional cancellation observed before the write starts.
65
+ */
66
+ append(events: readonly SessionEvent[], options?: SessionHandleAppendOptions): Promise<void>
67
+
68
+ /**
69
+ * The durability barrier — the one operation that promises storage: on
70
+ * resolution every acknowledged append is durable and the session is
71
+ * materialized for other processes; an empty created session becomes
72
+ * durably listable here. Callers that must survive a crash flush; a backend
73
+ * whose `append` already persists on resolution treats this as
74
+ * materialize-if-needed. Rejects with `SessionReadOnlyError` on a read
75
+ * handle.
76
+ * @param options - optional cancellation observed before the barrier starts.
77
+ */
78
+ flush(options?: SessionHandleFlushOptions): Promise<void>
79
+
80
+ /**
81
+ * Release the handle: a read handle frees local resources; a write handle
82
+ * completes pending durability and releases write ownership. Idempotent,
83
+ * asynchronous, and deliberately not cancellable.
84
+ */
85
+ close(): Promise<void>
86
+ }
87
+ ```
88
+
89
+ A created session is observable in this process from the moment `create` resolves, while a backend may defer physical materialization (a pure optimization) until the first `append` or `flush`; other processes see only materialized sessions, and a session that never materialized before a crash never existed.
8
90
 
9
91
  ## The flush checkpoint
10
92
 
11
- `session/event` is a *synchronous* notification; persistence plugins copy the event into a per-session controller without blocking the producer. The first pending event starts a fixed batching window, and later events join without resetting its deadline. Expiry starts one durable batch; events admitted during that write receive their own deadline and form a follow-up batch. `session/flush` cancels the wait and drains through quiescence, so the loop still uses it as the ordering and error-observation checkpoint before claiming the next ordinary turn. A rejected background write retains its events and pauses automatic retry; a new event starts a fresh window, while explicit flush retries immediately and reports failure through `agent/error` and the logger, never as a session event past the closed turn. Disposal performs the same final drain. The configured maximum bounds only intentional batching wait, not event-loop scheduling or backend durability latency ([decision](../../.agents/notes/implemented/architecture/2026-08-08-bounded-session-persistence-write-batching.md)).
93
+ `session/event` is a *synchronous* notification; the mounted backend routes it by session id into the active write handle's bounded write-behind window without blocking the producer (the backend installs these listeners once, because persistence already enforces one active write handle per id). The first pending event starts a fixed internal batching window, and later events join without resetting its deadline. Expiry starts one durable `append` through the session's write handle; events admitted during that write receive their own deadline and form a follow-up batch. `session/flush` cancels the wait and drains through quiescence, so the loop still uses it as the ordering and error-observation checkpoint before claiming the next ordinary turn. A rejected background write retains its events in order, pauses the automatic path, and is reported through the logger; the next explicit flush retries and rejects loudly to its caller. `session/disposed` performs the same final drain and closes the handle, and `close()` itself drains the routed buffer through the still-open storage, so backend teardown's close sweep loses nothing. The window bounds only intentional batching wait, not event-loop scheduling or backend durability latency ([decision](../../.agents/notes/implemented/architecture/2026-08-08-bounded-session-persistence-write-batching.md)).
12
94
 
13
95
  ## Crash recovery preserves an interrupted turn
14
96
 
15
- A backend that reloads a log crashed mid-turn finds an open `turn/start` with no `turn/end`. It does **not** truncate — a single turn can be huge in a long-horizon task (many steps, large tool output), and those events were durably appended before the crash. Instead it closes the orphaned turn with a synthetic `turn/end { reason: { kind: 'interrupted' } }`, keeping the interrupted execution balanced without changing any standalone events before or after it. `interrupted` is the one `TurnEndReason` no loop emits (see [session.md](session.md#why-a-turn-ended-turnendreasonmap)).
97
+ A log crashed mid-turn ends with an open `turn/start` and no `turn/end`. Persistence does **not** truncate or repair it — a single turn can be huge in a long-horizon task (many steps, large tool output), and those events were durably appended before the crash. It returns the physically valid contiguous log; only the incomplete fragment of a torn physical tail, belonging to an append that never resolved, is discarded — complete records recovered from it (the JSONL backend partially decodes a torn Zstandard frame) are durably rewritten by the write path before the handle's first new append. Repair is the reader's job: resume (agent-loop) reads the stored log through its write handle, computes `interruptedTurnClosers` — missing tool errors, any open `step/end`, and a synthetic `turn/end { reason: { kind: 'interrupted' } }` and appends them through the same handle as an ordinary batch before publishing the Session. `interrupted` is the one `TurnEndReason` no loop emits (see [session.md](session.md#why-a-turn-ended-turnendreasonmap)).
16
98
 
17
- Repair applies only to cold sessions. For a live id, `SessionPersistence.load(id)` waits until the authoritative in-memory snapshot is durable and returns it only when balanced; an open live turn rejects rather than receiving synthetic interruption boundaries. HMR adopts a live prefix without closing its active turn.
99
+ Repair therefore writes only under write ownership: a live session's write handle is held by its lifecycle owner, so a concurrent `open(id, 'write')` rejects with `SessionAlreadyOwnedError` instead of racing repair against a live turn. Read-only observers (session-query) balance an interrupted cold log with the same closers in memory only, writing nothing back.
18
100
 
19
- `SessionPersistence.inspect(id)` constructs an immutable logical Session without publishing it or writing recovery. Cold inspection balances an interrupted turn in memory while leaving torn physical tails untouched; inspection of an already-live Session borrows its current immutable snapshot and may therefore contain an open turn. Coordinator-backed implementations retain the exact cold unpublished Session in a bounded LRU, so repeated history reads and a later `prepare(id)` share one read, decompression, validation, freeze, and Session construction. `prepare(id)` reserves the Session, commits pending repair, and returns a disposable publication handle; `load(id)` uses the same machinery to commit repair without publication. The [Session preparation decision](../../.agents/notes/implemented/architecture/2026-08-05-session-preparation.md) owns this lifecycle.
101
+ Read-only observation is `open(id, 'read')`: the handle serves validated contiguous prefix slices, never a torn tail, and repeated reads on one handle never observe an older state than a prior read. There is no persistence-side prepared-Session cache: session-query owns its cold-read cache, keying one balanced cold Session per id on the `stat().revision` change token and re-reading only when the token changes. The [handle-based persistence Agent Note](../../.agents/notes/implemented/architecture/2026-08-27-handle-based-session-persistence.md) owns this lifecycle; the [Session preparation decision](../../.agents/notes/implemented/architecture/2026-08-05-session-preparation.md) records the publication-boundary `SessionPreparation` that remains.
20
102
 
21
- ## `SessionLocation` — optional per-session artifact target
103
+ ## `SessionLocation` — refusal-diagnostics artifact target
22
104
 
23
- `SessionPersistence.locate(meta)` synchronously resolves a backend-owned independent artifact without reading, creating, or flushing it. JSONL returns the absolute transcript path inside its project/session directory; a backend without one independent artifact per session returns `undefined`. A returned path can therefore name a file that does not yet exist or lacks the current unflushed turn; it is a location hint, not authorization or a freshness guarantee.
105
+ `SessionLocation` is not a consumer-facing query: log access goes through a session handle's `read`. It survives only as refusal diagnostics, letting a `SessionFormatUnsupportedError` name the raw log a build refused to interpret. JSONL supplies the absolute transcript path inside its project/session directory; a backend without one artifact per session supplies nothing.
24
106
 
25
107
  ```ts type-equiv
26
108
  /**
27
- * A backend-resolved, per-session local artifact location. The path is an
28
- * absolute target path and can name an artifact that has not materialized yet.
29
- * Consumers must treat it as a location hint, never as an authorization token.
109
+ * A backend-resolved, per-session local artifact location. Carried only by
110
+ * refusal diagnostics ({@link SessionFormatUnsupportedError}) so a user can
111
+ * find the raw log a build refused to interpret; it is not a consumer-facing
112
+ * query — log access goes through a session handle's `read`.
30
113
  */
31
114
  interface SessionLocation {
32
115
  /** Backend-specific artifact kind, for example `jsonl`. */
@@ -40,7 +123,7 @@ interface SessionLocation {
40
123
 
41
124
  ## `SessionHeader` — metadata beside the log
42
125
 
43
- Per-session metadata travels **separately** from the event log: format version, cwd, lineage, and the seed boundary are storage concerns, not conversation events, so they stay out of `SessionEventMap` and never reach `deriveMessages()`. The header is attached to a `Session` via `session.header`.
126
+ Per-session metadata travels **separately** from the event log: the header carries format version, cwd, and the `isSeeded` lineage bit, while body-bearing storage values carry the exact inherited cut beside it. Neither belongs to `SessionEventMap` or reaches `deriveMessages()`. The logical header is attached through `session.header`; the Session exposes its cut as `inheritedEventCount`.
44
127
 
45
128
  Source: [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts)
46
129
 
@@ -64,10 +147,10 @@ interface SessionHeader {
64
147
  /** The session this one was forked from (seed lineage), if any. */
65
148
  readonly parentSession?: SessionId
66
149
  /**
67
- * How many leading events were inherited through a seed. Persisting this
68
- * boundary lets resume and replay distinguish parent history from child work.
150
+ * Whether this Session contains a fork-inherited event prefix. The exact prefix
151
+ * length is Session state rather than ordinary header metadata.
69
152
  */
70
- readonly seedLength?: number
153
+ readonly isSeeded: boolean
71
154
  /**
72
155
  * Coarse product classification for a session created as a subagent child.
73
156
  * This is presentation metadata, not proof that the child is continuable.
@@ -91,11 +174,11 @@ interface SessionHeader {
91
174
 
92
175
  ## Format refusal — logs a build cannot faithfully read
93
176
 
94
- A backend refuses a log it cannot faithfully interpret with `SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged. A header `version` ahead of `SESSION_FORMAT_VERSION` names the direction ("written by a newer harness — upgrade the harness to open it"); one behind it states that this build ships no upgrade path. After legacy-shape normalization, an event type outside this build's generated vocabulary (`KNOWN_SESSION_EVENT_TYPES`, emitted by `gen-persistence-catalog`) refuses the same way unless the event's envelope carries `ignorable: true` — silently skipping an unrecognized required event could change how the rest of the log must be read. The message appends the raw log path when the backend keeps one artifact per session, so the refused text stays reachable. The JSONL backend refuses a foreign version straight from the raw header line, before validating this format version's header shape or decoding any event row — a structurally different future format still reports the upgrade direction, never "corrupt". An out-of-tree backend must enforce the equivalent direction-aware refusal at its own physical-format boundary. Design rationale and the deferred upgrader chain live in the [session-log-version-mechanism note](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md).
177
+ A backend refuses a log it cannot faithfully interpret with `SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged. A header `version` ahead of `SESSION_FORMAT_VERSION` names the direction ("written by a newer harness — upgrade the harness to open it"); one behind it states that this build ships no upgrade path. An event type outside this build's generated vocabulary (`KNOWN_SESSION_EVENT_TYPES`, emitted by `gen-persistence-catalog`) refuses the same way unless the event's envelope carries `ignorable: true` — silently skipping an unrecognized required event could change how the rest of the log must be read. The message appends the raw log path when the backend keeps one artifact per session, so the refused text stays reachable. The JSONL backend refuses a foreign version straight from the raw header line, before validating this format version's header shape or decoding any event row — a structurally different future format still reports the upgrade direction, never "corrupt". An out-of-tree backend must enforce the equivalent direction-aware refusal at its own physical-format boundary. Design rationale and the deferred upgrader chain live in the [session-log-version-mechanism note](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md).
95
178
 
96
179
  ## `CreateSessionOptions` — seeding and metadata
97
180
 
98
- Creating a `Session` through the store takes a `seed` (initial replay or fork history) and `meta` (the storage-level fields the store folds into a `SessionHeader`). The store fills in `version`/`id` and defaults `createdAt`; the caller may supply the validated absolute `cwd`, the `parentSession` lineage, the `seedLength` seed boundary, the optional coarse `origin`, the `delegationDepth`, the `agentPreset` the agent was composed from, and an existing `createdAt`. `origin: 'subagent'` lets product navigation hide duplicate child rows; it does not prove that a descriptor is valid or that the child can resume.
181
+ Creating a `Session` through the store takes a `seed` (initial replay or fork history), an optional exact `inheritedEventCount`, and `meta` (the storage-level fields the store folds into a `SessionHeader`). The store fills in `version`/`id` and defaults `createdAt`; the caller may supply the validated absolute `cwd`, `parentSession` lineage, `isSeeded` lineage bit, optional coarse `origin`, `delegationDepth`, `agentPreset`, and an existing `createdAt`. A seeded creation requires both an explicit seed and exact cut because child-owned setup events may follow the inherited prefix. `origin: 'subagent'` lets product navigation hide duplicate child rows; it does not prove that a descriptor is valid or that the child can resume.
99
182
 
100
183
  ```ts type-equiv
101
184
  /**
@@ -107,14 +190,19 @@ interface CreateSessionOptions {
107
190
  /** Initial replay or fork history supplied at construction. */
108
191
  readonly seed?: readonly SessionEvent[]
109
192
  /**
110
- * Storage metadata read once before publication. `seedLength` is explicit
111
- * because a resumed seed contains the full stored log, not only its inherited prefix.
193
+ * Exact fork-inherited prefix length when `meta.isSeeded` is true. A
194
+ * constructor seed may also contain child-owned setup events after this cut.
195
+ */
196
+ readonly inheritedEventCount?: SessionLogOffset
197
+ /**
198
+ * Storage metadata read once before publication. `isSeeded` marks fork
199
+ * lineage; supplying replay history alone does not make it inherited.
112
200
  */
113
201
  readonly meta?: {
114
202
  readonly cwd?: string
115
203
  readonly parentSession?: SessionId
116
204
  readonly createdAt?: number
117
- readonly seedLength?: number
205
+ readonly isSeeded?: boolean
118
206
  readonly origin?: 'subagent'
119
207
  readonly delegationDepth?: number
120
208
  readonly agentPreset?: string
@@ -122,27 +210,11 @@ interface CreateSessionOptions {
122
210
  }
123
211
  ```
124
212
 
125
- Replay/fork is therefore `ctx.sessions.create(id, { seed: seedEvents })`; resuming a *persisted* session into a live agent is `ctx.agents.resume({ resumeSessionId })`.
126
-
127
- ## `SessionRawArtifact` — verbatim stored artifact text
128
-
129
- A backend's own artifact text for one session, byte-identical to what it durably wrote (decoded from its physical encoding). `readRaw` returns it without reconstructing from parsed events, so backend-specific serialization (chunk packing, key order, line breaks) survives. Consumers first test `supportsRawArtifacts`: `false` means the backend does not provide this capability, while `readRaw(...) === undefined` means a supported backend has no materialized artifact for that session.
130
-
131
- ```ts type-equiv
132
- /** A backend's own raw artifact text for one session, verbatim. */
133
- interface SessionRawArtifact {
134
- /** The session header parsed from the artifact's own first line. */
135
- readonly meta: SessionHeader
136
- /** The artifact's base filename on disk, without any physical encoding suffix. */
137
- readonly filename: string
138
- /** The artifact's full text content, decoded from the backend's physical encoding. */
139
- readonly content: string
140
- }
141
- ```
213
+ Replay/fork is therefore `ctx.agents.create({ sessionId, seed, meta })` — a fork additionally supplies `inheritedEventCount` with `meta.isSeeded: true`, and only agent-loop-published sessions persist, and the loop stores the seed through the new session's write handle before publication; resuming a *persisted* session into a live agent is `ctx.agents.resume({ resumeSessionId })`.
142
214
 
143
215
  ## Preparation and restoration ownership
144
216
 
145
- `SessionStore.prepare()` accepts ordinary creation options or fresh persistence graphs transferred through `RestoredSessionOptions`. The restoration branch validates and freezes the transferred header and events in place, so callers must retain no mutable aliases. `SessionPreparation` then owns the exact unpublished Session until publication or rollback; disposal is synchronous and idempotent. Persistence inspection exposes only `SessionInspection`, an immutable logical view borrowed from the same prepared Session.
217
+ `SessionStore.prepare()` accepts ordinary creation options or fresh persistence graphs transferred through `RestoredSessionOptions`. The restoration branch validates and freezes the transferred header and events in place, so callers must retain no mutable aliases. `SessionPreparation` then owns the exact unpublished Session until publication or rollback; disposal is synchronous and idempotent. agent-loop's resume builds these graphs by reading the stored log through the session's write handle and appending any needed `interruptedTurnClosers` before preparation.
146
218
 
147
219
  ```ts type-equiv
148
220
  /**
@@ -154,6 +226,8 @@ interface RestoredSessionOptions {
154
226
  readonly seed: SessionEvent[]
155
227
  /** Fresh detached storage metadata to validate and freeze in place. */
156
228
  readonly meta: SessionHeader
229
+ /** Exact number of fork-inherited leading events decoded from storage. */
230
+ readonly inheritedEventCount: SessionLogOffset
157
231
  /** Select the persistence ownership-transfer path. */
158
232
  readonly seedSource: 'persistence'
159
233
  }
@@ -196,19 +270,9 @@ declare class SessionPreparation implements Disposable {
196
270
  }
197
271
  ```
198
272
 
199
- ```ts type-equiv
200
- /** Immutable logical session prepared from persistence or a live owner. */
201
- interface SessionInspection {
202
- /** Validated immutable session metadata. */
203
- readonly meta: SessionHeader
204
- /** Validated contiguous logical event log. */
205
- readonly events: readonly SessionEvent[]
206
- }
207
- ```
208
-
209
273
  ## Lightweight source revisions
210
274
 
211
- Consumers of derived state compare a cheap opaque revision before loading a full event log. The persistence backend owns its representation and changes it transactionally with append or mutating load repair; callers compare it only for equality.
275
+ Consumers of derived read models compare a cheap opaque revision before loading a full event log. The revision is a per-backend-instance change token from `stat`/`list`: equal revisions may be treated as an unchanged log; unequal revisions promise nothing, and write-ownership churn never changes one. session-query keys its cold-read cache on it; the token plays no part in open, read, or resume.
212
276
 
213
277
  ```ts type-equiv
214
278
  /**
@@ -219,20 +283,29 @@ type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'>
219
283
  ```
220
284
 
221
285
  ```ts type-equiv
222
- /** Lightweight immutable source identity returned without loading a full log. */
286
+ /**
287
+ * Lightweight stored-session observation returned by {@link SessionPersistence.stat}
288
+ * and {@link SessionPersistence.list} without reading the full event log.
289
+ */
223
290
  interface SessionPersistenceSnapshot {
224
- /** Detached metadata for one materialized session. */
225
- header: SessionHeader
226
- /** Opaque source-qualified token that changes whenever this stored log changes. */
227
- revision: SessionPersistenceRevision
291
+ /** Detached metadata for one stored session. */
292
+ readonly header: SessionHeader
293
+ /** Opaque change token; see {@link SessionPersistence.stat}. */
294
+ readonly revision: SessionPersistenceRevision
295
+ /** Logical event count, when the backend can provide it cheaply from metadata; otherwise absent. */
296
+ readonly eventCount?: number
297
+ /** Physical artifact byte size, when the backend can provide it cheaply (JSONL); otherwise absent. */
298
+ readonly sizeBytes?: number
228
299
  }
229
300
  ```
230
301
 
302
+ The optional `eventCount`/`sizeBytes` hints let the session list's cold blank probe bound its work from metadata alone (session-controller config `coldBlankProbeMaxEvents`/`coldBlankProbeMaxBytes`) without opening any log.
303
+
231
304
  ## The backend
232
305
 
233
- The shipped provider implements the abstract `SessionPersistence` contract (locate/create/append/prepare/load/inspect/readFrom/list/listSnapshots over `SessionEvent`, with optional cancellation on observation methods) and passes the shared `runPersistenceContract` suite:
306
+ The shipped provider implements the abstract `SessionPersistence` contract (`create`/`open`/`stat`/`list`, with per-session `SessionHandle`s carrying `read`/`append`/`flush`/`close` and optional cancellation throughout) and passes the shared persistence contract suite:
234
307
 
235
- - **[dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl)** — an append-only logical JSONL log per session, stored as checksummed concatenated Zstandard frames by default or raw lines by configuration, with crash-safe atomic writes, interrupted-turn recovery, and a read/replay path.
308
+ - **[dsh-session-persistence-jsonl](../../packages/session/session-persistence-jsonl)** — an append-only logical JSONL log per session, stored as checksummed concatenated Zstandard frames by default or raw lines by configuration, with crash-safe atomic materialization, per-batch `fsync` appends, and torn-tail truncation before the first new append. `stat`/`list` carry `sizeBytes` and a best-effort `fs.stat`-derived revision.
236
309
 
237
310
  <!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
238
311
 
@@ -246,158 +319,77 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
246
319
 
247
320
  ### `ctx.sessionPersistence` — `SessionPersistence` (abstract seam)
248
321
 
249
- Durable append-only session storage. Implementations preserve contiguous, losslessly JSON-serializable events; append resolves only after durability, and load balances a complete interrupted tail without rewriting committed events.
250
-
251
- ```ts cordis-catalog
252
- /**
253
- * Resolve this backend's independent local artifact for a session without
254
- * reading, creating, flushing, or otherwise materializing it. A backend
255
- * that does not own one artifact per Session returns `undefined`.
256
- * @param meta - the immutable session header whose artifact is requested.
257
- * @returns the backend-specific absolute location, when one exists.
258
- */
259
- abstract locate(meta: SessionHeader): SessionLocation | undefined
260
-
261
- /**
262
- * Read a session's backend-owned artifact text verbatim — the exact durable
263
- * bytes the backend wrote (decoded from its physical encoding, e.g. a
264
- * decompressed JSONL). The returned `content` is the raw text, not a
265
- * reconstruction from parsed events, so it preserves backend-specific
266
- * serialization (chunk packing, key order, line breaks). Callers first test
267
- * {@link supportsRawArtifacts}; `undefined` then means only that the requested
268
- * session has no materialized artifact.
269
- * @param _id - the persisted session to read (unused by the default: no
270
- * per-session artifact).
271
- * @param signal - optional cancellation for backend read work.
272
- * @returns the raw artifact plus its parsed header, or `undefined` when the
273
- * session is absent.
274
- * @throws when this backend does not expose per-session raw artifacts.
275
- */
276
- readRaw(_id: SessionId, signal?: AbortSignal): Promise<SessionRawArtifact | undefined>
277
-
278
- /**
279
- * Register a new session's metadata. A backend MAY defer the physical write
280
- * until the first {@link append} (lazy materialization), in which case a
281
- * created-but-never-appended session is absent from {@link list}
282
- * — abandoned sessions leave nothing behind.
283
- * @param meta - the immutable header (id, version, cwd, lineage) to record.
284
- */
285
- abstract create(meta: SessionHeader): Promise<void>
286
-
287
- /**
288
- * Ensure a live session has a durable header even when it has no events.
289
- * Ordinary sessions remain lazily materialized; lifecycle frontends call
290
- * this only when an empty session itself is a durable resumable resource.
291
- * @param _session - exact live session whose registered header is materialized.
292
- */
293
- ensureMaterialized(_session: Session): Promise<void>
322
+ Durable append-only session storage addressed through per-session handles.
294
323
 
295
- /**
296
- * Durably persist a batch of events. Honors the append-only and contiguous-
297
- * seq contracts: the first event's `seq` MUST equal the stored next-seq
298
- * (after `load` has durably closed any interrupted turn). Rejects non-JSON-
299
- * serializable `event.data` with an error naming the offending event type.
300
- * @param id - the session the batch belongs to.
301
- * @param events - the contiguous batch to persist, in seq order.
302
- */
303
- abstract append(id: SessionId, events: readonly SessionEvent[]): Promise<void>
324
+ Storage semantics shared by every backend: events are contiguous from seq 0 and never rewritten; a torn physical tail is never returned to a reader and is truncated by the write path before its first append; reads validate current-format records only and refuse unknown vocabulary fail-closed. `append` persists best-effort; `flush` — per handle or service-wide — is the durability barrier.
304
325
 
305
- /**
306
- * Prepare the exact unpublished Session used by resume. Implementations may
307
- * reuse object graphs retained by an earlier {@link inspect} after confirming
308
- * their durable revision is still current; disposal releases an unpublished
309
- * reservation. Revision retries require the durable log to remain unchanged
310
- * for one read/check round trip; continuous external writers may delay completion.
311
- * @param id - persisted session to prepare.
312
- * @param signal - optional cancellation for preparation work.
313
- * @returns one owned unpublished Session preparation.
314
- */
315
- async prepare(id: SessionId, signal?: AbortSignal): Promise<SessionPreparation>
326
+ Visibility: a created session is observable through `stat`/`list`/`open` in this process from the moment `create` resolves, even while a backend defers physical materialization (a pure optimization); other processes see the session only once it materializes, and a session that never materialized before a crash never existed. `SessionHandle.flush` forces materialization.
316
327
 
317
- /**
318
- * Load an immutable balanced logical view and commit any required cold
319
- * recovery. A complete interrupted final turn is preserved and durably
320
- * closed with missing tool errors plus any open step and turn boundaries;
321
- * only a torn final record is discarded. Unknown versions and corruption in
322
- * the committed prefix reject. Implementations MUST NOT crash-repair an
323
- * identity still bound to a live Session: a balanced live log may return as a
324
- * durable snapshot, while an open live turn rejects. Returned values may be
325
- * shared with immutable live or prepared state and must not be mutated.
326
- * Revision-based implementations may wait for one stable read/check round trip.
327
- * @param id - the persisted session to reload.
328
- * @returns the header and a log ending on a balanced `turn/end`.
329
- */
330
- abstract load(id: SessionId): Promise<SessionInspection>
328
+ Freshness: once an `append` or `flush` resolves, reads started afterwards on this backend instance observe at least that prefix.
331
329
 
330
+ ```ts cordis-catalog
332
331
  /**
333
- * Inspect an immutable logical session without committing recovery or
334
- * publishing it. A cold complete interrupted turn receives synthetic closers
335
- * in memory and a torn physical tail remains untouched. An already-live
336
- * Session instead yields its current immutable snapshot, which may contain an
337
- * open turn and its `session/end-seed` boundary. Coordinator-backed
338
- * implementations retain the exact cold unpublished Session for bounded
339
- * reuse by a later {@link prepare}. A stale ready source is reloaded; a source
340
- * already committing or reserved for resume remains exclusive, and inspection
341
- * may borrow its immutable view. Callers borrow only the immutable header and
342
- * log. Continuous external writers may delay revision convergence.
343
- * @param id - the persisted session to inspect.
344
- * @param signal - optional cancellation for queued and backend read work.
345
- * @returns the validated header and current logical event log.
332
+ * Create a new stored session and take its write ownership.
333
+ * @param header - the immutable header (id, version, cwd, lineage) to store.
334
+ * @param options - optional cancellation.
335
+ * @returns a `write` handle owned by the caller; close it to release ownership.
336
+ * @throws {SessionAlreadyExistsError} when the id already exists.
346
337
  */
347
- abstract inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>
338
+ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle>
348
339
 
349
340
  /**
350
- * Borrow one exact inspection while retaining any reusable prepared source.
351
- * A cold observation must pin the exact prepared Session that a later
352
- * {@link prepare} reserves. Implementations must not degrade this operation
353
- * to a detached {@link inspect} result.
354
- * @param id - persisted session to observe.
355
- * @param signal - optional cancellation for preparation work.
356
- * @returns a disposable immutable observation.
341
+ * Open an existing stored session.
342
+ *
343
+ * `read` never takes ownership and works while another handle (or process)
344
+ * holds write ownership. `write` atomically claims single-writer ownership;
345
+ * an existing active owner rejects.
346
+ * @param id - the stored session to open.
347
+ * @param access - `read` or `write`.
348
+ * @param options - optional cancellation.
349
+ * @returns the open handle.
350
+ * @throws {SessionPersistenceNotFoundError} when the session does not exist.
351
+ * @throws {SessionAlreadyOwnedError} for `write` when ownership is taken.
357
352
  */
358
- abstract borrowSession(id: SessionId, signal?: AbortSignal): Promise<BorrowedSessionSource>
353
+ abstract open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>
359
354
 
360
355
  /**
361
- * Read the stored events from `fromSeq` onward the read-from-seq
362
- * primitive for read models that resume from a watermark (e.g. a persisted
363
- * projection cache folding only the tail past its checkpoint). Unlike
364
- * {@link inspect}, it is a detached physical suffix read: no preparation
365
- * cache, torn-tail truncation, synthetic closers, or coordinator-state
366
- * publication. Only events from the valid contiguous stored prefix are
367
- * returned, so a torn fragment never reaches the caller. `fromSeq` at or
368
- * beyond the stored prefix returns an empty event list (never an error).
369
- * A backend whose medium can seek by seq may read only the suffix;
370
- * sequential media such as JSONL still parse the whole artifact and skip
371
- * forward. The primitive bounds what is returned and refolded, not every
372
- * backend's physical read.
373
- * @param id - the persisted session to read.
374
- * @param fromSeq - first event seq to include; a non-negative safe integer.
375
- * @param signal - optional cancellation for queued and backend read work.
376
- * @returns the header and the stored events with `seq >= fromSeq`.
356
+ * Flush every active write handle owned by this service instance in one
357
+ * durability barrier: each handle's routed live events drain durably and
358
+ * its session materializes, exactly as that handle's own
359
+ * `SessionHandle.flush` would. Read handles buffer nothing and are
360
+ * untouched. A handle closed concurrently counts as flushed — close itself
361
+ * drains durably.
362
+ * @returns resolution once every write handle active at the call has flushed.
363
+ * @throws {AggregateError} naming each session whose flush failed; the
364
+ * remaining handles still flush.
377
365
  */
378
- abstract readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }>
366
+ abstract flush(): Promise<void>
379
367
 
380
368
  /**
381
- * Lightweight listing from metadata, without a full-log parse.
382
- * @param signal - optional cancellation for backend listing work.
383
- * @returns one header per materialized session.
369
+ * Observe one stored session without reading its event log or taking
370
+ * ownership.
371
+ *
372
+ * The snapshot's `revision` is an opaque change token comparable only
373
+ * against revisions from the same service instance and session id: equal
374
+ * revisions may be treated as an unchanged log; unequal revisions promise
375
+ * nothing. Write-ownership churn does not change a revision. It exists for
376
+ * derived read-model caches keyed off `stat`/`list`; it plays no part in
377
+ * open, read, or resume.
378
+ * @param id - the stored session to observe.
379
+ * @param options - optional cancellation.
380
+ * @returns the snapshot, or `undefined` when the session does not exist.
384
381
  */
385
- abstract list(signal?: AbortSignal): Promise<SessionHeader[]>
382
+ abstract stat(id: SessionId, options?: SessionPersistenceStatOptions): Promise<SessionPersistenceSnapshot | undefined>
386
383
 
387
384
  /**
388
- * List materialized sessions with cheap per-log change tokens.
389
- *
390
- * Repeated observations of an unchanged log return the same revision. A
391
- * successful mutating {@link load} repair changes the next listed revision.
392
- * Revisions also distinguish independently backed stores so backend-local
393
- * counters cannot compare equal across different persistence sources.
394
- * @param signal - optional cancellation for backend snapshot-listing work.
395
- * @returns one header and opaque revision per materialized session without loading full logs.
385
+ * List every stored session visible to this process, in no promised order.
386
+ * @param options - optional cancellation.
387
+ * @returns one snapshot per stored session.
396
388
  */
397
- abstract listSnapshots(signal?: AbortSignal): Promise<SessionPersistenceSnapshot[]>
389
+ abstract list(options?: SessionPersistenceListOptions): Promise<readonly SessionPersistenceSnapshot[]>
398
390
  ```
399
391
 
400
- Types: [Session](session.md) · [SessionEvent](session.md) · [SessionId](core.md)
392
+ Types: [SessionId](core.md)
401
393
 
402
394
  Source: [`packages/session/session-persistence/src/index.ts`](../../packages/session/session-persistence/src/index.ts)
403
395
  <!-- END GENERATED cordis-surface -->