dsh-session-branch 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ /**
2
+ * On-disk fingerprint cache for the lineage host half.
3
+ *
4
+ * Prefix content is immutable after a session is created, so the cumulative
5
+ * prefix hashes computed from a stored log never change. Persisting them turns
6
+ * the first request after a DSH restart from "decode every cold session log"
7
+ * into a file read. The cache is disposable: a missing or unreadable file is
8
+ * simply rebuilt from the session logs.
9
+ *
10
+ * @module dsh-session-lineage/fingerprint-store
11
+ */
12
+
13
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
+ import { homedir } from 'node:os'
15
+ import { dirname, join } from 'node:path'
16
+
17
+ const FORMAT = 'dsh-session-lineage-fingerprints'
18
+ const VERSION = 1
19
+ const MAX_BYTES = 4 * 1024 * 1024
20
+ const MAX_SESSIONS = 2000
21
+
22
+ /** Serialized writes: never interleave two cache saves. */
23
+ let writeChain = Promise.resolve()
24
+
25
+ /**
26
+ * @param task - async file operation.
27
+ * @returns the task's own result.
28
+ */
29
+ function serialize(task) {
30
+ const run = writeChain.then(task, task)
31
+ writeChain = run.catch(() => {})
32
+ return run
33
+ }
34
+
35
+ /**
36
+ * Resolve the DSH home the rest of the harness uses.
37
+ *
38
+ * @returns absolute DSH home directory.
39
+ */
40
+ function resolveDshHome() {
41
+ const configured = String(process.env.DSH_HOME || '').trim()
42
+ if (configured !== '') {
43
+ if (configured === '~') return homedir()
44
+ if (configured.startsWith('~/') || configured.startsWith('~\\')) {
45
+ return join(homedir(), configured.slice(2))
46
+ }
47
+ return configured
48
+ }
49
+ return join(homedir(), '.dsh')
50
+ }
51
+
52
+ /** @returns fingerprint cache path. */
53
+ function cacheFile() {
54
+ return join(resolveDshHome(), 'storages', 'session-lineage', 'fingerprints.json')
55
+ }
56
+
57
+ /**
58
+ * Encode one cache entry for JSON storage (hashes as base64, 4 bytes each).
59
+ *
60
+ * @param entry - `{ header, n, eventCount, hashes }` as built by the trail.
61
+ * @returns serializable record.
62
+ */
63
+ export function encodeFingerprint(entry) {
64
+ const bytes = Buffer.from(entry.hashes.buffer, entry.hashes.byteOffset, entry.hashes.byteLength)
65
+ return {
66
+ createdAt: Number(entry.header.createdAt),
67
+ isSeeded: entry.header.isSeeded === true,
68
+ origin: entry.header.origin ?? null,
69
+ parentSession: entry.header.parentSession ?? null,
70
+ n: entry.n,
71
+ eventCount: entry.eventCount,
72
+ hashes: bytes.toString('base64'),
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Decode one stored record back into a cache entry.
78
+ *
79
+ * @param id - session id.
80
+ * @param record - stored record.
81
+ * @returns `{ header, n, eventCount, hashes }`.
82
+ */
83
+ export function decodeFingerprint(id, record) {
84
+ const raw = Buffer.from(String(record.hashes ?? ''), 'base64')
85
+ const copy = new Uint8Array(raw.byteLength)
86
+ copy.set(raw)
87
+ return {
88
+ header: {
89
+ id,
90
+ createdAt: Number(record.createdAt) || 0,
91
+ isSeeded: record.isSeeded === true,
92
+ ...(record.origin === null || record.origin === undefined ? {} : { origin: record.origin }),
93
+ ...(record.parentSession === null || record.parentSession === undefined
94
+ ? {}
95
+ : { parentSession: record.parentSession }),
96
+ },
97
+ n: Number(record.n) || 0,
98
+ eventCount: Number(record.eventCount) || 0,
99
+ hashes: new Uint32Array(copy.buffer),
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Read the cache; any failure yields an empty cache.
105
+ *
106
+ * @returns `Map<sessionId, entry>`.
107
+ */
108
+ export async function readFingerprints() {
109
+ const entries = new Map()
110
+ try {
111
+ const raw = await readFile(cacheFile(), 'utf8')
112
+ if (Buffer.byteLength(raw, 'utf8') > MAX_BYTES) return entries
113
+ const parsed = JSON.parse(raw)
114
+ if (parsed === null || typeof parsed !== 'object') return entries
115
+ if (parsed.format !== FORMAT || parsed.version !== VERSION) return entries
116
+ const sessions = parsed.sessions
117
+ if (sessions === null || typeof sessions !== 'object') return entries
118
+ for (const [id, record] of Object.entries(sessions)) {
119
+ if (typeof id !== 'string' || id === '' || record === null || typeof record !== 'object') continue
120
+ entries.set(id, decodeFingerprint(id, record))
121
+ if (entries.size >= MAX_SESSIONS) break
122
+ }
123
+ } catch {
124
+ // Missing or unreadable cache: rebuild from the logs.
125
+ }
126
+ return entries
127
+ }
128
+
129
+ /**
130
+ * Persist the cache atomically.
131
+ *
132
+ * @param entries - `Map<sessionId, entry>`.
133
+ * @returns whether the cache was written.
134
+ */
135
+ export function writeFingerprints(entries) {
136
+ return serialize(async () => {
137
+ const sessions = {}
138
+ let count = 0
139
+ for (const [id, entry] of entries) {
140
+ if (typeof id !== 'string' || id === '') continue
141
+ sessions[id] = encodeFingerprint(entry)
142
+ count += 1
143
+ if (count >= MAX_SESSIONS) break
144
+ }
145
+ const body = JSON.stringify({
146
+ format: FORMAT,
147
+ version: VERSION,
148
+ updatedAt: new Date().toISOString(),
149
+ sessions,
150
+ })
151
+ if (Buffer.byteLength(body, 'utf8') > MAX_BYTES) return false
152
+ try {
153
+ await mkdir(dirname(cacheFile()), { recursive: true })
154
+ const temporary = `${cacheFile()}.${process.pid}.${Date.now().toString(36)}.tmp`
155
+ await writeFile(temporary, body, 'utf8')
156
+ await rename(temporary, cacheFile())
157
+ return true
158
+ } catch {
159
+ return false
160
+ }
161
+ })
162
+ }
package/lib/index.js ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `dsh-session-lineage` host half.
3
+ *
4
+ * Exposes the inferred lineage of one workspace (and the small display-state
5
+ * document used by the sidebar client) over the Host Connection's
6
+ * authenticated `/api` Fetch routes.
7
+ *
8
+ * @module dsh-session-lineage
9
+ */
10
+
11
+ import { LineageIndex } from './trail.js'
12
+ import { readState, writeState } from './state-store.js'
13
+
14
+ /** Stable Cordis plugin name. */
15
+ export const name = 'session-lineage'
16
+
17
+ /** Host services this plugin cannot work without. */
18
+ export const inject = ['connection', 'workspaceRegistry', 'sessionQuery', 'sessions']
19
+
20
+ const TREE_CHANNEL = '/api/session-lineage'
21
+ const STATE_CHANNEL = '/api/session-lineage.state'
22
+
23
+ /**
24
+ * Write one JSON response without leaking request details.
25
+ *
26
+ * @param value - JSON-serializable payload.
27
+ * @param status - HTTP status.
28
+ * @returns the Fetch `Response`.
29
+ */
30
+ function json(value, status = 200) {
31
+ return new Response(JSON.stringify(value), {
32
+ status,
33
+ headers: {
34
+ 'content-type': 'application/json; charset=utf-8',
35
+ 'cache-control': 'no-store',
36
+ },
37
+ })
38
+ }
39
+
40
+ /**
41
+ * Mount the host half.
42
+ *
43
+ * @param ctx - Cordis plugin context with the services listed in {@link inject}.
44
+ */
45
+ export function apply(ctx) {
46
+ const log = ctx.logger('session-lineage')
47
+ const index = new LineageIndex(ctx, log)
48
+ ctx.effect(() => () => index.dispose(), 'session-lineage: index')
49
+
50
+ // Workspace lineage (R1.7): owner-only, authenticated by the Connection service.
51
+ ctx.connection.fetch.register({
52
+ path: TREE_CHANNEL,
53
+ methods: ['GET'],
54
+ requestBody: 'buffered',
55
+ fetch: async (request) => {
56
+ try {
57
+ const url = new URL(request.url)
58
+ const workspaceId = url.searchParams.get('workspaceId') ?? ''
59
+ const idsParam = url.searchParams.get('ids')
60
+ const ids = idsParam === null || idsParam === '' ? undefined : idsParam.split(',')
61
+ const debug = url.searchParams.get('debug') === '1'
62
+ return json(await index.tree(workspaceId, { debug, ids }))
63
+ } catch (error) {
64
+ log.warn(error)
65
+ return json({ workspaceId: null, sessions: [] })
66
+ }
67
+ },
68
+ })
69
+
70
+ // Display state (R1.8): manual sibling order and collapsed subtrees.
71
+ ctx.connection.fetch.register({
72
+ path: STATE_CHANNEL,
73
+ methods: ['GET', 'POST'],
74
+ requestBody: 'buffered',
75
+ fetch: async (request) => {
76
+ if (request.method === 'GET') return json(await readState())
77
+ try {
78
+ const body = await request.json()
79
+ return json(await writeState(body?.state ?? body))
80
+ } catch (error) {
81
+ log.warn(error)
82
+ return json({ ok: false, error: 'could not save lineage state' }, 400)
83
+ }
84
+ },
85
+ })
86
+ }
package/lib/lineage.js ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Pure lineage inference over inherited event prefixes.
3
+ *
4
+ * DSH forks copy the parent's events verbatim (marked by `inheritedEventCount`
5
+ * and a trailing `session/end-seed` with `data.inherited === true`), so a child
6
+ * can be recognized by comparing its first N events with every candidate's.
7
+ * This module owns the comparison only; reading sessions and caching belongs to
8
+ * `trail.js`.
9
+ *
10
+ * @module dsh-session-lineage/lineage
11
+ */
12
+
13
+ /**
14
+ * Upper bound of events kept in a prefix fingerprint.
15
+ *
16
+ * A fork cut after this many events cannot be matched against its parent's
17
+ * prefix, so the branch silently renders as a root. The cap bounds memory only
18
+ * (`min(events.length, HASH_CAP)` hashes are kept, 4 bytes each), so it sits far
19
+ * above any realistic session length.
20
+ */
21
+ export const HASH_CAP = 262144
22
+
23
+ /** FNV-1a prime, applied per event over the canonical JSON text. */
24
+ const FNV_PRIME = 16777619
25
+ const FNV_OFFSET = 2166136261
26
+
27
+ /**
28
+ * Canonical text of one raw event. Fork seeds keep `seq/time/data` identical,
29
+ * so this projection is stable across the parent and every copy of its prefix.
30
+ *
31
+ * @param event - one session event.
32
+ * @returns the comparable JSON text.
33
+ */
34
+ export function canonicalEvent(event) {
35
+ return JSON.stringify({
36
+ type: event.type,
37
+ seq: event.seq,
38
+ time: event.time,
39
+ data: event.data,
40
+ })
41
+ }
42
+
43
+ /**
44
+ * Extend one FNV-1a hash with UTF-16 code units.
45
+ *
46
+ * @param hash - previous 32-bit hash.
47
+ * @param text - canonical event text.
48
+ * @returns the next 32-bit hash.
49
+ */
50
+ function fnv1a(hash, text) {
51
+ let value = hash >>> 0
52
+ for (let index = 0; index < text.length; index += 1) {
53
+ value = Math.imul(value ^ text.charCodeAt(index), FNV_PRIME)
54
+ }
55
+ return value >>> 0
56
+ }
57
+
58
+ /**
59
+ * Cumulative prefix fingerprints for one event log: `hashes[i]` identifies the
60
+ * first `i + 1` events, so two logs share a prefix of length N exactly when
61
+ * their `hashes[N - 1]` values match.
62
+ *
63
+ * @param events - raw event log (any iterable is not needed; it is a readonly array).
64
+ * @param limit - maximum number of events to fingerprint.
65
+ * @returns 32-bit hashes, one per fingerprinted event.
66
+ */
67
+ export function prefixHashes(events, limit = HASH_CAP) {
68
+ const size = Math.min(events.length, limit)
69
+ const hashes = new Uint32Array(size)
70
+ let hash = FNV_OFFSET
71
+ for (let index = 0; index < size; index += 1) {
72
+ hash = fnv1a(hash, canonicalEvent(events[index]))
73
+ hashes[index] = hash
74
+ }
75
+ return hashes
76
+ }
77
+
78
+ /**
79
+ * Continue a prefix fingerprint over more events, starting from the last
80
+ * cached hash. A growing log only hashes its new events, while a fork cut
81
+ * anywhere in the log still finds a covering candidate.
82
+ *
83
+ * @param hashes - existing prefix hashes.
84
+ * @param events - raw event log.
85
+ * @param limit - maximum number of events to fingerprint.
86
+ * @returns a longer `Uint32Array`, or the input when nothing new needs hashing.
87
+ */
88
+ export function extendPrefixHashes(hashes, events, limit = HASH_CAP) {
89
+ const size = Math.min(events.length, limit)
90
+ if (size <= hashes.length) return hashes
91
+ const extended = new Uint32Array(size)
92
+ extended.set(hashes)
93
+ let hash = hashes.length === 0 ? FNV_OFFSET : hashes[hashes.length - 1]
94
+ for (let index = hashes.length; index < size; index += 1) {
95
+ hash = fnv1a(hash, canonicalEvent(events[index]))
96
+ extended[index] = hash
97
+ }
98
+ return extended
99
+ }
100
+
101
+ /**
102
+ * Whether one cached entry belongs to the sidebar tree at all. Native subagent
103
+ * sessions are hidden by DSH's own sidebar and render their own lineage, so
104
+ * they never take part in the inference here.
105
+ *
106
+ * @param entry - cached entry for one session.
107
+ * @returns true for an ordinary (non-subagent) session.
108
+ */
109
+ function isOrdinary(entry) {
110
+ return entry.header.origin !== 'subagent'
111
+ }
112
+
113
+ /**
114
+ * The parent a historical fork recorded in its own header.
115
+ *
116
+ * Current DSH forks omit `parentSession`; sessions created by older versions
117
+ * may keep their source id there, and DSH's own sidebar never indents such
118
+ * ordinary rows, so the header can be trusted once `origin` rules out a native
119
+ * subagent child.
120
+ *
121
+ * @param entry - cached entry for one session.
122
+ * @param visible - ids of the ordinary workspace members.
123
+ * @param entries - cached entries keyed by session id.
124
+ * @returns the durable parent id, or undefined when there is no usable one.
125
+ */
126
+ function headerParentOf(entry, visible, entries) {
127
+ if (!isOrdinary(entry)) return undefined
128
+ if (entry.header.isSeeded !== true) return undefined
129
+ const parentId = entry.header.parentSession
130
+ if (typeof parentId !== 'string' || parentId === entry.header.id) return undefined
131
+ if (!visible.has(parentId)) return undefined
132
+ const parent = entries.get(parentId)
133
+ if (parent === undefined || !isOrdinary(parent)) return undefined
134
+ return parentId
135
+ }
136
+
137
+ /**
138
+ * Whether one ordinary workspace member still needs its inherited prefix
139
+ * compared: only seeded sessions whose whole inherited prefix fits the
140
+ * fingerprint take part.
141
+ *
142
+ * @param entry - cached entry for one session.
143
+ * @returns true when the prefix can identify a parent.
144
+ */
145
+ function isInferableChild(entry) {
146
+ if (!isOrdinary(entry)) return false
147
+ if (entry.header.isSeeded !== true) return false
148
+ const count = entry.n
149
+ return Number.isSafeInteger(count) && count > 0 && count <= entry.hashes.length
150
+ }
151
+
152
+ /**
153
+ * Whether `candidate` could be the parent of `child`: its own history must be
154
+ * earlier (createdAt), shorter (`n < child.n`, which excludes sibling branches
155
+ * that share the same inherited length) and long enough to cover the child's
156
+ * prefix. Historical forks keep taking part: a `parentSession` header does not
157
+ * stop them from being the source of a newer fork.
158
+ *
159
+ * @param candidate - cached entry for one workspace peer.
160
+ * @param child - cached entry for the session being explained.
161
+ * @returns true when the candidate's prefix can be compared.
162
+ */
163
+ function isCandidate(candidate, child) {
164
+ if (!isOrdinary(candidate)) return false
165
+ if (!(candidate.header.createdAt < child.header.createdAt)) return false
166
+ if (candidate.n >= child.n) return false
167
+ if (candidate.hashes.length < child.n) return false
168
+ return true
169
+ }
170
+
171
+ /**
172
+ * Drop the edge of every node that sits on a cycle, so a corrupt or stale
173
+ * header chain can never produce an endless walk in the client's display tree.
174
+ * Prefix edges are acyclic by construction (`createdAt` order); header edges
175
+ * are the only ones that can close a loop.
176
+ *
177
+ * @param parents - child id -> parent id, mutated in place.
178
+ */
179
+ function breakCycles(parents) {
180
+ const done = new Set()
181
+ for (const start of parents.keys()) {
182
+ if (done.has(start)) continue
183
+ const path = []
184
+ const visiting = new Set()
185
+ let current = start
186
+ while (current !== undefined && !done.has(current)) {
187
+ if (visiting.has(current)) {
188
+ parents.delete(current)
189
+ break
190
+ }
191
+ visiting.add(current)
192
+ path.push(current)
193
+ current = parents.get(current)
194
+ }
195
+ for (const id of path) done.add(id)
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Infer the parent of every workspace member.
201
+ *
202
+ * An ordinary seeded session with a usable `parentSession` header (a fork made
203
+ * by an older DSH) uses it directly; every other seeded session compares its
204
+ * inherited prefix against the workspace peers. Candidates are ranked by their
205
+ * own inherited length (the nearest ancestor that still explains the prefix);
206
+ * an exact tie stays unresolved, so the branch renders as a root instead of
207
+ * guessing. Native subagent sessions never take part.
208
+ *
209
+ * @param ids - workspace session ids in display order.
210
+ * @param entries - cached entries keyed by session id.
211
+ * @returns parent id per session; absent ids render as roots.
212
+ */
213
+ export function inferParents(ids, entries) {
214
+ const parents = new Map()
215
+ const visible = new Set()
216
+ for (const id of ids) {
217
+ const entry = entries.get(id)
218
+ if (entry !== undefined && isOrdinary(entry)) visible.add(id)
219
+ }
220
+ for (const id of visible) {
221
+ const child = entries.get(id)
222
+ const parentId = headerParentOf(child, visible, entries)
223
+ if (parentId !== undefined) {
224
+ parents.set(id, parentId)
225
+ continue
226
+ }
227
+ if (!isInferableChild(child)) continue
228
+ let best
229
+ let ambiguous = false
230
+ for (const otherId of visible) {
231
+ if (otherId === id) continue
232
+ const candidate = entries.get(otherId)
233
+ if (candidate === undefined || !isCandidate(candidate, child)) continue
234
+ if (candidate.hashes[child.n - 1] !== child.hashes[child.n - 1]) continue
235
+ if (best === undefined || candidate.n > best.n) {
236
+ best = candidate
237
+ ambiguous = false
238
+ } else if (candidate.n === best.n) {
239
+ ambiguous = true
240
+ }
241
+ }
242
+ if (best !== undefined && !ambiguous) parents.set(id, best.header.id)
243
+ }
244
+ breakCycles(parents)
245
+ return parents
246
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Durable display state for the sidebar lineage: manual sibling order,
3
+ * collapsed subtrees and sessions detached from their parent in the display
4
+ * tree. One small JSON document under the DSH home; writes are serialized,
5
+ * rotated to `.bak`, and replaced atomically.
6
+ *
7
+ * @module dsh-session-lineage/state-store
8
+ */
9
+
10
+ import { copyFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises'
11
+ import { homedir } from 'node:os'
12
+ import { dirname, join } from 'node:path'
13
+
14
+ const FORMAT = 'dsh-session-lineage'
15
+ const STATE_VERSION = 1
16
+ const MAX_STATE_BYTES = 256 * 1024
17
+ const MAX_ORDER_ENTRIES = 20000
18
+ const MAX_FORK_ENTRIES = 20000
19
+
20
+ /** Serialized file operations: two tabs must never interleave writes. */
21
+ let writeChain = Promise.resolve()
22
+
23
+ /**
24
+ * @param task - async file operation.
25
+ * @returns the task's own result.
26
+ */
27
+ function serialize(task) {
28
+ const run = writeChain.then(task, task)
29
+ writeChain = run.catch(() => {})
30
+ return run
31
+ }
32
+
33
+ /**
34
+ * Resolve the DSH home the rest of the harness uses.
35
+ *
36
+ * @returns absolute DSH home directory.
37
+ */
38
+ function resolveDshHome() {
39
+ const configured = String(process.env.DSH_HOME || '').trim()
40
+ if (configured !== '') {
41
+ if (configured === '~') return homedir()
42
+ if (configured.startsWith('~/') || configured.startsWith('~\\')) {
43
+ return join(homedir(), configured.slice(2))
44
+ }
45
+ return configured
46
+ }
47
+ return join(homedir(), '.dsh')
48
+ }
49
+
50
+ /** @returns state document path. */
51
+ function stateFile() {
52
+ return join(resolveDshHome(), 'storages', 'session-lineage', 'state.json')
53
+ }
54
+
55
+ /** @returns rotated previous state document path. */
56
+ function backupFile() {
57
+ return stateFile() + '.bak'
58
+ }
59
+
60
+ /** @returns a fresh empty state document. */
61
+ export function emptyState() {
62
+ return { version: STATE_VERSION, order: {}, collapsed: [], detached: [], forks: {}, display: { numbers: true } }
63
+ }
64
+
65
+ /**
66
+ * Validate and normalize a state document. Unknown or malformed parts are
67
+ * dropped instead of failing the whole save: this is display-only data.
68
+ *
69
+ * @param input - candidate document.
70
+ * @returns normalized `{ version, order, collapsed, detached, display }`.
71
+ */
72
+ export function normalizeState(input) {
73
+ const source = input !== null && typeof input === 'object' && !Array.isArray(input) ? input : {}
74
+ const order = {}
75
+ let entries = 0
76
+ const rawOrder = source.order
77
+ if (rawOrder !== null && typeof rawOrder === 'object' && !Array.isArray(rawOrder)) {
78
+ for (const [parentId, childIds] of Object.entries(rawOrder)) {
79
+ if (parentId === '' || !Array.isArray(childIds)) continue
80
+ const ids = childIds.filter((id) => typeof id === 'string' && id !== '')
81
+ if (ids.length === 0) continue
82
+ entries += ids.length
83
+ if (entries > MAX_ORDER_ENTRIES) break
84
+ order[parentId] = ids
85
+ }
86
+ }
87
+ const collapsed = []
88
+ const seen = new Set()
89
+ if (Array.isArray(source.collapsed)) {
90
+ for (const id of source.collapsed) {
91
+ if (typeof id !== 'string' || id === '' || seen.has(id)) continue
92
+ seen.add(id)
93
+ collapsed.push(id)
94
+ }
95
+ }
96
+ const detached = []
97
+ const detachedSeen = new Set()
98
+ if (Array.isArray(source.detached)) {
99
+ for (const id of source.detached) {
100
+ if (typeof id !== 'string' || id === '' || detachedSeen.has(id)) continue
101
+ detachedSeen.add(id)
102
+ detached.push(id)
103
+ }
104
+ }
105
+ const forks = {}
106
+ let forkEntries = 0
107
+ const rawForks = source.forks
108
+ if (rawForks !== null && typeof rawForks === 'object' && !Array.isArray(rawForks)) {
109
+ for (const [childId, parentId] of Object.entries(rawForks)) {
110
+ if (childId === '' || typeof parentId !== 'string' || parentId === '' || parentId === childId) continue
111
+ forks[childId] = parentId
112
+ forkEntries += 1
113
+ if (forkEntries >= MAX_FORK_ENTRIES) break
114
+ }
115
+ }
116
+ return {
117
+ version: STATE_VERSION,
118
+ order,
119
+ collapsed,
120
+ detached,
121
+ forks,
122
+ display: { numbers: source.display?.numbers !== false },
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Read one stored document.
128
+ *
129
+ * @param file - document path.
130
+ * @returns normalized state, or `undefined` when absent or unusable.
131
+ */
132
+ async function readDocument(file) {
133
+ try {
134
+ const raw = await readFile(file, 'utf8')
135
+ if (Buffer.byteLength(raw, 'utf8') > MAX_STATE_BYTES) return undefined
136
+ const parsed = JSON.parse(raw)
137
+ if (parsed === null || typeof parsed !== 'object') return undefined
138
+ if (parsed.format !== FORMAT || parsed.version !== STATE_VERSION) return undefined
139
+ return normalizeState(parsed.state)
140
+ } catch {
141
+ return undefined
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Read the current display state, falling back to the rotated backup and then
147
+ * to an empty document.
148
+ *
149
+ * @returns normalized state document.
150
+ */
151
+ export function readState() {
152
+ return serialize(async () => {
153
+ const primary = await readDocument(stateFile())
154
+ if (primary !== undefined) return primary
155
+ const backup = await readDocument(backupFile())
156
+ if (backup !== undefined) return backup
157
+ return emptyState()
158
+ })
159
+ }
160
+
161
+ /**
162
+ * Persist a state document (serialized, atomic, `.bak`-rotated).
163
+ *
164
+ * @param input - candidate document.
165
+ * @returns the normalized state that was written.
166
+ */
167
+ export function writeState(input) {
168
+ return serialize(async () => {
169
+ const state = normalizeState(input)
170
+ const file = stateFile()
171
+ const body = JSON.stringify({
172
+ format: FORMAT,
173
+ version: STATE_VERSION,
174
+ updatedAt: new Date().toISOString(),
175
+ state,
176
+ }, null, 2)
177
+ if (Buffer.byteLength(body, 'utf8') > MAX_STATE_BYTES) {
178
+ throw new Error('session-lineage state is too large to save')
179
+ }
180
+ await mkdir(dirname(file), { recursive: true })
181
+ try {
182
+ const previous = await readFile(file, 'utf8')
183
+ if (Buffer.byteLength(previous, 'utf8') <= MAX_STATE_BYTES) {
184
+ await copyFile(file, backupFile())
185
+ }
186
+ } catch {
187
+ // No readable previous document; the backup is simply not rotated.
188
+ }
189
+ const temporary = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`
190
+ await writeFile(temporary, body, 'utf8')
191
+ await rename(temporary, file)
192
+ return state
193
+ })
194
+ }