@kabxx/dsh-session-move 0.0.0-stage → 0.1.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.
package/src/ledger.js ADDED
@@ -0,0 +1,323 @@
1
+ /** Workspace ledger adapter for the stock DSH 0.2.2-rc.5 JSON backend. */
2
+
3
+ import { isAbsolute, parse } from 'node:path'
4
+ import { realpath, stat } from 'node:fs/promises'
5
+
6
+ const WORKSPACE = 'workspace'
7
+ const TABLE = 'workspaces'
8
+ const ORIGINAL = Symbol.for('cordis.original')
9
+
10
+ function ledgerError(code, cause) {
11
+ return Object.assign(new Error(`Workspace ledger (${code})`, { cause }), { code })
12
+ }
13
+
14
+ function access(ctx, { domain: offline } = {}) {
15
+ const domain = offline ?? ctx.get('storageDomain')?.get(WORKSPACE)
16
+ const registry = offline ? undefined : ctx.workspaceRegistry
17
+ const native = registry?.[ORIGINAL] ?? registry
18
+ const table = domain?.table(TABLE)
19
+ const unit = domain?.unit
20
+ const records = unit?.state?.tables?.get(TABLE)
21
+ // Neither KvTable nor KvUnit exposes multi-record puts. The standard backend
22
+ // already atomically publishes this entire unit. Use its write slot and
23
+ // publish function so Host writes compose with the same authoritative state.
24
+ if (domain?.name !== WORKSPACE || typeof domain.enqueue !== 'function'
25
+ || typeof domain.emitChanged !== 'function' || unit?.descriptor?.name !== WORKSPACE
26
+ || unit.descriptor.version !== 2 || unit.descriptor.layout === 'per-record'
27
+ || typeof unit.publish !== 'function' || !(records instanceof Map)
28
+ || !(table?.records instanceof Map) || (!offline && !native)
29
+ || (native && (native.table !== table || typeof native.enqueueOperation !== 'function'
30
+ || !(native.entities instanceof Map) || !(native.headers instanceof Map)
31
+ || !(native.sessionPaths instanceof Map) || !(native.missingSessionPaths instanceof Set)
32
+ || !(native.invalidSessionPaths instanceof Map)))) {
33
+ throw ledgerError('unsupported')
34
+ }
35
+ return { domain, native, table, unit, records }
36
+ }
37
+
38
+ function scope(plan) {
39
+ if (!Array.isArray(plan?.members) || plan.members.length === 0
40
+ || typeof plan.targetWorkspaceId !== 'string' || typeof plan.targetCwd !== 'string') {
41
+ throw ledgerError('changed')
42
+ }
43
+ const ids = plan.members.map((member) => member?.id)
44
+ if (ids.some((id) => typeof id !== 'string' || !id) || new Set(ids).size !== ids.length) {
45
+ throw ledgerError('changed')
46
+ }
47
+ return new Set(ids)
48
+ }
49
+
50
+ /** Capture raw membership before publishing a prepared migration journal. */
51
+ export function captureLedger(ctx, plan) {
52
+ const ids = scope(plan)
53
+ const { table } = access(ctx)
54
+ if (table.get(plan.targetWorkspaceId)?.path !== plan.targetCwd) throw ledgerError('target-missing')
55
+ return [...table.entries()]
56
+ .filter(([id, record]) => id === plan.targetWorkspaceId || record.sessionIds.some((candidate) => ids.has(candidate)))
57
+ .map(([id, { path, sessionIds }]) => ({ id, path, sessionIds: [...sessionIds] }))
58
+ }
59
+
60
+ function savedRecords(snapshot, plan) {
61
+ const records = new Map()
62
+ if (!Array.isArray(snapshot)) throw ledgerError('changed')
63
+ for (const record of snapshot) {
64
+ if (typeof record?.id !== 'string' || typeof record.path !== 'string' || records.has(record.id)
65
+ || !Array.isArray(record.sessionIds) || record.sessionIds.some((id) => typeof id !== 'string')) {
66
+ throw ledgerError('changed')
67
+ }
68
+ records.set(record.id, record)
69
+ }
70
+ if (records.get(plan.targetWorkspaceId)?.path !== plan.targetCwd) throw ledgerError('changed')
71
+ return records
72
+ }
73
+
74
+ function sameSequence(left, right) {
75
+ return left.length === right.length && left.every((value, index) => value === right[index])
76
+ }
77
+
78
+ function sameOwners(current, saved, ids) {
79
+ // Compare only moved IDs, independent of edits to the rest of either list.
80
+ const owners = (records) => [...records].flatMap(([workspace, { sessionIds }]) =>
81
+ sessionIds.filter((id) => ids.has(id)).map((id) => JSON.stringify([workspace, id]))).sort()
82
+ return sameSequence(owners(current), owners(saved))
83
+ }
84
+
85
+ async function prepareIndexEntry(header) {
86
+ const { cwd } = header
87
+ if (typeof cwd !== 'string') return { header, invalid: 'header has no cwd' }
88
+ const root = parse(cwd).root
89
+ if (!isAbsolute(cwd) || (process.platform === 'win32' && (root === '\\' || root === '/'))) {
90
+ return { header, invalid: `cwd '${cwd}' is not fully qualified` }
91
+ }
92
+ try {
93
+ const path = await realpath(cwd)
94
+ if ((await stat(path)).isDirectory()) return { header, path }
95
+ return { header, invalid: `cwd '${cwd}' is not a directory` }
96
+ } catch (error) {
97
+ return { header, missing: error.code === 'ENOENT', invalid: `cwd '${cwd}' does not resolve` }
98
+ }
99
+ }
100
+
101
+ async function prepareIndexes(ctx, plan, direction) {
102
+ return Promise.all(plan.members.map(async (member) => {
103
+ const header = (await ctx.sessionPersistence.stat(member.id))?.header
104
+ const cwd = direction === 'forward' ? plan.targetCwd : member.oldCwd
105
+ if (header?.id !== member.id || header.cwd !== cwd) throw ledgerError('changed')
106
+ const entry = await prepareIndexEntry(header)
107
+ if (direction === 'forward' && entry.path !== plan.targetCwd) throw ledgerError('target-missing')
108
+ return entry
109
+ }))
110
+ }
111
+
112
+ function publishIndexes(registry, indexes) {
113
+ if (!registry) return
114
+ for (const { header, path, missing, invalid } of indexes) {
115
+ const { id } = header
116
+ registry.headers.set(id, header)
117
+ if (path === undefined) registry.sessionPaths.delete(id)
118
+ else registry.sessionPaths.set(id, path)
119
+ if (missing) registry.missingSessionPaths.add(id)
120
+ else registry.missingSessionPaths.delete(id)
121
+ if (invalid === undefined) registry.invalidSessionPaths.delete(id)
122
+ else registry.invalidSessionPaths.set(id, invalid)
123
+ }
124
+ }
125
+
126
+ function inLedgerQueue({ domain, native }, run) {
127
+ const execute = () => domain.enqueue(run)
128
+ return native ? native.enqueueOperation(execute) : execute()
129
+ }
130
+
131
+ /** Run one batch in the registry and domain queues, then publish feed updates. */
132
+ function transact(adapter, update, indexes = []) {
133
+ const { domain, native, table, unit, records } = adapter
134
+ return inLedgerQueue(adapter, async () => {
135
+ const changes = update(new Map(table.entries()))
136
+ const previous = new Map()
137
+ const entities = new Map()
138
+ for (const [id] of changes) {
139
+ if (!records.has(id)) throw ledgerError('changed')
140
+ previous.set(id, records.get(id))
141
+ if (native) {
142
+ const entity = native.entities.get(id)
143
+ if (!entity || entity.record?.path !== table.get(id)?.path) throw ledgerError('changed')
144
+ entities.set(id, entity)
145
+ }
146
+ }
147
+ if (changes.size) {
148
+ for (const [id, record] of changes) records.set(id, record)
149
+ try {
150
+ await unit.publish()
151
+ } catch (cause) {
152
+ for (const [id, record] of previous) records.set(id, record)
153
+ // The backend's error may follow rename (e.g. directory fsync failed).
154
+ // Re-publish the old state before native writes can use it again.
155
+ try {
156
+ await unit.publish()
157
+ } catch (undo) {
158
+ const failure = ledgerError('unknown-state', new AggregateError([cause, undo]))
159
+ domain.failure = failure
160
+ throw failure
161
+ }
162
+ throw cause
163
+ }
164
+ for (const [id, record] of changes) {
165
+ table.records.set(id, record)
166
+ const entity = entities.get(id)
167
+ if (entity) entity.record = record
168
+ }
169
+ }
170
+ // Make all three memory mirrors coherent before any follow observer runs.
171
+ publishIndexes(native, indexes)
172
+ for (const [key, value] of changes) {
173
+ domain.emitChanged({ domain: WORKSPACE, table: TABLE, operation: 'put', key, value })
174
+ }
175
+ })
176
+ }
177
+
178
+ /** Keep ownership evidence stable until the caller saves the commit marker. */
179
+ export async function withPublishedLedger(ctx, plan, snapshot, confirm, options) {
180
+ const ids = scope(plan)
181
+ const saved = savedRecords(snapshot, plan)
182
+ const targetOwners = new Map([[plan.targetWorkspaceId, { sessionIds: [...ids] }]])
183
+ if (sameOwners(saved, targetOwners, ids)) return false
184
+ const adapter = access(ctx, options)
185
+ return inLedgerQueue(adapter, async () => {
186
+ const current = new Map(adapter.table.entries())
187
+ if (current.get(plan.targetWorkspaceId)?.path !== plan.targetCwd || !sameOwners(current, targetOwners, ids)) {
188
+ return false
189
+ }
190
+ await confirm()
191
+ return true
192
+ })
193
+ }
194
+
195
+ function saveChanged(changes, id, record, sessionIds) {
196
+ if (!sameSequence(record.sessionIds, sessionIds)) {
197
+ changes.set(id, { ...record, sessionIds, updatedAt: new Date().toISOString() })
198
+ }
199
+ }
200
+
201
+ /** Publish the source removals and target insertion in one atomic ledger write. */
202
+ export async function moveLedger(ctx, plan, snapshot, options) {
203
+ const ids = scope(plan)
204
+ const saved = savedRecords(snapshot, plan)
205
+ const adapter = access(ctx, options)
206
+ const indexes = await prepareIndexes(ctx, plan, 'forward')
207
+ await transact(adapter, (current) => {
208
+ const target = current.get(plan.targetWorkspaceId)
209
+ if (target?.path !== plan.targetCwd) throw ledgerError('target-missing')
210
+ const changes = new Map()
211
+ const exactTarget = new Map([[plan.targetWorkspaceId, { sessionIds: [...ids] }]])
212
+ if (sameOwners(current, exactTarget, ids)) return changes // committed recovery
213
+ if (!sameOwners(current, saved, ids)) throw ledgerError('changed')
214
+ for (const [id, original] of saved) {
215
+ const record = current.get(id)
216
+ if (record?.path !== original.path) throw ledgerError('changed')
217
+ const next = record.sessionIds.filter((candidate) => !ids.has(candidate))
218
+ if (id === plan.targetWorkspaceId) {
219
+ const anchor = next.indexOf(plan.beforeSessionId)
220
+ next.splice(anchor < 0 ? 0 : anchor, 0, ...ids)
221
+ }
222
+ saveChanged(changes, id, record, next)
223
+ }
224
+ return changes
225
+ }, indexes)
226
+ }
227
+
228
+ function restorePositions(current, original, ids) {
229
+ const next = current.filter((id) => !ids.has(id))
230
+ for (const [index, id] of original.entries()) {
231
+ if (!ids.has(id)) continue
232
+ const right = original.slice(index + 1).find((anchor) => !ids.has(anchor) && next.includes(anchor))
233
+ const left = original.slice(0, index).findLast((anchor) => next.includes(anchor))
234
+ const at = right !== undefined ? next.indexOf(right)
235
+ : left !== undefined ? next.indexOf(left) + 1 : Math.min(index, next.length)
236
+ next.splice(at, 0, id)
237
+ }
238
+ return next
239
+ }
240
+
241
+ /** Restore original ownership and member order against the current unrelated IDs. */
242
+ export async function restoreLedger(ctx, plan, snapshot, options) {
243
+ const ids = scope(plan)
244
+ const saved = savedRecords(snapshot, plan)
245
+ const adapter = access(ctx, options)
246
+ const indexes = await prepareIndexes(ctx, plan, 'rollback')
247
+ await transact(adapter, (current) => {
248
+ const changes = new Map()
249
+ for (const [id, original] of saved) {
250
+ const record = current.get(id)
251
+ // A folder removed (or replaced) during the transfer is a user edit.
252
+ // Roll back only records that still represent the original workspace.
253
+ if (record?.path !== original.path) continue
254
+ const moved = (sessionId) => ids.has(sessionId)
255
+ if (sameSequence(record.sessionIds.filter(moved), original.sessionIds.filter(moved))) continue
256
+ saveChanged(changes, id, record, restorePositions(record.sessionIds, original.sessionIds, ids))
257
+ }
258
+ return changes
259
+ }, indexes)
260
+ }
261
+
262
+ /** Fix only legacy duplicates for which one stored header identifies one owner. */
263
+ export async function repairLegacyDuplicates(ctx, options) {
264
+ const domain = options?.domain ?? ctx.get('storageDomain')?.get(WORKSPACE)
265
+ const table = domain?.table(TABLE)
266
+ if (!table) throw ledgerError('unsupported')
267
+ const candidates = new Map()
268
+ for (const [workspace, { path, sessionIds }] of table.entries()) {
269
+ for (const id of new Set(sessionIds)) {
270
+ const owners = candidates.get(id) ?? []
271
+ owners.push({ workspace, path })
272
+ candidates.set(id, owners)
273
+ }
274
+ }
275
+ const fixes = new Map()
276
+ for (const [id, owners] of candidates) {
277
+ if (owners.length < 2) continue
278
+ const header = (await ctx.sessionPersistence.stat(id))?.header
279
+ if (header?.id !== id) continue
280
+ const entry = await prepareIndexEntry(header)
281
+ const matches = owners.filter(({ path }) => path === entry.path)
282
+ if (matches.length === 1) fixes.set(id, { owners, keep: matches[0].workspace })
283
+ }
284
+ let repaired = 0
285
+ if (fixes.size === 0) return repaired
286
+ await transact(access(ctx, options), (current) => {
287
+ const changes = new Map()
288
+ for (const [id, { owners, keep }] of fixes) {
289
+ if (owners.some(({ workspace, path }) => {
290
+ const record = current.get(workspace)
291
+ return record?.path !== path || !record.sessionIds.includes(id)
292
+ })) continue
293
+ for (const { workspace } of owners) {
294
+ if (workspace === keep) continue
295
+ const record = changes.get(workspace) ?? current.get(workspace)
296
+ saveChanged(changes, workspace, record, record.sessionIds.filter((candidate) => candidate !== id))
297
+ repaired++
298
+ }
299
+ }
300
+ return changes
301
+ })
302
+ return repaired
303
+ }
304
+
305
+ /** Reconcile the search index if the deployment has opened it. */
306
+ export async function refreshSearchIndex(ctx) {
307
+ try {
308
+ const query = ctx.get('sessionQuery')
309
+ if (query?.config?.openAt === 'never' || typeof query?.searchSessions !== 'function') return
310
+ const { openAt, path } = query.config ?? {}
311
+ if (openAt === 'first-search' && typeof path === 'string' && path !== ':memory:') {
312
+ try {
313
+ await stat(path)
314
+ } catch (error) {
315
+ if (error.code === 'ENOENT') return
316
+ throw error
317
+ }
318
+ }
319
+ await query.searchSessions({ query: 'session', limit: 1 })
320
+ } catch (error) {
321
+ ctx.logger?.warn?.('Session move: search reconciliation failed: %s', error)
322
+ }
323
+ }
package/src/move.js ADDED
@@ -0,0 +1,160 @@
1
+ import { assertExpectedSource, buildPlan, fail, validId, validSourceWorkspaceId } from './plan.js'
2
+ import { idleWebWriter, releaseIdleWebWriters } from './lease.js'
3
+ import { captureLedger, moveLedger, restoreLedger, refreshSearchIndex } from './ledger.js'
4
+ import { recoverMove } from './recovery.js'
5
+ import { moveStorage } from './transaction.js'
6
+ import { readMoveEvents } from './inbox.js'
7
+ import { refreshSessionSummaries } from './sidebar.js'
8
+
9
+ const knownErrors = new Set([
10
+ 'bad-request', 'busy', 'locked', 'missing', 'target-missing', 'target-not-canonical',
11
+ 'same-workspace', 'stale-source', 'collision', 'changed', 'unsupported', 'restore-pending', 'cleanup-pending',
12
+ 'archived', 'subagent', 'unsafe-path', 'cross-device', 'restored',
13
+ ])
14
+
15
+ function destinationMembers(plan) {
16
+ return plan.members.map(({ id }) => ({ id, cwd: plan.targetCwd }))
17
+ }
18
+
19
+ export function createSessionMove(ctx, { root, base, previous, checkpoint, activity = async (id) => {
20
+ return await ctx.waterfall('workspace/session-activity', { sessionId: id }, async () => [])
21
+ }, release = releaseIdleWebWriters, storage = moveStorage(root, base, { checkpoint }) }) {
22
+ const previousStorages = (Array.isArray(previous) ? previous : [previous]).filter(Boolean)
23
+ .map((directory) => moveStorage(root, directory))
24
+ let chain = Promise.resolve()
25
+
26
+ async function checkIdle(plan) {
27
+ for (const { id } of plan.members) if ((await activity(id)).length) throw fail('busy')
28
+ }
29
+
30
+ async function verifyDestination(state) {
31
+ const verified = new Map()
32
+ for (const member of state.members) {
33
+ const handle = await ctx.sessionPersistence.open(member.id, 'read')
34
+ try {
35
+ if (handle.header.id !== member.id || handle.header.cwd !== state.targetCwd) throw fail('changed')
36
+ if (member.oldCwd === state.targetCwd) continue
37
+ const cut = { header: handle.header, inheritedEventCount: handle.inheritedEventCount, ...await handle.read() }
38
+ const directory = cut.events.at(-1)
39
+ if (directory?.type !== 'working-directory/change' || directory.seq !== member.cwdChangeSeq
40
+ || directory.data?.cwd !== state.targetCwd) throw fail('changed')
41
+ verified.set(member.id, cut)
42
+ } finally { await handle.close() }
43
+ }
44
+ return verified
45
+ }
46
+
47
+ async function move(body, signal) {
48
+ for (const previousStorage of previousStorages) await recoverMove(ctx, previousStorage)
49
+ await recoverMove(ctx, storage)
50
+ return storage.withLock(async () => {
51
+ if (await storage.readState()) throw fail('restore-pending')
52
+ const plan = await buildPlan(ctx, { root }, body)
53
+ await checkIdle(plan)
54
+ assertExpectedSource(ctx.workspaceRegistry.list(), body)
55
+ const writers = plan.members.flatMap(({ id }) => {
56
+ const session = ctx.sessions.get(id)
57
+ if (!session) return []
58
+ const writer = idleWebWriter(ctx, session)
59
+ if (writer.settling) throw fail('busy')
60
+ return [writer]
61
+ })
62
+ signal?.throwIfAborted()
63
+ try {
64
+ await release(ctx, writers)
65
+ return await storage.withSessionLocks(plan, async (lockStage) => {
66
+ if (plan.members.some(({ id }) => ctx.sessions.get(id))) throw fail('locked')
67
+ await checkIdle(plan)
68
+ const current = await buildPlan(ctx, { root }, body)
69
+ if (current.targetCwd !== plan.targetCwd || current.members.length !== plan.members.length
70
+ || current.members.some((member, i) => member.id !== plan.members[i].id
71
+ || member.oldCwd !== plan.members[i].oldCwd || member.oldFile !== plan.members[i].oldFile)) throw fail('changed')
72
+ assertExpectedSource(ctx.workspaceRegistry.list(), body)
73
+ const ledger = captureLedger(ctx, current)
74
+ signal?.throwIfAborted()
75
+ if (current.members.every(({ oldCwd }) => oldCwd === current.targetCwd)) {
76
+ // Reattaching to the same project only changes its workspace record.
77
+ for (const member of current.members) await readMoveEvents(ctx, member)
78
+ signal?.throwIfAborted()
79
+ try {
80
+ await moveLedger(ctx, current, ledger)
81
+ } catch (error) {
82
+ if (error.code === 'unknown-state') throw fail('restore-pending', error)
83
+ throw error
84
+ }
85
+ const synced = await refreshSessionSummaries(ctx, destinationMembers(current))
86
+ return synced ? { moved: true } : { moved: true, sidebarPending: true }
87
+ }
88
+ const state = await storage.prepare(ctx, current, ledger, lockStage)
89
+ await storage.save(state)
90
+ let committing = false
91
+ let verified
92
+ try {
93
+ await checkpoint?.('prepared', state)
94
+ await storage.publish(state)
95
+ verified = await verifyDestination(state)
96
+ await moveLedger(ctx, state, ledger)
97
+ committing = true
98
+ await checkpoint?.('ledger-published', state)
99
+ await storage.save({ ...state, phase: 'committed' })
100
+ } catch (error) {
101
+ if (committing || error.code === 'unknown-state') {
102
+ // The ledger rename may already be durable. Let recovery prove
103
+ // which side is authoritative before touching the transcript.
104
+ throw fail('restore-pending', error)
105
+ }
106
+ try {
107
+ await storage.rollback(state)
108
+ await restoreLedger(ctx, state, ledger)
109
+ await storage.save({ ...state, phase: 'rolled-back' })
110
+ await storage.finish(state)
111
+ } catch (restoreError) { throw fail('restore-pending', restoreError) }
112
+ ctx.logger?.warn?.('Session move rolled back: %s', error)
113
+ throw fail('restored', error)
114
+ }
115
+ let cleanupPending = false
116
+ try {
117
+ await checkpoint?.('committed', state)
118
+ await storage.cleanCommitted(state)
119
+ } catch (error) {
120
+ cleanupPending = true
121
+ ctx.logger?.warn?.('Session move cleanup: %s', error)
122
+ }
123
+ const synced = await refreshSessionSummaries(ctx, destinationMembers(state), verified)
124
+ await refreshSearchIndex(ctx)
125
+ return { moved: true, ...(cleanupPending ? { cleanupPending } : {}), ...(!synced ? { sidebarPending: true } : {}) }
126
+ })
127
+ } catch (error) {
128
+ // Disposing a resident writer also removes its list row. Republish
129
+ // an unchanged or restored source if the move failed after disposal.
130
+ if (error.code !== 'restore-pending') {
131
+ const disposed = writers.filter(({ session }) => !ctx.sessions.get(session.id))
132
+ await refreshSessionSummaries(ctx, disposed.map(({ session }) => ({ id: session.id, cwd: session.header.cwd })))
133
+ }
134
+ throw error
135
+ }
136
+ })
137
+ }
138
+
139
+ return (request) => {
140
+ const result = chain.then(async () => {
141
+ const headers = { 'Cache-Control': 'no-store' }
142
+ try {
143
+ if (request.method !== 'POST' || request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json') {
144
+ throw fail('bad-request')
145
+ }
146
+ let body
147
+ try { body = await request.json() } catch { throw fail('bad-request') }
148
+ if (!validId(body?.sessionId) || !validId(body?.targetWorkspaceId) || !validSourceWorkspaceId(body.sourceWorkspaceId)
149
+ || (body.beforeSessionId !== undefined && !validId(body.beforeSessionId))) throw fail('bad-request')
150
+ return Response.json(await move(body, request.signal), { headers })
151
+ } catch (error) {
152
+ const code = knownErrors.has(error?.code) ? error.code : 'failed'
153
+ if (code === 'failed' || code === 'restore-pending') ctx.logger?.warn?.('Session move: %s', error)
154
+ return Response.json({ error: code }, { headers, status: code === 'bad-request' ? 400 : code === 'failed' ? 500 : 409 })
155
+ }
156
+ })
157
+ chain = result.then(() => {}, () => {})
158
+ return result
159
+ }
160
+ }
package/src/paths.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Session log path derivation, mirroring
3
+ * `@deepseek-ai/dsh-session-persistence-jsonl/src/format.ts` exactly.
4
+ *
5
+ * Vendored instead of imported: the shipped module is TypeScript resolved from
6
+ * the DSH install, and a profile-installed bundle must not depend on how that
7
+ * install is laid out. `test/paths.test.js` pins this copy against the shipped
8
+ * implementation so a drift in either side fails loudly.
9
+ *
10
+ * @module dsh-session-move/paths
11
+ */
12
+
13
+ import { join } from 'node:path'
14
+
15
+ /** Escape one arbitrary string into a single safe path segment (`~XXXX` per code unit). */
16
+ export function encodeSegment(raw) {
17
+ if (raw.length === 0) throw new Error('cannot encode an empty path segment')
18
+ if (raw === '.') return '~002E'
19
+ if (raw === '..') return '~002E~002E'
20
+ let out = ''
21
+ for (let i = 0; i < raw.length; i++) {
22
+ const code = raw.charCodeAt(i)
23
+ const ch = String.fromCharCode(code)
24
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) out += ch
25
+ else out += '~' + code.toString(16).toUpperCase().padStart(4, '0')
26
+ }
27
+ return out
28
+ }
29
+
30
+ /** Build the human-navigable project directory key for a project path. */
31
+ export function projectKey(cwd) {
32
+ if (cwd.length === 0) throw new Error('cannot encode an empty project path')
33
+ let readable = ''
34
+ let separatorRun = false
35
+ for (let i = 0; i < cwd.length; i++) {
36
+ const code = cwd.charCodeAt(i)
37
+ const ch = String.fromCharCode(code)
38
+ if (ch === '/' || ch === '\\' || ch === ':') {
39
+ if (!separatorRun) readable += '-'
40
+ separatorRun = true
41
+ } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
42
+ readable += ch
43
+ separatorRun = false
44
+ } else {
45
+ readable += '~' + code.toString(16).toUpperCase().padStart(4, '0')
46
+ separatorRun = false
47
+ }
48
+ }
49
+ const slug = readable.replace(/^-+/, '') || 'root'
50
+ return `--${slug.slice(0, 251)}--`
51
+ }
52
+
53
+ /** The project directory a session with this cwd lives under. */
54
+ export function projectDir(root, cwd) {
55
+ if (cwd === undefined) return join(root, '_no-cwd')
56
+ return join(root, projectKey(cwd))
57
+ }
58
+
59
+ /** The directory owned by one session. */
60
+ export function sessionDir(root, cwd, id) {
61
+ return join(projectDir(root, cwd), encodeSegment(id))
62
+ }
63
+
64
+ /** The current generation's log filename. */
65
+ export const LOG_FILENAME = 'session.v4.jsonl.zstd'
66
+
67
+ /** The write-lease file DSH keeps beside the log. */
68
+ export const LOCK_FILENAME = 'session.lock'