dsh-conversation-recycle-bin 0.3.11 → 0.3.13

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.
@@ -1,351 +1,368 @@
1
- /**
2
- * Read-only gateway over the Host services this plugin depends on.
3
- *
4
- * All services are optional at construction time and probed per request, so a
5
- * slimmer composition yields a readable `E_INTERNAL`/`E_NOT_FOUND` instead of a
6
- * failed plugin fiber. The gateway normalizes the several DSH shapes into ONE
7
- * session record used by policy, previews and the cascade:
8
- *
9
- * { id, title, cwd, origin, blank, running, live, archived, pinned,
10
- * createdAt, updatedAt, events, sizeBytes, workspace, workspaceIndex }
11
- *
12
- * Titles come from the durable session projection cache when present (a cheap
13
- * read of `storages/session_projcache.json`) and fall back to the Client's
14
- * display title; nothing here trusts the Client for authorization.
15
- */
16
- import { findSessionDir, readJsonFile } from './paths.js'
17
- import { join } from 'node:path'
18
- import { isPathInside } from '../core/policy.js'
19
- import { SESSION_ID_PATTERN } from '../core/ids.js'
20
-
21
- const LIST_TTL_MS = 1_500
22
- const STATE_TTL_MS = 1_500
23
-
24
- export function createSessionGateway({ ctx, paths, now = Date.now }) {
25
- let listCache = null
26
- let listCachedAt = -Infinity
27
- let stateCache = null
28
- let stateCachedAt = -Infinity
29
-
30
- const service = (name) => {
31
- try {
32
- return ctx.get?.(name) ?? ctx[name]
33
- } catch {
34
- return undefined
35
- }
36
- }
37
-
38
- async function readWorkspaceState() {
39
- if (stateCache !== null && now() - stateCachedAt < STATE_TTL_MS) return stateCache
40
- let archived = []
41
- let pinned = []
42
- try {
43
- const document = await readJsonFile(paths.workspaceFile)
44
- archived = Array.isArray(document?.global?.archivedSessionIds) ? document.global.archivedSessionIds : []
45
- pinned = Array.isArray(document?.global?.pinnedSessionIds) ? document.global.pinnedSessionIds : []
46
- } catch {
47
- // A missing or being-rewritten registry is treated as "no archive data";
48
- // the authoritative mutate path is workspaceRegistry, not this read.
49
- }
50
- stateCache = { archived: new Set(archived), pinned: new Set(pinned) }
51
- stateCachedAt = now()
52
- return stateCache
53
- }
54
-
55
- async function readTitles() {
56
- try {
57
- const document = await readJsonFile(paths.projectionCacheFile)
58
- const sessions = document?.tables?.sessions
59
- if (sessions === null || typeof sessions !== 'object') return new Map()
60
- const map = new Map()
61
- for (const [sessionId, record] of Object.entries(sessions)) {
62
- const title = record?.rows?.title?.val
63
- const blank = record?.rows?.sessionListMetadata?.val?.blank
64
- map.set(sessionId, { title: typeof title === 'string' ? title : '', blank: blank === true })
65
- }
66
- return map
67
- } catch {
68
- return new Map()
69
- }
70
- }
71
-
72
- /**
73
- * The authoritative projection checkpoint is the per-session file
74
- * (`storages/session_projcache/sessions/<id>.json`, format version 7); the
75
- * root `session_projcache.json` is a legacy domain dump and is intentionally
76
- * only a bulk fallback.
77
- */
78
- async function readSessionProjection(sessionId) {
79
- const file = join(paths.storagesDir, 'session_projcache', 'sessions', `${sessionId}.json`)
80
- try {
81
- const document = await readJsonFile(file)
82
- const rows = document?.record?.rows
83
- if (rows === null || typeof rows !== 'object') return null
84
- return {
85
- title: typeof rows.title?.val === 'string' ? rows.title.val : '',
86
- blank: rows.sessionListMetadata?.val?.blank === true,
87
- createdAt: document?.record?.identity?.createdAt ?? null,
88
- }
89
- } catch {
90
- return null
91
- }
92
- }
93
-
94
- async function workspaceEntities() {
95
- const registry = service('workspaceRegistry')
96
- if (registry === undefined || typeof registry.list !== 'function') return []
97
- try {
98
- return registry.list()
99
- } catch {
100
- return []
101
- }
102
- }
103
-
104
- async function loadList() {
105
- if (listCache !== null && now() - listCachedAt < LIST_TTL_MS) return listCache
106
- const controller = service('sessionController')
107
- const persistence = service('sessionPersistence')
108
- let items = []
109
- if (controller !== undefined && typeof controller.list === 'function') {
110
- const value = await controller.list({}, AbortSignal.timeout(5_000))
111
- items = Array.isArray(value?.items) ? value.items : []
112
- } else if (persistence !== undefined && typeof persistence.list === 'function') {
113
- const snapshots = await persistence.list({ signal: AbortSignal.timeout(5_000) })
114
- items = snapshots.map((snapshot) => ({
115
- sessionId: snapshot.header.id,
116
- updatedAt: snapshot.header.createdAt,
117
- running: false,
118
- blank: false,
119
- cwd: snapshot.header.cwd,
120
- origin: snapshot.header.origin,
121
- }))
122
- }
123
- const workspaces = await workspaceEntities()
124
- const workspaceBySession = new Map()
125
- for (const workspace of workspaces) {
126
- const ids = Array.isArray(workspace.sessionIds) ? workspace.sessionIds : []
127
- ids.forEach((sessionId, index) => {
128
- if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, { workspace, index })
129
- })
130
- }
131
- // Ownership is also decided by cwd containment, exactly like `inspect`'s
132
- // `workspaceFor` fallback: a session whose directory moved out of every
133
- // registered workspace is an orphan, and `/sessions` must say so per row.
134
- // Without this, `evaluateSessionPolicy` saw `workspace: undefined` on every
135
- // list row and marked the whole batch picker non-deletable.
136
- const workspaceByCwd = (cwd) => {
137
- if (typeof cwd !== 'string' || cwd === '') return null
138
- return workspaces.find((workspace) => isPathInside(workspace.path, cwd)) ?? null
139
- }
140
- const titles = await readTitles()
141
- const state = await readWorkspaceState()
142
- listCache = items.map((item) => {
143
- const member = workspaceBySession.get(item.sessionId) ?? null
144
- const byCwd = member === null ? workspaceByCwd(item.cwd) : null
145
- const owned = member ?? (byCwd === null ? null : { workspace: byCwd, index: -1 })
146
- const cached = titles.get(item.sessionId) ?? { title: '', blank: item.blank === true }
147
- return {
148
- id: String(item.sessionId),
149
- title: cached.title,
150
- cwd: item.cwd ?? null,
151
- origin: item.origin ?? null,
152
- blank: item.blank === true || cached.blank === true,
153
- running: item.running === true,
154
- live: isLive(item.sessionId),
155
- archived: state.archived.has(item.sessionId),
156
- pinned: state.pinned.has(item.sessionId),
157
- createdAt: cached.createdAt ?? null,
158
- updatedAt: item.updatedAt ?? null,
159
- events: null,
160
- sizeBytes: null,
161
- workspace: owned === null ? null : { id: owned.workspace.id, title: owned.workspace.title, path: owned.workspace.path, index: owned.index },
162
- workspaceId: owned?.workspace?.id ?? null,
163
- workspacePath: owned?.workspace?.path ?? null,
164
- workspaceIndex: owned?.index ?? -1,
165
- }
166
- })
167
- listCachedAt = now()
168
- return listCache
169
- }
170
-
171
- function isLive(sessionId) {
172
- // Two independent signals: the in-memory session table, and the agent
173
- // registry the Host itself uses to compute a row's `running` flag. A
174
- // composition that publishes only `agents` used to look "not live" here,
175
- // which skipped quiescing and moved a running conversation's log.
176
- const sessions = service('sessions')
177
- if (sessions !== undefined && typeof sessions.get === 'function') {
178
- try {
179
- if (sessions.get(sessionId) !== undefined) return true
180
- } catch {
181
- // fall through to the agent registry
182
- }
183
- }
184
- const agents = service('agents')
185
- if (agents !== undefined && typeof agents.get === 'function') {
186
- try {
187
- if (agents.get(sessionId) !== undefined && agents.get(sessionId) !== null) return true
188
- } catch {
189
- return false
190
- }
191
- }
192
- return false
193
- }
194
-
195
- /**
196
- * Lightweight running probe for the bounded drain: reads only the in-memory
197
- * live-sessions table instead of rebuilding the whole session list on every
198
- * poll. Returns `undefined` when the service is absent or the entry shape is
199
- * unknown, so the caller falls back to a full `inspect()`.
200
- * @returns {boolean|undefined}
201
- */
202
- function probeRunning(sessionId) {
203
- // Authoritative cheap probe first: the Host computes a list row's `running`
204
- // flag from exactly this check (`api-session-controller`: `agents.get(id)
205
- // ?.status === "running"`). The `Session` object handed out by `sessions.get`
206
- // carries no `running`/`active`/`busy` field, so the legacy probe below can
207
- // only ever answer `undefined` on current Hosts.
208
- const agents = service('agents')
209
- if (agents !== undefined && typeof agents.get === 'function') {
210
- try {
211
- const agent = agents.get(sessionId)
212
- if (agent === undefined || agent === null) return false
213
- if (typeof agent.status === 'string') return agent.status === 'running'
214
- } catch {
215
- // Fall through to the legacy field probe.
216
- }
217
- }
218
- const sessions = service('sessions')
219
- if (sessions === undefined || typeof sessions.get !== 'function') return undefined
220
- let current
221
- try {
222
- current = sessions.get(sessionId)
223
- } catch {
224
- return undefined
225
- }
226
- if (current === null || current === undefined) return false
227
- if (typeof current !== 'object') return undefined
228
- if (typeof current.running === 'boolean') return current.running
229
- if (typeof current.active === 'boolean') return current.active
230
- if (typeof current.busy === 'boolean') return current.busy
231
- return undefined
232
- }
233
-
234
- /**
235
- * Event count when it is cheaply knowable, `null` otherwise.
236
- *
237
- * `sessionPersistence.stat()` reports `header`/`revision`/`sizeBytes` (and no
238
- * `eventCount` on 0.2.1), so the old `snapshot.eventCount` read was dead. A
239
- * live session does expose the count exactly: the session store defines `seq`
240
- * as "always the log length" (`dsh-session` `get seq()`), and it is a plain
241
- * number read, not a materialized `snapshotEvents()` (that API is deprecated).
242
- * For a stored, non-live session there is no equivalent that avoids reading
243
- * and parsing the whole log, so the field stays `null` instead of presenting
244
- * a projection cursor as an exact count.
245
- * @returns {number|null}
246
- */
247
- function eventCountFor(sessionId, snapshot) {
248
- if (typeof snapshot?.eventCount === 'number') return snapshot.eventCount
249
- const sessions = service('sessions')
250
- if (sessions === undefined || typeof sessions.get !== 'function') return null
251
- try {
252
- const seq = sessions.get(sessionId)?.seq
253
- return typeof seq === 'number' && Number.isFinite(seq) && seq >= 0 ? seq : null
254
- } catch {
255
- return null
256
- }
257
- }
258
-
259
- async function workspaceFor(session) {
260
- const workspaces = await workspaceEntities()
261
- const byId = workspaces.find((workspace) => workspace.id === session.workspaceId)
262
- if (byId !== undefined) return byId
263
- const byCwd = workspaces.find((workspace) => {
264
- if (typeof workspace.path !== 'string' || typeof session.cwd !== 'string') return false
265
- // Shared path semantics: drive-letter paths compare case-insensitively,
266
- // POSIX paths stay case-sensitive, and UNC roots are handled like Windows.
267
- return isPathInside(workspace.path, session.cwd)
268
- })
269
- return byCwd ?? null
270
- }
271
-
272
- return {
273
- workspaceState: readWorkspaceState,
274
- list: loadList,
275
- isRunning: probeRunning,
276
-
277
- /** Normalize one session; throws E_NOT_FOUND-shaped data as `null`. */
278
- async inspect(sessionId) {
279
- if (typeof sessionId !== 'string' || !SESSION_ID_PATTERN.test(sessionId)) return null
280
- const persistence = service('sessionPersistence')
281
- let snapshot
282
- if (persistence !== undefined && typeof persistence.stat === 'function') {
283
- try {
284
- snapshot = await persistence.stat(sessionId, { signal: AbortSignal.timeout(5_000) })
285
- } catch {
286
- snapshot = undefined
287
- }
288
- }
289
- const fromList = (await loadList()).find((item) => item.id === sessionId)
290
- if (snapshot === undefined && fromList === undefined && !isLive(sessionId)) return null
291
- const projection = await readSessionProjection(sessionId)
292
- const workspace = await workspaceFor(fromList ?? { workspaceId: null, cwd: snapshot?.header?.cwd ?? null })
293
- const entity = workspace !== null && typeof workspace.sessionIds?.indexOf === 'function'
294
- ? workspace.sessionIds.indexOf(sessionId)
295
- : -1
296
- // `controller.list()` does not have to carry archive state, and treating
297
- // its silence as "not archived" made restore un-hide conversations the
298
- // user had archived. The workspace registry is the authoritative record,
299
- // so it wins when it knows about the session.
300
- const state = await readWorkspaceState()
301
- return {
302
- id: sessionId,
303
- title: projection?.title || fromList?.title || '',
304
- cwd: snapshot?.header?.cwd ?? fromList?.cwd ?? null,
305
- origin: snapshot?.header?.origin ?? fromList?.origin ?? null,
306
- blank: projection?.blank ?? fromList?.blank ?? false,
307
- running: fromList?.running ?? false,
308
- live: isLive(sessionId),
309
- archived: state.archived.has(sessionId) || fromList?.archived === true,
310
- pinned: state.pinned.has(sessionId) || fromList?.pinned === true,
311
- createdAt: snapshot?.header?.createdAt ?? null,
312
- updatedAt: fromList?.updatedAt ?? null,
313
- events: eventCountFor(sessionId, snapshot),
314
- sizeBytes: typeof snapshot?.sizeBytes === 'number' ? snapshot.sizeBytes : null,
315
- workspace: workspace === null ? null : { id: workspace.id, title: workspace.title, path: workspace.path, index: entity },
316
- workspaceId: workspace?.id ?? null,
317
- workspaceIndex: entity,
318
- }
319
- },
320
-
321
- findSessionDir(sessionId) {
322
- return findSessionDir(paths.sessionsRoot, sessionId)
323
- },
324
-
325
- /**
326
- * Fill missing titles from the per-session projection checkpoints for the
327
- * first `limit` rows. The bulk list is read-only UI data, so this is done
328
- * lazily here rather than on every inspect; a missing checkpoint simply
329
- * leaves the id/cwd fallback the Client renders.
330
- */
331
- async enrichTitles(sessions, limit = 80) {
332
- const slice = sessions.slice(0, Math.max(1, limit))
333
- await Promise.all(slice.map(async (session) => {
334
- if (typeof session.title === 'string' && session.title !== '') return
335
- const projection = await readSessionProjection(session.id)
336
- if (projection === null) return
337
- if (typeof projection.title === 'string' && projection.title !== '') session.title = projection.title
338
- if (projection.blank === true) session.blank = true
339
- if (session.createdAt === null) session.createdAt = projection.createdAt ?? null
340
- }))
341
- return sessions
342
- },
343
-
344
- invalidate() {
345
- listCache = null
346
- listCachedAt = -Infinity
347
- stateCache = null
348
- stateCachedAt = -Infinity
349
- },
350
- }
351
- }
1
+ /**
2
+ * Read-only gateway over the Host services this plugin depends on.
3
+ *
4
+ * All services are optional at construction time and probed per request, so a
5
+ * slimmer composition yields a readable `E_INTERNAL`/`E_NOT_FOUND` instead of a
6
+ * failed plugin fiber. The gateway normalizes the several DSH shapes into ONE
7
+ * session record used by policy, previews and the cascade:
8
+ *
9
+ * { id, title, cwd, origin, blank, running, live, archived, pinned,
10
+ * createdAt, updatedAt, events, sizeBytes, workspace, workspaceIndex }
11
+ *
12
+ * Titles come from the durable session projection cache when present (a cheap
13
+ * read of `storages/session_projcache.json`) and fall back to the Client's
14
+ * display title; nothing here trusts the Client for authorization.
15
+ */
16
+ import { findSessionDir, readJsonFile } from './paths.js'
17
+ import { join } from 'node:path'
18
+ import { isPathInside } from '../core/policy.js'
19
+ import { SESSION_ID_PATTERN } from '../core/ids.js'
20
+
21
+ const LIST_TTL_MS = 1_500
22
+ const STATE_TTL_MS = 1_500
23
+
24
+ export function createSessionGateway({ ctx, paths, now = Date.now }) {
25
+ let listCache = null
26
+ let listCachedAt = -Infinity
27
+ let stateCache = null
28
+ let stateCachedAt = -Infinity
29
+
30
+ const service = (name) => {
31
+ try {
32
+ return ctx.get?.(name) ?? ctx[name]
33
+ } catch {
34
+ return undefined
35
+ }
36
+ }
37
+
38
+ async function readWorkspaceState() {
39
+ if (stateCache !== null && now() - stateCachedAt < STATE_TTL_MS) return stateCache
40
+ let archived = []
41
+ let pinned = []
42
+ try {
43
+ const document = await readJsonFile(paths.workspaceFile)
44
+ archived = Array.isArray(document?.global?.archivedSessionIds) ? document.global.archivedSessionIds : []
45
+ pinned = Array.isArray(document?.global?.pinnedSessionIds) ? document.global.pinnedSessionIds : []
46
+ } catch {
47
+ // A missing or being-rewritten registry is treated as "no archive data";
48
+ // the authoritative mutate path is workspaceRegistry, not this read.
49
+ }
50
+ stateCache = { archived: new Set(archived), pinned: new Set(pinned) }
51
+ stateCachedAt = now()
52
+ return stateCache
53
+ }
54
+
55
+ async function readTitles() {
56
+ try {
57
+ const document = await readJsonFile(paths.projectionCacheFile)
58
+ const sessions = document?.tables?.sessions
59
+ if (sessions === null || typeof sessions !== 'object') return new Map()
60
+ const map = new Map()
61
+ for (const [sessionId, record] of Object.entries(sessions)) {
62
+ const title = record?.rows?.title?.val
63
+ const blank = record?.rows?.sessionListMetadata?.val?.blank
64
+ map.set(sessionId, { title: typeof title === 'string' ? title : '', blank: blank === true })
65
+ }
66
+ return map
67
+ } catch {
68
+ return new Map()
69
+ }
70
+ }
71
+
72
+ /**
73
+ * The authoritative projection checkpoint is the per-session file
74
+ * (`storages/session_projcache/sessions/<id>.json`, format version 7); the
75
+ * root `session_projcache.json` is a legacy domain dump and is intentionally
76
+ * only a bulk fallback.
77
+ */
78
+ async function readSessionProjection(sessionId) {
79
+ const file = join(paths.storagesDir, 'session_projcache', 'sessions', `${sessionId}.json`)
80
+ try {
81
+ const document = await readJsonFile(file)
82
+ const rows = document?.record?.rows
83
+ if (rows === null || typeof rows !== 'object') return null
84
+ return {
85
+ title: typeof rows.title?.val === 'string' ? rows.title.val : '',
86
+ blank: rows.sessionListMetadata?.val?.blank === true,
87
+ createdAt: document?.record?.identity?.createdAt ?? null,
88
+ }
89
+ } catch {
90
+ return null
91
+ }
92
+ }
93
+
94
+ async function workspaceEntities() {
95
+ const registry = service('workspaceRegistry')
96
+ if (registry === undefined || typeof registry.list !== 'function') return []
97
+ try {
98
+ return registry.list()
99
+ } catch {
100
+ return []
101
+ }
102
+ }
103
+
104
+ async function loadList() {
105
+ if (listCache !== null && now() - listCachedAt < LIST_TTL_MS) return listCache
106
+ const controller = service('sessionController')
107
+ const persistence = service('sessionPersistence')
108
+ let items = []
109
+ if (controller !== undefined && typeof controller.list === 'function') {
110
+ const value = await controller.list({}, AbortSignal.timeout(5_000))
111
+ items = Array.isArray(value?.items) ? value.items : []
112
+ } else if (persistence !== undefined && typeof persistence.list === 'function') {
113
+ const snapshots = await persistence.list({ signal: AbortSignal.timeout(5_000) })
114
+ items = snapshots.map((snapshot) => ({
115
+ sessionId: snapshot.header.id,
116
+ updatedAt: snapshot.header.createdAt,
117
+ running: false,
118
+ blank: false,
119
+ cwd: snapshot.header.cwd,
120
+ origin: snapshot.header.origin,
121
+ }))
122
+ }
123
+ const workspaces = await workspaceEntities()
124
+ const workspaceBySession = new Map()
125
+ for (const workspace of workspaces) {
126
+ const ids = Array.isArray(workspace.sessionIds) ? workspace.sessionIds : []
127
+ ids.forEach((sessionId, index) => {
128
+ if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, { workspace, index })
129
+ })
130
+ }
131
+ // Ownership is also decided by cwd containment, exactly like `inspect`'s
132
+ // `workspaceFor` fallback: a session whose directory moved out of every
133
+ // registered workspace is an orphan, and `/sessions` must say so per row.
134
+ // Without this, `evaluateSessionPolicy` saw `workspace: undefined` on every
135
+ // list row and marked the whole batch picker non-deletable.
136
+ const workspaceByCwd = (cwd) => {
137
+ if (typeof cwd !== 'string' || cwd === '') return null
138
+ return workspaces.find((workspace) => isPathInside(workspace.path, cwd)) ?? null
139
+ }
140
+ const titles = await readTitles()
141
+ const state = await readWorkspaceState()
142
+ listCache = items.map((item) => {
143
+ const member = workspaceBySession.get(item.sessionId) ?? null
144
+ const byCwd = member === null ? workspaceByCwd(item.cwd) : null
145
+ const owned = member ?? (byCwd === null ? null : { workspace: byCwd, index: -1 })
146
+ const cached = titles.get(item.sessionId) ?? { title: '', blank: item.blank === true }
147
+ return {
148
+ id: String(item.sessionId),
149
+ title: cached.title,
150
+ cwd: item.cwd ?? null,
151
+ origin: item.origin ?? null,
152
+ blank: item.blank === true || cached.blank === true,
153
+ running: item.running === true,
154
+ live: isLive(item.sessionId),
155
+ archived: state.archived.has(item.sessionId),
156
+ pinned: state.pinned.has(item.sessionId),
157
+ createdAt: cached.createdAt ?? null,
158
+ updatedAt: item.updatedAt ?? null,
159
+ events: null,
160
+ sizeBytes: null,
161
+ workspace: owned === null ? null : { id: owned.workspace.id, title: owned.workspace.title, path: owned.workspace.path, index: owned.index },
162
+ workspaceId: owned?.workspace?.id ?? null,
163
+ workspacePath: owned?.workspace?.path ?? null,
164
+ workspaceIndex: owned?.index ?? -1,
165
+ }
166
+ })
167
+ listCachedAt = now()
168
+ return listCache
169
+ }
170
+
171
+ function isLive(sessionId) {
172
+ // Two independent signals: the in-memory session table, and the agent
173
+ // registry the Host itself uses to compute a row's `running` flag. A
174
+ // composition that publishes only `agents` used to look "not live" here,
175
+ // which skipped quiescing and moved a running conversation's log.
176
+ const sessions = service('sessions')
177
+ if (sessions !== undefined && typeof sessions.get === 'function') {
178
+ try {
179
+ if (sessions.get(sessionId) !== undefined) return true
180
+ } catch {
181
+ // fall through to the agent registry
182
+ }
183
+ }
184
+ const agents = service('agents')
185
+ if (agents !== undefined && typeof agents.get === 'function') {
186
+ try {
187
+ if (agents.get(sessionId) !== undefined && agents.get(sessionId) !== null) return true
188
+ } catch {
189
+ return false
190
+ }
191
+ }
192
+ return false
193
+ }
194
+
195
+ /**
196
+ * Lightweight running probe for the bounded drain: reads only the in-memory
197
+ * live-sessions table instead of rebuilding the whole session list on every
198
+ * poll. Returns `undefined` when the service is absent or the entry shape is
199
+ * unknown, so the caller falls back to a full `inspect()`.
200
+ * @returns {boolean|undefined}
201
+ */
202
+ /**
203
+ * Merge the two running signals: the cached list row and the live probe.
204
+ * Either saying "running" wins (a stale list must not hide a live turn); a
205
+ * probe that cannot answer leaves the list's value alone, `undefined`
206
+ * included, so callers can stay fail-closed.
207
+ */
208
+ function runningFlag(fromList, probed) {
209
+ if (fromList?.running === true || probed === true) return true
210
+ if (probed !== undefined) return probed
211
+ return fromList?.running
212
+ }
213
+
214
+ function probeRunning(sessionId) {
215
+ // Authoritative cheap probe first: the Host computes a list row's `running`
216
+ // flag from exactly this check (`api-session-controller`: `agents.get(id)
217
+ // ?.status === "running"`). The `Session` object handed out by `sessions.get`
218
+ // carries no `running`/`active`/`busy` field, so the legacy probe below can
219
+ // only ever answer `undefined` on current Hosts.
220
+ const agents = service('agents')
221
+ if (agents !== undefined && typeof agents.get === 'function') {
222
+ try {
223
+ const agent = agents.get(sessionId)
224
+ if (agent === undefined || agent === null) return false
225
+ if (typeof agent.status === 'string') return agent.status === 'running'
226
+ } catch {
227
+ // Fall through to the legacy field probe.
228
+ }
229
+ }
230
+ const sessions = service('sessions')
231
+ if (sessions === undefined || typeof sessions.get !== 'function') return undefined
232
+ let current
233
+ try {
234
+ current = sessions.get(sessionId)
235
+ } catch {
236
+ return undefined
237
+ }
238
+ if (current === null || current === undefined) return false
239
+ if (typeof current !== 'object') return undefined
240
+ if (typeof current.running === 'boolean') return current.running
241
+ if (typeof current.active === 'boolean') return current.active
242
+ if (typeof current.busy === 'boolean') return current.busy
243
+ return undefined
244
+ }
245
+
246
+ /**
247
+ * Event count when it is cheaply knowable, `null` otherwise.
248
+ *
249
+ * `sessionPersistence.stat()` reports `header`/`revision`/`sizeBytes` (and no
250
+ * `eventCount` on 0.2.1), so the old `snapshot.eventCount` read was dead. A
251
+ * live session does expose the count exactly: the session store defines `seq`
252
+ * as "always the log length" (`dsh-session` `get seq()`), and it is a plain
253
+ * number read, not a materialized `snapshotEvents()` (that API is deprecated).
254
+ * For a stored, non-live session there is no equivalent that avoids reading
255
+ * and parsing the whole log, so the field stays `null` instead of presenting
256
+ * a projection cursor as an exact count.
257
+ * @returns {number|null}
258
+ */
259
+ function eventCountFor(sessionId, snapshot) {
260
+ if (typeof snapshot?.eventCount === 'number') return snapshot.eventCount
261
+ const sessions = service('sessions')
262
+ if (sessions === undefined || typeof sessions.get !== 'function') return null
263
+ try {
264
+ const seq = sessions.get(sessionId)?.seq
265
+ return typeof seq === 'number' && Number.isFinite(seq) && seq >= 0 ? seq : null
266
+ } catch {
267
+ return null
268
+ }
269
+ }
270
+
271
+ async function workspaceFor(session) {
272
+ const workspaces = await workspaceEntities()
273
+ const byId = workspaces.find((workspace) => workspace.id === session.workspaceId)
274
+ if (byId !== undefined) return byId
275
+ const byCwd = workspaces.find((workspace) => {
276
+ if (typeof workspace.path !== 'string' || typeof session.cwd !== 'string') return false
277
+ // Shared path semantics: drive-letter paths compare case-insensitively,
278
+ // POSIX paths stay case-sensitive, and UNC roots are handled like Windows.
279
+ return isPathInside(workspace.path, session.cwd)
280
+ })
281
+ return byCwd ?? null
282
+ }
283
+
284
+ return {
285
+ workspaceState: readWorkspaceState,
286
+ list: loadList,
287
+ isRunning: probeRunning,
288
+
289
+ /** Normalize one session; throws E_NOT_FOUND-shaped data as `null`. */
290
+ async inspect(sessionId) {
291
+ if (typeof sessionId !== 'string' || !SESSION_ID_PATTERN.test(sessionId)) return null
292
+ const persistence = service('sessionPersistence')
293
+ let snapshot
294
+ if (persistence !== undefined && typeof persistence.stat === 'function') {
295
+ try {
296
+ snapshot = await persistence.stat(sessionId, { signal: AbortSignal.timeout(5_000) })
297
+ } catch {
298
+ snapshot = undefined
299
+ }
300
+ }
301
+ const fromList = (await loadList()).find((item) => item.id === sessionId)
302
+ if (snapshot === undefined && fromList === undefined && !isLive(sessionId)) return null
303
+ const projection = await readSessionProjection(sessionId)
304
+ const workspace = await workspaceFor(fromList ?? { workspaceId: null, cwd: snapshot?.header?.cwd ?? null })
305
+ const entity = workspace !== null && typeof workspace.sessionIds?.indexOf === 'function'
306
+ ? workspace.sessionIds.indexOf(sessionId)
307
+ : -1
308
+ // `controller.list()` does not have to carry archive state, and treating
309
+ // its silence as "not archived" made restore un-hide conversations the
310
+ // user had archived. The workspace registry is the authoritative record,
311
+ // so it wins when it knows about the session.
312
+ const state = await readWorkspaceState()
313
+ return {
314
+ id: sessionId,
315
+ title: projection?.title || fromList?.title || '',
316
+ cwd: snapshot?.header?.cwd ?? fromList?.cwd ?? null,
317
+ origin: snapshot?.header?.origin ?? fromList?.origin ?? null,
318
+ blank: projection?.blank ?? fromList?.blank ?? false,
319
+ // `?? false` made "the Host did not say" indistinguishable from "it is
320
+ // stopped", which turned lifecycle's fail-closed branch into dead code.
321
+ // `controller.list()` is cached for a few seconds, so a turn that
322
+ // started since then still reads as stopped there; the live agent
323
+ // registry is cheap and authoritative, so any `true` from either wins.
324
+ running: runningFlag(fromList, probeRunning(sessionId)),
325
+ live: isLive(sessionId),
326
+ archived: state.archived.has(sessionId) || fromList?.archived === true,
327
+ pinned: state.pinned.has(sessionId) || fromList?.pinned === true,
328
+ createdAt: snapshot?.header?.createdAt ?? null,
329
+ updatedAt: fromList?.updatedAt ?? null,
330
+ events: eventCountFor(sessionId, snapshot),
331
+ sizeBytes: typeof snapshot?.sizeBytes === 'number' ? snapshot.sizeBytes : null,
332
+ workspace: workspace === null ? null : { id: workspace.id, title: workspace.title, path: workspace.path, index: entity },
333
+ workspaceId: workspace?.id ?? null,
334
+ workspaceIndex: entity,
335
+ }
336
+ },
337
+
338
+ findSessionDir(sessionId) {
339
+ return findSessionDir(paths.sessionsRoot, sessionId)
340
+ },
341
+
342
+ /**
343
+ * Fill missing titles from the per-session projection checkpoints for the
344
+ * first `limit` rows. The bulk list is read-only UI data, so this is done
345
+ * lazily here rather than on every inspect; a missing checkpoint simply
346
+ * leaves the id/cwd fallback the Client renders.
347
+ */
348
+ async enrichTitles(sessions, limit = 80) {
349
+ const slice = sessions.slice(0, Math.max(1, limit))
350
+ await Promise.all(slice.map(async (session) => {
351
+ if (typeof session.title === 'string' && session.title !== '') return
352
+ const projection = await readSessionProjection(session.id)
353
+ if (projection === null) return
354
+ if (typeof projection.title === 'string' && projection.title !== '') session.title = projection.title
355
+ if (projection.blank === true) session.blank = true
356
+ if (session.createdAt === null) session.createdAt = projection.createdAt ?? null
357
+ }))
358
+ return sessions
359
+ },
360
+
361
+ invalidate() {
362
+ listCache = null
363
+ listCachedAt = -Infinity
364
+ stateCache = null
365
+ stateCachedAt = -Infinity
366
+ },
367
+ }
368
+ }